PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions
runloop.h File Reference
#include <petscpf.h>
#include <petscdmswarm.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <petsctime.h>
#include <petscsys.h>
#include <petscdmcomposite.h>
#include <petscsystypes.h>
#include "variables.h"
#include "ParticleSwarm.h"
#include "walkingsearch.h"
#include "grid.h"
#include "logging.h"
#include "io.h"
#include "interpolation.h"
#include "initialcondition.h"
#include "AnalyticalSolutions.h"
#include "ParticleMotion.h"
#include "ParticlePhysics.h"
#include "Boundaries.h"
#include "setup.h"
#include "solvers.h"
Include dependency graph for runloop.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PetscErrorCode InitializeRuntimeSignalHandlers (void)
 Installs lightweight signal handlers for graceful shutdown requests.
 
PetscReal RuntimeWalltimeGuardUpdateEWMA (PetscBool has_previous, PetscReal previous_ewma_seconds, PetscReal latest_step_seconds, PetscReal alpha)
 Update an EWMA estimate for timestep wall-clock duration.
 
PetscReal RuntimeWalltimeGuardConservativeEstimate (PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds)
 Return the conservative timestep estimate used by the walltime guard.
 
PetscReal RuntimeWalltimeGuardRequiredHeadroom (PetscReal min_seconds, PetscReal multiplier, PetscReal conservative_estimate_seconds)
 Compute the required shutdown headroom from timestep estimate and floor.
 
PetscBool RuntimeWalltimeGuardShouldTrigger (PetscInt completed_steps, PetscInt warmup_steps, PetscReal remaining_seconds, PetscReal min_seconds, PetscReal multiplier, PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds, PetscReal *required_headroom_seconds_out)
 Decide whether the runtime walltime guard should stop before another step.
 
PetscErrorCode UpdateSolverHistoryVectors (UserCtx *user, PetscBool preserve_previous_state)
 Copies the current time step's solution fields into history vectors (e.g., U(t_n) -> U_o, U_o -> U_rm1) for the next time step's calculations.
 
PetscErrorCode AdvanceSimulation (SimCtx *simCtx)
 Executes the main time-marching loop for the particle simulation.
 
PetscErrorCode PerformInitializedParticleSetup (SimCtx *simCtx)
 Finalizes the simulation setup at t=0, ensuring a consistent state before time marching.
 
PetscErrorCode PerformLoadedParticleSetup (SimCtx *simCtx)
 Finalizes the simulation state after particle and fluid data have been loaded from a restart.
 
PetscErrorCode FinalizeRestartState (SimCtx *simCtx)
 Performs post-load/post-init consistency checks for a restarted simulation.
 

Function Documentation

◆ InitializeRuntimeSignalHandlers()

PetscErrorCode InitializeRuntimeSignalHandlers ( void  )

Installs lightweight signal handlers for graceful shutdown requests.

The handlers only record that a shutdown signal was received. The actual output flush and exit path happens later at safe checkpoints in the run loop.

Returns
PetscErrorCode 0 on success.

Installs lightweight signal handlers for graceful shutdown requests.

Full API contract (arguments, ownership, side effects) is documented with the matching public header declaration.

See also
InitializeRuntimeSignalHandlers()

Definition at line 165 of file runloop.c.

166{
167 PetscErrorCode ierr;
168
169 PetscFunctionBeginUser;
173
174#ifdef SIGTERM
175 ierr = RegisterRuntimeSignalHandler(SIGTERM); CHKERRQ(ierr);
176#endif
177#ifdef SIGUSR1
178 ierr = RegisterRuntimeSignalHandler(SIGUSR1); CHKERRQ(ierr);
179#endif
180#ifdef SIGINT
181 ierr = RegisterRuntimeSignalHandler(SIGINT); CHKERRQ(ierr);
182#endif
183
185 PetscFunctionReturn(0);
186}
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
static PetscBool g_runtime_shutdown_auto_requested
Definition runloop.c:15
static PetscErrorCode RegisterRuntimeSignalHandler(int signum)
Install the process signal handler used to request graceful simulation shutdown.
Definition runloop.c:138
static volatile sig_atomic_t g_runtime_shutdown_signal
Definition runloop.c:14
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RuntimeWalltimeGuardUpdateEWMA()

PetscReal RuntimeWalltimeGuardUpdateEWMA ( PetscBool  has_previous,
PetscReal  previous_ewma_seconds,
PetscReal  latest_step_seconds,
PetscReal  alpha 
)

Update an EWMA estimate for timestep wall-clock duration.

Parameters
[in]has_previousWhether a previous EWMA estimate exists.
[in]previous_ewma_secondsPrior EWMA estimate in seconds.
[in]latest_step_secondsLatest completed timestep duration in seconds.
[in]alphaEWMA weighting factor in (0, 1].
Returns
PetscReal Updated EWMA estimate in seconds.

Update an EWMA estimate for timestep wall-clock duration.

Full API contract (arguments, ownership, side effects) is documented with the matching public header declaration.

See also
RuntimeWalltimeGuardUpdateEWMA()

Definition at line 194 of file runloop.c.

195{
197 if (!has_previous) { PROFILE_HELPER_END; return latest_step_seconds; }
198 const PetscReal ewma = alpha * latest_step_seconds + (1.0 - alpha) * previous_ewma_seconds;
200 return ewma;
201}
Here is the caller graph for this function:

◆ RuntimeWalltimeGuardConservativeEstimate()

PetscReal RuntimeWalltimeGuardConservativeEstimate ( PetscReal  warmup_average_seconds,
PetscReal  ewma_seconds,
PetscReal  latest_step_seconds 
)

Return the conservative timestep estimate used by the walltime guard.

Parameters
[in]warmup_average_secondsAverage duration across warmup steps.
[in]ewma_secondsCurrent EWMA duration estimate.
[in]latest_step_secondsMost recent completed timestep duration.
Returns
PetscReal Conservative timestep estimate in seconds.

Return the conservative timestep estimate used by the walltime guard.

Full API contract (arguments, ownership, side effects) is documented with the matching public header declaration.

See also
RuntimeWalltimeGuardConservativeEstimate()

Definition at line 209 of file runloop.c.

210{
212 const PetscReal estimate = PetscMax(warmup_average_seconds, PetscMax(ewma_seconds, latest_step_seconds));
214 return estimate;
215}
Here is the caller graph for this function:

◆ RuntimeWalltimeGuardRequiredHeadroom()

