56 PetscFunctionBeginUser;
57 if (!user) PetscFunctionReturn(0);
62 PetscFunctionReturn(0);
72 case SIGTERM:
return "SIGTERM";
75 case SIGUSR1:
return "SIGUSR1";
78 case SIGINT:
return "SIGINT";
80 default:
return "UNKNOWN";
93 return "AUTO_WALLTIME_GUARD";
103 struct sigaction action;
105 PetscFunctionBeginUser;
106 memset(&action, 0,
sizeof(action));
109 if (sigemptyset(&action.sa_mask) != 0) {
110 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS,
"sigemptyset failed for signal %d.", signum);
113 if (sigaction(signum, &action, NULL) != 0) {
114 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS,
"sigaction failed for signal %d.", signum);
117 PetscFunctionReturn(0);
130 PetscFunctionBeginUser;
144 PetscFunctionReturn(0);
155 if (!has_previous)
return latest_step_seconds;
156 return alpha * latest_step_seconds + (1.0 - alpha) * previous_ewma_seconds;
167 return PetscMax(warmup_average_seconds, PetscMax(ewma_seconds, latest_step_seconds));
178 return PetscMax(min_seconds, multiplier * conservative_estimate_seconds);
187PetscBool
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)
189 PetscReal conservative_estimate = 0.0;
190 PetscReal required_headroom = 0.0;
192 if (required_headroom_seconds_out) *required_headroom_seconds_out = 0.0;
193 if (completed_steps < warmup_steps)
return PETSC_FALSE;
197 if (required_headroom_seconds_out) *required_headroom_seconds_out = required_headroom;
198 return (PetscBool)(remaining_seconds <= required_headroom);
206 time_t now = time(NULL);
208 if (now == (time_t)-1)
return -1.0;
233 completed_step_seconds,
244 PetscReal remaining_seconds = 0.0;
245 PetscReal required_headroom = 0.0;
247 PetscFunctionBeginUser;
260 &required_headroom)) {
261 PetscFunctionReturn(0);
268 "[T=%.4f, Step=%d] AUTO_WALLTIME_GUARD requested at %s: remaining walltime %.1f s <= required headroom %.1f s "
269 "(warmup avg %.1f s, ewma %.1f s, latest %.1f s).\n",
273 (
double)remaining_seconds,
274 (
double)required_headroom,
280 PetscFunctionReturn(0);
290 PetscFunctionBeginUser;
295 "[T=%.4f, Step=%d] Shutdown requested by %s during %s. Writing final output outside the normal cadence before exiting.\n",
304 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRMPI(ierr);
307 PetscFunctionReturn(0);
319 PetscFunctionBeginUser;
327 if (!preserve_previous_state) {
331 ierr = VecCopy(user->
Ucont, user->
Ucont_o); CHKERRQ(ierr);
337 ierr = VecCopy(user->
Ucat, user->
Ucat_o); CHKERRQ(ierr);
338 ierr = VecCopy(user->
P, user->
P_o); CHKERRQ(ierr);
342 ierr = VecCopy(user->
Nvert, user->
Nvert_o); CHKERRQ(ierr);
355 PetscFunctionReturn(0);
359#define __FUNCT__ "PerformInitialSetup"
371 PetscFunctionBeginUser;
376 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
412 ierr = DMSwarmGetLocalSize(user->
swarm, &nlocal); CHKERRQ(ierr);
424 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
440 PetscFunctionReturn(0);
444#define __FUNCT__ "PerformLoadedParticleSetup"
452 PetscFunctionBeginUser;
457 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
472 LOG(
GLOBAL,
LOG_DEBUG,
"[T=%.4f, Step=%d] Particle field states after locating loaded particles...\n", simCtx->
ti, simCtx->
step);
486 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
502 PetscFunctionReturn(0);
506#define __FUNCT__ "FinalizeRestartState"
514 PetscFunctionBeginUser;
520 if (simCtx->
np > 0) {
526 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Particle Mode 'load': Verifying particle locations and building grid links...\n");
532 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Particle Mode 'init': Running full initial setup for new particles in restarted flow.\n");
543 PetscFunctionReturn(0);
547#define __FUNCT__ "AdvanceSimulation"
555 PetscReal step_start_seconds = 0.0;
556 PetscReal step_elapsed_local = 0.0;
557 PetscReal step_elapsed_max = 0.0;
562 const PetscInt StartStep = simCtx->
StartStep;
563 const PetscInt StepsToRun = simCtx->
StepsToRun;
564 const PetscReal dt = simCtx->
dt;
568 PetscInt removed_local_lost, removed_global_lost;
569 PetscReal removed_scalar_lost = 0.0;
570 PetscBool terminated_early = PETSC_FALSE;
571 PetscInt last_completed_loop_index = StartStep - 1;
573 PetscFunctionBeginUser;
576 StepsToRun, StartStep, simCtx->
StartTime, dt);
579 for (PetscInt step = StartStep; step < StartStep + StepsToRun; step++) {
583 terminated_early = PETSC_TRUE;
587 step_start_seconds = MPI_Wtime();
594 simCtx->
step = step + 1;
595 simCtx->
ti += simCtx->
dt;
601 if (simCtx->
np > 0) {
629 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Eulerian Source 'analytical'. Updating Eulerian field via the Analytical Solution Engine ...\n");
661 if (simCtx->
np > 0) {
670 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
693 &removed_scalar_lost); CHKERRQ(ierr);
698 if (removed_global_lost> 0) {
744 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
754 if (simCtx->
np > 0) {
771 if(simCtx->
rank == 0) {
776 last_completed_loop_index = step;
778 step_elapsed_local = MPI_Wtime() - step_start_seconds;
779 step_elapsed_max = step_elapsed_local;
780 ierr = MPI_Allreduce(&step_elapsed_local, &step_elapsed_max, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
788 terminated_early = PETSC_TRUE;
795 if (simCtx->
rank == 0 && StepsToRun > 0) {
796 if (!terminated_early && last_completed_loop_index >= StartStep) {
798 }
else if (terminated_early && last_completed_loop_index >= StartStep) {
801 PetscPrintf(PETSC_COMM_SELF,
"\n");
805 if (terminated_early) {
807 "Time marching stopped early after %s. Final retained state is step %d at t=%.4f.\n",
810 if (StepsToRun > 0) {
816 PetscFunctionReturn(0);
PetscErrorCode AnalyticalSolutionEngine(SimCtx *simCtx)
Dispatches to the appropriate analytical solution function based on simulation settings.
PetscBool AnalyticalTypeSupportsInterpolationError(const char *analytical_type)
Reports whether an analytical type has a non-trivial velocity field for which interpolation error mea...
Configured initial values of particle-carried fields, and the expression language that defines them.
PetscErrorCode ParticleFieldPlanSummarize(UserCtx *user, const ParticleFieldPlan *plan)
Log and record the realized initial values of every planned field.
PetscErrorCode ParticleFieldPlanApply(UserCtx *user, const 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 CheckAndRemoveLostParticles(UserCtx *user, PetscInt *removedCountLocal, PetscInt *removedCountGlobal, PetscReal *removedScalarSumGlobal)
Removes particles that have been definitively flagged as LOST by the location algorithm.
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 CalculateParticleCountPerCell(UserCtx *user)
Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.
PetscErrorCode LocateAllParticlesInGrid(UserCtx *user, BoundingBox *bboxlist)
Orchestrates the complete particle location and migration process for one timestep.
PetscErrorCode ResetAllParticleStatuses(UserCtx *user)
Marks all local particles as NEEDS_LOCATION for the next settlement pass.
PetscErrorCode ReinitializeParticlesOnInletSurface(UserCtx *user, PetscReal currentTime, PetscInt step)
Re-initializes the positions of particles currently on this rank if this rank owns part of the design...
PetscErrorCode UpdateAllParticleFields(UserCtx *user)
Orchestrates the update of all physical properties for particles.
@ 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 all relevant fields from the DMDA to the DMSwarm.
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.
PetscErrorCode LOG_PARTICLE_METRICS(UserCtx *user, const char *stageName)
Logs particle swarm metrics, adapting its behavior based on a boolean flag in SimCtx.
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.
#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.
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Emits one particle console snapshot into the main solver log.
#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.
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime)
Prints a progress bar to the console.
PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
Append a reduced runtime memory sample to the configured memory log.
LogLevel get_log_level()
Retrieves the current logging level from the environment variable LOG_LEVEL.
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 code block (typically a function).
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 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)
Internal helper implementation: 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.
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)
Internal helper implementation: 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)
Internal helper implementation: PerformInitializedParticleSetup().
PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user, PetscBool preserve_previous_state)
Internal helper implementation: 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)
Internal helper implementation: 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 inletFaceDefined
PetscBool walltimeGuardActive
PetscReal walltimeGuardWarmupTotalSeconds
SimCtx * simCtx
Back-pointer to the master simulation context.
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
@ PARTICLE_INIT_SURFACE_EDGES
Deterministic placement at inlet face edges.
PetscBool walltimeGuardHasEWMA
PetscInt particlesLostLastStep
PetscReal walltimeGuardMinSeconds
PetscReal walltimeGuardLatestStepSeconds
char particleRestartMode[16]
PetscInt walltimeGuardCompletedSteps
char eulerianSource[PETSC_MAX_PATH_LEN]
PetscInt walltimeGuardWarmupSteps
ParticleInitializationType ParticleInitialization
PetscInt wallfunction
Enable wall functions on WALL faces.
PetscInt particlesLostCumulative
char AnalyticalSolutionType[PETSC_MAX_PATH_LEN]
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.
PetscBool restartHistoryAvailable
PetscReal walltimeGuardMultiplier
PetscReal walltimeGuardJobStartEpochSeconds
PetscInt LoggingFrequency
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.