61 PetscFunctionBeginUser;
69 PetscFunctionReturn(0);
84 int global[2] = {0, 0};
86 PetscFunctionBeginUser;
88 PetscCallMPI(MPI_Allreduce(local, global, 2, MPI_INT, MPI_MAX, PETSC_COMM_WORLD));
91 *requested = (PetscBool)(global[0] != 0 || global[1] != 0);
93 PetscFunctionReturn(0);
129 return "AUTO_WALLTIME_GUARD";
140 struct sigaction action;
142 PetscFunctionBeginUser;
144 memset(&action, 0,
sizeof(action));
147 if (sigemptyset(&action.sa_mask) != 0) {
148 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS,
"sigemptyset failed for signal %d.", signum);
151 if (sigaction(signum, &action, NULL) != 0) {
152 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS,
"sigaction failed for signal %d.", signum);
156 PetscFunctionReturn(0);
169 PetscFunctionBeginUser;
185 PetscFunctionReturn(0);
198 const PetscReal ewma = alpha * latest_step_seconds + (1.0 - alpha) * previous_ewma_seconds;
212 const PetscReal estimate = PetscMax(warmup_average_seconds, PetscMax(ewma_seconds, latest_step_seconds));
226 const PetscReal headroom = PetscMax(min_seconds, multiplier * conservative_estimate_seconds);
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)
240 PetscReal conservative_estimate = 0.0;
241 PetscReal required_headroom = 0.0;
243 if (required_headroom_seconds_out) *required_headroom_seconds_out = 0.0;
248 if (required_headroom_seconds_out) *required_headroom_seconds_out = required_headroom;
250 return (PetscBool)(remaining_seconds <= required_headroom);
259 time_t now = time(NULL);
289 completed_step_seconds,
301 PetscReal remaining_seconds = 0.0;
302 PetscReal required_headroom = 0.0;
304 PetscFunctionBeginUser;
318 &required_headroom)) {
320 PetscFunctionReturn(0);
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",
332 (
double)remaining_seconds,
333 (
double)required_headroom,
340 PetscFunctionReturn(0);
350 PetscFunctionBeginUser;
356 "[T=%.4f, Step=%" PetscInt_FMT
"] Shutdown requested by %s during %s. Writing final output outside the normal cadence before exiting.\n",
365 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRMPI(ierr);
369 PetscFunctionReturn(0);
381 PetscFunctionBeginUser;
390 if (!preserve_previous_state) {
394 ierr = VecCopy(user->
Ucont, user->
Ucont_o); CHKERRQ(ierr);
400 ierr = VecCopy(user->
Ucat, user->
Ucat_o); CHKERRQ(ierr);
401 ierr = VecCopy(user->
P, user->
P_o); CHKERRQ(ierr);
405 ierr = VecCopy(user->
Nvert, user->
Nvert_o); CHKERRQ(ierr);
419 PetscFunctionReturn(0);
433 PetscFunctionBeginUser;
439 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
447 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"[T=%.4f, Step=%" PetscInt_FMT
"] Initial Settlement: Locating and migrating all particles...\n", simCtx->
ti, simCtx->
step);
464 ierr = DMSwarmGetLocalSize(user->
swarm, &nlocal); CHKERRQ(ierr);
470 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"[T=%.4f, Step=%" PetscInt_FMT
"] Interpolating initial fields to settled particles.\n", simCtx->
ti, simCtx->
step);
476 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
493 PetscFunctionReturn(0);
503 PetscFunctionBeginUser;
509 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
524 LOG(
GLOBAL,
LOG_DEBUG,
"[T=%.4f, Step=%" PetscInt_FMT
"] Particle field states after locating loaded particles...\n", simCtx->
ti, simCtx->
step);
528 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"[T=%.4f, Step=%" PetscInt_FMT
"] Interpolating initial fields to settled particles.\n", simCtx->
ti, simCtx->
step);
538 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
555 PetscFunctionReturn(0);
565 PetscFunctionBeginUser;
578 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Particle Mode 'load': Verifying particle locations and building grid links...\n");
584 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Particle Mode 'init': Running full initial setup for new particles in restarted flow.\n");
596 PetscFunctionReturn(0);
606 PetscReal step_start_seconds = 0.0;
607 PetscReal step_elapsed_local = 0.0;
608 PetscReal step_elapsed_max = 0.0;
613 const PetscInt StartStep = simCtx->
StartStep;
614 const PetscInt StepsToRun = simCtx->
StepsToRun;
615 const PetscReal dt = simCtx->
dt;
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;
623 PetscReal steps_elapsed_sum = 0.0;
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);
631 for (PetscInt step = StartStep; step < StartStep + StepsToRun; step++) {
634 if (shutdown_requested) {
636 terminated_early = PETSC_TRUE;
640 step_start_seconds = MPI_Wtime();
647 simCtx->
step = step + 1;
648 simCtx->
ti += simCtx->
dt;
664 if (step == StartStep) {
685 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Eulerian Source 'analytical'. Updating Eulerian field via the Analytical Solution Engine ...\n");
728 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
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);
811 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
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);
840 steps_elapsed_sum += step_elapsed_max;
845 if(simCtx->
rank == 0) {
846 PrintProgressBar(step,StartStep,StepsToRun,simCtx->
ti, steps_elapsed_sum / (PetscReal)steps_timed,
856 if (shutdown_requested) {
858 terminated_early = PETSC_TRUE;
866 PetscPrintf(PETSC_COMM_SELF,
"\n");
870 if (terminated_early) {
872 "Time marching stopped early after %s. Final retained state is step %" PetscInt_FMT
" at t=%.4f.\n",
875 if (StepsToRun > 0) {
881 PetscFunctionReturn(0);
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_DIFFUSIVITY_GRADIENT
@ FIELD_ID_PARTICLE_COUNT
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.
PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step)
Returns whether full field/restart output should be written for the.
PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
Write and atomically publish one complete checkpoint bundle.
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
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.
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.
#define LOCAL
Logging scope definitions for controlling message output.
PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user)
Logs the interpolation error between the analytical and computed solutions.
#define GLOBAL
Scope for global logging across all processes.
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Returns whether a particle console snapshot should be emitted for the completed timestep.
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Returns whether periodic particle console snapshots are enabled.
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Emits one particle console snapshot into the main solver log.
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime, PetscReal seconds_per_step, PetscInt64 lost_cumulative)
Prints a progress bar to the console.
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
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.
PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
Logs the performance summary for the current timestep and resets timers.
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Prints particle fields in a table that automatically adjusts its column widths.
PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user)
Computes advanced particle statistics and stores them in SimCtx.
PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
Logs physical solution-convergence metrics once per completed timestep.
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...
PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
Writes compact runtime search metrics to CSV and optionally to console.
@ LOG_INFO
Informational messages about program execution.
@ LOG_WARNING
Non-critical issues that warrant attention.
@ LOG_DEBUG
Detailed debugging information.
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
PetscErrorCode InitializeRuntimeSignalHandlers(void)
Implementation of InitializeRuntimeSignalHandlers().
static PetscReal RuntimeWalltimeGuardRemainingSeconds(const SimCtx *simCtx)
Estimate the remaining scheduler walltime after reserving the configured shutdown margin.
static PetscErrorCode MaybeRequestRuntimeWalltimeGuardShutdown(SimCtx *simCtx, const char *checkpoint_name)
Request graceful shutdown when another timestep would exceed the walltime budget.
PetscErrorCode AdvanceSimulation(SimCtx *simCtx)
Implementation of AdvanceSimulation().
static PetscErrorCode RefreshScatteredParticleState(UserCtx *user)
Makes the Eulerian particle averages consistent with the particles before step 1.
PetscReal RuntimeWalltimeGuardUpdateEWMA(PetscBool has_previous, PetscReal previous_ewma_seconds, PetscReal latest_step_seconds, PetscReal alpha)
Implementation of RuntimeWalltimeGuardUpdateEWMA().
static PetscBool g_runtime_shutdown_auto_requested
static void RuntimeShutdownSignalHandler(int signum)
Record receipt of a termination signal for safe handling by the run loop.
static void RuntimeRequestAutoWalltimeGuard(void)
Request a controlled shutdown because the estimated walltime margin is exhausted.
static PetscErrorCode RuntimeShutdownSynchronize(PetscBool *requested)
Agree across ranks on whether to stop, and on why.
PetscReal RuntimeWalltimeGuardConservativeEstimate(PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds)
Implementation of RuntimeWalltimeGuardConservativeEstimate().
PetscReal RuntimeWalltimeGuardRequiredHeadroom(PetscReal min_seconds, PetscReal multiplier, PetscReal conservative_estimate_seconds)
Implementation of RuntimeWalltimeGuardRequiredHeadroom().
PetscErrorCode FinalizeRestartState(SimCtx *simCtx)
Implementation of FinalizeRestartState().
static PetscErrorCode WriteForcedTerminationOutput(SimCtx *simCtx, UserCtx *user, const char *phase)
Write restart-safe output when a controlled shutdown interrupts the run loop.
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().
static const char * RuntimeShutdownSignalName(PetscInt signum)
Translate a recorded termination signal into a user-facing signal name.
PetscErrorCode PerformInitializedParticleSetup(SimCtx *simCtx)
Implementation of PerformInitializedParticleSetup().
PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user, PetscBool preserve_previous_state)
Implementation of UpdateSolverHistoryVectors().
static const char * RuntimeShutdownReasonName(void)
Translate the current shutdown reason into a user-facing diagnostic label.
static PetscErrorCode RegisterRuntimeSignalHandler(int signum)
Install the process signal handler used to request graceful simulation shutdown.
static PetscBool RuntimeShutdownRequested(void)
Report whether a signal or walltime guard has requested run-loop shutdown.
static volatile sig_atomic_t g_runtime_shutdown_signal
PetscErrorCode PerformLoadedParticleSetup(SimCtx *simCtx)
Implementation of PerformLoadedParticleSetup().
static void UpdateRuntimeWalltimeGuardEstimator(SimCtx *simCtx, PetscReal completed_step_seconds)
Update the timestep-duration estimate used by the automatic walltime guard.
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
PetscErrorCode FlowSolver(SimCtx *simCtx)
Orchestrates a single time step of the Eulerian fluid solver.
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.
PetscBool walltimeGuardActive
PetscReal walltimeGuardWarmupTotalSeconds
SimCtx * simCtx
Back-pointer to the master simulation context.
PetscBool walltimeGuardHasEWMA
PetscInt particlesLostLastStep
Particles removed this step because their search failed.
PetscReal walltimeGuardMinSeconds
PetscReal walltimeGuardLatestStepSeconds
static PetscBool ParticlesEnabled(const SimCtx *simCtx)
Whether the run carries particles: a seeded or restored population, or inlets that inject them.
PetscReal particlesExitedScalarLastStep
Sum of Psi over the particles that left the domain this step.
char particleRestartMode[16]
PetscInt walltimeGuardCompletedSteps
PetscInt64 particlesLostCumulative
char eulerianSource[PETSC_MAX_PATH_LEN]
PetscInt walltimeGuardWarmupSteps
PetscInt wallfunction
Enable wall functions on WALL faces.
PetscInt64 particlesExitedCumulative
PetscInt particlesExitedLastStep
Particles removed this step because they left the domain.
PetscReal walltimeGuardWarmupAverageSeconds
PetscReal walltimeGuardEWMASeconds
PetscReal walltimeGuardLimitSeconds
PetscReal walltimeGuardEstimatorAlpha
PetscInt les
Active LES closure; an LESModelType value.
PetscReal particlesLostScalarLastStep
Sum of Psi over the particles removed this step as LOST.
PetscBool restartHistoryAvailable
PetscReal walltimeGuardMultiplier
PetscReal walltimeGuardJobStartEpochSeconds
PetscInt LoggingFrequency
PetscReal lastStepWallSeconds
Slowest rank's wall time of the last completed step (0 before one).
struct ParticleFieldPlan * particleFieldPlan
Configured initial particle-field values, or NULL.
Defines a 3D axis-aligned bounding box.
The master context for the entire simulation.
User-defined context containing data specific to a single computational grid level.
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.