PetscReal RuntimeWalltimeGuardRequiredHeadroom ( PetscReal  min_seconds,
PetscReal  multiplier,
PetscReal  conservative_estimate_seconds 
)

Compute the required shutdown headroom from timestep estimate and floor.

Parameters
[in]min_secondsAbsolute minimum shutdown headroom.
[in]multiplierSafety multiplier applied to the timestep estimate.
[in]conservative_estimate_secondsConservative timestep estimate in seconds.
Returns
PetscReal Required headroom in seconds.

Compute the required shutdown headroom from timestep estimate and floor.

Full API contract (arguments, ownership, side effects) is documented with the matching public header declaration.

See also
RuntimeWalltimeGuardRequiredHeadroom()

Definition at line 223 of file runloop.c.

224{
226 const PetscReal headroom = PetscMax(min_seconds, multiplier * conservative_estimate_seconds);
228 return headroom;
229}
Here is the caller graph for this function:

◆ RuntimeWalltimeGuardShouldTrigger()

PetscBool RuntimeWalltimeGuardShouldTrigger ( PetscInt  completed_steps,
PetscInt  warmup_steps,
PetscReal  remaining_seconds,
PetscReal  min_seconds,
PetscReal  multiplier,
PetscReal  warmup_average_seconds,
PetscReal  ewma_seconds,
PetscReal  latest_step_seconds,
PetscReal *  required_headroom_seconds_out 
)

Decide whether the runtime walltime guard should stop before another step.

Parameters
[in]completed_stepsNumber of completed timesteps observed so far.
[in]warmup_stepsMinimum completed timesteps required before guarding.
[in]remaining_secondsRemaining walltime in seconds.
[in]min_secondsAbsolute minimum shutdown headroom.
[in]multiplierSafety multiplier applied to timestep estimate.
[in]warmup_average_secondsAverage duration across warmup steps.
[in]ewma_secondsCurrent EWMA duration estimate.
[in]latest_step_secondsLatest completed timestep duration.
[out]required_headroom_seconds_outComputed required headroom in seconds.
Returns
PetscBool PETSC_TRUE when shutdown should be requested.

Decide whether the runtime walltime guard should stop before another step.

Full API contract (arguments, ownership, side effects) is documented with the matching public header declaration.

See also
RuntimeWalltimeGuardShouldTrigger()

Definition at line 237 of file runloop.c.

238{
240 PetscReal conservative_estimate = 0.0;
241 PetscReal required_headroom = 0.0;
242
243 if (required_headroom_seconds_out) *required_headroom_seconds_out = 0.0;
244 if (completed_steps < warmup_steps) { PROFILE_HELPER_END; return PETSC_FALSE; }
245
246 conservative_estimate = RuntimeWalltimeGuardConservativeEstimate(warmup_average_seconds, ewma_seconds, latest_step_seconds);
247 required_headroom = RuntimeWalltimeGuardRequiredHeadroom(min_seconds, multiplier, conservative_estimate);
248 if (required_headroom_seconds_out) *required_headroom_seconds_out = required_headroom;
250 return (PetscBool)(remaining_seconds <= required_headroom);
251}
PetscReal RuntimeWalltimeGuardConservativeEstimate(PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds)
Implementation of RuntimeWalltimeGuardConservativeEstimate().
Definition runloop.c:209
PetscReal RuntimeWalltimeGuardRequiredHeadroom(PetscReal min_seconds, PetscReal multiplier, PetscReal conservative_estimate_seconds)
Implementation of RuntimeWalltimeGuardRequiredHeadroom().
Definition runloop.c:223
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateSolverHistoryVectors()

PetscErrorCode UpdateSolverHistoryVectors ( UserCtx *  user,
PetscBool  preserve_previous_state 
)

Copies the current time step's solution fields into history vectors (e.g., U(t_n) -> U_o, U_o -> U_rm1) for the next time step's calculations.

This function is critical for multi-step time integration schemes (like BDF2) used by the legacy solver. It must be called at the end of every time step, after the new solution has been fully computed.

The order of operations is important to avoid overwriting data prematurely.

Parameters
userThe UserCtx for a single block. The function modifies the history vectors (Ucont_o, Ucont_rm1, etc.) within this context.
preserve_previous_stateKeep a restored Ucont_rm1 checkpoint instead of replacing it with the current state during restart setup.
Returns
PetscErrorCode 0 on success.

Copies the current time step's solution fields into history vectors (e.g., U(t_n) -> U_o, U_o -> U_rm1) for the next time step's calculations.

See also
UpdateSolverHistoryVectors()

Definition at line 376 of file runloop.c.

377{
378 PetscErrorCode ierr;
379 SimCtx *simCtx = user->simCtx; // Access global settings if needed
380
381 PetscFunctionBeginUser;
383 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d, Block %" PetscInt_FMT ": Updating solver history vectors.\n",
384 simCtx->rank, user->_this);
385
386 // --- Primary Contravariant Velocity History ---
387 // The order is critical here.
388 // 1. Move n-1 into n-2 during normal advancement. A restored checkpoint
389 // already supplied the authoritative n-1 state in Ucont_rm1.
390 if (!preserve_previous_state) {
391 ierr = VecCopy(user->Ucont_o, user->Ucont_rm1); CHKERRQ(ierr);
392 }
393 // 2. Then, move the new n state (Ucont) to the n-1 slot (Ucont_o).
394 ierr = VecCopy(user->Ucont, user->Ucont_o); CHKERRQ(ierr);
395
396 LOG_ALLOW(LOCAL,LOG_DEBUG, "Rank %d, Block %" PetscInt_FMT ", Ucont history updated.\n",simCtx->rank,user->_this);
397
398 // --- Update History for Other Fields ---
399 // These are typically only needed at the n-1 state.
400 ierr = VecCopy(user->Ucat, user->Ucat_o); CHKERRQ(ierr);
401 ierr = VecCopy(user->P, user->P_o); CHKERRQ(ierr);
402 LOG_ALLOW(LOCAL,LOG_DEBUG, "Rank %d, Block %" PetscInt_FMT ", Ucat & P history updated.\n",simCtx->rank,user->_this);
403
404 if (simCtx->immersed) {
405 ierr = VecCopy(user->Nvert, user->Nvert_o); CHKERRQ(ierr);
406 }
407
408 // --- Synchronize Local Ghost Regions for the new history vectors ---
409 // This is essential so that stencils in the next time step's calculations
410 // have correct values from neighboring processes.
411 ierr = UpdateLocalGhosts(user, FIELD_ID_UCONT_O); CHKERRQ(ierr);
412 ierr = UpdateLocalGhosts(user, FIELD_ID_UCONT_RM1); CHKERRQ(ierr);
413
414 if (simCtx->immersed) {
415 ierr = UpdateLocalGhosts(user, FIELD_ID_NVERT_O); CHKERRQ(ierr);
416 }
417
419 PetscFunctionReturn(0);
420}
@ FIELD_ID_NVERT_O
@ FIELD_ID_UCONT_O
@ FIELD_ID_UCONT_RM1
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
PetscMPIInt rank
Definition variables.h:919
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscInt _this
Definition variables.h:1175
Vec Ucont
Definition variables.h:1197
Vec Ucat_o
Definition variables.h:1204
Vec Ucont_o
Definition variables.h:1204
Vec Nvert_o
Definition variables.h:1204
Vec Ucont_rm1
Definition variables.h:1207
Vec Nvert
Definition variables.h:1197
PetscInt immersed
Definition variables.h:950
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AdvanceSimulation()

