52 PetscFunctionBeginUser;
56 PetscFunctionReturn(0);
67 case SIGTERM:
return "SIGTERM";
70 case SIGUSR1:
return "SIGUSR1";
73 case SIGINT:
return "SIGINT";
75 default:
return "UNKNOWN";
89 return "AUTO_WALLTIME_GUARD";
100 struct sigaction action;
102 PetscFunctionBeginUser;
103 memset(&action, 0,
sizeof(action));
106 if (sigemptyset(&action.sa_mask) != 0) {
107 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS,
"sigemptyset failed for signal %d.", signum);
110 if (sigaction(signum, &action, NULL) != 0) {
111 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SYS,
"sigaction failed for signal %d.", signum);
114 PetscFunctionReturn(0);
127 PetscFunctionBeginUser;
141 PetscFunctionReturn(0);
152 if (!has_previous)
return latest_step_seconds;
153 return alpha * latest_step_seconds + (1.0 - alpha) * previous_ewma_seconds;
164 return PetscMax(warmup_average_seconds, PetscMax(ewma_seconds, latest_step_seconds));
175 return PetscMax(min_seconds, multiplier * conservative_estimate_seconds);
184PetscBool
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)
186 PetscReal conservative_estimate = 0.0;
187 PetscReal required_headroom = 0.0;
189 if (required_headroom_seconds_out) *required_headroom_seconds_out = 0.0;
190 if (completed_steps < warmup_steps)
return PETSC_FALSE;
194 if (required_headroom_seconds_out) *required_headroom_seconds_out = required_headroom;
195 return (PetscBool)(remaining_seconds <= required_headroom);
204 time_t now = time(NULL);
206 if (now == (time_t)-1)
return -1.0;
232 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);
291 PetscFunctionBeginUser;
294 "[T=%.4f, Step=%d] Shutdown requested by %s during %s. Writing final output outside the normal cadence before exiting.\n",
297 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
301 if (simCtx->
np > 0) {
309 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRMPI(ierr);
312 PetscFunctionReturn(0);
324 PetscFunctionBeginUser;
333 ierr = VecCopy(user->
Ucont, user->
Ucont_o); CHKERRQ(ierr);
339 ierr = VecCopy(user->
Ucat, user->
Ucat_o); CHKERRQ(ierr);
340 ierr = VecCopy(user->
P, user->
P_o); CHKERRQ(ierr);
344 ierr = VecCopy(user->
Nvert, user->
Nvert_o); CHKERRQ(ierr);
355 ierr = DMGlobalToLocalBegin(user->
fda, user->
Ucont_o, INSERT_VALUES, user->
lUcont_o); CHKERRQ(ierr);
356 ierr = DMGlobalToLocalEnd(user->
fda, user->
Ucont_o, INSERT_VALUES, user->
lUcont_o); CHKERRQ(ierr);
362 ierr = DMGlobalToLocalBegin(user->
da, user->
Nvert_o, INSERT_VALUES, user->
lNvert_o); CHKERRQ(ierr);
363 ierr = DMGlobalToLocalEnd(user->
da, user->
Nvert_o, INSERT_VALUES, user->
lNvert_o); CHKERRQ(ierr);
371 PetscFunctionReturn(0);
375#define __FUNCT__ "PerformInitialSetup"
387 PetscFunctionBeginUser;
392 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
427 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
436 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
447 PetscFunctionReturn(0);
451#define __FUNCT__ "PerformLoadedParticleSetup"
459 PetscFunctionBeginUser;
464 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
479 LOG(
GLOBAL,
LOG_DEBUG,
"[T=%.4f, Step=%d] Particle field states after locating loaded particles...\n", simCtx->
ti, simCtx->
step);
497 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
506 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
517 PetscFunctionReturn(0);
521#define __FUNCT__ "FinalizeRestartState"
531 PetscFunctionBeginUser;
537 if (simCtx->
np > 0) {
543 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Particle Mode 'load': Verifying particle locations and building grid links...\n");
549 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Particle Mode 'init': Running full initial setup for new particles in restarted flow.\n");
563 PetscFunctionReturn(0);
567#define __FUNCT__ "AdvanceSimulation"
575 PetscReal step_start_seconds = 0.0;
576 PetscReal step_elapsed_local = 0.0;
577 PetscReal step_elapsed_max = 0.0;
582 const PetscInt StartStep = simCtx->
StartStep;
583 const PetscInt StepsToRun = simCtx->
StepsToRun;
584 const PetscReal dt = simCtx->
dt;
588 PetscInt removed_local_lost, removed_global_lost;
589 PetscBool terminated_early = PETSC_FALSE;
590 PetscInt last_completed_loop_index = StartStep - 1;
592 PetscFunctionBeginUser;
595 StepsToRun, StartStep, simCtx->
StartTime, dt);
598 for (PetscInt step = StartStep; step < StartStep + StepsToRun; step++) {
602 terminated_early = PETSC_TRUE;
606 step_start_seconds = MPI_Wtime();
613 simCtx->
step = step + 1;
614 simCtx->
ti += simCtx->
dt;
620 if (simCtx->
np > 0) {
633 ierr =
LOG_FIELD_ANATOMY(&user[0],
"Center-Coordinates",
"PreFlowSolver"); CHKERRQ(ierr);
634 ierr =
LOG_FIELD_ANATOMY(&user[0],
"X-Face-Centers",
"PreFlowSolver"); CHKERRQ(ierr);
635 ierr =
LOG_FIELD_ANATOMY(&user[0],
"Y-Face-Centers",
"PreFlowSolver"); CHKERRQ(ierr);
636 ierr =
LOG_FIELD_ANATOMY(&user[0],
"Z-Face-Centers",
"PreFlowSolver"); CHKERRQ(ierr);
648 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Eulerian Source 'analytical'. Updating Eulerian field via the Analytical Solution Engine ...\n");
669 if (simCtx->
np > 0) {
676 if (simCtx->
les || simCtx->
rans) {
677 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
689 ierr =
LOG_FIELD_ANATOMY(&user[0],
"Diffusivity",
"PostDiffusivityUpdate"); CHKERRQ(ierr);
703 if (removed_global_lost> 0) {
738 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
747 for (PetscInt bi = 0; bi < simCtx->
block_number; bi++) {
750 if (simCtx->
np > 0) {
767 if(simCtx->
rank == 0) {
772 last_completed_loop_index = step;
774 step_elapsed_local = MPI_Wtime() - step_start_seconds;
775 step_elapsed_max = step_elapsed_local;
776 ierr = MPI_Allreduce(&step_elapsed_local, &step_elapsed_max, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
784 terminated_early = PETSC_TRUE;
791 if (simCtx->
rank == 0 && StepsToRun > 0) {
792 if (!terminated_early && last_completed_loop_index >= StartStep) {
794 }
else if (terminated_early && last_completed_loop_index >= StartStep) {
797 PetscPrintf(PETSC_COMM_SELF,
"\n");
801 if (terminated_early) {
803 "Time marching stopped early after %s. Final retained state is step %d at t=%.4f.\n",
809 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...
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 CheckAndRemoveLostParticles(UserCtx *user, PetscInt *removedCountLocal, PetscInt *removedCountGlobal)
Removes particles that have been definitively flagged as LOST by the location algorithm.
PetscErrorCode UpdateAllParticleFields(UserCtx *user)
Orchestrates the update of all physical properties for particles.
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 WriteAllSwarmFields(UserCtx *user)
Writes a predefined set of PETSc Swarm fields to files.
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 WriteSimulationFields(UserCtx *user)
Writes simulation fields to files.
PetscErrorCode LOG_PARTICLE_METRICS(UserCtx *user, const char *stageName)
Logs particle swarm metrics, adapting its behavior based on a boolean flag in SimCtx.
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 LOG_FIELD_MIN_MAX(UserCtx *user, const char *fieldName)
Computes and logs the local and global min/max values of a 3-component vector field.
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime)
Prints a progress bar to the console.
PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, const char *field_name, const char *stage_name)
Logs the anatomy of a specified field at key boundary locations, respecting the solver's specific gri...
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_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)
Internal helper implementation: RuntimeWalltimeGuardRemainingSeconds().
static PetscErrorCode MaybeRequestRuntimeWalltimeGuardShutdown(SimCtx *simCtx, const char *checkpoint_name)
Internal helper implementation: MaybeRequestRuntimeWalltimeGuardShutdown().
PetscErrorCode AdvanceSimulation(SimCtx *simCtx)
Internal helper implementation: AdvanceSimulation().
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)
Internal helper implementation: RuntimeShutdownSignalHandler().
static void RuntimeRequestAutoWalltimeGuard(void)
Internal helper implementation: RuntimeRequestAutoWalltimeGuard().
PetscReal RuntimeWalltimeGuardConservativeEstimate(PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds)
Implementation of RuntimeWalltimeGuardConservativeEstimate().
PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user)
Internal helper implementation: UpdateSolverHistoryVectors().
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)
Internal helper implementation: WriteForcedTerminationOutput().
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 PetscErrorCode RefreshVerificationScalarScatterState(UserCtx *user)
Applies verification-only scalar truth and refreshes the scattered Eulerian scalar state.
static const char * RuntimeShutdownSignalName(PetscInt signum)
Internal helper implementation: RuntimeShutdownSignalName().
PetscErrorCode PerformInitializedParticleSetup(SimCtx *simCtx)
Internal helper implementation: PerformInitializedParticleSetup().
static const char * RuntimeShutdownReasonName(void)
Internal helper implementation: RuntimeShutdownReasonName().
static PetscErrorCode RegisterRuntimeSignalHandler(int signum)
Internal helper implementation: RegisterRuntimeSignalHandler().
static PetscBool RuntimeShutdownRequested(void)
Internal helper implementation: RuntimeShutdownRequested().
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)
Internal helper implementation: UpdateRuntimeWalltimeGuardEstimator().
PetscErrorCode FlowSolver(SimCtx *simCtx)
Orchestrates a single time step of the Eulerian fluid solver.
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 particlesLostCumulative
char AnalyticalSolutionType[PETSC_MAX_PATH_LEN]
PetscReal walltimeGuardWarmupAverageSeconds
PetscReal walltimeGuardEWMASeconds
PetscReal walltimeGuardLimitSeconds
PetscReal walltimeGuardEstimatorAlpha
PetscReal walltimeGuardMultiplier
PetscReal walltimeGuardJobStartEpochSeconds
PetscInt LoggingFrequency
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.