PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
runloop.c
Go to the documentation of this file.
1/**
2 * @file runloop.c
3 * @brief Test program for DMSwarm interpolation using the fdf-curvIB method.
4 * Provides the setup to start any simulation with DMSwarm and DMDAs.
5 **/
6
7#include <signal.h>
8
9#include "runloop.h"
10#include "statistics_window.h"
13
14static volatile sig_atomic_t g_runtime_shutdown_signal = 0;
15static PetscBool g_runtime_shutdown_auto_requested = PETSC_FALSE;
16
17/**
18 * @brief Record receipt of a termination signal for safe handling by the run loop.
19 */
20static void RuntimeShutdownSignalHandler(int signum)
21{
24 }
25}
26
27/**
28 * @brief Request a controlled shutdown because the estimated walltime margin is exhausted.
29 */
38
39/**
40 * @brief Report whether a signal or walltime guard has requested run-loop shutdown.
41 */
42static PetscBool RuntimeShutdownRequested(void)
43{
45 const PetscBool requested = (PetscBool)(g_runtime_shutdown_signal != 0 || g_runtime_shutdown_auto_requested);
47 return requested;
48}
49
50/**
51 * @brief Makes the Eulerian particle averages consistent with the particles before step 1.
52 * @details The first step's particle update relaxes each particle toward the scattered
53 * Eulerian mean, and its own scatter comes only after that update. So whatever
54 * the particles hold at setup - an initial condition, a loaded state, or the
55 * verification profile - must be scattered here, or step 1 relaxes toward a mean
56 * that never saw it. The verification profile, when active, is applied first.
57 * Local to this translation unit.
58 */
59static PetscErrorCode RefreshScatteredParticleState(UserCtx *user)
60{
61 PetscFunctionBeginUser;
63 if (!user) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
66 }
69 PetscFunctionReturn(0);
70}
71
72/**
73 * @brief Agree across ranks on whether to stop, and on why.
74 * @details A forwarded signal reaches the ranks at slightly different times, and the walltime
75 * guard reads each rank's own clock. A rank that stopped alone would enter the
76 * collective termination output while the others entered the next step's solves, so
77 * the loop stops on every rank or on none; every rank then reports the same reason.
78 * @param[out] requested Whether any rank has a shutdown request.
79 * @return PetscErrorCode 0 on success.
80 */
81static PetscErrorCode RuntimeShutdownSynchronize(PetscBool *requested)
82{
84 int global[2] = {0, 0};
85
86 PetscFunctionBeginUser;
88 PetscCallMPI(MPI_Allreduce(local, global, 2, MPI_INT, MPI_MAX, PETSC_COMM_WORLD));
89 if (global[0] != 0 && g_runtime_shutdown_signal == 0) g_runtime_shutdown_signal = global[0];
90 if (global[1] != 0) g_runtime_shutdown_auto_requested = PETSC_TRUE;
91 *requested = (PetscBool)(global[0] != 0 || global[1] != 0);
93 PetscFunctionReturn(0);
94}
95
96/**
97 * @brief Translate a recorded termination signal into a user-facing signal name.
98 */
99static const char *RuntimeShutdownSignalName(PetscInt signum)
100{
102 switch (signum) {
103#ifdef SIGTERM
104 case SIGTERM: PROFILE_HELPER_END; return "SIGTERM";
105#endif
106#ifdef SIGUSR1
107 case SIGUSR1: PROFILE_HELPER_END; return "SIGUSR1";
108#endif
109#ifdef SIGINT
110 case SIGINT: PROFILE_HELPER_END; return "SIGINT";
111#endif
112 default: PROFILE_HELPER_END; return "UNKNOWN";
113 }
115}
116
117/**
118 * @brief Translate the current shutdown reason into a user-facing diagnostic label.
119 */
120static const char *RuntimeShutdownReasonName(void)
121{
123 if (g_runtime_shutdown_signal != 0) {
126 }
129 return "AUTO_WALLTIME_GUARD";
130 }
132 return "NONE";
133}
134
135/**
136 * @brief Install the process signal handler used to request graceful simulation shutdown.
137 */
138static PetscErrorCode RegisterRuntimeSignalHandler(int signum)
139{
140 struct sigaction action;
141
142 PetscFunctionBeginUser;
144 memset(&action, 0, sizeof(action));
145 action.sa_handler = RuntimeShutdownSignalHandler;
146
147 if (sigemptyset(&action.sa_mask) != 0) {
148 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS, "sigemptyset failed for signal %d.", signum);
149 }
150
151 if (sigaction(signum, &action, NULL) != 0) {
152 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS, "sigaction failed for signal %d.", signum);
153 }
154
156 PetscFunctionReturn(0);
157}
158
159/**
160 * @brief Implementation of \ref InitializeRuntimeSignalHandlers().
161 * @details Full API contract (arguments, ownership, side effects) is documented with
162 * the matching public header declaration.
163 * @see InitializeRuntimeSignalHandlers()
164 */
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}
187
188/**
189 * @brief Implementation of \ref RuntimeWalltimeGuardUpdateEWMA().
190 * @details Full API contract (arguments, ownership, side effects) is documented with
191 * the matching public header declaration.
192 * @see RuntimeWalltimeGuardUpdateEWMA()
193 */
194PetscReal RuntimeWalltimeGuardUpdateEWMA(PetscBool has_previous, PetscReal previous_ewma_seconds, PetscReal latest_step_seconds, PetscReal alpha)
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}
202
203/**
204 * @brief Implementation of \ref RuntimeWalltimeGuardConservativeEstimate().
205 * @details Full API contract (arguments, ownership, side effects) is documented with
206 * the matching public header declaration.
207 * @see RuntimeWalltimeGuardConservativeEstimate()
208 */
209PetscReal RuntimeWalltimeGuardConservativeEstimate(PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds)
210{
212 const PetscReal estimate = PetscMax(warmup_average_seconds, PetscMax(ewma_seconds, latest_step_seconds));
214 return estimate;
215}
216
217/**
218 * @brief Implementation of \ref RuntimeWalltimeGuardRequiredHeadroom().
219 * @details Full API contract (arguments, ownership, side effects) is documented with
220 * the matching public header declaration.
221 * @see RuntimeWalltimeGuardRequiredHeadroom()
222 */
223PetscReal RuntimeWalltimeGuardRequiredHeadroom(PetscReal min_seconds, PetscReal multiplier, PetscReal conservative_estimate_seconds)
224{
226 const PetscReal headroom = PetscMax(min_seconds, multiplier * conservative_estimate_seconds);
228 return headroom;
229}
230
231/**
232 * @brief Implementation of \ref RuntimeWalltimeGuardShouldTrigger().
233 * @details Full API contract (arguments, ownership, side effects) is documented with
234 * the matching public header declaration.
235 * @see RuntimeWalltimeGuardShouldTrigger()
236 */
237PetscBool 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)
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}
252
253/**
254 * @brief Estimate the remaining scheduler walltime after reserving the configured shutdown margin.
255 */
256static PetscReal RuntimeWalltimeGuardRemainingSeconds(const SimCtx *simCtx)
257{
259 time_t now = time(NULL);
260
261 if (now == (time_t)-1) { PROFILE_HELPER_END; return -1.0; }
263 return simCtx->walltimeGuardLimitSeconds - ((PetscReal)now - simCtx->walltimeGuardJobStartEpochSeconds);
264}
265
266/**
267 * @brief Update the timestep-duration estimate used by the automatic walltime guard.
268 */
269static void UpdateRuntimeWalltimeGuardEstimator(SimCtx *simCtx, PetscReal completed_step_seconds)
270{
273 simCtx->walltimeGuardLatestStepSeconds = completed_step_seconds;
274
276 simCtx->walltimeGuardWarmupTotalSeconds += completed_step_seconds;
280 simCtx->walltimeGuardHasEWMA = PETSC_TRUE;
281 }
283 return;
284 }
285
287 simCtx->walltimeGuardHasEWMA,
289 completed_step_seconds,
291 );
292 simCtx->walltimeGuardHasEWMA = PETSC_TRUE;
294}
295
296/**
297 * @brief Request graceful shutdown when another timestep would exceed the walltime budget.
298 */
299static PetscErrorCode MaybeRequestRuntimeWalltimeGuardShutdown(SimCtx *simCtx, const char *checkpoint_name)
300{
301 PetscReal remaining_seconds = 0.0;
302 PetscReal required_headroom = 0.0;
303
304 PetscFunctionBeginUser;
306 if (!simCtx->walltimeGuardActive || RuntimeShutdownRequested()) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
307
308 remaining_seconds = RuntimeWalltimeGuardRemainingSeconds(simCtx);
312 remaining_seconds,
318 &required_headroom)) {
320 PetscFunctionReturn(0);
321 }
322
324 LOG_ALLOW(
325 GLOBAL,
327 "[T=%.4f, Step=%" PetscInt_FMT "] AUTO_WALLTIME_GUARD requested at %s: remaining walltime %.1f s <= required headroom %.1f s "
328 "(warmup avg %.1f s, ewma %.1f s, latest %.1f s).\n",
329 simCtx->ti,
330 simCtx->step,
331 checkpoint_name,
332 (double)remaining_seconds,
333 (double)required_headroom,
334 (double)simCtx->walltimeGuardWarmupAverageSeconds,
335 (double)simCtx->walltimeGuardEWMASeconds,
336 (double)simCtx->walltimeGuardLatestStepSeconds
337 );
338
340 PetscFunctionReturn(0);
341}
342
343/**
344 * @brief Write restart-safe output when a controlled shutdown interrupts the run loop.
345 */
346static PetscErrorCode WriteForcedTerminationOutput(SimCtx *simCtx, UserCtx *user, const char *phase)
347{
348 PetscErrorCode ierr;
349
350 PetscFunctionBeginUser;
352
353 ierr = RuntimeMemoryLogSample(simCtx, simCtx->step, "Shutdown", RuntimeShutdownReasonName()); CHKERRQ(ierr);
354
356 "[T=%.4f, Step=%" PetscInt_FMT "] Shutdown requested by %s during %s. Writing final output outside the normal cadence before exiting.\n",
357 simCtx->ti, simCtx->step, RuntimeShutdownReasonName(), phase);
358
359 ierr = WriteCheckpointBundle(simCtx, "signal"); CHKERRQ(ierr);
360
362 ierr = EmitParticleConsoleSnapshot(user, simCtx, simCtx->step); CHKERRQ(ierr);
363 }
364
365 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRMPI(ierr);
366 fflush(stdout);
367
369 PetscFunctionReturn(0);
370}
371
372/**
373 * @brief Implementation of \ref UpdateSolverHistoryVectors().
374 * @see UpdateSolverHistoryVectors()
375 */
376PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user, PetscBool preserve_previous_state)
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}
421
422/**
423 * @brief Implementation of \ref PerformInitializedParticleSetup().
424 * @see PerformInitializedParticleSetup()
425 */
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}
495
496/**
497 * @brief Implementation of \ref PerformLoadedParticleSetup().
498 * @see PerformLoadedParticleSetup()
499 */
500PetscErrorCode PerformLoadedParticleSetup(SimCtx *simCtx)
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}
557
558/**
559 * @brief Implementation of \ref FinalizeRestartState().
560 * @see FinalizeRestartState()
561 */
562PetscErrorCode FinalizeRestartState(SimCtx *simCtx)
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}
598
599/**
600 * @brief Implementation of \ref AdvanceSimulation().
601 * @see AdvanceSimulation()
602 */
603PetscErrorCode AdvanceSimulation(SimCtx *simCtx)
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.
Configured initial values of particle-carried fields.
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 SortParticlesByCell(DM swarm)
Reorders the local swarm points so that points in the same host cell are contiguous.
PetscErrorCode MigrateRestartParticlesUsingCellID(UserCtx *user)
Fast-path migration for restart particles using preloaded Cell IDs.
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_NVERT_O
@ FIELD_ID_COORDINATES
@ FIELD_ID_UCONT_O
@ 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_UCONT_RM1
@ 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 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
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
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
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
#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
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Returns whether periodic particle console snapshots are enabled.
Definition logging.c:484
#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
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
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
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 LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Prints particle fields in a table that automatically adjusts its column widths.
Definition logging.c:399
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_DEBUG
Detailed debugging information.
Definition logging.h:32
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
PetscErrorCode InitializeRuntimeSignalHandlers(void)
Implementation of InitializeRuntimeSignalHandlers().
Definition runloop.c:165
static PetscReal RuntimeWalltimeGuardRemainingSeconds(const SimCtx *simCtx)
Estimate the remaining scheduler walltime after reserving the configured shutdown margin.
Definition runloop.c:256
static PetscErrorCode MaybeRequestRuntimeWalltimeGuardShutdown(SimCtx *simCtx, const char *checkpoint_name)
Request graceful shutdown when another timestep would exceed the walltime budget.
Definition runloop.c:299
PetscErrorCode AdvanceSimulation(SimCtx *simCtx)
Implementation of AdvanceSimulation().
Definition runloop.c:603
static PetscErrorCode RefreshScatteredParticleState(UserCtx *user)
Makes the Eulerian particle averages consistent with the particles before step 1.
Definition runloop.c:59
PetscReal RuntimeWalltimeGuardUpdateEWMA(PetscBool has_previous, PetscReal previous_ewma_seconds, PetscReal latest_step_seconds, PetscReal alpha)
Implementation of RuntimeWalltimeGuardUpdateEWMA().
Definition runloop.c:194
static PetscBool g_runtime_shutdown_auto_requested
Definition runloop.c:15
static void RuntimeShutdownSignalHandler(int signum)
Record receipt of a termination signal for safe handling by the run loop.
Definition runloop.c:20
static void RuntimeRequestAutoWalltimeGuard(void)
Request a controlled shutdown because the estimated walltime margin is exhausted.
Definition runloop.c:30
static PetscErrorCode RuntimeShutdownSynchronize(PetscBool *requested)
Agree across ranks on whether to stop, and on why.
Definition runloop.c:81
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
PetscErrorCode FinalizeRestartState(SimCtx *simCtx)
Implementation of FinalizeRestartState().
Definition runloop.c:562
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
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)
Implementation of RuntimeWalltimeGuardShouldTrigger().
Definition runloop.c:237
static const char * RuntimeShutdownSignalName(PetscInt signum)
Translate a recorded termination signal into a user-facing signal name.
Definition runloop.c:99
PetscErrorCode PerformInitializedParticleSetup(SimCtx *simCtx)
Implementation of PerformInitializedParticleSetup().
Definition runloop.c:426
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 PetscErrorCode RegisterRuntimeSignalHandler(int signum)
Install the process signal handler used to request graceful simulation shutdown.
Definition runloop.c:138
static PetscBool RuntimeShutdownRequested(void)
Report whether a signal or walltime guard has requested run-loop shutdown.
Definition runloop.c:42
static volatile sig_atomic_t g_runtime_shutdown_signal
Definition runloop.c:14
PetscErrorCode PerformLoadedParticleSetup(SimCtx *simCtx)
Implementation of PerformLoadedParticleSetup().
Definition runloop.c:500
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 UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
PetscErrorCode FlowSolver(SimCtx *simCtx)
Orchestrates a single time step of the Eulerian fluid solver.
Definition solvers.c:9
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
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
PetscMPIInt rank
Definition variables.h:919
PetscInt block_number
Definition variables.h:1009
PetscBool walltimeGuardActive
Definition variables.h:1110
PetscReal walltimeGuardWarmupTotalSeconds
Definition variables.h:1118
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal StartTime
Definition variables.h:932
PetscBool walltimeGuardHasEWMA
Definition variables.h:1120
PetscInt particlesLostLastStep
Particles removed this step because their search failed.
Definition variables.h:1057
UserMG usermg
Definition variables.h:1082
PetscReal walltimeGuardMinSeconds
Definition variables.h:1113
PetscInt _this
Definition variables.h:1175
PetscReal walltimeGuardLatestStepSeconds
Definition variables.h:1122
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
Vec Ucont
Definition variables.h:1197
PetscInt StartStep
Definition variables.h:926
PetscReal particlesExitedScalarLastStep
Sum of Psi over the particles that left the domain this step.
Definition variables.h:1062
Vec Ucat_o
Definition variables.h:1204
char particleRestartMode[16]
Definition variables.h:1056
BoundingBox * bboxlist
Definition variables.h:1053
PetscInt walltimeGuardCompletedSteps
Definition variables.h:1117
PetscInt64 particlesLostCumulative
Definition variables.h:1058
char eulerianSource[PETSC_MAX_PATH_LEN]
Definition variables.h:938
PetscInt walltimeGuardWarmupSteps
Definition variables.h:1111
Vec Ucont_o
Definition variables.h:1204
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
Vec Nvert_o
Definition variables.h:1204
PetscReal walltimeGuardWarmupAverageSeconds
Definition variables.h:1119
Vec Ucont_rm1
Definition variables.h:1207
PetscInt step
Definition variables.h:924
PetscReal walltimeGuardEWMASeconds
Definition variables.h:1121
PetscReal walltimeGuardLimitSeconds
Definition variables.h:1116
PetscReal walltimeGuardEstimatorAlpha
Definition variables.h:1114
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
Vec Nvert
Definition variables.h:1197
MGCtx * mgctx
Definition variables.h:778
PetscReal particlesLostScalarLastStep
Sum of Psi over the particles removed this step as LOST.
Definition variables.h:1059
PetscBool restartHistoryAvailable
Definition variables.h:947
PetscReal ti
Definition variables.h:925
PetscReal walltimeGuardMultiplier
Definition variables.h:1112
PetscInt immersed
Definition variables.h:950
PetscReal walltimeGuardJobStartEpochSeconds
Definition variables.h:1115
PetscInt LoggingFrequency
Definition variables.h:1087
PetscReal lastStepWallSeconds
Slowest rank's wall time of the last completed step (0 before one).
Definition variables.h:1128
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
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
PetscErrorCode ApplyVerificationScalarOverrideToParticles(UserCtx *user)
Populates the particle Psi field from a verification-only source override.
PetscBool VerificationScalarOverrideActive(const SimCtx *simCtx)
Reports whether a verification-only scalar override is active.