PetscErrorCode AdvanceSimulation ( SimCtx *  simCtx)

Executes the main time-marching loop for the particle simulation.

This version uses the new, integrated LocateAllParticlesInGrid orchestrator and the ResetAllParticleStatuses helper for a clean, robust, and understandable workflow.

For each timestep, it performs:

  1. Sets the background fluid velocity field (Ucat) for the current step.
  2. Updates particle positions using velocity from the previous step's interpolation.
  3. Removes any particles that have left the global domain.
  4. A single call to ‘LocateAllParticlesInGrid’, which handles all particle location and migration until the swarm is fully settled.
  5. Interpolates the current fluid velocity to the newly settled particle locations.
  6. Scatters particle data back to Eulerian fields.
  7. Outputs data at specified intervals.
Parameters
simCtxPointer to the master simulation context.
Returns
PetscErrorCode 0 on success, non-zero on failure.

Executes the main time-marching loop for the particle simulation.

See also
AdvanceSimulation()

Definition at line 603 of file runloop.c.

604{
605 PetscErrorCode ierr;
606 PetscReal step_start_seconds = 0.0;
607 PetscReal step_elapsed_local = 0.0;
608 PetscReal step_elapsed_max = 0.0;
609 // Get the master context from the first block. All blocks share it.
610 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels-1].user;
611
612 // Retrieve control parameters from SimCtx for clarity
613 const PetscInt StartStep = simCtx->StartStep;
614 const PetscInt StepsToRun = simCtx->StepsToRun;
615 const PetscReal dt = simCtx->dt;
616
617 // Variables for particle removal statistics
618 PetscInt removed_local_lost, removed_global_lost;
619 PetscReal removed_scalar_lost = 0.0;
620 PetscBool terminated_early = PETSC_FALSE;
621 PetscBool shutdown_requested = PETSC_FALSE;
622 PetscInt steps_timed = 0; // Steps whose slowest-rank wall time is in steps_elapsed_sum
623 PetscReal steps_elapsed_sum = 0.0;
624
625 PetscFunctionBeginUser;
627 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting main time-marching loop: %" PetscInt_FMT " steps from step %" PetscInt_FMT " (t=%.4f), dt=%.4f\n",
628 StepsToRun, StartStep, simCtx->StartTime, dt);
629
630 // --- Main Time-Marching Loop ---
631 for (PetscInt step = StartStep; step < StartStep + StepsToRun; step++) {
632 ierr = MaybeRequestRuntimeWalltimeGuardShutdown(simCtx, "pre-step checkpoint"); CHKERRQ(ierr);
633 ierr = RuntimeShutdownSynchronize(&shutdown_requested); CHKERRQ(ierr);
634 if (shutdown_requested) {
635 ierr = WriteForcedTerminationOutput(simCtx, user, "pre-step checkpoint"); CHKERRQ(ierr);
636 terminated_early = PETSC_TRUE;
637 break;
638 }
639
640 step_start_seconds = MPI_Wtime();
641
642 // =================================================================
643 // 1. PRE-STEP SETUP
644 // =================================================================
645
646 // Update simulation time and step counters in the master context
647 simCtx->step = step + 1;
648 simCtx->ti += simCtx->dt; //simCtx->StartTime + step * simCtx->dt;
649
650 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Advancing Step %" PetscInt_FMT " (To t=%.4f) ---\n", simCtx->step, simCtx->ti);
651
652
653 // For particles, reset their status to prepare for the new advection/location cycle
654 if (ParticlesEnabled(simCtx)) {
655 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Resetting all particle statuses to NEEDS_LOCATION.\n");
656 ierr = ResetAllParticleStatuses(user); CHKERRQ(ierr);
657 }
658
659 // =================================================================
660 // 2. EULERIAN SOLVER STEP
661 // =================================================================
662 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true){
663 // The grid and its metrics do not change during the run: shown on its first step only.
664 if (step == StartStep) {
665 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_COORDINATES, "PreFlowSolver"); CHKERRQ(ierr);
666 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_CSI, "PreFlowSolver"); CHKERRQ(ierr);
667 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_ETA, "PreFlowSolver"); CHKERRQ(ierr);
668 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_ZET, "PreFlowSolver"); CHKERRQ(ierr);
669 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_CENT, "PreFlowSolver"); CHKERRQ(ierr);
670 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_CENTX, "PreFlowSolver"); CHKERRQ(ierr);
671 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_CENTY, "PreFlowSolver"); CHKERRQ(ierr);
672 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_CENTZ, "PreFlowSolver"); CHKERRQ(ierr);
673 }
674 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_UCAT, "PreFlowSolver"); CHKERRQ(ierr);
675 }
676 LOG_ALLOW(GLOBAL, LOG_INFO, "Updating Eulerian Field ...\n");
677 if(strcmp(simCtx->eulerianSource,"load")==0){
678 //LOAD mode: Read pre-computed fields for the current step.
679 LOG_ALLOW(GLOBAL,LOG_INFO,"Eulerian Source 'load': Reading fields (t=%.4f,step=%" PetscInt_FMT ")...\n",simCtx->ti,simCtx->step);
680 for(PetscInt bi = 0; bi < simCtx->block_number;bi++){
681 ierr = ReadSimulationFields(&user[bi],simCtx->step); CHKERRQ(ierr);
682 }
683 }else if(strcmp(simCtx->eulerianSource,"analytical")==0){
684 // ANALYTICAL mode: the field is the case's source, evaluated at this step's time.
685 LOG_ALLOW(GLOBAL,LOG_INFO,"Eulerian Source 'analytical'. Updating Eulerian field via the Analytical Solution Engine ...\n");
686 ierr = AnalyticalSolutionEngine(simCtx); CHKERRQ(ierr);
687 }else if(strcmp(simCtx->eulerianSource,"solve")==0){
688 // SOLVE mode:Call the refactored, high-level legacy solver. This single function
689 // advances the entire multi-block fluid field from t_n to t_{n+1}.
690 LOG_ALLOW(GLOBAL,LOG_INFO,"Eulerian Source 'solve'. Updating Eulerian field via Solver...\n");
691 ierr = FlowSolver(simCtx); CHKERRQ(ierr);
692 }
693 LOG_ALLOW(GLOBAL, LOG_INFO, "Eulerian Field Updated ...\n");
694 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true){
695 LOG_ALLOW(GLOBAL, LOG_VERBOSE, "Post FlowSolver field states:\n");
696 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_UCAT, "PostFlowSolver"); CHKERRQ(ierr);
697 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_P, "PostFlowSolver"); CHKERRQ(ierr);
698 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_UCONT, "PostFlowSolver"); CHKERRQ(ierr);
699 /* Model fields exist only when their model is active. */
700 if (simCtx->les) {
701 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_NU_T, "PostFlowSolver"); CHKERRQ(ierr);
702 }
703 if (simCtx->les == DYNAMIC_SMAGORINSKY) {
704 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_CS, "PostFlowSolver"); CHKERRQ(ierr);
705 }
706 if (simCtx->wallfunction) {
707 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_U_TAU, "PostFlowSolver"); CHKERRQ(ierr);
708 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_WALL_STRESS, "PostFlowSolver"); CHKERRQ(ierr);
709 }
710 }
711
712
713 // =================================================================
714 // 3. LAGRANGIAN PARTICLE STEP
715 // =================================================================
716
717 if (ParticlesEnabled(simCtx)) {
718 LOG_ALLOW(GLOBAL, LOG_INFO, "Updating Lagrangian particle system...\n");
719 simCtx->particlesLostLastStep = 0;
720 simCtx->particlesLostScalarLastStep = 0.0;
721 simCtx->particlesExitedLastStep = 0;
722 simCtx->particlesExitedScalarLastStep = 0.0;
723
724 // a. Update Eulerian Transport Properties:
725 // Optimization: Only recalculate if turbulence is active (Nu_t changes).
726 // For Laminar flow, the value calculated at Setup is constant.
727 if (simCtx->les) {
728 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
729 ierr = ComputeEulerianDiffusivity(&user[bi]); CHKERRQ(ierr);
730 ierr = ComputeEulerianDiffusivityGradient(&user[bi]); CHKERRQ(ierr);
731 }
732 }
733
734 // a.1 (Optional) Log Eulerian Diffusivity min/max and anatomy for debugging.
735 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true){
736 LOG_ALLOW(GLOBAL, LOG_VERBOSE, "Updated Diffusivity Min/Max:\n");
737 ierr = LOG_FIELD_MIN_MAX(&user[0], FIELD_ID_DIFFUSIVITY); CHKERRQ(ierr);
738 ierr = LOG_FIELD_MIN_MAX(&user[0], FIELD_ID_DIFFUSIVITY_GRADIENT); CHKERRQ(ierr);
739 //LOG_ALLOW(GLOBAL, LOG_VERBOSE, "Updated Diffusivity Anatomy:\n");
740 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_DIFFUSIVITY, "PostDiffusivityUpdate"); CHKERRQ(ierr);
741 }
742 // b. Advect particles using the velocity interpolated from the *previous* step.
743 // P(t_{n+1}) = P(t_n) + V_p(t_n) * dt
744 ierr = UpdateAllParticlePositions(user); CHKERRQ(ierr);
745
746 // b.1 Particles that entered through the inlets during this step join before the search.
747 ierr = InjectParticlesAtInlets(user); CHKERRQ(ierr);
748
749 // c. Settle all particles: find their new host cells and migrate them across ranks.
750 ierr = LocateAllParticlesInGrid(user, simCtx->bboxlist); CHKERRQ(ierr);
751
752 // d. Remove the particles whose search failed (LOST) or that left the domain (EXITED).
753 ierr = CheckAndRemoveLostParticles(user, &removed_local_lost, &removed_global_lost,
754 &removed_scalar_lost, &simCtx->particlesExitedLastStep,
755 &simCtx->particlesExitedScalarLastStep); CHKERRQ(ierr);
756 simCtx->particlesLostLastStep = removed_global_lost;
757 simCtx->particlesLostScalarLastStep = removed_scalar_lost;
758 simCtx->particlesLostCumulative += removed_global_lost;
760 if (removed_global_lost > 0) {
761 LOG_ALLOW(GLOBAL, LOG_WARNING, "Removed %" PetscInt_FMT " particles whose search failed (LOST) this step.\n", removed_global_lost);
762 }
763 if (simCtx->particlesExitedLastStep > 0) {
764 LOG_ALLOW(GLOBAL, LOG_INFO, "Removed %" PetscInt_FMT " particles that left the domain this step.\n", simCtx->particlesExitedLastStep);
765 }
766
767 // d2. Store the particles in host-cell order, so the per-particle loops below and in
768 // the next step read neighbouring grid data for consecutive particles.
769 ierr = SortParticlesByCell(user->swarm); CHKERRQ(ierr);
770
771 // e. Interpolate the NEW fluid velocity (just computed by FlowSolver) onto the
772 // particles' new positions. This gives them V_p(t_{n+1}) for the *next* advection step.
773 ierr = InterpolateAllFieldsToSwarm(user); CHKERRQ(ierr);
774
775 // f. Update the Particle Fields (e.g., temperature, concentration) if applicable.
776 // This can be extended to include reactions, growth, etc.
777 ierr = UpdateAllParticleFields(user); CHKERRQ(ierr);
778
779 // g. (For Two-Way Coupling) Scatter particle data back to the grid to act as a source term.
780 // The scatter recounts the particles per cell, which the metrics below also read.
781 ierr = ScatterAllParticleFieldsToEulerFields(user); CHKERRQ(ierr);
782
783 // h. (Optional) Calculate advanced particle metrics for logging/debugging.
784 ierr = CalculateAdvancedParticleMetrics(user); CHKERRQ(ierr);
785 ierr = LOG_SEARCH_METRICS(user); CHKERRQ(ierr);
786
787
788 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true){
789 LOG_ALLOW(GLOBAL, LOG_VERBOSE, "Post Lagrangian update field states:\n");
790 ierr = LOG_FIELD_MIN_MAX(&user[0], FIELD_ID_PSI); CHKERRQ(ierr);
791 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_PSI, "PostScatter"); CHKERRQ(ierr);
792 ierr = LOG_FIELD_ANATOMY(&user[0], FIELD_ID_PARTICLE_COUNT, "PostScatter"); CHKERRQ(ierr);
793 }
794 }
795
796 // =================================================================
797 // 4. UPDATE HISTORY & I/O
798 // =================================================================
799
800 // The completed-state event feeds statistics windows before physical-solution
801 // monitoring, and before history rotation replaces the state just computed.
802 ierr = FieldStatisticsUpdateWindows(simCtx, simCtx->step, simCtx->ti); CHKERRQ(ierr);
804 ierr = EmitStatisticsConsoleSnapshot(user, simCtx, simCtx->step); CHKERRQ(ierr);
805 }
806
807 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
808
809 // Copy the newly computed fields (Ucont, P, etc.) to the history vectors
810 // (_o, _rm1) to prepare for the next time step.
811 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
812 ierr = UpdateSolverHistoryVectors(&user[bi], PETSC_FALSE); CHKERRQ(ierr);
813 }
814
815 //ierr = LOG_UCAT_ANATOMY(&user[0],"Final"); CHKERRQ(ierr);
816
817 // Handle periodic file output
818 if (ShouldWriteDataOutput(simCtx, simCtx->step)) {
819 LOG_ALLOW(GLOBAL, LOG_INFO, "Writing output for step %" PetscInt_FMT ".\n",simCtx->step);
820 ierr = WriteCheckpointBundle(simCtx, "cadence"); CHKERRQ(ierr);
821 if (ParticlesEnabled(simCtx)) {
822 if (strcmp(simCtx->eulerianSource, "analytical") == 0 &&
825 }
826 ierr = LOG_SCATTER_METRICS(user); CHKERRQ(ierr);
827 }
828 }
829
830 if (ShouldEmitPeriodicParticleConsoleSnapshot(simCtx, simCtx->step)) {
831 ierr = EmitParticleConsoleSnapshot(user, simCtx, simCtx->step); CHKERRQ(ierr);
832 }
833
834 ProfilingLogTimestepSummary(simCtx, simCtx->step);
835
836 step_elapsed_local = MPI_Wtime() - step_start_seconds;
837 step_elapsed_max = step_elapsed_local;
838 ierr = MPI_Allreduce(&step_elapsed_local, &step_elapsed_max, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
839 steps_timed++;
840 steps_elapsed_sum += step_elapsed_max;
841 simCtx->lastStepWallSeconds = step_elapsed_max;
842 ierr = RuntimeMemoryLogSample(simCtx, simCtx->step, "Step", "-"); CHKERRQ(ierr);
843
844 // Update Progress Bar: the slowest rank's mean step time, and the run's lost particles.
845 if(simCtx->rank == 0) {
846 PrintProgressBar(step,StartStep,StepsToRun,simCtx->ti, steps_elapsed_sum / (PetscReal)steps_timed,
847 (ParticlesEnabled(simCtx)) ? simCtx->particlesLostCumulative : -1);
848 if(get_log_level()>=LOG_WARNING) PetscPrintf(PETSC_COMM_SELF,"\n");
849 }
850 if (simCtx->walltimeGuardActive) {
851 UpdateRuntimeWalltimeGuardEstimator(simCtx, step_elapsed_max);
852 ierr = MaybeRequestRuntimeWalltimeGuardShutdown(simCtx, "post-step checkpoint"); CHKERRQ(ierr);
853 }
854
855 ierr = RuntimeShutdownSynchronize(&shutdown_requested); CHKERRQ(ierr);
856 if (shutdown_requested) {
857 ierr = WriteForcedTerminationOutput(simCtx, user, "post-step checkpoint"); CHKERRQ(ierr);
858 terminated_early = PETSC_TRUE;
859 break;
860 }
861 } // --- End of Time-Marching Loop ---
862
863 // The last completed step's progress line is already printed. Below WARNING it ends in a
864 // carriage return, so end the line before later output.
865 if (simCtx->rank == 0 && StepsToRun > 0 && get_log_level() < LOG_WARNING) {
866 PetscPrintf(PETSC_COMM_SELF, "\n");
867 fflush(stdout);
868 }
869
870 if (terminated_early) {
872 "Time marching stopped early after %s. Final retained state is step %" PetscInt_FMT " at t=%.4f.\n",
873 RuntimeShutdownReasonName(), simCtx->step, simCtx->ti);
874 } else {
875 if (StepsToRun > 0) {
876 ierr = WriteCheckpointBundle(simCtx, "final"); CHKERRQ(ierr);
877 }
878 LOG_ALLOW(GLOBAL, LOG_INFO, "Time marching completed. Final time t=%.4f.\n", simCtx->ti);
879 }
881 PetscFunctionReturn(0);
882}
PetscErrorCode AnalyticalSolutionEngine(SimCtx *simCtx)
Sets the Eulerian fields from the case's source (-ic_source_*) at the step's time.
PetscBool AnalyticalFieldSupportsInterpolationError(const SimCtx *simCtx)
Reports whether the analytical field can be compared with interpolated particle velocities.
PetscErrorCode SortParticlesByCell(DM swarm)
Reorders the local swarm points so that points in the same host cell are contiguous.
PetscErrorCode UpdateAllParticlePositions(UserCtx *user)
Loops over all local particles in the DMSwarm, updating their positions based on velocity and the glo...
PetscErrorCode LocateAllParticlesInGrid(UserCtx *user, BoundingBox *bboxlist)
Orchestrates the complete particle location and migration process for one timestep.
PetscErrorCode CheckAndRemoveLostParticles(UserCtx *user, PetscInt *removedCountLocal, PetscInt *removedCountGlobal, PetscReal *removedScalarSumGlobal, PetscInt *exitedCountGlobal, PetscReal *exitedScalarSumGlobal)
Removes particles that the location algorithm flagged as LOST or EXITED.
PetscErrorCode ResetAllParticleStatuses(UserCtx *user)
Marks all local particles as NEEDS_LOCATION for the next settlement pass.
PetscErrorCode ComputeEulerianDiffusivity(UserCtx *user)
Computes the effective diffusivity scalar field (Gamma_eff) on the Eulerian grid.
PetscErrorCode ComputeEulerianDiffusivityGradient(UserCtx *user)
Computes the Eulerian gradient of the effective diffusivity field.
PetscErrorCode UpdateAllParticleFields(UserCtx *user)
Orchestrates the update of all physical properties for particles.
PetscErrorCode InjectParticlesAtInlets(UserCtx *user)
Add the particles that entered through each injecting inlet during this step.
@ FIELD_ID_PSI
@ FIELD_ID_CENTZ
@ FIELD_ID_CSI
@ FIELD_ID_UCAT
@ FIELD_ID_COORDINATES
@ FIELD_ID_NU_T
@ FIELD_ID_CENTY
@ FIELD_ID_DIFFUSIVITY_GRADIENT
@ FIELD_ID_UCONT
@ FIELD_ID_U_TAU
@ FIELD_ID_ETA
@ FIELD_ID_WALL_STRESS
@ FIELD_ID_CS
@ FIELD_ID_CENT
@ FIELD_ID_P
@ FIELD_ID_ZET
@ FIELD_ID_CENTX
@ FIELD_ID_PARTICLE_COUNT
@ FIELD_ID_DIFFUSIVITY
PetscErrorCode ScatterAllParticleFieldsToEulerFields(UserCtx *user)
Scatters a predefined set of particle fields to their corresponding Eulerian fields.
PetscErrorCode InterpolateAllFieldsToSwarm(UserCtx *user)
Interpolates the Eulerian fields the particles carry to every local particle.
PetscErrorCode ReadSimulationFields(UserCtx *user, PetscInt ti)
Reads binary field data for velocity, pressure, and other required vectors.
Definition io.c:1387
PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step)
Returns whether full field/restart output should be written for the.
Definition io.c:521
PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
Write and atomically publish one complete checkpoint bundle.
Definition io.c:2501
PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
Computes and logs the local and global min/max values of a 3-component vector field.
Definition logging.c:2501
PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const struct SimCtx *simCtx, PetscInt completed_step)
Reports whether a completed step falls on the console snapshot cadence.
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user)
Logs the interpolation error between the analytical and computed solutions.
Definition logging.c:3024
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Returns whether a particle console snapshot should be emitted for the completed timestep.
Definition logging.c:501
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Emits one particle console snapshot into the main solver log.
Definition logging.c:518
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime, PetscReal seconds_per_step, PetscInt64 lost_cumulative)
Prints a progress bar to the console.
Definition logging.c:2446
PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const struct SimCtx *simCtx, PetscInt step)
Emits one console snapshot of window progress.
PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
Append a reduced runtime memory sample to the configured memory log.
Definition logging.c:2170
PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
Logs the performance summary for the current timestep and resets timers.
Definition logging.c:2100
PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user)
Computes advanced particle statistics and stores them in SimCtx.
Definition logging.c:3484
PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
Definition logging.c:3101
PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
Logs physical solution-convergence metrics once per completed timestep.
Definition logging.c:1714
PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name)
Logs the anatomy of a specified field at key boundary locations, respecting the solver's specific gri...
Definition logging.c:2903
PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
Writes compact runtime search metrics to CSV and optionally to console.
Definition logging.c:3288
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
static PetscErrorCode MaybeRequestRuntimeWalltimeGuardShutdown(SimCtx *simCtx, const char *checkpoint_name)
Request graceful shutdown when another timestep would exceed the walltime budget.
Definition runloop.c:299
static PetscErrorCode RuntimeShutdownSynchronize(PetscBool *requested)
Agree across ranks on whether to stop, and on why.
Definition runloop.c:81
static PetscErrorCode WriteForcedTerminationOutput(SimCtx *simCtx, UserCtx *user, const char *phase)
Write restart-safe output when a controlled shutdown interrupts the run loop.
Definition runloop.c:346
PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user, PetscBool preserve_previous_state)
Implementation of UpdateSolverHistoryVectors().
Definition runloop.c:376
static const char * RuntimeShutdownReasonName(void)
Translate the current shutdown reason into a user-facing diagnostic label.
Definition runloop.c:120
static void UpdateRuntimeWalltimeGuardEstimator(SimCtx *simCtx, PetscReal completed_step_seconds)
Update the timestep-duration estimate used by the automatic walltime guard.
Definition runloop.c:269
PetscErrorCode FlowSolver(SimCtx *simCtx)
Orchestrates a single time step of the Eulerian fluid solver.
Definition solvers.c:9
PetscErrorCode FieldStatisticsUpdateWindows(struct SimCtx *simCtx, PetscInt step, PetscReal time)
Offers one completed state to every configured window.
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
UserCtx * user
Definition variables.h:768
PetscInt block_number
Definition variables.h:1009
PetscBool walltimeGuardActive
Definition variables.h:1110
PetscReal StartTime
Definition variables.h:932
PetscInt particlesLostLastStep
Particles removed this step because their search failed.
Definition variables.h:1057
UserMG usermg
Definition variables.h:1082
PetscReal dt
Definition variables.h:933
PetscInt StepsToRun
Definition variables.h:927
static PetscBool ParticlesEnabled(const SimCtx *simCtx)
Whether the run carries particles: a seeded or restored population, or inlets that inject them.
Definition variables.h:1143
PetscInt StartStep
Definition variables.h:926
PetscReal particlesExitedScalarLastStep
Sum of Psi over the particles that left the domain this step.
Definition variables.h:1062
BoundingBox * bboxlist
Definition variables.h:1053
PetscInt64 particlesLostCumulative
Definition variables.h:1058
char eulerianSource[PETSC_MAX_PATH_LEN]
Definition variables.h:938
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
PetscInt mglevels
Definition variables.h:775
PetscInt64 particlesExitedCumulative
Definition variables.h:1061
PetscInt particlesExitedLastStep
Particles removed this step because they left the domain.
Definition variables.h:1060
PetscInt step
Definition variables.h:924
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
MGCtx * mgctx
Definition variables.h:778
PetscReal particlesLostScalarLastStep
Sum of Psi over the particles removed this step as LOST.
Definition variables.h:1059
PetscReal ti
Definition variables.h:925
PetscReal lastStepWallSeconds
Slowest rank's wall time of the last completed step (0 before one).
Definition variables.h:1128
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PerformInitializedParticleSetup()

PetscErrorCode PerformInitializedParticleSetup ( SimCtx *  simCtx)

Finalizes the simulation setup at t=0, ensuring a consistent state before time marching.

This function is called from main() after the initial Eulerian and Lagrangian states have been created but before the main time loop begins. Its responsibilities are:

  1. Settling the particle swarm: Migrates particles to their correct owner ranks and finds their initial host cells. This includes handling special surface initializations.
  2. Coupling the fields: Interpolates the initial Eulerian fields to the settled particle locations.
  3. Preparing for the first step: Scatters particle data back to the grid.
  4. Writing the initial output for step 0.
Parameters
simCtxPointer to the main simulation context structure.
Returns
PetscErrorCode 0 on success, non-zero on failure.

Finalizes the simulation setup at t=0, ensuring a consistent state before time marching.

See also
PerformInitializedParticleSetup()

Definition at line 426 of file runloop.c.

427{
428 PetscErrorCode ierr;
429 // --- Get pointers from SimCtx instead of passing them as arguments ---
430 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels-1].user;
431 BoundingBox *bboxlist = simCtx->bboxlist;
432
433 PetscFunctionBeginUser;
435
436 LOG_ALLOW(GLOBAL, LOG_INFO, "[T=%.4f, Step=%" PetscInt_FMT "] Performing initial particle setup procedures.\n", simCtx->ti, simCtx->step);
437
438 // --- 0. Loop over all blocks to compute Eulerian diffusivity.
439 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
440 ierr = ComputeEulerianDiffusivity(&user[bi]); CHKERRQ(ierr);
441 ierr = ComputeEulerianDiffusivityGradient(&user[bi]); CHKERRQ(ierr);
442 }
443
444 // --- 1. Initial Particle Settlement (Location and Migration) ---
445 // Seeding records each particle's cell where it knows it; particles whose cell another rank
446 // owns (a point source) go straight to that owner first, as restarted particles do.
447 LOG_ALLOW(GLOBAL, LOG_INFO, "[T=%.4f, Step=%" PetscInt_FMT "] Initial Settlement: Locating and migrating all particles...\n", simCtx->ti, simCtx->step);
448 ierr = MigrateRestartParticlesUsingCellID(user); CHKERRQ(ierr);
449 ierr = LocateAllParticlesInGrid(user, bboxlist); CHKERRQ(ierr);
450
451 if(get_log_level() >= LOG_DEBUG && is_function_allowed(__func__)==true){
452 LOG_ALLOW(GLOBAL, LOG_DEBUG, "[T=%.4f, Step=%" PetscInt_FMT "] Particle field states after Initial settlement...\n", simCtx->ti, simCtx->step);
453 ierr = LOG_PARTICLE_FIELDS(user,simCtx->LoggingFrequency); CHKERRQ(ierr);
454 }
455
456 // --- 2. Configured initial particle-field values, once positions are final ---
457 // Positions are final after the settlement above; the scatter below then carries the
458 // values to the Eulerian mean before the first update.
459 if (simCtx->particleFieldPlan) {
460 PetscInt nlocal = 0;
461 ParticleFieldEvent event = {0.0, 0};
462
463 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &event.physical_time); CHKERRQ(ierr);
464 ierr = DMSwarmGetLocalSize(user->swarm, &nlocal); CHKERRQ(ierr);
465 ierr = ParticleFieldPlanApply(user, simCtx->particleFieldPlan, &event, 0, nlocal); CHKERRQ(ierr);
466 ierr = ParticleFieldPlanSummarize(user, simCtx->particleFieldPlan); CHKERRQ(ierr);
467 }
468
469 // --- 3. Finalize State for t=0 ---
470 LOG_ALLOW(GLOBAL, LOG_INFO, "[T=%.4f, Step=%" PetscInt_FMT "] Interpolating initial fields to settled particles.\n", simCtx->ti, simCtx->step);
471 ierr = InterpolateAllFieldsToSwarm(user); CHKERRQ(ierr);
472 ierr = RefreshScatteredParticleState(user); CHKERRQ(ierr);
473
474 // --- 4. Initial History and Output ---
475 // Update solver history vectors with the t=0 state before the first real step
476 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
477 ierr = UpdateSolverHistoryVectors(&user[bi],
478 (PetscBool)(simCtx->StartStep > 0 && simCtx->restartHistoryAvailable)); CHKERRQ(ierr);
479 }
480
481 {
482 LOG_ALLOW(GLOBAL, LOG_INFO, "[T=%.4f, Step=%" PetscInt_FMT "] Writing initialized checkpoint.\n", simCtx->ti, simCtx->step);
483 ierr = WriteCheckpointBundle(simCtx, simCtx->StartStep == 0 ? "initial" : "branch_start"); CHKERRQ(ierr);
484 ierr = LOG_SCATTER_METRICS(user); CHKERRQ(ierr);
485 }
486
488 ierr = EmitParticleConsoleSnapshot(user, simCtx, simCtx->step); CHKERRQ(ierr);
489 }
490
491 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Initial setup complete. Ready for time marching. ---\n");
493 PetscFunctionReturn(0);
494}
PetscErrorCode ParticleFieldPlanSummarize(UserCtx *user, const ParticleFieldPlan *plan)
Log and record the realized initial values of every planned field.
PetscErrorCode ParticleFieldPlanApply(UserCtx *user, ParticleFieldPlan *plan, const ParticleFieldEvent *event, PetscInt first, PetscInt end)
Write the plan's values into swarm entries [first, end) of this rank.
When and why a plan is applied.
PetscErrorCode MigrateRestartParticlesUsingCellID(UserCtx *user)
Fast-path migration for restart particles using preloaded Cell IDs.
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Returns whether periodic particle console snapshots are enabled.
Definition logging.c:484
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Prints particle fields in a table that automatically adjusts its column widths.
Definition logging.c:399
static PetscErrorCode RefreshScatteredParticleState(UserCtx *user)
Makes the Eulerian particle averages consistent with the particles before step 1.
Definition runloop.c:59
PetscBool restartHistoryAvailable
Definition variables.h:947
PetscInt LoggingFrequency
Definition variables.h:1087
struct ParticleFieldPlan * particleFieldPlan
Configured initial particle-field values, or NULL.
Definition variables.h:1063
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PerformLoadedParticleSetup()

PetscErrorCode PerformLoadedParticleSetup ( SimCtx *  simCtx)

Finalizes the simulation state after particle and fluid data have been loaded from a restart.

This helper function performs the critical sequence of operations required to ensure the loaded Lagrangian and Eulerian states are fully consistent and the solver is ready to proceed. This includes:

  1. Verifying particle locations in the grid and building runtime links.
  2. Synchronizing particle velocity with the authoritative grid velocity via interpolation.
  3. Scattering particle source terms (e.g., volume fraction) back to the grid.
  4. Updating the solver's history vectors with the final, fully-coupled state.
  5. Writing the complete, consistent state to output files for the restart step.
Parameters
simCtxThe main simulation context.
Returns
PetscErrorCode 0 on success.

Finalizes the simulation state after particle and fluid data have been loaded from a restart.

See also
PerformLoadedParticleSetup()

Definition at line 500 of file runloop.c.

501{
502 PetscErrorCode ierr;
503 PetscFunctionBeginUser;
505 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels-1].user;
506
507 // --- 0. Re-compute Eulerian Diffusivity from loaded fields.
508 LOG_ALLOW(GLOBAL, LOG_INFO, "Re-computing Eulerian Diffusivity from loaded fields...\n");
509 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
510 ierr = ComputeEulerianDiffusivity(&user[bi]); CHKERRQ(ierr);
511 ierr = ComputeEulerianDiffusivityGradient(&user[bi]); CHKERRQ(ierr);
512 }
513
514 // 0.1 This moves particles to their correct ranks immediately using the loaded Cell ID.
515 LOG_ALLOW(GLOBAL, LOG_INFO, "Performing fast restart migration using preloaded Cell IDs...\n");
516 ierr = MigrateRestartParticlesUsingCellID(user); CHKERRQ(ierr);
517
518 // 1. To catch any edge cases (particles with invalid CellIDs or newcomers).
519 // Because we kept the statuses, this function will now SKIP all the particles
520 // that are already on the correct rank,
521 ierr = LocateAllParticlesInGrid(user, simCtx->bboxlist); CHKERRQ(ierr);
522
523 if(get_log_level() >= LOG_DEBUG && is_function_allowed(__func__)){
524 LOG(GLOBAL, LOG_DEBUG, "[T=%.4f, Step=%" PetscInt_FMT "] Particle field states after locating loaded particles...\n", simCtx->ti, simCtx->step);
525 ierr = LOG_PARTICLE_FIELDS(user,simCtx->LoggingFrequency); CHKERRQ(ierr);
526 }
527
528 LOG_ALLOW(GLOBAL, LOG_INFO, "[T=%.4f, Step=%" PetscInt_FMT "] Interpolating initial fields to settled particles.\n", simCtx->ti, simCtx->step);
529
530 // 2. Ensure particles have velocity from the authoritative loaded grid for consistency.
531 ierr = InterpolateAllFieldsToSwarm(user); CHKERRQ(ierr);
532
533 // 3. Update Eulerian source terms from the loaded particle data.
534 ierr = RefreshScatteredParticleState(user); CHKERRQ(ierr);
535
536 // --- 4. Initial History and Output ---
537 // Update solver history vectors with the t=0 state before the first real step
538 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
539 ierr = UpdateSolverHistoryVectors(&user[bi],
540 (PetscBool)(simCtx->StartStep > 0 && simCtx->restartHistoryAvailable)); CHKERRQ(ierr);
541 }
542
543 {
544 LOG_ALLOW(GLOBAL, LOG_INFO, "[T=%.4f, Step=%" PetscInt_FMT "] Writing restored checkpoint.\n", simCtx->ti, simCtx->step);
545 ierr = WriteCheckpointBundle(simCtx, "branch_start"); CHKERRQ(ierr);
546 ierr = LOG_SCATTER_METRICS(user); CHKERRQ(ierr);
547 }
548
550 ierr = EmitParticleConsoleSnapshot(user, simCtx, simCtx->step); CHKERRQ(ierr);
551 }
552
553 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Initial setup complete. Ready for time marching. ---\n");
555 PetscFunctionReturn(0);
556}
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FinalizeRestartState()

PetscErrorCode FinalizeRestartState ( SimCtx *  simCtx)

Performs post-load/post-init consistency checks for a restarted simulation.

This function is called from main() ONLY when a restart is being performed (i.e., StartStep > 0). It inspects the particle restart mode to determine the correct finalization procedure for the Lagrangian swarm.

  • If particles were loaded from a file (mode == "load"), it verifies their locations within the grid to establish necessary runtime links.
  • If new particles were initialized into the restarted flow (mode == "init"), it runs the full PerformInitialSetup sequence to migrate, locate, and couple the new particles with the existing fluid state.
Parameters
simCtxThe main simulation context.
Returns
PetscErrorCode 0 on success.

Performs post-load/post-init consistency checks for a restarted simulation.

See also
FinalizeRestartState()

Definition at line 562 of file runloop.c.

563{
564 PetscErrorCode ierr;
565 PetscFunctionBeginUser;
567
568 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Finalizing RESTART from state (step=%" PetscInt_FMT ", t=%.4f) ---\n", simCtx->StartStep, simCtx->ti);
569
570 // This function only needs to handle the particle finalization logic.
571 // The Eulerian state is assumed to be fully loaded and consistent at this point.
572 if (ParticlesEnabled(simCtx)) {
573
574 // Use the particle restart mode to decide the workflow.
575 if (strcmp(simCtx->particleRestartMode, "load") == 0) {
576 // PARTICLES WERE LOADED: The state is complete, but we must verify
577 // the loaded CellIDs and build the in-memory grid-to-particle links.
578 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Mode 'load': Verifying particle locations and building grid links...\n");
579 ierr = PerformLoadedParticleSetup(simCtx); CHKERRQ(ierr);
580
581 } else { // Mode must be "init"
582 // PARTICLES WERE RE-INITIALIZED: They need to be fully settled and coupled
583 // to the surrounding (restarted) fluid state.
584 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Mode 'init': Running full initial setup for new particles in restarted flow.\n");
585 ierr = PerformInitializedParticleSetup(simCtx); CHKERRQ(ierr);
586 }
587 } else {
588 LOG_ALLOW(GLOBAL, LOG_INFO, "No particles in simulation, restart finalization is complete.\n");
589
590 ierr = WriteCheckpointBundle(simCtx, "branch_start"); CHKERRQ(ierr);
591 }
592
593 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Restart state successfully finalized. --\n");
594
596 PetscFunctionReturn(0);
597}
PetscErrorCode PerformInitializedParticleSetup(SimCtx *simCtx)
Implementation of PerformInitializedParticleSetup().
Definition runloop.c:426
PetscErrorCode PerformLoadedParticleSetup(SimCtx *simCtx)
Implementation of PerformLoadedParticleSetup().
Definition runloop.c:500
char particleRestartMode[16]
Definition variables.h:1056
Here is the call graph for this function:
Here is the caller graph for this function: