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

Go to the source code of this file.

Macros

#define Allocate3DArray(array, nz, ny, nx)
 
#define Deallocate3DArray(array, nz, ny)
 

Functions

int PicurvHandleVersionArgument (int argc, char **argv, const char *executable_name)
 Print the shared native build identity when a version flag is present.
 
int PicurvCheckLinkedPetscIndexWidth (int argc, char **argv, const char *executable_name)
 Refuse to start when the loaded libpetsc's PetscInt width differs from this build's.
 
PetscErrorCode PicurvCheckPetscIntRange (MPI_Comm comm, PetscInt64 entries, const char *object)
 Refuse a PETSc object whose global size this build's PetscInt cannot index.
 
PetscErrorCode CreateSimulationContext (int argc, char **argv, SimCtx **p_simCtx)
 Allocates and populates the master SimulationContext object.
 
PetscBool RuntimeWalltimeGuardParsePositiveSeconds (const char *text, PetscReal *seconds_out)
 Parse a positive floating-point seconds value from runtime metadata.
 
PetscErrorCode SetupSimulationEnvironment (SimCtx *simCtx)
 Verifies and prepares the complete I/O environment for a simulation run.
 
PetscErrorCode SetupGridAndSolvers (SimCtx *simCtx)
 The main orchestrator for setting up all grid-related components.
 
PetscErrorCode CreateAndInitializeAllVectors (SimCtx *simCtx)
 Creates and initializes all PETSc Vec objects for all fields.
 
PetscErrorCode UpdateLocalGhosts (UserCtx *user, FieldId field_id)
 Updates the local vector (including ghost points) from its corresponding global vector.
 
PetscErrorCode RepairPeriodicFieldGhosts (UserCtx *user, const FieldView *view, Vec local_vec)
 Applies a catalogued field's periodic normal-face ghost repair to a local vector.
 
PetscErrorCode SetupBoundaryConditions (SimCtx *simCtx)
 (Orchestrator) Sets up all boundary conditions for the simulation.
 
PetscErrorCode InitializeSolutionConvergenceState (SimCtx *simCtx)
 Allocates any runtime storage required by solution-convergence logging.
 
PetscErrorCode DestroySolutionConvergenceState (SimCtx *simCtx)
 Frees any runtime storage allocated for solution-convergence logging.
 
PetscErrorCode Allocate3DArrayScalar (PetscReal ****array, PetscInt nz, PetscInt ny, PetscInt nx)
 Allocates a 3D array of PetscReal values using PetscCalloc.
 
PetscErrorCode Deallocate3DArrayScalar (PetscReal ***array, PetscInt nz, PetscInt ny)
 Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.
 
PetscErrorCode Allocate3DArrayVector (Cmpnts ****array, PetscInt nz, PetscInt ny, PetscInt nx)
 Allocates a contiguous 3D array of Cmpnts values.
 
PetscErrorCode Deallocate3DArrayVector (Cmpnts ***array, PetscInt nz, PetscInt ny)
 Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.
 
PetscErrorCode GetOwnedCellRange (const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
 Determines the global starting index and number of CELLS owned by the current processor in a specified dimension.
 
static void GetPeriodicAxes (const SimCtx *simCtx, PetscBool periodic[3])
 Which grid axes are periodic.
 
static void GetOwnedInteriorCellBounds (const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
 Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned range with the dummy layer at index 0 and at index m-1 removed.
 
PetscErrorCode ComputeAndStoreNeighborRanks (UserCtx *user)
 Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.
 
PetscErrorCode SetDMDAProcLayout (DM dm, UserCtx *user)
 Sets the processor layout for a given DMDA based on PETSc options.
 
PetscErrorCode SetupDomainRankInfo (SimCtx *simCtx)
 Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchange.
 
PetscErrorCode Contra2Cart (UserCtx *user)
 Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on cell faces.
 
static PetscErrorCode ContravariantToCartesianInCell (Cmpnts ***lucont, Cmpnts ***lcsi, Cmpnts ***leta, Cmpnts ***lzet, PetscInt i, PetscInt j, PetscInt k, Cmpnts w, Cmpnts *ucat)
 Cartesian velocity at a point of one cell from the cell's face fluxes.
 
PetscErrorCode Cart2Contra (UserCtx *user)
 Convert the ghosted Cartesian velocity field to contravariant face fluxes.
 
PetscErrorCode SetupDomainCellDecompositionMap (UserCtx *user)
 Creates and distributes a map of the domain's cell decomposition to all ranks.
 
PetscErrorCode BinarySearchInt64 (PetscInt n, const PetscInt64 arr[], PetscInt64 key, PetscBool *found)
 Performs a binary search for a key in a sorted array of PetscInt64.
 
PetscErrorCode ComputeDivergence (UserCtx *user)
 Computes the discrete divergence of the contravariant velocity field.
 
void TransformScalarDerivativesToPhysical (PetscReal jacobian, Cmpnts csi_metrics, Cmpnts eta_metrics, Cmpnts zet_metrics, PetscReal dPhi_dcsi, PetscReal dPhi_deta, PetscReal dPhi_dzet, Cmpnts *gradPhi)
 Transforms scalar derivatives from computational space to physical space.
 
PetscErrorCode ComputeScalarFieldDerivatives (UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscReal ***field_data, Cmpnts *grad)
 Computes the gradient of a cell-centered SCALAR field at a specific grid point.
 
PetscErrorCode ComputeVectorFieldDerivatives (UserCtx *user, PetscInt i, PetscInt j, PetscInt k, Cmpnts ***field_data, Cmpnts *dudx, Cmpnts *dvdx, Cmpnts *dwdx)
 Computes the derivatives of a cell-centered vector field at a specific grid point.
 
PetscErrorCode LESConfigSetDefaults (LESConfig *config)
 Installs the shipped defaults for every LES closure parameter.
 
PetscErrorCode DestroyUserVectors (UserCtx *user)
 Destroys all PETSc Vec objects within a single UserCtx structure.
 
PetscErrorCode DestroyUserContext (UserCtx *user)
 Destroys all resources allocated within a single UserCtx structure.
 
PetscErrorCode FinalizeSimulation (SimCtx *simCtx)
 Main cleanup function for the entire simulation context.
 

Macro Definition Documentation

◆ Allocate3DArray

#define Allocate3DArray (   array,
  nz,
  ny,
  nx 
)
Value:
_Generic((array), \
PetscReal ****: Allocate3DArrayScalar, \
)(array, nz, ny, nx)
PetscErrorCode Allocate3DArrayScalar(PetscReal ****array, PetscInt nz, PetscInt ny, PetscInt nx)
Allocates a 3D array of PetscReal values using PetscCalloc.
Definition setup.c:2819
PetscErrorCode Allocate3DArrayVector(Cmpnts ****array, PetscInt nz, PetscInt ny, PetscInt nx)
Allocates a contiguous 3D array of Cmpnts values.
Definition setup.c:2902
A 3D point or vector with PetscScalar components.
Definition variables.h:144

Definition at line 71 of file setup.h.

75 )(array, nz, ny, nx)

◆ Deallocate3DArray

#define Deallocate3DArray (   array,
  nz,
  ny 
)
Value:
_Generic((array), \
PetscReal ***: Deallocate3DArrayScalar, \
)(array, nz, ny)
PetscErrorCode Deallocate3DArrayVector(Cmpnts ***array, PetscInt nz, PetscInt ny)
Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.
Definition setup.c:2954
PetscErrorCode Deallocate3DArrayScalar(PetscReal ***array, PetscInt nz, PetscInt ny)
Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.
Definition setup.c:2856

Definition at line 78 of file setup.h.

82 )(array, nz, ny)

Function Documentation

◆ PicurvHandleVersionArgument()

int PicurvHandleVersionArgument ( int  argc,
char **  argv,
const char *  executable_name 
)

Print the shared native build identity when a version flag is present.

Prints two lines: <name> <release>+g<commit>[.dirty], then the PETSc this binary was compiled against, petsc <version> <debug|optimized> <int32|int64> <arch> <dir>, the third field being the width of PetscInt. The second line is also kept in the binary behind a PICURV_PETSC_BUILD: marker, so the conductor can read it from a binary that cannot start.

Parameters
[in]argcNative executable argument count.
[in]argvNative executable argument vector.
[in]executable_nameName printed when argv[0] is absent; otherwise the basename of argv[0] is printed, so simulator64 names itself as the conductor staged it.
Returns
Nonzero when a version flag was handled and execution should stop.

Print the shared native build identity when a version flag is present.

The public argument and return contract is documented in include/setup.h.

See also
PicurvHandleVersionArgument()

Definition at line 119 of file setup.c.

120{
122 /* The file's own name: the conductor stages against the basename it launches. */
123 const char *name = PicurvExecutableName(argc, argv, executable_name);
124 for (int index = 1; index < argc; ++index) {
125 if (!strcmp(argv[index], "--version") || !strcmp(argv[index], "-version")) {
126 printf("%s %s+g%.12s%s\n", name, PICURV_BUILD_VERSION,
128 !strcmp(PICURV_BUILD_DIRTY, "true") ? ".dirty" : "");
129 printf("%s\n", picurv_petsc_build_stamp + sizeof(PICURV_PETSC_STAMP_MARKER) - 1);
131 return 1;
132 }
133 }
135 return 0;
136}
#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
#define PICURV_PETSC_STAMP_MARKER
Definition setup.c:38
static const char picurv_petsc_build_stamp[]
Definition setup.c:43
static const char * PicurvExecutableName(int argc, char **argv, const char *fallback)
The name an executable reports itself by: the basename of argv[0].
Definition setup.c:66
#define PICURV_BUILD_DIRTY
Definition variables.h:41
#define PICURV_GIT_COMMIT
Definition variables.h:38
#define PICURV_BUILD_VERSION
Definition variables.h:35
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvCheckLinkedPetscIndexWidth()

int PicurvCheckLinkedPetscIndexWidth ( int  argc,
char **  argv,
const char *  executable_name 
)

Refuse to start when the loaded libpetsc's PetscInt width differs from this build's.

The 32- and 64-bit-index PETSc builds share the library name libpetsc.so.MAJOR.MINOR, so another build's library first on LD_LIBRARY_PATH (a PETSc module, say) is loaded without complaint and corrupts every size it is handed. The library reports its own width through PetscDataTypeGetSize(PETSC_INT), whose signature does not depend on it, so this is safe to call before PetscInitialize().

Parameters
[in]argcNative executable argument count.
[in]argvNative executable argument vector; the message names argv[0]'s basename.
[in]executable_nameName used in the message when argv[0] is absent.
Returns
0 when the widths agree; nonzero, after a message on stderr, when they do not.

Refuse to start when the loaded libpetsc's PetscInt width differs from this build's.

See also
PicurvCheckLinkedPetscIndexWidth()

Definition at line 79 of file setup.c.

80{
81 size_t linked = 0;
82
84 if (PetscDataTypeGetSize(PETSC_INT, &linked) || linked != sizeof(PetscInt)) {
85 fprintf(stderr,
86 "[FATAL] %s was built against a PETSc with %d-byte indices, but the libpetsc it loaded has "
87 "%d-byte indices: another PETSc build's library is first on LD_LIBRARY_PATH, as when the "
88 "other build's PETSc module is loaded. Launch it through picurv, which puts its own "
89 "PETSc first, or unload that module.\n",
90 PicurvExecutableName(argc, argv, executable_name), (int)sizeof(PetscInt), (int)linked);
92 return 1;
93 }
95 return 0;
96}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvCheckPetscIntRange()

PetscErrorCode PicurvCheckPetscIntRange ( MPI_Comm  comm,
PetscInt64  entries,
const char *  object 
)

Refuse a PETSc object whose global size this build's PetscInt cannot index.

A vector's or matrix's global size, and every index into it, is a PetscInt. Past PETSC_MAX_INT a 32-bit-index build overflows silently, corrupting sizes, ownership ranges and checkpoint headers, so every object PICurv sizes passes through here before it is created: particle fields at setup, each grid DM where grid.c creates it, and so every solver's vectors and matrices built on those DMs.

Parameters
[in]commCommunicator on which the refusal is raised (collective when it is).
[in]entriesGlobal entries the object needs, computed in 64 bits.
[in]objectWhat the object is, for the message (e.g. "a 3-component grid DM").
Returns
0, or PETSC_ERR_ARG_OUTOFRANGE naming the remedy (a 64-bit-index PETSc build).

Refuse a PETSc object whose global size this build's PetscInt cannot index.

See also
PicurvCheckPetscIntRange()

Definition at line 102 of file setup.c.

103{
104 PetscFunctionBeginUser;
106 PetscCheck(entries <= (PetscInt64)PETSC_MAX_INT, comm, PETSC_ERR_ARG_OUTOFRANGE,
107 "%s needs %" PetscInt64_FMT " entries, beyond the %" PetscInt64_FMT " this PETSc's %d-byte PetscInt "
108 "can index; use a PICurv built on a PETSc configured with --with-64-bit-indices.",
109 object, entries, (PetscInt64)PETSC_MAX_INT, (int)sizeof(PetscInt));
111 PetscFunctionReturn(0);
112}
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
Here is the caller graph for this function:

◆ CreateSimulationContext()

PetscErrorCode CreateSimulationContext ( int  argc,
char **  argv,
SimCtx **  p_simCtx 
)

Allocates and populates the master SimulationContext object.

This function serves as the single, authoritative entry point for all simulation configuration. It merges the setup logic from both the legacy FSI/IBM solver and the modern particle solver into a unified, robust process.

The function follows a strict sequence:

  1. Allocate Context & Set Defaults: It first allocates the SimulationContext and populates every field with a sane, hardcoded default value. This ensures the simulation starts from a known, predictable state.
  2. Configure Logging System: It configures the custom logging framework. It parses the -func_config_file option to load a list of function names allowed to produce log output. This configuration (the file path and the list of function names) is stored within the SimulationContext for later reference and cleanup.
  3. Parse All Options: It performs a comprehensive pass of PetscOptionsGet... calls for every possible command-line flag, overriding the default values set in step 1.
  4. Log Summary: After all options are parsed, it uses the now-active logging system to print a summary of the key simulation parameters.
Parameters
[in]argcArgument count passed from main.
[in]argvArgument vector passed from main.
[out]p_simCtxOn success, this will point to the newly created and fully configured SimulationContext pointer. The caller is responsible for eventually destroying this object by calling FinalizeSimulation().
Returns
PetscErrorCode Returns 0 on success, or a non-zero PETSc error code on failure.

Allocates and populates the master SimulationContext object.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
CreateSimulationContext()

Definition at line 453 of file setup.c.

454{
455 PetscErrorCode ierr;
456 (void)argc;
457 (void)argv;
458 SimCtx *simCtx;
459 char control_filename[PETSC_MAX_PATH_LEN] = ""; // Temporary placeholder for control file name.
460 PetscBool control_flg; // Temporary placeholder for control file tag existence check flag.
461 PetscBool particle_console_output_freq_flg = PETSC_FALSE;
462
463 PetscFunctionBeginUser;
464
466
467 // === 1. Allocate the Context Struct and Set ALL Defaults ==================
468 ierr = PetscNew(p_simCtx); CHKERRQ(ierr);
469 simCtx = *p_simCtx;
470
471 // --- Group 1: Parallelism & MPI ---
472 simCtx->rank = 0; simCtx->size = 1;
473
474 // --- Group 2: Simulation Control, Time, and I/O ---
475 simCtx->step = 0; simCtx->ti = 0.0; simCtx->StartStep = 0; simCtx->StepsToRun = 10;
476 simCtx->tiout = 10; simCtx->particleConsoleOutputFreq = simCtx->tiout;
477 simCtx->StartTime = 0.0; simCtx->dt = 0.001;
478 simCtx->OnlySetup = PETSC_FALSE;
479 simCtx->continueMode = PETSC_FALSE;
480 simCtx->logviewer = NULL;
481 strcpy(simCtx->eulerianSource,"solve");
482 strcpy(simCtx->restart_dir,"restart");
483 strcpy(simCtx->output_dir,"output");
484 strcpy(simCtx->log_dir,"logs");
485 strcpy(simCtx->analysis_dir,"output/analysis/metrics");
486 simCtx->_io_context_buffer[0] = '\0';
487 simCtx->current_io_directory = NULL;
488 simCtx->checkpointGeometrySHA256[0] = '\0';
489 simCtx->checkpointGeometryHashReady = PETSC_FALSE;
490 simCtx->restartHistoryAvailable = PETSC_FALSE;
491
492 // --- Group 3: High-Level Physics & Model Selection Flags ---
493 simCtx->immersed = 0; simCtx->movefsi = 0; simCtx->rotatefsi = 0;
494 simCtx->invicid = 0;
495 simCtx->TwoD = 0; simCtx->moveframe = 0; simCtx->rotateframe = 0;
496
497 // --- Group 4: Immersed-body flux corrections (refused; see Group 3 parsing) ---
498 simCtx->MHV=0; simCtx->LV=0;
499
500 // --- Group 5: Solver & Numerics Parameters ---
502 simCtx->mom_dt_jameson_residual_norm_noise_allowance_factor = 1.1; // raised from 1.05; less aggressive rejection
503 simCtx->mom_atol = 1e-7; simCtx->mom_rtol = 1e-4;
504 /* Residual-based convergence is the default. Leaving both at 0.0 selected the
505 * update-only branch, where |dU| <= mom_atol can pass purely because dtau collapsed
506 * (|dU| ~ dtau*|R|), converging on a state that does not satisfy the equations.
507 * Shipped configs all set these explicitly; these defaults protect a minimal
508 * user-written config. Set both non-positive to opt back out deliberately. */
509 simCtx->mom_resid_atol = 1e-8; simCtx->mom_resid_rtol = 1e-3;
510 simCtx->imp_stol = 1.e-8;
511 simCtx->mglevels = 3;
512 simCtx->mg_preItr = 1; simCtx->mg_poItr = 1;
513 simCtx->poisson = 0;
514 simCtx->central=0;
515 /* pseudo_cfl and its bounds are now dimensionless Courant numbers: CFL = dtau * lambda_max,
516 where lambda_max is the global spectral radius computed at each physical timestep.
517 Stable range for 4-stage Jameson RK: ~0–2.83. Initial 0.5 gives a comfortable margin. */
518 simCtx->ren = 100.0; simCtx->pseudo_cfl = 0.5;
519 simCtx->max_pseudo_cfl = 2.0; simCtx->min_pseudo_cfl = 0.001;
520 simCtx->pseudo_cfl_reduction_factor = 0.75;
521 simCtx->pseudo_cfl_growth_factor = 1.1; // raised from 1.0; controller can now increase CFL
522 simCtx->no_pseudo_cfl_backtrack = PETSC_FALSE;
523 simCtx->mom_ratio_ema_alpha = 0.3; /* moderate smoothing; set to 1.0 to recover original raw-ratio behavior */
524 simCtx->mom_last_converged = PETSC_TRUE;
525 simCtx->mom_max_unconverged_steps = 0; /* off: unconverged steps never stop a run unless asked */
526 simCtx->mom_unconverged_streak = 0;
527 simCtx->mom_last_lambda_max = 0.0; /* populated after first momentum solve */
528 simCtx->mom_nk_monitor_history = PETSC_FALSE;
529 simCtx->ps_ksp_pic_monitor_true_residual = PETSC_FALSE;
530 simCtx->cdisx = 0.0; simCtx->cdisy = 0.0; simCtx->cdisz = 0.0;
531 simCtx->initialConditionStaged = PETSC_FALSE;
533 strcpy(simCtx->initialConditionDirectory, "config/initial_condition");
534 simCtx->fieldStatisticsEnabled = PETSC_FALSE;
535 simCtx->fieldStatisticsWindowCount = 0;
536 simCtx->fieldStatisticsWindows = NULL;
537 simCtx->statisticsConsoleOutputFreq = 0;
538 simCtx->fieldStatisticsContinue = PETSC_FALSE;
539 simCtx->solutionConvergenceEnabled = PETSC_TRUE;
546 simCtx->verificationDiffusivity.expression = NULL;
547 simCtx->verificationScalar.expression = NULL;
548
549 // --- Group 6: Physical & Geometric Parameters ---
550 simCtx->Flux_in = 1.0; simCtx->angle = 0.0;
551 simCtx->max_angle = -54. * 3.1415926 / 180.;
552 simCtx->CMx_c=0.0; simCtx->CMy_c=0.0; simCtx->CMz_c=0.0;
553 simCtx->wall_roughness_height = 1e-16;
554 simCtx->schmidt_number = 1.0; simCtx->Turbulent_schmidt_number = 0.7;
555 simCtx->iem_constant = 2.0;
556
557 // --- Group 7: Grid, Domain, and Boundary Condition Settings ---
558 simCtx->block_number = 1; simCtx->inletprofile = 1;
559 simCtx->i_periodic = 0; simCtx->j_periodic = 0; simCtx->k_periodic = 0;
560 simCtx->pseudo_periodic = 0;
561 strcpy(simCtx->grid_file, "config/grid.run");
562 simCtx->generate_grid = PETSC_FALSE;
563 simCtx->da_procs_x = PETSC_DECIDE;
564 simCtx->da_procs_y = PETSC_DECIDE;
565 simCtx->da_procs_z = PETSC_DECIDE;
566 simCtx->num_bcs_files = 1;
567 ierr = PetscMalloc1(1, &simCtx->bcs_files); CHKERRQ(ierr);
568 ierr = PetscStrallocpy("config/bcs.run", &simCtx->bcs_files[0]); CHKERRQ(ierr);
569 simCtx->FluxInSum = 0.0; simCtx->FluxOutSum = 0.0; simCtx->Fluxsum = 0.0;
570 simCtx->drivingForceMagnitude = 0.0, simCtx->forceScalingFactor = 1.8;
571 simCtx->drivingForceStep = -1;
572 simCtx->drivenFluxMeasured = 0.0; simCtx->drivenFluxArea = 0.0;
573 simCtx->targetVolumetricFlux = 0.0;
574 simCtx->drivenFluxTargetLatched = PETSC_FALSE;
575 simCtx->bulkVelocityCorrection = 0.0;
576 simCtx->boundaryVelocityCorrection = 0.0;
577 simCtx->AreaInSum = 0.0; simCtx->AreaOutSum = 0.0;
578 simCtx->ccc = 0;
579 simCtx->ratio = 0.0;
580
581
582 // --- Group 8: Turbulence Modeling (LES) ---
583 simCtx->les = NO_LES_MODEL;
584 simCtx->wallfunction = 0; simCtx->les_gradient_model = 0;
585 simCtx->inflowFluctuations = PETSC_FALSE; simCtx->inflowFluctuationsRestored = PETSC_FALSE;
586 ierr = LESConfigSetDefaults(&simCtx->les_config); CHKERRQ(ierr);
587
588 // --- Group 9: Particle / DMSwarm Data & Settings ---
589 simCtx->np = 0;
590 simCtx->particleInlets = NULL;
591 simCtx->particleInletCount = 0;
592 simCtx->particleRandomSeed = 12345;
593 simCtx->sourceRandomSeed = 12345;
594 simCtx->dm_swarm = NULL; simCtx->bboxlist = NULL;
597 strcpy(simCtx->particleRestartMode,"load");
598 simCtx->particlesLostLastStep = 0;
599 simCtx->particlesLostCumulative = 0;
600 simCtx->particlesLostScalarLastStep = 0.0;
601 simCtx->particlesExitedLastStep = 0;
602 simCtx->particlesExitedCumulative = 0;
603 simCtx->particlesExitedScalarLastStep = 0.0;
604 simCtx->particlesMigratedLastStep = 0;
605 simCtx->occupiedCellCount = 0;
606 simCtx->particlesPerCellMin = 0; simCtx->particlesPerCellMax = 0; simCtx->particlesPerCellMean = 0.0;
607 simCtx->particleLoadImbalance = 0.0;
608 simCtx->migrationPassesLastStep = 0;
609 simCtx->searchMetrics.searchAttempts = 0;
612 simCtx->searchMetrics.searchLostCount = 0;
614 simCtx->searchMetrics.reSearchCount = 0;
617 simCtx->searchMetrics.tieBreakCount = 0;
623 simCtx->C_IEM = 2.0;
624
625 // --- Group 10: Immersed Boundary & FSI Data Object Pointers ---
626 simCtx->ibm = NULL; simCtx->ibmv = NULL; simCtx->fsi = NULL;
627
628 // --- Group 11: Logging and Custom Configuration ---
629 strcpy(simCtx->allowedFile, "config/whitelist.run");
630 simCtx->useCfg = PETSC_FALSE;
631 simCtx->allowedFuncs = NULL;
632 simCtx->nAllowed = 0;
633 simCtx->LoggingFrequency = 10;
634 simCtx->tracePIDs = NULL;
635 simCtx->nTracePIDs = 0;
636 simCtx->poissonSourceImbalance = 0.0;
637 simCtx->MaxDiv = 0.0;
638 simCtx->MaxDivFlatArg = 0; simCtx->MaxDivx = 0; simCtx->MaxDivy = 0; simCtx->MaxDivz = 0;
639 strcpy(simCtx->profilingSelectedFuncsFile, "config/profile.run");
640 simCtx->useProfilingSelectedFuncsCfg = PETSC_FALSE;
641 simCtx->profilingSelectedFuncs = NULL;
642 simCtx->profilingHelpers = NULL;
643 simCtx->nProfilingHelpers = 0;
644 simCtx->profilingAllHelpers = PETSC_FALSE;
645 simCtx->nProfilingSelectedFuncs = 0;
646 strcpy(simCtx->profilingTimestepMode, "selected");
647 simCtx->profilingFinalSummary = PETSC_TRUE;
648 simCtx->walltimeGuardEnabled = PETSC_FALSE;
649 simCtx->walltimeGuardActive = PETSC_FALSE;
650 simCtx->walltimeGuardWarmupSteps = 10;
651 simCtx->walltimeGuardMultiplier = 2.0;
652 simCtx->walltimeGuardMinSeconds = 60.0;
653 simCtx->walltimeGuardEstimatorAlpha = 0.35;
655 simCtx->walltimeGuardLimitSeconds = 0.0;
656 simCtx->walltimeGuardCompletedSteps = 0;
659 simCtx->walltimeGuardHasEWMA = PETSC_FALSE;
660 simCtx->walltimeGuardEWMASeconds = 0.0;
661 simCtx->walltimeGuardLatestStepSeconds = 0.0;
662 simCtx->runtimeMemoryLogEnabled = PETSC_TRUE;
663 simCtx->lastStepWallSeconds = 0.0;
664 simCtx->runCsvWrittenCount = 0;
665 simCtx->runtimeMemoryLogHasPrevious = PETSC_FALSE;
667 // --- Group 11: Post-Processing Information ---
668 strcpy(simCtx->PostprocessingControlFile, "config/post.run");
669 ierr = PetscNew(&simCtx->pps); CHKERRQ(ierr);
670
671 // === 2. Get MPI Info and Handle Config File =============================
672 // -- Group 1: Parallelism & MPI Information
673 ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &simCtx->rank); CHKERRQ(ierr);
674 ierr = MPI_Comm_size(PETSC_COMM_WORLD, &simCtx->size); CHKERRQ(ierr);
675
676 // First, check if the -control_file argument was provided by the user/script.
677 ierr = PetscOptionsGetString(NULL, NULL, "-control_file", control_filename, sizeof(control_filename), &control_flg); CHKERRQ(ierr);
678
679 // If the flag is NOT present or the filename is empty, abort with a helpful error.
680 if (!control_flg || strlen(control_filename) == 0) {
681 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
682 "\n\n*** MANDATORY ARGUMENT MISSING ***\n"
683 "The -control_file argument was not provided.\n"
684 "This program must be launched with a configuration file.\n"
685 "Example: mpiexec -n 4 ./simulator -control_file /path/to/your/config.control\n"
686 "This is typically handled automatically by the 'picurv' script.\n");
687 }
688
689 // At this point, we have a valid filename. Attempt to load it.
690 LOG(GLOBAL, LOG_INFO, "Loading mandatory configuration from: %s\n", control_filename);
691 ierr = PetscOptionsInsertFile(PETSC_COMM_WORLD, NULL, control_filename, PETSC_FALSE);
692 if (ierr == PETSC_ERR_FILE_OPEN) {
693 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_FILE_OPEN, "The specified control file was not found or could not be opened: %s", control_filename);
694 }
695 CHKERRQ(ierr);
696
697 {
698 PetscBool legacy_averaging = PETSC_FALSE;
699 ierr = PetscOptionsHasName(NULL, NULL, "-averaging", &legacy_averaging); CHKERRQ(ierr);
700 PetscCheck(!legacy_averaging, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
701 "Legacy -averaging was removed. Use instantaneous output and offline "
702 "postprocessing until the replacement field-statistics pipeline is available.");
703 }
704
705 // === 3. A Configure Logging System ========================================
706 // This logic determines the logging configuration and STORES it in simCtx for
707 // later reference and cleanup.
708 ierr = PetscOptionsGetString(NULL, NULL, "-whitelist_config_file", simCtx->allowedFile, PETSC_MAX_PATH_LEN, &simCtx->useCfg); CHKERRQ(ierr);
709
710 if (simCtx->useCfg) {
711 ierr = LoadAllowedFunctionsFromFile(simCtx->allowedFile, &simCtx->allowedFuncs, &simCtx->nAllowed);
712 if (ierr) {
713 // Use direct PetscPrintf as logging system isn't fully active yet.
714 PetscPrintf(PETSC_COMM_SELF, "[%s] WARNING: Failed to load allowed functions from '%s'. Falling back to default list.\n", __func__, simCtx->allowedFile);
715 simCtx->useCfg = PETSC_FALSE; // Mark as failed.
716 ierr = 0; // Clear the error to allow fallback.
717 } else if (simCtx->nAllowed == 0) {
718 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
719 "Whitelist config file '%s' is empty. Omit -whitelist_config_file to use the default allow-list, or list at least one function.",
720 simCtx->allowedFile);
721 }
722 }
723 if (!simCtx->useCfg) {
724 // Fallback to default logging functions if no file was used or if loading failed.
725 simCtx->nAllowed = 2;
726 ierr = PetscMalloc1(simCtx->nAllowed, &simCtx->allowedFuncs); CHKERRQ(ierr);
727 ierr = PetscStrallocpy("main", &simCtx->allowedFuncs[0]); CHKERRQ(ierr);
728 ierr = PetscStrallocpy("CreateSimulationContext", &simCtx->allowedFuncs[1]); CHKERRQ(ierr);
729 }
730
731 // Activate the configuration by passing it to the logging module's setup function.
732 set_allowed_functions((const char**)simCtx->allowedFuncs, (size_t)simCtx->nAllowed);
733
734 // Now that the logger is configured, we can use it.
735 LOG_ALLOW_SYNC(LOCAL, LOG_INFO, "Context created. Initializing on rank %d of %d.\n", simCtx->rank, simCtx->size);
736 print_log_level(); // This will now correctly reflect the LOG_LEVEL environment variable.
737
738 // === 3.B Configure Profiling System ========================================
739 ierr = PetscOptionsGetString(NULL, NULL, "-profiling_timestep_mode", simCtx->profilingTimestepMode, sizeof(simCtx->profilingTimestepMode), NULL); CHKERRQ(ierr);
740 ierr = PetscOptionsGetBool(NULL, NULL, "-profiling_final_summary", &simCtx->profilingFinalSummary, NULL); CHKERRQ(ierr);
741 ierr = PetscOptionsGetBool(NULL, NULL, "-picurv_verify_ghost_updates", &simCtx->verifyGhostUpdates, NULL); CHKERRQ(ierr);
742 if (strcmp(simCtx->profilingTimestepMode, "off") != 0 &&
743 strcmp(simCtx->profilingTimestepMode, "selected") != 0 &&
744 strcmp(simCtx->profilingTimestepMode, "all") != 0) {
745 PetscPrintf(PETSC_COMM_SELF, "[%s] WARNING: Unknown profiling timestep mode '%s'. Falling back to 'selected'.\n", __func__, simCtx->profilingTimestepMode);
746 strcpy(simCtx->profilingTimestepMode, "selected");
747 }
748
749 if (strcmp(simCtx->profilingTimestepMode, "selected") == 0) {
750 ierr = PetscOptionsGetString(NULL, NULL, "-profile_config_file", simCtx->profilingSelectedFuncsFile, PETSC_MAX_PATH_LEN, &simCtx->useProfilingSelectedFuncsCfg); CHKERRQ(ierr);
751 if (simCtx->useProfilingSelectedFuncsCfg) {
753 if (ierr) {
754 PetscPrintf(PETSC_COMM_SELF, "[%s] WARNING: Failed to load selected profiling functions from '%s'. Falling back to default list.\n", __func__, simCtx->profilingSelectedFuncsFile);
755 simCtx->useProfilingSelectedFuncsCfg = PETSC_FALSE;
756 ierr = 0;
757 }
758 }
759 if (!simCtx->useProfilingSelectedFuncsCfg) {
760 // Fallback to a hardcoded default list if no file was provided or loading failed.
761 simCtx->nProfilingSelectedFuncs = 4;
762 ierr = PetscMalloc1(simCtx->nProfilingSelectedFuncs, &simCtx->profilingSelectedFuncs); CHKERRQ(ierr);
763 ierr = PetscStrallocpy("FlowSolver", &simCtx->profilingSelectedFuncs[0]); CHKERRQ(ierr);
764 ierr = PetscStrallocpy("AdvanceSimulation", &simCtx->profilingSelectedFuncs[1]); CHKERRQ(ierr);
765 ierr = PetscStrallocpy("LocateAllParticlesInGrid", &simCtx->profilingSelectedFuncs[2]); CHKERRQ(ierr);
766 ierr = PetscStrallocpy("InterpolateAllFieldsToSwarm", &simCtx->profilingSelectedFuncs[3]); CHKERRQ(ierr);
767 }
768 }
769
770 // Helper timers (per-particle and per-cell functions) are off unless named, or 'all'.
771 {
772 PetscInt nmax = 512;
773 PetscBool found = PETSC_FALSE;
774 ierr = PetscMalloc1(nmax, &simCtx->profilingHelpers); CHKERRQ(ierr);
775 ierr = PetscOptionsGetStringArray(NULL, NULL, "-profiling_helpers", simCtx->profilingHelpers, &nmax, &found); CHKERRQ(ierr);
776 simCtx->nProfilingHelpers = found ? nmax : 0;
777 for (PetscInt i = 0; i < simCtx->nProfilingHelpers; ++i) {
778 if (strcmp(simCtx->profilingHelpers[i], "all") == 0) simCtx->profilingAllHelpers = PETSC_TRUE;
779 }
780 }
781
782 // Initialize the profiling system with the current updated simulation context.
783 ierr = ProfilingInitialize(simCtx); CHKERRQ(ierr);
784
785 // === 4. Parse All Command Line Options ==================================
786 LOG_ALLOW(GLOBAL, LOG_INFO, "Parsing command-line options...\n");
787
788 // --- Group 2
789 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 2: Simulation Control,Time and I/O.\n");
790 // Read the physical time to start from.
791 // The default is already 0.0, so this will only be non-zero if the user provides it.
792 ierr = PetscOptionsGetInt(NULL, NULL, "-start_step", &simCtx->StartStep, NULL); CHKERRQ(ierr);
793 ierr = PetscOptionsGetInt(NULL,NULL, "-totalsteps", &simCtx->StepsToRun, NULL); CHKERRQ(ierr);
794 ierr = PetscOptionsGetBool(NULL, NULL, "-only_setup", &simCtx->OnlySetup, NULL); CHKERRQ(ierr);
795 ierr = PetscOptionsGetBool(NULL, NULL, "-continue_mode", &simCtx->continueMode, NULL); CHKERRQ(ierr);
796 /* Resuming in the same run directory continues accumulated statistics by
797 * default; branching with --restart-from must opt in, because the branch may
798 * follow a different physical trajectory than the samples already collected. */
799 simCtx->fieldStatisticsContinue = simCtx->continueMode;
800 ierr = PetscOptionsGetBool(NULL, NULL, "-field_statistics_continue",
801 &simCtx->fieldStatisticsContinue, NULL); CHKERRQ(ierr);
802 ierr = PetscOptionsGetReal(NULL, NULL, "-dt", &simCtx->dt, NULL); CHKERRQ(ierr);
803 ierr = PetscOptionsGetInt(NULL, NULL, "-tio", &simCtx->tiout, NULL); CHKERRQ(ierr);
804 {
805 // Boundary checkpoints (the run's first and last states) are written unless turned off.
806 PetscBool write_initial = PETSC_TRUE, write_final = PETSC_TRUE;
807 ierr = PetscOptionsGetBool(NULL, NULL, "-write_initial_checkpoint", &write_initial, NULL); CHKERRQ(ierr);
808 ierr = PetscOptionsGetBool(NULL, NULL, "-write_final_checkpoint", &write_final, NULL); CHKERRQ(ierr);
809 simCtx->skipInitialCheckpoint = (PetscBool)!write_initial;
810 simCtx->skipFinalCheckpoint = (PetscBool)!write_final;
811 }
812 ierr = PetscOptionsGetInt(NULL, NULL, "-particle_console_output_freq", &simCtx->particleConsoleOutputFreq, &particle_console_output_freq_flg); CHKERRQ(ierr);
813 if (!particle_console_output_freq_flg) {
814 simCtx->particleConsoleOutputFreq = simCtx->tiout;
815 }
816 ierr = PetscOptionsGetString(NULL,NULL,"-euler_field_source",simCtx->eulerianSource,sizeof(simCtx->eulerianSource),NULL);CHKERRQ(ierr);
817 ierr = PetscOptionsGetString(NULL,NULL,"-output_dir",simCtx->output_dir,sizeof(simCtx->output_dir),NULL);CHKERRQ(ierr);
818 ierr = PetscOptionsGetString(NULL,NULL,"-restart_dir",simCtx->restart_dir,sizeof(simCtx->restart_dir),NULL);CHKERRQ(ierr);
819 ierr = PetscOptionsGetString(NULL,NULL,"-log_dir",simCtx->log_dir,sizeof(simCtx->log_dir),NULL);CHKERRQ(ierr);
820 ierr = PetscOptionsGetString(NULL,NULL,"-analysis_dir",simCtx->analysis_dir,sizeof(simCtx->analysis_dir),NULL);CHKERRQ(ierr);
821 ierr = PetscOptionsGetBool(NULL, NULL, "-walltime_guard_enabled", &simCtx->walltimeGuardEnabled, NULL); CHKERRQ(ierr);
822 ierr = PetscOptionsGetInt(NULL, NULL, "-walltime_guard_warmup_steps", &simCtx->walltimeGuardWarmupSteps, NULL); CHKERRQ(ierr);
823 ierr = PetscOptionsGetReal(NULL, NULL, "-walltime_guard_multiplier", &simCtx->walltimeGuardMultiplier, NULL); CHKERRQ(ierr);
824 ierr = PetscOptionsGetBool(NULL, NULL, "-runtime_memory_log_enabled", &simCtx->runtimeMemoryLogEnabled, NULL); CHKERRQ(ierr);
825 ierr = PetscOptionsGetReal(NULL, NULL, "-walltime_guard_min_seconds", &simCtx->walltimeGuardMinSeconds, NULL); CHKERRQ(ierr);
826 ierr = PetscOptionsGetReal(NULL, NULL, "-walltime_guard_estimator_alpha", &simCtx->walltimeGuardEstimatorAlpha, NULL); CHKERRQ(ierr);
827
828 if (simCtx->walltimeGuardWarmupSteps <= 0) {
829 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Invalid value for -walltime_guard_warmup_steps: %" PetscInt_FMT ". Must be > 0.", simCtx->walltimeGuardWarmupSteps);
830 }
831 if (simCtx->walltimeGuardMultiplier <= 0.0 || simCtx->walltimeGuardMultiplier > 5.0) {
832 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Invalid value for -walltime_guard_multiplier: %.6f. Must be in (0, 5].", (double)simCtx->walltimeGuardMultiplier);
833 }
834 if (simCtx->walltimeGuardMinSeconds <= 0.0) {
835 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Invalid value for -walltime_guard_min_seconds: %.6f. Must be > 0.", (double)simCtx->walltimeGuardMinSeconds);
836 }
837 if (simCtx->walltimeGuardEstimatorAlpha <= 0.0 || simCtx->walltimeGuardEstimatorAlpha > 1.0) {
838 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Invalid value for -walltime_guard_estimator_alpha: %.6f. Must be in (0, 1].", (double)simCtx->walltimeGuardEstimatorAlpha);
839 }
840
841 if(strcmp(simCtx->eulerianSource,"solve")!= 0 && strcmp(simCtx->eulerianSource,"load") != 0 && strcmp(simCtx->eulerianSource,"analytical")!=0){
842 SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_WRONG,"Invalid value for -euler_field_source. Must be 'load','analytical' or 'solve'. You provided '%s'.",simCtx->eulerianSource);
843 }
844
845 // --- Group 3
846 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 3: High-Level Physics & Model Selection Flags\n");
847 ierr = PetscOptionsGetInt(NULL, NULL, "-imm", &simCtx->immersed, NULL); CHKERRQ(ierr);
848 ierr = PetscOptionsGetInt(NULL, NULL, "-fsi", &simCtx->movefsi, NULL); CHKERRQ(ierr);
849 ierr = PetscOptionsGetInt(NULL, NULL, "-rfsi", &simCtx->rotatefsi, NULL); CHKERRQ(ierr);
850 ierr = PetscOptionsGetInt(NULL, NULL, "-inv", &simCtx->invicid, NULL); CHKERRQ(ierr);
851 ierr = PetscOptionsGetInt(NULL, NULL, "-TwoD", &simCtx->TwoD, NULL); CHKERRQ(ierr);
852 ierr = PetscOptionsGetInt(NULL, NULL, "-mframe", &simCtx->moveframe, NULL); CHKERRQ(ierr);
853 ierr = PetscOptionsGetInt(NULL, NULL, "-rframe", &simCtx->rotateframe, NULL); CHKERRQ(ierr);
854
855 /* Immersed boundaries, moving bodies and moving reference frames are planned, not
856 implemented. No body geometry is ever loaded, and the IBM interpolation the
857 momentum solvers would call is commented out and defined nowhere, so -imm only
858 reconfigures the Poisson solve around a body that is not there. The moving-frame
859 convection branch in ComputeRHS is commented out as well, so -mframe/-rframe would
860 drop the convective term. Each would run a different problem without saying so;
861 the conductor refuses the YAML switches, and this refuses the same flags arriving
862 through a PETSc passthrough. */
863 PetscCheck(!simCtx->immersed && !simCtx->movefsi && !simCtx->rotatefsi, PETSC_COMM_WORLD, PETSC_ERR_SUP,
864 "Immersed boundaries and moving bodies (-imm, -fsi, -rfsi) are planned, not implemented.");
865 PetscCheck(!simCtx->moveframe && !simCtx->rotateframe, PETSC_COMM_WORLD, PETSC_ERR_SUP,
866 "Moving and rotating reference frames (-mframe, -rframe) are planned, not implemented: "
867 "their convection branch is absent, so the convective term would be dropped.");
868
869 // --- Group 4
870 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 4: Immersed-Body Flux Corrections and Driven-Flow Controls\n");
871 ierr = PetscOptionsGetInt(NULL, NULL, "-mhv", &simCtx->MHV, NULL); CHKERRQ(ierr);
872 ierr = PetscOptionsGetInt(NULL, NULL, "-lv", &simCtx->LV, NULL); CHKERRQ(ierr);
873 /* The heart-valve volume-flux corrections balance flux across an immersed body, which
874 cannot exist while immersed boundaries are unimplemented (see the Group 3 check). */
875 PetscCheck(!simCtx->MHV && !simCtx->LV, PETSC_COMM_WORLD, PETSC_ERR_SUP,
876 "The -mhv/-lv immersed-body flux corrections need immersed boundaries, which are planned, not implemented.");
877 ierr = PetscOptionsGetReal(NULL,NULL,"-driven_flow_initial_force",&simCtx->drivingForceMagnitude,NULL);CHKERRQ(ierr);
878 ierr = PetscOptionsGetReal(NULL,NULL,"-driven_flow_scaling_factor",&simCtx->forceScalingFactor,NULL);CHKERRQ(ierr);
879 // --- Group 5
880 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 5: Solver & Numerics Parameters \n");
881 char mom_solver_type_char[PETSC_MAX_PATH_LEN];
882 char solution_convergence_mode_char[PETSC_MAX_PATH_LEN];
883 PetscBool mom_solver_type_flg = PETSC_FALSE;
884 PetscBool solution_convergence_mode_flg = PETSC_FALSE;
885 ierr = PetscOptionsGetString(NULL, NULL, "-mom_solver_type", mom_solver_type_char, sizeof(mom_solver_type_char), &mom_solver_type_flg); CHKERRQ(ierr);
886 ierr = PetscOptionsGetInt(NULL, NULL, "-mom_max_pseudo_steps", &simCtx->mom_max_pseudo_steps, NULL); CHKERRQ(ierr);
887 ierr = PetscOptionsGetInt(NULL, NULL, "-mom_max_unconverged_steps", &simCtx->mom_max_unconverged_steps, NULL); CHKERRQ(ierr);
888 PetscCheck(simCtx->mom_max_unconverged_steps >= 0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
889 "-mom_max_unconverged_steps must be 0 (never stop) or a positive step count; received %" PetscInt_FMT ".",
891 ierr = PetscOptionsGetReal(NULL, NULL, "-mom_atol", &simCtx->mom_atol, NULL); CHKERRQ(ierr);
892 ierr = PetscOptionsGetReal(NULL, NULL, "-mom_rtol", &simCtx->mom_rtol, NULL); CHKERRQ(ierr);
893 ierr = PetscOptionsGetReal(NULL, NULL, "-mom_resid_atol", &simCtx->mom_resid_atol, NULL); CHKERRQ(ierr);
894 ierr = PetscOptionsGetReal(NULL, NULL, "-mom_resid_rtol", &simCtx->mom_resid_rtol, NULL); CHKERRQ(ierr);
895 ierr = PetscOptionsGetReal(NULL, NULL, "-imp_stol", &simCtx->imp_stol, NULL); CHKERRQ(ierr);
896 ierr = PetscOptionsGetInt(NULL, NULL, "-central", &simCtx->central, NULL); CHKERRQ(ierr);
897 ierr = PetscOptionsGetString(NULL, NULL, "-solution_convergence_mode",
898 solution_convergence_mode_char, sizeof(solution_convergence_mode_char),
899 &solution_convergence_mode_flg); CHKERRQ(ierr);
900 ierr = PetscOptionsGetBool(NULL, NULL, "-solution_convergence_enabled", &simCtx->solutionConvergenceEnabled, NULL); CHKERRQ(ierr);
901 ierr = PetscOptionsGetInt(NULL, NULL, "-solution_convergence_period_steps", &simCtx->solutionConvergencePeriodSteps, NULL); CHKERRQ(ierr);
902 ierr = PetscOptionsGetInt(NULL, NULL, "-solution_convergence_window_steps", &simCtx->solutionConvergenceWindowSteps, NULL); CHKERRQ(ierr);
903 /* Field statistics resolve here rather than inline, because a variable-arity
904 * window list needs its own parse site; see statistics_config.c. It must
905 * precede CreateAndInitializeAllVectors, which sizes the per-window
906 * accumulators from the window count resolved here. */
907 ierr = ParseFieldStatisticsConfig(simCtx); CHKERRQ(ierr);
908
909 // Keep parser acceptance aligned with the enum and FlowSolver dispatch.
910 if (mom_solver_type_flg) {
911 if(strcmp(mom_solver_type_char, "DUALTIME_PICARD_JAMESON_RK") == 0 ||
912 strcmp(mom_solver_type_char, "DUALTIME_PICARD_RK4") == 0) {
914 } else if (strcmp(mom_solver_type_char, "EXPLICIT_RK") == 0) {
916 } else if (strcmp(mom_solver_type_char, "newton_krylov") == 0) {
918 } else {
919 LOG(GLOBAL, LOG_ERROR, "Invalid value for -mom_solver_type: '%s'. Valid options are: 'DUALTIME_PICARD_JAMESON_RK', 'EXPLICIT_RK', 'newton_krylov'.\n", mom_solver_type_char);
920 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Invalid value for -mom_solver_type: '%s'.", mom_solver_type_char);
921 }
922 }
923
924 if (solution_convergence_mode_flg) {
925 if (strcmp(solution_convergence_mode_char, "STEADY_DETERMINISTIC") == 0) {
927 } else if (strcmp(solution_convergence_mode_char, "PERIODIC_DETERMINISTIC") == 0) {
929 } else if (strcmp(solution_convergence_mode_char, "STATISTICAL_STEADY") == 0) {
931 } else if (strcmp(solution_convergence_mode_char, "TRANSIENT") == 0) {
933 } else {
934 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
935 "Invalid value for -solution_convergence_mode: '%s'.", solution_convergence_mode_char);
936 }
937 }
938
940 simCtx->solutionConvergencePeriodSteps <= 0) {
941 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
942 "solution convergence mode PERIODIC_DETERMINISTIC requires -solution_convergence_period_steps > 0.");
943 }
945 simCtx->solutionConvergenceWindowSteps <= 0) {
946 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
947 "solution convergence mode STATISTICAL_STEADY requires -solution_convergence_window_steps > 0.");
948 }
949
950 // --- Multigrid Options ---
951 ierr = PetscOptionsGetInt(NULL, NULL, "-mg_level", &simCtx->mglevels, NULL); CHKERRQ(ierr);
952 /* Coarse levels exist only for the pressure solve. Without one they would only constrain the
953 finest split: rank boundaries refined from a coarse level land on every 2^(levels-1)-th node,
954 so e.g. 128 cells on 4 ranks at 3 levels own 33/32/32/31 instead of 32 each. */
955 if (strcmp(simCtx->eulerianSource, "solve") != 0 && simCtx->mglevels != 1) {
956 LOG_ALLOW(GLOBAL, LOG_INFO, "Eulerian source '%s' solves no pressure: using 1 grid level instead of %d.\n",
957 simCtx->eulerianSource, (int)simCtx->mglevels);
958 simCtx->mglevels = 1;
959 }
960 ierr = PetscOptionsGetInt(NULL, NULL, "-mg_pre_it", &simCtx->mg_preItr, NULL); CHKERRQ(ierr);
961 ierr = PetscOptionsGetInt(NULL, NULL, "-mg_post_it", &simCtx->mg_poItr, NULL); CHKERRQ(ierr);
962
963 // --- Other Solver Options ---
964 ierr = PetscOptionsGetInt(NULL, NULL, "-poisson", &simCtx->poisson, NULL); CHKERRQ(ierr);
965 ierr = PetscOptionsGetReal(NULL, NULL, "-ren", &simCtx->ren, NULL); CHKERRQ(ierr);
966 ierr = PetscOptionsGetReal(NULL, NULL, "-pseudo_cfl", &simCtx->pseudo_cfl, NULL); CHKERRQ(ierr);
967 ierr = PetscOptionsGetReal(NULL, NULL, "-max_pseudo_cfl", &simCtx->max_pseudo_cfl, NULL); CHKERRQ(ierr);
968 ierr = PetscOptionsGetReal(NULL, NULL, "-min_pseudo_cfl", &simCtx->min_pseudo_cfl, NULL); CHKERRQ(ierr);
969 ierr = PetscOptionsGetReal(NULL, NULL, "-pseudo_cfl_reduction_factor", &simCtx->pseudo_cfl_reduction_factor, NULL); CHKERRQ(ierr);
970 ierr = PetscOptionsGetReal(NULL, NULL, "-pseudo_cfl_growth_factor", &simCtx->pseudo_cfl_growth_factor, NULL); CHKERRQ(ierr);
971 // Read the deprecated RK4 spelling first so the canonical Jameson option wins if both are present.
972 ierr = PetscOptionsGetReal(NULL,NULL, "-mom_dt_rk4_residual_norm_noise_allowance_factor",&simCtx->mom_dt_jameson_residual_norm_noise_allowance_factor,NULL);CHKERRQ(ierr);
973 ierr = PetscOptionsGetReal(NULL,NULL, "-mom_dt_jameson_residual_norm_noise_allowance_factor",&simCtx->mom_dt_jameson_residual_norm_noise_allowance_factor,NULL);CHKERRQ(ierr);
974 ierr = PetscOptionsGetBool(NULL, NULL, "-no_pseudo_cfl_backtrack", &simCtx->no_pseudo_cfl_backtrack, NULL); CHKERRQ(ierr);
975 ierr = PetscOptionsGetReal(NULL, NULL, "-mom_ratio_ema_alpha", &simCtx->mom_ratio_ema_alpha, NULL); CHKERRQ(ierr);
976 if (simCtx->min_pseudo_cfl <= 0.0 ||
977 simCtx->pseudo_cfl < simCtx->min_pseudo_cfl ||
978 simCtx->pseudo_cfl > simCtx->max_pseudo_cfl) {
979 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
980 "Pseudo-CFL controls require 0 < minimum <= initial <= maximum.");
981 }
982 if (simCtx->pseudo_cfl_growth_factor < 1.0 ||
983 simCtx->pseudo_cfl_reduction_factor <= 0.0 ||
984 simCtx->pseudo_cfl_reduction_factor >= 1.0 ||
986 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
987 "Pseudo-CFL controls require growth_factor >= 1, 0 < reduction_factor < 1, and noise allowance >= 1.");
988 }
989 if (simCtx->mom_ratio_ema_alpha < 0.0 || simCtx->mom_ratio_ema_alpha > 1.0) {
990 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
991 "-mom_ratio_ema_alpha must be in [0, 1].");
992 }
993 ierr = PetscOptionsHasName(NULL, NULL, "-ps_ksp_pic_monitor_true_residual", &simCtx->ps_ksp_pic_monitor_true_residual); CHKERRQ(ierr);
994 ierr = PetscOptionsGetBool(NULL, NULL, "-mom_nk_pic_monitor", &simCtx->mom_nk_monitor_history, NULL); CHKERRQ(ierr);
995 {
996 PetscInt ic_field = (PetscInt)simCtx->initialConditionField;
997 ierr = PetscOptionsGetInt(NULL, NULL, "-ic_field", &ic_field, NULL); CHKERRQ(ierr);
999 }
1000 ierr = PetscOptionsGetString(NULL, NULL, "-ic_dir", simCtx->initialConditionDirectory,
1001 sizeof(simCtx->initialConditionDirectory), &simCtx->initialConditionStaged); CHKERRQ(ierr);
1003 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1004 "Invalid value for -ic_field. Expected 0 (Ucat) or 1 (Ucont), got %d.",
1005 simCtx->initialConditionField);
1006 }
1007 ierr = VerificationFieldsCreate(simCtx); CHKERRQ(ierr);
1008 // NOTE: cdisx,cdisy,cdisz haven't been parsed, add if necessary.
1009
1010 // --- Group 6
1011 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 6: Physical & Geometric Parameters \n");
1012 ierr = PetscOptionsGetReal(NULL,NULL,"-schmidt_number",&simCtx->schmidt_number,NULL);CHKERRQ(ierr);
1013 ierr = PetscOptionsGetReal(NULL,NULL,"-turb_schmidt_number",&simCtx->Turbulent_schmidt_number,NULL);CHKERRQ(ierr);
1014 ierr = PetscOptionsGetReal(NULL,NULL,"-iem_constant",&simCtx->iem_constant,NULL);CHKERRQ(ierr);
1015 /* Zero is valid: it switches micromixing off, so a particle scalar is carried unchanged. */
1016 PetscCheck(simCtx->iem_constant >= 0.0 && !PetscIsInfOrNanReal(simCtx->iem_constant),
1017 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1018 "-iem_constant must be a non-negative finite number (got %g).", (double)simCtx->iem_constant);
1019 ierr = PetscOptionsGetReal(NULL,NULL,"-wall_roughness",&simCtx->wall_roughness_height,NULL);CHKERRQ(ierr);
1020 // NOTE: angle is not parsed in the original code, it set programmatically. We will follow that.
1021 // NOTE: max_angle is calculated based on other flags (like MHV) in the legacy code.
1022 // We will defer that logic to a later setup stage and not parse them directly.
1023 // The Scaling Information is calculated here
1024 ierr = ParseScalingInformation(simCtx); CHKERRQ(ierr);
1025
1026 // --- Group 7
1027 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 7: Grid, Domain, and Boundary Condition Settings \n");
1028 ierr = PetscOptionsGetInt(NULL, NULL, "-nblk", &simCtx->block_number, NULL); CHKERRQ(ierr); // This is also a modern option
1029 /* Every inter-block exchange (Block_Interface_U) is commented out in the momentum
1030 solvers and the initial condition, so blocks would be solved as isolated domains.
1031 Multi-block coupling is planned, not implemented. */
1032 PetscCheck(simCtx->block_number == 1, PETSC_COMM_WORLD, PETSC_ERR_SUP,
1033 "Multi-block domains are planned, not implemented: blocks are never coupled (got -nblk %" PetscInt_FMT ").",
1034 simCtx->block_number);
1035 ierr = PetscOptionsGetInt(NULL, NULL, "-inlet", &simCtx->inletprofile, NULL); CHKERRQ(ierr);
1036 // NOTE: channelz was not parsed, likely set programmatically. We will omit its parsing call.
1037 ierr = PetscOptionsGetBool(NULL, NULL, "-grid", &simCtx->generate_grid, NULL); CHKERRQ(ierr);
1038 ierr = PetscOptionsGetString(NULL, NULL, "-grid_file", simCtx->grid_file, PETSC_MAX_PATH_LEN, NULL); CHKERRQ(ierr);
1039 ierr = PetscOptionsGetInt(NULL, NULL, "-da_processors_x", &simCtx->da_procs_x, NULL); CHKERRQ(ierr);
1040 ierr = PetscOptionsGetInt(NULL, NULL, "-da_processors_y", &simCtx->da_procs_y, NULL); CHKERRQ(ierr);
1041 ierr = PetscOptionsGetInt(NULL, NULL, "-da_processors_z", &simCtx->da_procs_z, NULL); CHKERRQ(ierr);
1042 // NOTE: pseudo_periodic was not parsed. We will omit its parsing call.
1043 PetscBool bcs_flg;
1044 char file_list_str[PETSC_MAX_PATH_LEN * 10]; // Buffer for comma-separated list
1045
1046 ierr = PetscOptionsGetString(NULL, NULL, "-bcs_files", file_list_str, sizeof(file_list_str), &bcs_flg); CHKERRQ(ierr);
1047
1048 if (bcs_flg) {
1049 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Found -bcs_files option, overriding default.\n");
1050
1051 // A. Clean up the default memory we allocated in Phase 1.
1052 ierr = PetscFree(simCtx->bcs_files[0]); CHKERRQ(ierr);
1053 ierr = PetscFree(simCtx->bcs_files); CHKERRQ(ierr);
1054 simCtx->num_bcs_files = 0;
1055 simCtx->bcs_files = NULL;
1056
1057 // B. Parse the user-provided comma-separated list.
1058 char *token;
1059 char *str_copy;
1060 ierr = PetscStrallocpy(file_list_str, &str_copy); CHKERRQ(ierr);
1061
1062 // First pass: count the number of files.
1063 token = strtok(str_copy, ",");
1064 while (token) {
1065 simCtx->num_bcs_files++;
1066 token = strtok(NULL, ",");
1067 }
1068 ierr = PetscFree(str_copy); CHKERRQ(ierr);
1069
1070 // Second pass: allocate memory and store the filenames.
1071 ierr = PetscMalloc1(simCtx->num_bcs_files, &simCtx->bcs_files); CHKERRQ(ierr);
1072 ierr = PetscStrallocpy(file_list_str, &str_copy); CHKERRQ(ierr);
1073 token = strtok(str_copy, ",");
1074 for (PetscInt i = 0; i < simCtx->num_bcs_files; i++) {
1075 ierr = PetscStrallocpy(token, &simCtx->bcs_files[i]); CHKERRQ(ierr);
1076 token = strtok(NULL, ",");
1077 }
1078 ierr = PetscFree(str_copy); CHKERRQ(ierr);
1079 }
1080
1081
1082 // --- Group 8
1083 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 8: Turbulence Modeling (LES) \n");
1084 // Seeded from the default already in simCtx: PetscOptionsGetInt leaves the target
1085 // untouched when -les is absent, and an uninitialized value would become the model.
1086 PetscInt temp_les_model = (PetscInt)simCtx->les;
1087 ierr = PetscOptionsGetInt(NULL, NULL, "-les", &temp_les_model, NULL); CHKERRQ(ierr);
1088 PetscCheck(temp_les_model >= NO_LES_MODEL && temp_les_model <= WALE, PETSC_COMM_WORLD,
1089 PETSC_ERR_ARG_OUTOFRANGE,
1090 "-les must be 0 (none), 1 (constant_smagorinsky), 2 (dynamic_smagorinsky), "
1091 "3 (vreman), or 4 (wale); received %" PetscInt_FMT ".", temp_les_model);
1092 simCtx->les = (LESModelType)temp_les_model;
1093 {
1094 /* RANS is planned, not implemented: the k-omega transport update was never
1095 written and its fields were never allocated. The selector and its dead
1096 hooks were removed on 2026-09-22 (see src/guide.md); this refuses the flag
1097 arriving through a PETSc passthrough. */
1098 PetscInt requested_rans = 0;
1099 ierr = PetscOptionsGetInt(NULL, NULL, "-rans", &requested_rans, NULL); CHKERRQ(ierr);
1100 PetscCheck(requested_rans == 0, PETSC_COMM_WORLD, PETSC_ERR_SUP,
1101 "RANS closures (-rans) are planned, not implemented: no transport equation is "
1102 "solved for them. Use an LES closure, or run laminar.");
1103 }
1104 ierr = PetscOptionsGetInt(NULL, NULL, "-wallfunction", &simCtx->wallfunction, NULL); CHKERRQ(ierr);
1105 ierr = PetscOptionsGetBool(NULL, NULL, "-inflow_fluctuations", &simCtx->inflowFluctuations, NULL); CHKERRQ(ierr);
1106 PetscCheck(simCtx->wallfunction >= WALL_FUNCTION_NONE && simCtx->wallfunction <= WALL_FUNCTION_CABOT,
1107 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1108 "-wallfunction must be 0 (none), 1 (log_law), 2 (werner), or 3 (cabot); received %" PetscInt_FMT ".",
1109 simCtx->wallfunction);
1110 ierr = PetscOptionsGetInt(NULL, NULL, "-les_gradient_model", &simCtx->les_gradient_model, NULL); CHKERRQ(ierr);
1111 ierr = ParseLESConfiguration(simCtx); CHKERRQ(ierr);
1112
1113 // --- Group 9
1114 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 9: Particle / DMSwarm Data & Settings \n");
1115 ierr = PetscOptionsGetInt(NULL, NULL, "-numParticles", &simCtx->np, NULL); CHKERRQ(ierr);
1116 /* Each swarm field is one PETSc vector of np x components entries, so the widest field must
1117 fit in PetscInt; past it, a 32-bit build corrupts the field's sizes and its checkpoint header. */
1118 {
1119 PetscInt widest = 1;
1120 for (PetscInt id = 0; id < (PetscInt)PARTICLE_FIELD_ID_COUNT; ++id) {
1121 const ParticleFieldDescriptor *descriptor = NULL;
1122 ierr = ParticleFieldGetDescriptor((ParticleFieldId)id, &descriptor); CHKERRQ(ierr);
1123 widest = PetscMax(widest, descriptor->components);
1124 }
1125 char object[128];
1126 ierr = PetscSNPrintf(object, sizeof(object), "-numParticles %" PetscInt_FMT " (a %" PetscInt_FMT
1127 "-component particle field; at most %" PetscInt_FMT " particles here)",
1128 simCtx->np, widest, (PetscInt)(PETSC_MAX_INT / widest)); CHKERRQ(ierr);
1129 ierr = PicurvCheckPetscIntRange(PETSC_COMM_WORLD, (PetscInt64)simCtx->np * widest, object); CHKERRQ(ierr);
1130 }
1131 PetscInt temp_pinit = (PetscInt)PARTICLE_INIT_SURFACE_RANDOM;
1132 ierr = PetscOptionsGetInt(NULL, NULL, "-pinit", &temp_pinit, NULL); CHKERRQ(ierr);
1134 PetscInt temp_interp = (PetscInt)INTERP_TRILINEAR;
1135 ierr = PetscOptionsGetInt(NULL, NULL, "-interpolation_method", &temp_interp, NULL); CHKERRQ(ierr);
1136 simCtx->interpolationMethod = (InterpolationMethod)temp_interp;
1137 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Interpolation method: %s\n", InterpolationMethodToString(simCtx->interpolationMethod));
1138 ierr = PetscOptionsGetReal(NULL, NULL, "-psrc_x", &simCtx->psrc_x, NULL); CHKERRQ(ierr);
1139 ierr = PetscOptionsGetReal(NULL, NULL, "-psrc_y", &simCtx->psrc_y, NULL); CHKERRQ(ierr);
1140 ierr = PetscOptionsGetReal(NULL, NULL, "-psrc_z", &simCtx->psrc_z, NULL); CHKERRQ(ierr);
1141 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Particle initialization mode: %s. Point source: (%.6f, %.6f, %.6f)\n",
1143 simCtx->psrc_x, simCtx->psrc_y, simCtx->psrc_z);
1144 ierr = PetscOptionsGetString(NULL,NULL,"-particle_restart_mode",simCtx->particleRestartMode,sizeof(simCtx->particleRestartMode),NULL); CHKERRQ(ierr);
1145 // Validation for Particle Restart Mode
1146 if (strcmp(simCtx->particleRestartMode, "load") != 0 && strcmp(simCtx->particleRestartMode, "init") != 0) {
1147 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Invalid value for -particle_restart_mode. Must be 'load' or 'init'. You provided '%s'.", simCtx->particleRestartMode);
1148 }
1149 ierr = PetscOptionsGetInt(NULL, NULL, "-particle_random_seed", &simCtx->particleRandomSeed, NULL); CHKERRQ(ierr);
1150 PetscCheck(simCtx->particleRandomSeed >= 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1151 "-particle_random_seed must be non-negative (got %" PetscInt_FMT ").", simCtx->particleRandomSeed);
1152 ierr = PetscOptionsGetInt(NULL, NULL, "-source_random_seed", &simCtx->sourceRandomSeed, NULL); CHKERRQ(ierr);
1153 PetscCheck(simCtx->sourceRandomSeed >= 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1154 "-source_random_seed must be non-negative (got %" PetscInt_FMT ").", simCtx->sourceRandomSeed);
1155 ierr = ParticleFieldPlanCreate("particle_fields", &simCtx->particleFieldPlan); CHKERRQ(ierr);
1156 ierr = ParticleInletsCreate(simCtx); CHKERRQ(ierr);
1157 PetscCheck(!simCtx->particleFieldPlan || ParticlesEnabled(simCtx), PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1158 "Particle field initial values are configured but the run has no particles.");
1159 PetscCheck(!simCtx->particleFieldPlan || !VerificationScalarOverrideActive(simCtx), PETSC_COMM_WORLD,
1160 PETSC_ERR_ARG_WRONG,
1161 "Particle field initial values cannot be combined with the verification scalar source, "
1162 "which prescribes Psi at every step.");
1163 // --- Group 10
1164 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 10: Immersed Boundary & FSI Data Object Pointers \n");
1165
1166 // --- Group 11
1167 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 11: Top-Level Managers & Custom Configuration \n");
1168 ierr = PetscOptionsGetInt(NULL, NULL, "-logfreq", &simCtx->LoggingFrequency, NULL); CHKERRQ(ierr);
1169 {
1170 PetscInt ids[PICURV_MAX_TRACED_PARTICLES + 1];
1171 PetscInt n = PICURV_MAX_TRACED_PARTICLES + 1;
1172 PetscBool found = PETSC_FALSE;
1173 ierr = PetscOptionsGetIntArray(NULL, NULL, "-picurv_trace_particles", ids, &n, &found); CHKERRQ(ierr);
1174 if (found && n > 0) {
1175 PetscCheck(n <= PICURV_MAX_TRACED_PARTICLES, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1176 "-picurv_trace_particles accepts at most %d particle IDs.", PICURV_MAX_TRACED_PARTICLES);
1177 ierr = PetscMalloc1(n, &simCtx->tracePIDs); CHKERRQ(ierr);
1178 for (PetscInt t = 0; t < n; ++t) {
1179 PetscCheck(ids[t] >= 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1180 "-picurv_trace_particles: particle IDs are non-negative (got %" PetscInt_FMT ").", ids[t]);
1181 simCtx->tracePIDs[t] = (PetscInt64)ids[t];
1182 }
1183 ierr = PetscSortInt64(n, simCtx->tracePIDs); CHKERRQ(ierr);
1184 simCtx->nTracePIDs = 1;
1185 for (PetscInt t = 1; t < n; ++t) {
1186 if (simCtx->tracePIDs[t] != simCtx->tracePIDs[simCtx->nTracePIDs - 1]) simCtx->tracePIDs[simCtx->nTracePIDs++] = simCtx->tracePIDs[t];
1187 }
1188 }
1189 }
1190
1191 if (simCtx->num_bcs_files != simCtx->block_number) {
1192 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP, "Number of BC files (%" PetscInt_FMT ") does not match number of blocks (%" PetscInt_FMT "). Use -bcs_files \"file1.dat,file2.dat,...\".", simCtx->num_bcs_files, simCtx->block_number);
1193 }
1194
1195 // --- Group 12
1196 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Parsing Group 12: Post-Processing Information.\n");
1197 // This logic determines the Post Processing configuration and STORES it in simCtx for later reference and cleanup.
1198 ierr = PetscOptionsGetString(NULL,NULL,"-postprocessing_config_file",simCtx->PostprocessingControlFile,PETSC_MAX_PATH_LEN,NULL); CHKERRQ(ierr);
1199 /* Parse post settings for both solver and post-processor binaries using the single pre-allocated pps object. */
1200 ierr = ParsePostProcessingSettings(simCtx); CHKERRQ(ierr);
1201
1202 // === 5. Dependent Parameter Calculations ================================
1203 // Some parameters depend on others, so we calculate them here.
1204 simCtx->StartTime = (PetscReal)simCtx->StartStep*simCtx->dt;
1205 simCtx->ti = simCtx->StartTime;
1206 simCtx->step = simCtx->StartStep;
1207
1208 // === 5. Log Summary and Finalize Setup ==================================
1209 LOG_ALLOW(GLOBAL, LOG_DEBUG, "-- Console Output Functions [Total : %" PetscInt_FMT "] : --\n", simCtx->nAllowed);
1210 for (PetscInt i = 0; i < simCtx->nAllowed; ++i) {
1211 LOG_ALLOW(GLOBAL, LOG_DEBUG, " [%2" PetscInt_FMT "] «%s»\n", i, simCtx->allowedFuncs[i]);
1212 }
1213
1214 LOG_ALLOW(GLOBAL, LOG_INFO, "Configuration complete. Key parameters:\n");
1215 LOG_ALLOW(GLOBAL, LOG_INFO, " - Run mode: %s\n", simCtx->OnlySetup ? "SETUP ONLY" : "Full Simulation");
1216 LOG_ALLOW(GLOBAL, LOG_INFO, " - Time steps: %" PetscInt_FMT " (from %" PetscInt_FMT " to %" PetscInt_FMT ")\n", simCtx->StepsToRun, simCtx->StartStep, simCtx->StartStep + simCtx->StepsToRun);
1217 LOG_ALLOW(GLOBAL, LOG_INFO, " - Time step size (dt): %g\n", simCtx->dt);
1218 if (simCtx->tiout > 0) {
1219 LOG_ALLOW(GLOBAL, LOG_INFO, " - Field/restart output cadence: every %" PetscInt_FMT " step(s)\n", simCtx->tiout);
1220 } else {
1221 LOG_ALLOW(GLOBAL, LOG_INFO, " - Field/restart output cadence: DISABLED\n");
1222 }
1223 LOG_ALLOW(GLOBAL, LOG_INFO, " - Immersed Boundary: %s\n", simCtx->immersed ? "ENABLED" : "DISABLED");
1224 LOG_ALLOW(GLOBAL, LOG_INFO, " - Particles: %" PetscInt_FMT "\n", simCtx->np);
1225 if (ParticlesEnabled(simCtx)) {
1226 if (simCtx->particleConsoleOutputFreq > 0) {
1227 LOG_ALLOW(GLOBAL, LOG_INFO, " - Particle console cadence: every %" PetscInt_FMT " step(s)\n", simCtx->particleConsoleOutputFreq);
1228 } else {
1229 LOG_ALLOW(GLOBAL, LOG_INFO, " - Particle console cadence: DISABLED\n");
1230 }
1231 LOG_ALLOW(GLOBAL, LOG_INFO, " - Particle console row subsampling: every %" PetscInt_FMT " particle(s)\n", simCtx->LoggingFrequency);
1232 }
1233 if (simCtx->StartStep > 0 && ParticlesEnabled(simCtx)) {
1234 LOG_ALLOW(GLOBAL, LOG_INFO, " - Particle Restart Mode: %s\n", simCtx->particleRestartMode);
1235 }
1236
1237 // --- Initialize PETSc's internal performance logging stage ---
1238 ierr = PetscLogDefaultBegin(); CHKERRQ(ierr); // REDUNDANT but safe.
1239 ierr = PetscMemorySetGetMaximumUsage(); CHKERRQ(ierr);
1240
1241 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Finished CreateSimulationContext successfully on rank %d.\n", simCtx->rank);
1242
1244 PetscFunctionReturn(0);
1245}
PetscErrorCode ParticleFieldPlanCreate(const char *prefix, ParticleFieldPlan **plan)
Read a plan from the options database.
PetscErrorCode ParticleInletsCreate(SimCtx *simCtx)
Read the inlets that inject particles from the options database.
PetscErrorCode ParsePostProcessingSettings(SimCtx *simCtx)
Initializes post-processing settings from a config file and command-line overrides.
Definition io.c:3051
PetscErrorCode ParseScalingInformation(SimCtx *simCtx)
Parses physical scaling parameters from command-line options.
Definition io.c:3256
void set_allowed_functions(const char **functionList, int count)
Sets the global list of function names that are allowed to log.
Definition logging.c:176
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#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
PetscErrorCode print_log_level(void)
Prints the current logging level to the console.
Definition logging.c:138
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[], char ***funcsOut, PetscInt *nOut)
Load function names from a text file.
Definition logging.c:561
const char * InterpolationMethodToString(InterpolationMethod method)
Returns the display name of a grid-to-particle interpolation method.
Definition logging.c:869
PetscErrorCode ProfilingInitialize(SimCtx *simCtx)
Applies the profiling configuration from SimCtx to PICurv's PETSc log events.
Definition logging.c:2015
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:662
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_COUNT
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
Immutable metadata for one persistent particle field.
static PetscErrorCode ParseLESConfiguration(SimCtx *simCtx)
Reads every LES closure parameter from the generated control file.
Definition setup.c:341
PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object)
Implementation of PicurvCheckPetscIntRange().
Definition setup.c:102
PetscErrorCode LESConfigSetDefaults(LESConfig *config)
Implementation of LESConfigSetDefaults().
Definition setup.c:288
PetscErrorCode ParseFieldStatisticsConfig(SimCtx *simCtx)
Resolves field-statistics configuration from the control file.
PetscBool inflowFluctuations
Some inlet adds synthetic fluctuations; their filter state is checkpointed.
Definition variables.h:1043
PetscInt particlesPerCellMin
Fewest particles in any cell after the step.
Definition variables.h:1069
PetscInt particleInletCount
Entries of particleInlets.
Definition variables.h:1065
LESModelType
Identifies the subgrid-scale closure evaluated during a timestep.
Definition variables.h:583
@ NO_LES_MODEL
Definition variables.h:584
@ WALE
Definition variables.h:588
PetscInt MHV
Definition variables.h:955
PetscBool mom_nk_monitor_history
Definition variables.h:975
PetscInt particlesPerCellMax
Most particles in any cell after the step.
Definition variables.h:1070
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
PetscInt movefsi
Definition variables.h:950
PetscBool continueMode
Definition variables.h:935
PetscInt moveframe
Definition variables.h:951
PetscInt TwoD
Definition variables.h:951
PetscInt pseudo_periodic
Definition variables.h:1010
PetscBool profilingFinalSummary
Definition variables.h:1107
PetscReal schmidt_number
Definition variables.h:1005
PetscMPIInt rank
Definition variables.h:919
PetscInt LV
Heart-valve flux corrections for immersed bodies; refused at setup.
Definition variables.h:955
PetscReal angle
Definition variables.h:1000
PetscBool verifyGhostUpdates
-picurv_verify_ghost_updates: test-only cross-checks of skipped or partial ghost updates,...
Definition variables.h:1108
PetscReal Turbulent_schmidt_number
Definition variables.h:1005
PetscInt64 searchLocatedCount
Definition variables.h:283
PetscInt statisticsConsoleOutputFreq
Definition variables.h:991
PetscInt block_number
Definition variables.h:1009
PetscReal mom_rtol
Definition variables.h:960
PetscInt64 searchLostCount
Definition variables.h:284
PetscInt da_procs_z
Definition variables.h:1013
PetscReal targetVolumetricFlux
Definition variables.h:1024
PetscBool walltimeGuardActive
Definition variables.h:1110
PetscReal mom_last_lambda_max
Definition variables.h:974
PetscReal walltimeGuardWarmupTotalSeconds
Definition variables.h:1118
LESConfig les_config
Parameters of the LES closure selected by les.
Definition variables.h:1046
PetscReal forceScalingFactor
Definition variables.h:1018
PetscReal pseudo_cfl_reduction_factor
Definition variables.h:966
ParticleInitializationType
Enumerator to identify the particle initialization strategy.
Definition variables.h:746
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
PetscReal StartTime
Definition variables.h:932
PetscReal * solutionConvergenceMeanSpeedHistory
Definition variables.h:985
PetscReal FluxOutSum
Definition variables.h:1016
PetscBool walltimeGuardHasEWMA
Definition variables.h:1120
PetscReal CMy_c
Definition variables.h:1001
PetscInt nTracePIDs
Number of entries in tracePIDs (at most PICURV_MAX_TRACED_PARTICLES).
Definition variables.h:1089
PetscBool runtimeMemoryLogEnabled
Enable the rank-reduced runtime memory log (log_dir/Runtime_Memory.csv).
Definition variables.h:1123
char ** bcs_files
Definition variables.h:1015
PetscReal boundaryVelocityCorrection
Definition variables.h:1031
PetscReal max_angle
Definition variables.h:1000
PetscReal min_pseudo_cfl
Definition variables.h:967
PetscInt64 boundaryClampCount
Definition variables.h:290
PetscInt particlesLostLastStep
Particles removed this step because their search failed.
Definition variables.h:1057
PetscInt tiout
Definition variables.h:928
PetscBool inflowFluctuationsRestored
That state was read from the restart checkpoint.
Definition variables.h:1044
PetscReal walltimeGuardMinSeconds
Definition variables.h:1113
char allowedFile[PETSC_MAX_PATH_LEN]
Definition variables.h:1083
PetscInt da_procs_y
Definition variables.h:1013
PetscInt64 traversalStepsSum
Definition variables.h:285
PetscBool mom_last_converged
Definition variables.h:971
PetscReal psrc_x
Definition variables.h:1002
PetscReal ren
Definition variables.h:965
PetscReal iem_constant
IEM mixing constant C_IEM in Omega = C_IEM Gamma / Delta^2 (default 2.0).
Definition variables.h:1006
PetscInt solutionConvergenceSamplesRecorded
Definition variables.h:984
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscBool drivenFluxTargetLatched
Definition variables.h:1029
IBMVNodes * ibmv
Definition variables.h:1078
PetscInt64 searchPopulation
Definition variables.h:282
char output_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:940
PetscBool solutionConvergenceEnabled
Definition variables.h:980
PetscReal * solutionConvergenceMeanKEHistory
Definition variables.h:986
PetscReal walltimeGuardLatestStepSeconds
Definition variables.h:1122
PetscReal dt
Definition variables.h:933
PetscInt occupiedCellCount
Definition variables.h:1068
PetscInt StepsToRun
Definition variables.h:927
char profilingTimestepMode[32]
Definition variables.h:1106
PetscInt k_periodic
Definition variables.h:1010
PetscInt inletprofile
Definition variables.h:1009
PetscReal bulkVelocityCorrection
Definition variables.h:1030
PetscReal cdisy
Definition variables.h:965
PetscReal mom_atol
Definition variables.h:960
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
@ WALL_FUNCTION_CABOT
Definition variables.h:604
@ WALL_FUNCTION_NONE
Definition variables.h:601
PetscInt currentSettlementPass
Definition variables.h:299
PetscInt np
Definition variables.h:1049
PetscBool fieldStatisticsEnabled
Definition variables.h:988
PetscBool no_pseudo_cfl_backtrack
Definition variables.h:969
PetscReal C_IEM
Definition variables.h:1074
PetscInt ccc
Definition variables.h:1037
PetscBool skipFinalCheckpoint
io.write_final_checkpoint false: no end-of-run bundle.
Definition variables.h:930
PetscReal ratio
Definition variables.h:1038
PetscInt StartStep
Definition variables.h:926
PetscBool OnlySetup
Definition variables.h:934
PetscInt rotatefsi
Refused at setup: immersed boundaries and moving bodies are not implemented.
Definition variables.h:950
@ MOMENTUM_SOLVER_DUALTIME_PICARD_JAMESON_RK
Definition variables.h:731
@ MOMENTUM_SOLVER_EXPLICIT_RK
Definition variables.h:730
@ MOMENTUM_SOLVER_NEWTON_KRYLOV
Definition variables.h:732
PetscInt solutionConvergencePeriodSteps
Definition variables.h:982
PetscReal cdisz
Definition variables.h:965
PetscInt64 reSearchCount
Definition variables.h:286
char * current_io_directory
Definition variables.h:944
PetscReal MaxDiv
Definition variables.h:1096
struct PicurvExpression * expression
Compiled expression, or NULL when the field is not configured.
Definition variables.h:276
char grid_file[PETSC_MAX_PATH_LEN]
Definition variables.h:1012
PetscInt invicid
Definition variables.h:951
char ** allowedFuncs
Definition variables.h:1085
PetscReal particlesExitedScalarLastStep
Sum of Psi over the particles that left the domain this step.
Definition variables.h:1062
PetscInt64 bboxGuessFallbackCount
Definition variables.h:292
InterpolationMethod interpolationMethod
Definition variables.h:1055
PetscReal psrc_z
Point source location for PARTICLE_INIT_POINT_SOURCE.
Definition variables.h:1002
PetscInt mg_poItr
Definition variables.h:961
PetscReal max_pseudo_cfl
Definition variables.h:967
VerificationFieldConfig verificationDiffusivity
Definition variables.h:996
PetscInt MaxDivx
Definition variables.h:1097
PetscInt poisson
Definition variables.h:962
PetscInt mom_unconverged_streak
Definition variables.h:973
char profilingSelectedFuncsFile[PETSC_MAX_PATH_LEN]
Definition variables.h:1099
PetscInt MaxDivy
Definition variables.h:1097
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
char particleRestartMode[16]
Definition variables.h:1056
PetscInt64 bboxGuessSuccessCount
Definition variables.h:291
PetscInt MaxDivz
Definition variables.h:1097
BoundingBox * bboxlist
Definition variables.h:1053
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscInt MaxDivFlatArg
Definition variables.h:1097
PetscReal FluxInSum
Definition variables.h:1016
PetscInt walltimeGuardCompletedSteps
Definition variables.h:1117
PetscInt64 maxParticlePassDepth
Definition variables.h:293
PetscInt les_gradient_model
Add the Clark gradient (tensor-diffusivity) term to the viscous flux.
Definition variables.h:1045
PetscReal CMz_c
Definition variables.h:1001
PetscInt64 maxTraversalSteps
Definition variables.h:287
PetscBool generate_grid
Definition variables.h:1011
PetscInt64 particlesLostCumulative
Definition variables.h:1058
char eulerianSource[PETSC_MAX_PATH_LEN]
Definition variables.h:938
PetscReal imp_stol
Definition variables.h:960
PetscInt nAllowed
Definition variables.h:1086
PetscBool walltimeGuardEnabled
Definition variables.h:1109
PetscBool checkpointGeometryHashReady
Definition variables.h:946
PetscReal wall_roughness_height
Definition variables.h:1004
PetscBool useProfilingSelectedFuncsCfg
Definition variables.h:1100
PetscInt walltimeGuardWarmupSteps
Definition variables.h:1111
ParticleInitializationType ParticleInitialization
Definition variables.h:1054
PetscReal mom_dt_jameson_residual_norm_noise_allowance_factor
Definition variables.h:968
InterpolationMethod
Selects the grid-to-particle interpolation method.
Definition variables.h:760
@ INTERP_TRILINEAR
Definition variables.h:761
PetscReal particlesPerCellMean
Particles counted in cells divided by the cell count.
Definition variables.h:1071
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
PetscInt drivingForceStep
Definition variables.h:1023
PetscReal Flux_in
Definition variables.h:1000
PetscReal drivenFluxMeasured
Definition variables.h:1035
PetscBool runtimeMemoryLogHasPrevious
True after the first process-memory sample.
Definition variables.h:1126
char ** profilingSelectedFuncs
Definition variables.h:1101
PetscReal cdisx
Definition variables.h:965
PetscInt mglevels
Definition variables.h:961
PetscInt num_bcs_files
Definition variables.h:1014
PetscInt64 particlesExitedCumulative
Definition variables.h:1061
DM dm_swarm
Definition variables.h:1052
PetscBool useCfg
Definition variables.h:1084
PetscReal psrc_y
Definition variables.h:1002
PetscInt solutionConvergenceWindowSteps
Definition variables.h:983
PetscInt central
Definition variables.h:963
PetscInt particlesExitedLastStep
Particles removed this step because they left the domain.
Definition variables.h:1060
PetscReal Fluxsum
Definition variables.h:1016
PetscReal pseudo_cfl_growth_factor
Definition variables.h:966
PetscInt mom_max_unconverged_steps
Definition variables.h:972
PetscInt nProfilingSelectedFuncs
Definition variables.h:1102
PetscInt particlesMigratedLastStep
Definition variables.h:1067
PetscInt particleRandomSeed
Base seed for every particle RNG stream (-particle_random_seed).
Definition variables.h:1050
char initialConditionDirectory[PETSC_MAX_PATH_LEN]
Definition variables.h:979
PetscInt64 * tracePIDs
Sorted, distinct IDs of the particles whose every stage is reported (-picurv_trace_particles); NULL w...
Definition variables.h:1088
PetscInt da_procs_x
Definition variables.h:1013
PetscReal walltimeGuardWarmupAverageSeconds
Definition variables.h:1119
PetscInt sourceRandomSeed
Seed of the draws in velocity and pressure sources (-source_random_seed).
Definition variables.h:1051
PetscInt particleConsoleOutputFreq
Definition variables.h:931
PetscBool initialConditionStaged
Definition variables.h:977
SearchMetricsState searchMetrics
Definition variables.h:1073
PetscInt i_periodic
Definition variables.h:1010
PetscBool skipInitialCheckpoint
io.write_initial_checkpoint false: no initial/branch_start bundle.
Definition variables.h:929
PetscReal mom_resid_rtol
Definition variables.h:960
char checkpointGeometrySHA256[65]
Definition variables.h:945
PetscReal runtimeMemoryLogPreviousProcessMB
Previous local process memory sample in MB.
Definition variables.h:1127
PetscInt step
Definition variables.h:924
PetscReal walltimeGuardEWMASeconds
Definition variables.h:1121
PetscReal AreaOutSum
Definition variables.h:1036
PetscInt mom_max_pseudo_steps
Definition variables.h:959
PetscReal drivenFluxArea
Definition variables.h:1035
PostProcessParams * pps
Definition variables.h:1131
PetscInt migrationPassesLastStep
Definition variables.h:1066
InitialConditionField
Selects the authoritative velocity representation in a staged file IC.
Definition variables.h:201
@ IC_FIELD_UCONT
Definition variables.h:203
@ IC_FIELD_UCAT
Definition variables.h:202
PetscMPIInt size
Definition variables.h:920
char _io_context_buffer[PETSC_MAX_PATH_LEN]
Definition variables.h:943
PetscReal walltimeGuardLimitSeconds
Definition variables.h:1116
PetscBool ps_ksp_pic_monitor_true_residual
Definition variables.h:976
PetscBool profilingAllHelpers
-profiling_helpers all: every helper timer is enabled.
Definition variables.h:1105
PetscReal walltimeGuardEstimatorAlpha
Definition variables.h:1114
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
@ SOLUTION_CONVERGENCE_TRANSIENT
Definition variables.h:742
@ SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC
Definition variables.h:740
@ SOLUTION_CONVERGENCE_STATISTICAL_STEADY
Definition variables.h:741
@ SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC
Definition variables.h:739
PetscInt mg_preItr
Definition variables.h:961
PetscReal mom_ratio_ema_alpha
Definition variables.h:970
SolutionConvergenceMode solutionConvergenceMode
Definition variables.h:981
PetscViewer logviewer
Definition variables.h:936
char ** profilingHelpers
Helper functions whose timers are enabled (-profiling_helpers).
Definition variables.h:1103
PetscReal particlesLostScalarLastStep
Sum of Psi over the particles removed this step as LOST.
Definition variables.h:1059
PetscInt64 searchAttempts
Definition variables.h:281
InitialConditionField initialConditionField
Definition variables.h:978
PetscInt64 tieBreakCount
Definition variables.h:289
PetscReal mom_resid_atol
Definition variables.h:960
PetscBool restartHistoryAvailable
Definition variables.h:947
PetscReal ti
Definition variables.h:925
PetscReal walltimeGuardMultiplier
Definition variables.h:1112
PetscInt rotateframe
moveframe/rotateframe are refused at setup.
Definition variables.h:951
IBMNodes * ibm
Definition variables.h:1077
PetscReal AreaInSum
Definition variables.h:1036
#define PICURV_MAX_TRACED_PARTICLES
Most particle IDs one run can trace (-picurv_trace_particles).
Definition variables.h:69
MomentumSolverType mom_solver_type
Definition variables.h:958
PetscInt immersed
Definition variables.h:950
PetscInt64 maxTraversalFailCount
Definition variables.h:288
char PostprocessingControlFile[PETSC_MAX_PATH_LEN]
Definition variables.h:1130
char restart_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:939
PetscReal walltimeGuardJobStartEpochSeconds
Definition variables.h:1115
PetscReal pseudo_cfl
Definition variables.h:965
PetscInt nProfilingHelpers
Definition variables.h:1104
PetscInt LoggingFrequency
Definition variables.h:1087
VerificationFieldConfig verificationScalar
Definition variables.h:997
PetscReal CMx_c
Definition variables.h:1001
PetscReal drivingForceMagnitude
Definition variables.h:1018
struct ParticleInlet * particleInlets
Inlet faces that inject particles, or NULL.
Definition variables.h:1064
PetscReal lastStepWallSeconds
Slowest rank's wall time of the last completed step (0 before one).
Definition variables.h:1128
PetscReal particleLoadImbalance
Definition variables.h:1072
struct ParticleFieldPlan * particleFieldPlan
Configured initial particle-field values, or NULL.
Definition variables.h:1063
PetscBool fieldStatisticsContinue
Definition variables.h:995
PetscInt runCsvWrittenCount
Entries of runCsvWritten in use.
Definition variables.h:1125
PetscInt j_periodic
Definition variables.h:1010
FSInfo * fsi
Definition variables.h:1079
The master context for the entire simulation.
Definition variables.h:916
PetscErrorCode VerificationFieldsCreate(SimCtx *simCtx)
Reads and compiles the configured verification fields (-verification_*_expr).
PetscBool VerificationScalarOverrideActive(const SimCtx *simCtx)
Reports whether a verification-only scalar override is active.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RuntimeWalltimeGuardParsePositiveSeconds()

PetscBool RuntimeWalltimeGuardParsePositiveSeconds ( const char *  text,
PetscReal *  seconds_out 
)

Parse a positive floating-point seconds value from runtime metadata.

This helper is used for shell-exported walltime metadata such as PICURV_JOB_START_EPOCH and PICURV_WALLTIME_LIMIT_SECONDS.

Parameters
[in]textString to parse.
[out]seconds_outParsed positive seconds value when successful.
Returns
PetscBool PETSC_TRUE when parsing succeeds, else PETSC_FALSE.

Parse a positive floating-point seconds value from runtime metadata.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
RuntimeWalltimeGuardParsePositiveSeconds()

Definition at line 144 of file setup.c.

145{
147 char *endptr = NULL;
148 double parsed_value;
149
150 if (seconds_out) *seconds_out = 0.0;
151 if (!text || text[0] == '\0') { PROFILE_HELPER_END; return PETSC_FALSE; }
152
153 errno = 0;
154 parsed_value = strtod(text, &endptr);
155 if (endptr == text || errno == ERANGE || !isfinite(parsed_value) || parsed_value <= 0.0) {
157 return PETSC_FALSE;
158 }
159
160 while (*endptr != '\0' && isspace((unsigned char)*endptr)) {
161 endptr++;
162 }
163 if (*endptr != '\0') { PROFILE_HELPER_END; return PETSC_FALSE; }
164
165 if (seconds_out) *seconds_out = (PetscReal)parsed_value;
167 return PETSC_TRUE;
168}
Here is the caller graph for this function:

◆ SetupSimulationEnvironment()

PetscErrorCode SetupSimulationEnvironment ( SimCtx *  simCtx)

Verifies and prepares the complete I/O environment for a simulation run.

This function performs a comprehensive series of checks and setup actions to ensure a valid and clean environment. It is parallel-safe; all filesystem operations and checks are performed by Rank 0, with collective error handling.

The function's responsibilities include:

  1. Checking Mandatory Inputs: Verifies existence of grid and BCs files.
  2. Checking Optional Inputs: Warns if optional config files (whitelist, profile) are missing.
  3. Validating Run Mode Paths: Ensures restart_dir or post-processing source directories exist when needed.
  4. Preparing Log Directory: Creates the log directory and cleans it of previous logs.
  5. Preparing Output Directories: Creates the main output directory and its required subdirectories.
Parameters
[in]simCtxThe fully configured SimulationContext object.
Returns
PetscErrorCode Returns 0 on success, or a non-zero error code if a mandatory file/directory is missing or a critical operation fails.

Verifies and prepares the complete I/O environment for a simulation run.

See also
SetupSimulationEnvironment()

Definition at line 1728 of file setup.c.

1729{
1730 PetscErrorCode ierr;
1731 PetscMPIInt rank;
1732 PetscBool exists;
1733
1734 PetscFunctionBeginUser;
1736 rank = simCtx->rank;
1737
1738 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Setting up simulation environment ---\n");
1739
1740 /* The walltime guard bounds the solver's time loop. The postprocessor reads the same
1741 * control file but never runs that loop, so only the solver resolves the job clock. */
1742 if (simCtx->exec_mode == EXEC_MODE_SOLVER && simCtx->walltimeGuardEnabled) {
1743 const char *job_start_env = getenv("PICURV_JOB_START_EPOCH");
1744 const char *limit_env = getenv("PICURV_WALLTIME_LIMIT_SECONDS");
1745 PetscBool job_start_ok = RuntimeWalltimeGuardParsePositiveSeconds(job_start_env, &simCtx->walltimeGuardJobStartEpochSeconds);
1746 PetscBool limit_ok = RuntimeWalltimeGuardParsePositiveSeconds(limit_env, &simCtx->walltimeGuardLimitSeconds);
1747
1748 if (!job_start_ok || !limit_ok) {
1749 simCtx->walltimeGuardActive = PETSC_FALSE;
1751 simCtx->walltimeGuardLimitSeconds = 0.0;
1752 LOG_ALLOW(
1753 GLOBAL,
1755 "Runtime walltime guard enabled but %s/%s are missing or invalid. Falling back to external shutdown signals only.\n",
1756 "PICURV_JOB_START_EPOCH",
1757 "PICURV_WALLTIME_LIMIT_SECONDS"
1758 );
1759 } else {
1760 simCtx->walltimeGuardActive = PETSC_TRUE;
1761 }
1762 }
1763
1764 /* =====================================================================
1765 * Phase 1: Check for all required and optional INPUT files.
1766 * ===================================================================== */
1767 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Phase 1: Verifying input files...\n");
1768
1769 // --- Mandatory Inputs ---
1770 if (!simCtx->generate_grid) {
1771 ierr = VerifyPathExistence(simCtx->grid_file, PETSC_FALSE, PETSC_FALSE, "Grid file", &exists); CHKERRQ(ierr);
1772 }
1773 for (PetscInt i = 0; i < simCtx->num_bcs_files; i++) {
1774 char desc[128];
1775 ierr = PetscSNPrintf(desc, sizeof(desc), "BCS file #%" PetscInt_FMT "", i + 1); CHKERRQ(ierr);
1776 ierr = VerifyPathExistence(simCtx->bcs_files[i], PETSC_FALSE, PETSC_FALSE, desc, &exists); CHKERRQ(ierr);
1777 }
1778
1779 // --- Optional Inputs (these produce warnings if missing) ---
1780 if (simCtx->useCfg) {
1781 ierr = VerifyPathExistence(simCtx->allowedFile, PETSC_FALSE, PETSC_TRUE, "Whitelist config file", &exists); CHKERRQ(ierr);
1782 }
1783 if (simCtx->useProfilingSelectedFuncsCfg) {
1784 ierr = VerifyPathExistence(simCtx->profilingSelectedFuncsFile, PETSC_FALSE, PETSC_TRUE, "Profiling config file", &exists); CHKERRQ(ierr);
1785 }
1786 if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) {
1787 ierr = VerifyPathExistence(simCtx->PostprocessingControlFile, PETSC_FALSE, PETSC_TRUE, "Post-processing control file", &exists); CHKERRQ(ierr);
1788 }
1789
1790
1791 /* =====================================================================
1792 * Phase 2: Validate directories specific to the execution mode.
1793 * ===================================================================== */
1794 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Phase 2: Verifying execution mode directories...\n");
1795 // The data source directory must exist if we intend to load any data from it.
1796 // This is true if:
1797 // 1. We are restarting from a previous time step (StartStep > 0), which implies
1798 // loading Eulerian fields and/or particle fields.
1799 // 2. We are starting from t=0 but are explicitly told to load the initial
1800 // Eulerian fields from a file (eulerianSource == "load").
1801 if (simCtx->StartStep > 0 || strcmp(simCtx->eulerianSource,"load")== 0){ // If this is a restart run
1802 ierr = VerifyPathExistence(simCtx->restart_dir, PETSC_TRUE, PETSC_FALSE, "Restart source directory", &exists); CHKERRQ(ierr);
1803 }
1804 if (simCtx->StartStep == 0 && strcmp(simCtx->eulerianSource, "solve") == 0 &&
1805 simCtx->initialConditionStaged) {
1806 ierr = VerifyPathExistence(simCtx->initialConditionDirectory, PETSC_TRUE, PETSC_FALSE,
1807 "Initial-condition source directory", &exists); CHKERRQ(ierr);
1808 }
1809 if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) {
1810 ierr = VerifyPathExistence(simCtx->pps->source_dir, PETSC_TRUE, PETSC_FALSE, "Post-processing source directory", &exists); CHKERRQ(ierr);
1811 }
1812
1813 /* =====================================================================
1814 * Phase 3: Create and prepare all OUTPUT directories.
1815 * ===================================================================== */
1816 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Phase 3: Preparing output directories...\n");
1817
1818 if (rank == 0){
1819 if(simCtx->exec_mode == EXEC_MODE_SOLVER){
1820 // --- Prepare Log Directory ---
1821 if (!simCtx->continueMode) {
1822 // Only wipe logs on fresh runs; continue mode appends to existing logs.
1823 // Final guard: this delete is recursive and irreversible, so re-check
1824 // containment here rather than trusting that the launcher validated it.
1825 {
1826 PetscBool unsafe_authorized = PETSC_FALSE;
1827 const char *refusal = NULL;
1828 ierr = PetscOptionsGetBool(NULL, NULL, "-allow_unsafe_log_dir",
1829 &unsafe_authorized, NULL); CHKERRQ(ierr);
1830 if (!LogDirectoryIsSafeToWipe(simCtx->log_dir, simCtx->output_dir,
1831 unsafe_authorized, &refusal)) {
1832 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1833 "Refusing to delete log directory '%s': it %s. Configure run "
1834 "directories through monitor.io.directories.",
1835 simCtx->log_dir, refusal);
1836 }
1837 if (unsafe_authorized) {
1839 "Deleting log directory '%s' outside the working directory, "
1840 "authorized by -allow_unsafe_log_dir.\n", simCtx->log_dir);
1841 }
1842 }
1843 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Creating/cleaning log directory: %s\n", simCtx->log_dir);
1844 ierr = PetscRMTree(simCtx->log_dir); // Wipes the directory and its contents
1845 if (ierr) { /* Ignore file-not-found error, but fail on others */
1846 PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, "Could not remove existing log directory '%s'. Check permissions.", simCtx->log_dir);
1847 }
1848 ierr = PetscMkdir(simCtx->log_dir); CHKERRQ(ierr);
1849 } else {
1850 // In continue mode, ensure log directory exists but don't wipe it.
1851 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Continue mode: preserving existing log directory: %s\n", simCtx->log_dir);
1852 ierr = PetscMkdir(simCtx->log_dir); CHKERRQ(ierr);
1853 }
1854
1855 // --- Prepare Output Directory ---
1856 // The checkpoint coordinator creates its fixed internal hierarchy
1857 // transactionally when a checkpoint is due.
1858 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Verifying main output directory: %s\n", simCtx->output_dir);
1859 ierr = PetscTestDirectory(simCtx->output_dir, 'r', &exists); CHKERRQ(ierr);
1860 if (!exists) {
1861 LOG_ALLOW(GLOBAL, LOG_INFO, "Output directory not found. Creating: %s\n", simCtx->output_dir);
1862 ierr = PetscMkdir(simCtx->output_dir); CHKERRQ(ierr);
1863 }
1864 // The analysis home is nested (output/analysis/metrics by default), so it
1865 // needs the recursive create the postprocessor branch already uses; PetscMkdir
1866 // fails on a path whose parents do not exist yet.
1867 ierr = PetscMkdirRecursive(simCtx->analysis_dir); CHKERRQ(ierr);
1868 } else if(simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR){
1869 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Preparing post-processing output directories ...\n");
1870
1871 PostProcessParams *pps = simCtx->pps;
1872 char path_buffer[PETSC_MAX_PATH_LEN];
1873
1874 const char *last_slash_euler = strrchr(pps->output_prefix, '/');
1875 if(last_slash_euler){
1876 size_t dir_len = last_slash_euler - pps->output_prefix;
1877 if(dir_len > 0){
1878 if(dir_len >= sizeof(path_buffer)) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_WRONG,"Post-processing output prefix path is too long.");
1879 strncpy(path_buffer, pps->output_prefix, dir_len);
1880 path_buffer[dir_len] = '\0';
1881
1882 ierr = PetscTestDirectory(path_buffer, 'r', &exists); CHKERRQ(ierr);
1883 if (!exists){
1884 LOG_ALLOW(GLOBAL, LOG_INFO, "Creating post-processing Eulerian output directory: %s\n", path_buffer);
1885 ierr = PetscMkdirRecursive(path_buffer); CHKERRQ(ierr);
1886 }
1887 }
1888 }
1889
1890 // Particle output directory
1891 if(pps->outputParticles){
1892 const char *last_slash_particle = strrchr(pps->particle_output_prefix, '/');
1893 if(last_slash_particle){
1894 size_t dir_len = last_slash_particle - pps->particle_output_prefix;
1895 if(dir_len > 0){
1896 if(dir_len > sizeof(path_buffer)) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_WRONG,"Post-processing particle output prefix path is too long.");
1897 strncpy(path_buffer, pps->particle_output_prefix, dir_len);
1898 path_buffer[dir_len] = '\0';
1899
1900 ierr = PetscTestDirectory(path_buffer, 'r', &exists); CHKERRQ(ierr);
1901
1902 if (!exists){
1903 LOG_ALLOW(GLOBAL, LOG_INFO, "Creating post-processing Particle output directory: %s\n", path_buffer);
1904 ierr = PetscMkdirRecursive(path_buffer); CHKERRQ(ierr);
1905 }
1906 }
1907 }
1908 }
1909
1910 // Statistics output directory
1911 if(pps->statistics_pipeline[0] != '\0'){
1912 const char *last_slash_stats = strrchr(pps->statistics_output_prefix, '/');
1913 if(last_slash_stats){
1914 size_t dir_len = last_slash_stats - pps->statistics_output_prefix;
1915 if(dir_len > 0){
1916 if(dir_len >= sizeof(path_buffer)) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_WRONG,"Post-processing statistics output prefix path is too long.");
1917 strncpy(path_buffer, pps->statistics_output_prefix, dir_len);
1918 path_buffer[dir_len] = '\0';
1919
1920 ierr = PetscTestDirectory(path_buffer, 'r', &exists); CHKERRQ(ierr);
1921 if (!exists){
1922 LOG_ALLOW(GLOBAL, LOG_INFO, "Creating post-processing Statistics output directory: %s\n", path_buffer);
1923 ierr = PetscMkdirRecursive(path_buffer); CHKERRQ(ierr);
1924 }
1925 }
1926 }
1927 }
1928 }
1929 }
1930
1931 // Synchronize all processes before proceeding
1932 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRMPI(ierr);
1933
1934 /* PETSc opens a -info file during PetscInitialize, before the fresh-run wipe above
1935 removes the log directory it usually lives in. Every later record would then go
1936 to an unlinked file and the run would end with no info log at all, so each rank
1937 reopens its file once the directory exists again. Records from initialization
1938 itself are the only ones lost. */
1939 if (simCtx->exec_mode == EXEC_MODE_SOLVER && !simCtx->continueMode) {
1940 char *info_name = NULL;
1941 FILE *info_file = NULL;
1942 ierr = PetscInfoGetFile(&info_name, &info_file); CHKERRQ(ierr);
1943 if (info_name && info_name[0] != '\0') {
1944 char reopen_name[PETSC_MAX_PATH_LEN];
1945 ierr = PetscStrncpy(reopen_name, info_name, sizeof(reopen_name)); CHKERRQ(ierr);
1946 if (info_file && info_file != PETSC_STDOUT) {
1947 ierr = PetscFClose(PETSC_COMM_SELF, info_file); CHKERRQ(ierr);
1948 }
1949 ierr = PetscInfoSetFile(reopen_name, "w"); CHKERRQ(ierr);
1950 }
1951 /* PetscInfoGetFile hands back its own copy of the name. */
1952 ierr = PetscFree(info_name); CHKERRQ(ierr);
1953 }
1954
1955 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Environment setup complete ---\n");
1956
1958 PetscFunctionReturn(0);
1959}
PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists)
A parallel-safe helper to verify the existence of a generic file or directory path.
Definition io.c:1202
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
static PetscBool LogDirectoryIsSafeToWipe(const char *log_dir, const char *output_dir, PetscBool authorized, const char **reason)
Final safety guard before the runtime deletes its log directory.
Definition setup.c:1712
static PetscErrorCode PetscMkdirRecursive(const char *path)
Create a directory path recursively using PETSc-compatible error handling.
Definition setup.c:1250
PetscBool RuntimeWalltimeGuardParsePositiveSeconds(const char *text, PetscReal *seconds_out)
Implementation of RuntimeWalltimeGuardParsePositiveSeconds().
Definition setup.c:144
char statistics_output_prefix[256]
basename for CSV output, e.g.
Definition variables.h:816
char particle_output_prefix[256]
Definition variables.h:811
char output_prefix[256]
Definition variables.h:808
char statistics_pipeline[1024]
e.g.
Definition variables.h:815
char source_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:795
PetscBool outputParticles
Definition variables.h:803
@ EXEC_MODE_SOLVER
Definition variables.h:888
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
ExecutionMode exec_mode
Definition variables.h:937
Holds all configuration parameters for a post-processing run.
Definition variables.h:793
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetupGridAndSolvers()

PetscErrorCode SetupGridAndSolvers ( SimCtx *  simCtx)

The main orchestrator for setting up all grid-related components.

This function is the high-level driver for creating the entire computational domain, including the multigrid hierarchy, PETSc DMDA and Vec objects, and calculating all necessary grid metrics.

Parameters
simCtxThe fully configured SimulationContext.
Returns
PetscErrorCode

The main orchestrator for setting up all grid-related components.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
SetupGridAndSolvers()

Definition at line 2066 of file setup.c.

2067{
2068 PetscErrorCode ierr;
2069 PetscFunctionBeginUser;
2070
2072
2073 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting Grid and Solvers Setup ---\n");
2074
2075 // Phase 1: Allocate the UserMG and UserCtx hierarchy
2076 ierr = AllocateContextHierarchy(simCtx); CHKERRQ(ierr);
2077
2078 ierr = DefineAllGridDimensions(simCtx); CHKERRQ(ierr);
2079 ierr = InitializeAllGridDMs(simCtx); CHKERRQ(ierr);
2080 ierr = AssignAllGridCoordinates(simCtx); CHKERRQ(ierr);
2081 ierr = CreateAndInitializeAllVectors(simCtx); CHKERRQ(ierr);
2082
2083 // NOTE: CalculateAllGridMetrics is now called inside SetupBoundaryConditions (not here) to ensure:
2084 // 1. Boundary condition configuration data (boundary_faces) is available for periodic BC corrections
2085 // 2. Computed metrics are available for inlet/outlet area calculations
2086 // This resolves the circular dependency between BC setup and metric calculations.
2087
2088 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Grid and Solvers Setup Complete ---\n");
2089
2091 PetscFunctionReturn(0);
2092}
PetscErrorCode DefineAllGridDimensions(SimCtx *simCtx)
Orchestrates the parsing and setting of grid dimensions for all blocks.
Definition grid.c:38
PetscErrorCode InitializeAllGridDMs(SimCtx *simCtx)
Orchestrates the creation of DMDA objects for every block and multigrid level.
Definition grid.c:309
PetscErrorCode AssignAllGridCoordinates(SimCtx *simCtx)
Orchestrates the assignment of physical coordinates to all DMDA objects.
Definition grid.c:389
PetscErrorCode CreateAndInitializeAllVectors(SimCtx *simCtx)
Implementation of CreateAndInitializeAllVectors().
Definition setup.c:2099
static PetscErrorCode AllocateContextHierarchy(SimCtx *simCtx)
Allocate the user-context objects required by every multigrid level.
Definition setup.c:1964
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CreateAndInitializeAllVectors()

PetscErrorCode CreateAndInitializeAllVectors ( SimCtx *  simCtx)

Creates and initializes all PETSc Vec objects for all fields.

This function iterates through every UserCtx in the multigrid and multi-block hierarchy. For each context, it creates the comprehensive set of global and local PETSc Vecs required by the flow solver (e.g., Ucont, P, Nvert, metrics, turbulence fields, etc.). Each vector is initialized to zero.

Parameters
simCtxThe master SimCtx, containing the configured UserCtx hierarchy.
Returns
PetscErrorCode

Creates and initializes all PETSc Vec objects for all fields.

See also
CreateAndInitializeAllVectors()

Definition at line 2099 of file setup.c.

2100{
2101 PetscErrorCode ierr;
2102 UserMG *usermg = &simCtx->usermg;
2103 MGCtx *mgctx = usermg->mgctx;
2104 PetscInt nblk = simCtx->block_number;
2105
2106 PetscFunctionBeginUser;
2107
2109
2110 LOG_ALLOW(GLOBAL, LOG_INFO, "Creating and initializing all simulation vectors...\n");
2111
2112 for (PetscInt level = usermg->mglevels-1; level >=0; level--) {
2113 for (PetscInt bi = 0; bi < nblk; bi++) {
2114 UserCtx *user = &mgctx[level].user[bi];
2115
2116 if(!user->da || !user->fda) {
2117 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "DMs not properly initialized in UserCtx before vector creation.");
2118 }
2119
2120 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Creating vectors for level %" PetscInt_FMT ", block %" PetscInt_FMT "\n", simCtx->rank, level, bi);
2121
2122 // --- Group A: Primary Flow Fields (Global and Local) ---
2123 // These are the core solution variables.
2124 ierr = DMCreateGlobalVector(user->fda, &user->Ucont); CHKERRQ(ierr); ierr = VecSet(user->Ucont, 0.0); CHKERRQ(ierr);
2125 ierr = DMCreateGlobalVector(user->fda, &user->Ucat); CHKERRQ(ierr); ierr = VecSet(user->Ucat, 0.0); CHKERRQ(ierr);
2126 ierr = DMCreateGlobalVector(user->da, &user->P); CHKERRQ(ierr); ierr = VecSet(user->P, 0.0); CHKERRQ(ierr);
2127 ierr = DMCreateGlobalVector(user->da, &user->Nvert); CHKERRQ(ierr); ierr = VecSet(user->Nvert, 0.0); CHKERRQ(ierr);
2128
2129 ierr = DMCreateLocalVector(user->fda, &user->lUcont); CHKERRQ(ierr); ierr = VecSet(user->lUcont, 0.0); CHKERRQ(ierr);
2130 ierr = DMCreateLocalVector(user->fda, &user->lUcat); CHKERRQ(ierr); ierr = VecSet(user->lUcat, 0.0); CHKERRQ(ierr);
2131 ierr = DMCreateLocalVector(user->da, &user->lP); CHKERRQ(ierr); ierr = VecSet(user->lP, 0.0); CHKERRQ(ierr);
2132 ierr = DMCreateLocalVector(user->da, &user->lNvert); CHKERRQ(ierr); ierr = VecSet(user->lNvert, 0.0); CHKERRQ(ierr);
2133
2134 // -- Group A2: Derived Flow Fields (Global and Local) ---
2135 ierr = VecDuplicate(user->P,&user->Diffusivity); CHKERRQ(ierr); ierr = VecSet(user->Diffusivity, 0.0); CHKERRQ(ierr);
2136 ierr = VecDuplicate(user->lP,&user->lDiffusivity); CHKERRQ(ierr); ierr = VecSet(user->lDiffusivity, 0.0); CHKERRQ(ierr);
2137 ierr = VecDuplicate(user->Ucat,&user->DiffusivityGradient); CHKERRQ(ierr); ierr = VecSet(user->DiffusivityGradient, 0.0); CHKERRQ(ierr);
2138 ierr = VecDuplicate(user->lUcat,&user->lDiffusivityGradient); CHKERRQ(ierr); ierr = VecSet(user->lDiffusivityGradient, 0.0); CHKERRQ(ierr);
2139
2140 // -- Group B: Solver Work Vectors (Global and Local) ---
2141 ierr = VecDuplicate(user->P, &user->Phi); CHKERRQ(ierr); ierr = VecSet(user->Phi, 0.0); CHKERRQ(ierr);
2142 ierr = VecDuplicate(user->lP, &user->lPhi); CHKERRQ(ierr); ierr = VecSet(user->lPhi, 0.0); CHKERRQ(ierr);
2143
2144 // --- Group C: Time-Stepping & Workspace Fields (Finest Level Only) ---
2145 if (level == usermg->mglevels - 1) {
2146 ierr = VecDuplicate(user->Ucont, &user->Ucont_o); CHKERRQ(ierr); ierr = VecSet(user->Ucont_o, 0.0); CHKERRQ(ierr);
2147 ierr = VecDuplicate(user->Ucont, &user->Ucont_rm1); CHKERRQ(ierr); ierr = VecSet(user->Ucont_rm1, 0.0); CHKERRQ(ierr);
2148 ierr = VecDuplicate(user->Ucat, &user->Ucat_o); CHKERRQ(ierr); ierr = VecSet(user->Ucat_o, 0.0); CHKERRQ(ierr);
2149 ierr = VecDuplicate(user->P, &user->P_o); CHKERRQ(ierr); ierr = VecSet(user->P_o, 0.0); CHKERRQ(ierr);
2150 ierr = VecDuplicate(user->lUcont, &user->lUcont_o); CHKERRQ(ierr); ierr = VecSet(user->lUcont_o, 0.0); CHKERRQ(ierr);
2151 ierr = VecDuplicate(user->lUcont, &user->lUcont_rm1); CHKERRQ(ierr); ierr = VecSet(user->lUcont_rm1, 0.0); CHKERRQ(ierr);
2152 ierr = DMCreateLocalVector(user->da, &user->lNvert_o); CHKERRQ(ierr); ierr = VecSet(user->lNvert_o, 0.0); CHKERRQ(ierr);
2153 ierr = VecDuplicate(user->Nvert, &user->Nvert_o); CHKERRQ(ierr); ierr = VecSet(user->Nvert_o, 0.0); CHKERRQ(ierr);
2154 }
2155
2156 // --- Group D: Grid Metrics (Face-Centered) ---
2157 ierr = DMCreateGlobalVector(user->fda, &user->Csi); CHKERRQ(ierr); ierr = VecSet(user->Csi, 0.0); CHKERRQ(ierr);
2158 ierr = VecDuplicate(user->Csi, &user->Eta); CHKERRQ(ierr); ierr = VecSet(user->Eta, 0.0); CHKERRQ(ierr);
2159 ierr = VecDuplicate(user->Csi, &user->Zet); CHKERRQ(ierr); ierr = VecSet(user->Zet, 0.0); CHKERRQ(ierr);
2160 ierr = DMCreateGlobalVector(user->da, &user->Aj); CHKERRQ(ierr); ierr = VecSet(user->Aj, 0.0); CHKERRQ(ierr);
2161
2162 ierr = DMCreateLocalVector(user->fda, &user->lCsi); CHKERRQ(ierr); ierr = VecSet(user->lCsi, 0.0); CHKERRQ(ierr);
2163 ierr = VecDuplicate(user->lCsi, &user->lEta); CHKERRQ(ierr); ierr = VecSet(user->lEta, 0.0); CHKERRQ(ierr);
2164 ierr = VecDuplicate(user->lCsi, &user->lZet); CHKERRQ(ierr); ierr = VecSet(user->lZet, 0.0); CHKERRQ(ierr);
2165 ierr = DMCreateLocalVector(user->da, &user->lAj); CHKERRQ(ierr); ierr = VecSet(user->lAj, 0.0); CHKERRQ(ierr);
2166
2167
2168 // --- Group E: Grid Metrics (Face-Centered) ---
2169 // Vector metrics are duplicated from Csi (DOF=3, fda-based)
2170 ierr = VecDuplicate(user->Csi, &user->ICsi); CHKERRQ(ierr); ierr = VecSet(user->ICsi, 0.0); CHKERRQ(ierr);
2171 ierr = VecDuplicate(user->Csi, &user->IEta); CHKERRQ(ierr); ierr = VecSet(user->IEta, 0.0); CHKERRQ(ierr);
2172 ierr = VecDuplicate(user->Csi, &user->IZet); CHKERRQ(ierr); ierr = VecSet(user->IZet, 0.0); CHKERRQ(ierr);
2173 ierr = VecDuplicate(user->Csi, &user->JCsi); CHKERRQ(ierr); ierr = VecSet(user->JCsi, 0.0); CHKERRQ(ierr);
2174 ierr = VecDuplicate(user->Csi, &user->JEta); CHKERRQ(ierr); ierr = VecSet(user->JEta, 0.0); CHKERRQ(ierr);
2175 ierr = VecDuplicate(user->Csi, &user->JZet); CHKERRQ(ierr); ierr = VecSet(user->JZet, 0.0); CHKERRQ(ierr);
2176 ierr = VecDuplicate(user->Csi, &user->KCsi); CHKERRQ(ierr); ierr = VecSet(user->KCsi, 0.0); CHKERRQ(ierr);
2177 ierr = VecDuplicate(user->Csi, &user->KEta); CHKERRQ(ierr); ierr = VecSet(user->KEta, 0.0); CHKERRQ(ierr);
2178 ierr = VecDuplicate(user->Csi, &user->KZet); CHKERRQ(ierr); ierr = VecSet(user->KZet, 0.0); CHKERRQ(ierr);
2179 // Scalar metrics are duplicated from Aj (DOF=1, da-based)
2180 ierr = VecDuplicate(user->Aj, &user->IAj); CHKERRQ(ierr); ierr = VecSet(user->IAj, 0.0); CHKERRQ(ierr);
2181 ierr = VecDuplicate(user->Aj, &user->JAj); CHKERRQ(ierr); ierr = VecSet(user->JAj, 0.0); CHKERRQ(ierr);
2182 ierr = VecDuplicate(user->Aj, &user->KAj); CHKERRQ(ierr); ierr = VecSet(user->KAj, 0.0); CHKERRQ(ierr);
2183
2184 ierr = VecDuplicate(user->lCsi, &user->lICsi); CHKERRQ(ierr); ierr = VecSet(user->lICsi, 0.0); CHKERRQ(ierr);
2185 ierr = VecDuplicate(user->lCsi, &user->lIEta); CHKERRQ(ierr); ierr = VecSet(user->lIEta, 0.0); CHKERRQ(ierr);
2186 ierr = VecDuplicate(user->lCsi, &user->lIZet); CHKERRQ(ierr); ierr = VecSet(user->lIZet, 0.0); CHKERRQ(ierr);
2187 ierr = VecDuplicate(user->lCsi, &user->lJCsi); CHKERRQ(ierr); ierr = VecSet(user->lJCsi, 0.0); CHKERRQ(ierr);
2188 ierr = VecDuplicate(user->lCsi, &user->lJEta); CHKERRQ(ierr); ierr = VecSet(user->lJEta, 0.0); CHKERRQ(ierr);
2189 ierr = VecDuplicate(user->lCsi, &user->lJZet); CHKERRQ(ierr); ierr = VecSet(user->lJZet, 0.0); CHKERRQ(ierr);
2190 ierr = VecDuplicate(user->lCsi, &user->lKCsi); CHKERRQ(ierr); ierr = VecSet(user->lKCsi, 0.0); CHKERRQ(ierr);
2191 ierr = VecDuplicate(user->lCsi, &user->lKEta); CHKERRQ(ierr); ierr = VecSet(user->lKEta, 0.0); CHKERRQ(ierr);
2192 ierr = VecDuplicate(user->lCsi, &user->lKZet); CHKERRQ(ierr); ierr = VecSet(user->lKZet, 0.0); CHKERRQ(ierr);
2193
2194 ierr = VecDuplicate(user->lAj, &user->lIAj); CHKERRQ(ierr); ierr = VecSet(user->lIAj, 0.0); CHKERRQ(ierr);
2195 ierr = VecDuplicate(user->lAj, &user->lJAj); CHKERRQ(ierr); ierr = VecSet(user->lJAj, 0.0); CHKERRQ(ierr);
2196 ierr = VecDuplicate(user->lAj, &user->lKAj); CHKERRQ(ierr); ierr = VecSet(user->lKAj, 0.0); CHKERRQ(ierr);
2197
2198 // --- Group F: Cell/Face Center Coordinates and Grid Spacing ---
2199 ierr = DMCreateGlobalVector(user->fda, &user->Cent); CHKERRQ(ierr); ierr = VecSet(user->Cent, 0.0); CHKERRQ(ierr);
2200 ierr = DMCreateLocalVector(user->fda, &user->lCent); CHKERRQ(ierr); ierr = VecSet(user->lCent, 0.0); CHKERRQ(ierr);
2201
2202
2203 ierr = VecDuplicate(user->Cent, &user->Centx); CHKERRQ(ierr); ierr = VecSet(user->Centx, 0.0); CHKERRQ(ierr);
2204 ierr = VecDuplicate(user->Cent, &user->Centy); CHKERRQ(ierr); ierr = VecSet(user->Centy, 0.0); CHKERRQ(ierr);
2205 ierr = VecDuplicate(user->Cent, &user->Centz); CHKERRQ(ierr); ierr = VecSet(user->Centz, 0.0); CHKERRQ(ierr);
2206 ierr = VecDuplicate(user->lCent, &user->lCentx); CHKERRQ(ierr); ierr = VecSet(user->lCentx, 0.0); CHKERRQ(ierr);
2207 ierr = VecDuplicate(user->lCent, &user->lCenty); CHKERRQ(ierr); ierr = VecSet(user->lCenty, 0.0); CHKERRQ(ierr);
2208 ierr = VecDuplicate(user->lCent, &user->lCentz); CHKERRQ(ierr); ierr = VecSet(user->lCentz, 0.0); CHKERRQ(ierr);
2209
2210 if(level == usermg->mglevels -1){
2211 // --- Group G: Turbulence Models (Finest Level Only) ---
2212 if (simCtx->les) {
2213 ierr = DMCreateGlobalVector(user->da, &user->Nu_t); CHKERRQ(ierr); ierr = VecSet(user->Nu_t, 0.0); CHKERRQ(ierr);
2214 ierr = DMCreateLocalVector(user->da, &user->lNu_t); CHKERRQ(ierr); ierr = VecSet(user->lNu_t, 0.0); CHKERRQ(ierr);
2215 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Turbulence viscosity (Nu_t) vectors created for the LES model.\n");
2216 // Only the dynamic model carries a coefficient field. The constant model
2217 // reads its coefficient straight from configuration, so allocating,
2218 // synchronizing, and checkpointing a field of one repeated number would
2219 // buy nothing.
2220 if(simCtx->les == DYNAMIC_SMAGORINSKY){
2221 ierr = DMCreateGlobalVector(user->da,&user->CS); CHKERRQ(ierr); ierr = VecSet(user->CS,0.0); CHKERRQ(ierr);
2222 ierr = DMCreateLocalVector(user->da,&user->lCs); CHKERRQ(ierr); ierr = VecSet(user->lCs,0.0); CHKERRQ(ierr);
2223 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Dynamic Smagorinsky coefficient (CS) vectors created.\n");
2224 }
2225
2226 // Add K_Omega etc. here as needed
2227
2228 // Note: Add any other vectors from the legacy MG_Initial here as needed.
2229 // For example: Rhs, Forcing, turbulence Vecs (K_Omega, Nu_t)...
2230
2231 }
2232
2233 /* A wall model is configured independently of LES and RANS - `wall_function`
2234 is their sibling in the schema, not their child - so its storage cannot sit
2235 inside their block. It did, which left `ApplyWallFunction` dereferencing a
2236 null vector on any case that enabled a wall model without one of them. */
2237 if (simCtx->wallfunction) {
2238 /* Scalar per cell, so it lives on `da`. It was previously created from
2239 `fda`, whose dof is 3, while every reader opens it through `da` - a
2240 pairing PETSc rejects outright. */
2241 ierr = DMCreateGlobalVector(user->da, &user->Friction_Velocity); CHKERRQ(ierr);
2242 ierr = VecSet(user->Friction_Velocity, 0.0); CHKERRQ(ierr);
2243 ierr = DMCreateLocalVector(user->da, &user->lFriction_Velocity); CHKERRQ(ierr);
2244 ierr = VecSet(user->lFriction_Velocity, 0.0); CHKERRQ(ierr);
2245 ierr = DMCreateGlobalVector(user->fda, &user->Wall_Stress); CHKERRQ(ierr);
2246 ierr = VecSet(user->Wall_Stress, 0.0); CHKERRQ(ierr);
2247 ierr = DMCreateLocalVector(user->fda, &user->lWall_Stress); CHKERRQ(ierr);
2248 ierr = VecSet(user->lWall_Stress, 0.0); CHKERRQ(ierr);
2249 }
2250 /* Inlet fluctuation filter state: its inlets write and read the global vector; the
2251 local one exists because every catalogued field has both. */
2252 if (simCtx->inflowFluctuations) {
2253 ierr = DMCreateGlobalVector(user->fda, &user->InflowFluctuation); CHKERRQ(ierr);
2254 ierr = VecSet(user->InflowFluctuation, 0.0); CHKERRQ(ierr);
2255 ierr = DMCreateLocalVector(user->fda, &user->lInflowFluctuation); CHKERRQ(ierr);
2256 ierr = VecSet(user->lInflowFluctuation, 0.0); CHKERRQ(ierr);
2257 }
2258 // --- Group H: Particle Methods
2259 if(ParticlesEnabled(simCtx)){
2260 ierr = DMCreateGlobalVector(user->da,&user->ParticleCount); CHKERRQ(ierr); ierr = VecSet(user->ParticleCount,0.0); CHKERRQ(ierr);
2261 ierr = DMCreateLocalVector(user->da,&user->lParticleCount); CHKERRQ(ierr); ierr = VecSet(user->lParticleCount,0.0); CHKERRQ(ierr);
2262 // Scalar field to hold particle scalar property (e.g., temperature, concentration)
2263 ierr = DMCreateGlobalVector(user->da,&user->Psi); CHKERRQ(ierr); ierr = VecSet(user->Psi,0.0); CHKERRQ(ierr);
2264 ierr = DMCreateLocalVector(user->da,&user->lPsi); CHKERRQ(ierr); ierr = VecSet(user->lPsi,0.0); CHKERRQ(ierr);
2265 LOG_ALLOW(GLOBAL,LOG_DEBUG,"ParticleCount & Scalar(Psi) created for %" PetscInt_FMT " particles.\n",simCtx->np);
2266 }
2267 }
2268 // --- Group I: Boundary Condition vectors ---
2269 ierr = DMCreateGlobalVector(user->fda, &user->Bcs.Ubcs); CHKERRQ(ierr);
2270 ierr = VecSet(user->Bcs.Ubcs, 0.0); CHKERRQ(ierr);
2271 ierr = DMCreateGlobalVector(user->fda, &user->Bcs.Uch); CHKERRQ(ierr);
2272 ierr = VecSet(user->Bcs.Uch, 0.0); CHKERRQ(ierr);
2273
2274 // --- Group L: Field-Statistics Accumulators (Finest Level Only) ---
2275 // Config-counted, like the convergence-state reference fields: the window
2276 // count is resolved before this factory runs, and each accumulator is
2277 // duplicated from a vector created above so it inherits DM and layout.
2278 if (level == usermg->mglevels - 1 && FieldStatisticsNeedsWorkspace(simCtx)) {
2279 ierr = PetscCalloc1((size_t)simCtx->fieldStatisticsWindowCount,
2280 &user->fieldStatisticsStorage); CHKERRQ(ierr);
2281 for (PetscInt w = 0; w < simCtx->fieldStatisticsWindowCount; ++w) {
2282 ierr = PicurvWindowStorageCreate(user,
2284 &user->fieldStatisticsStorage[w]); CHKERRQ(ierr);
2285 }
2287 "Allocated accumulators for %" PetscInt_FMT " statistics window(s).\n",
2289 }
2290
2291 // --- Group K: Corner-Staging Workspace (Finest Level Only) ---
2292 // One pair per block size. Previously these were created lazily inside
2293 // the interpolation routine and rebuilt whenever the block size changed;
2294 // allocating both here removes that churn and the cached-size check.
2295 if (level == usermg->mglevels - 1) {
2296 ierr = DMCreateGlobalVector(user->da, &user->CellScalarAtCorner); CHKERRQ(ierr);
2297 ierr = VecSet(user->CellScalarAtCorner, 0.0); CHKERRQ(ierr);
2298 ierr = DMCreateLocalVector(user->da, &user->lCellScalarAtCorner); CHKERRQ(ierr);
2299 ierr = VecSet(user->lCellScalarAtCorner, 0.0); CHKERRQ(ierr);
2300 ierr = DMCreateGlobalVector(user->fda, &user->CellVectorAtCorner); CHKERRQ(ierr);
2301 ierr = VecSet(user->CellVectorAtCorner, 0.0); CHKERRQ(ierr);
2302 ierr = DMCreateLocalVector(user->fda, &user->lCellVectorAtCorner); CHKERRQ(ierr);
2303 ierr = VecSet(user->lCellVectorAtCorner, 0.0); CHKERRQ(ierr);
2304 }
2305
2306 /* --- Group N: Statistics Output Staging (Finest Level Only) ---
2307 * The same kind of object as the corner workspace: a named buffer the
2308 * shared kernels can address, rather than simulation state. It exists only
2309 * to carry derived statistics to the nodal and VTK paths, so a run without
2310 * statistics allocates none of it. */
2311 if (level == usermg->mglevels - 1 && FieldStatisticsNeedsWorkspace(simCtx)) {
2312 ierr = DMCreateGlobalVector(user->da, &user->PostScalar); CHKERRQ(ierr);
2313 ierr = VecSet(user->PostScalar, 0.0); CHKERRQ(ierr);
2314 ierr = DMCreateLocalVector(user->da, &user->lPostScalar); CHKERRQ(ierr);
2315 ierr = VecSet(user->lPostScalar, 0.0); CHKERRQ(ierr);
2316 ierr = DMCreateGlobalVector(user->da, &user->PostScalarNodal); CHKERRQ(ierr);
2317 ierr = VecSet(user->PostScalarNodal, 0.0); CHKERRQ(ierr);
2318 ierr = DMCreateGlobalVector(user->fda, &user->PostVector); CHKERRQ(ierr);
2319 ierr = VecSet(user->PostVector, 0.0); CHKERRQ(ierr);
2320 ierr = DMCreateLocalVector(user->fda, &user->lPostVector); CHKERRQ(ierr);
2321 ierr = VecSet(user->lPostVector, 0.0); CHKERRQ(ierr);
2322 ierr = DMCreateGlobalVector(user->fda, &user->PostVectorNodal); CHKERRQ(ierr);
2323 ierr = VecSet(user->PostVectorNodal, 0.0); CHKERRQ(ierr);
2324 }
2325
2326 if(level == usermg->mglevels - 1){
2327 if(simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR){
2328 LOG_ALLOW(LOCAL, LOG_DEBUG, "Post-processor mode detected. Allocating derived field vectors.\n");
2329
2330 ierr = VecDuplicate(user->P, &user->P_nodal); CHKERRQ(ierr);
2331 ierr = VecSet(user->P_nodal, 0.0); CHKERRQ(ierr);
2332
2333 ierr = VecDuplicate(user->Ucat, &user->Ucat_nodal); CHKERRQ(ierr);
2334 ierr = VecSet(user->Ucat_nodal, 0.0); CHKERRQ(ierr);
2335
2336 ierr = VecDuplicate(user->P, &user->Qcrit); CHKERRQ(ierr);
2337 ierr = VecSet(user->Qcrit, 0.0); CHKERRQ(ierr);
2338 ierr = DMCreateLocalVector(user->da, &user->lQcrit); CHKERRQ(ierr);
2339 ierr = VecSet(user->lQcrit, 0.0); CHKERRQ(ierr);
2340 ierr = VecDuplicate(user->P, &user->Qcrit_nodal); CHKERRQ(ierr);
2341 ierr = VecSet(user->Qcrit_nodal, 0.0); CHKERRQ(ierr);
2342
2343 LOG_ALLOW(LOCAL, LOG_DEBUG, "Derived field vectors P_nodal, Ucat_nodal, and Qcrit created.\n");
2344
2345 if(ParticlesEnabled(simCtx)){
2346 ierr = VecDuplicate(user->Psi, &user->Psi_nodal); CHKERRQ(ierr);
2347 ierr = VecSet(user->Psi_nodal, 0.0); CHKERRQ(ierr);
2348
2349 LOG_ALLOW(LOCAL, LOG_DEBUG, "Derived field vector Psi_nodal created for particle scalar property.\n");
2350
2351 }
2352 }else{
2353 user->P_nodal = NULL;
2354 user->Ucat_nodal = NULL;
2355 user->Qcrit = NULL;
2356 user->lQcrit = NULL;
2357 user->Qcrit_nodal = NULL;
2358 user->Psi_nodal = NULL;
2359 }
2360 }
2361
2362 }
2363}
2364
2365 /* Config-counted vectors belong to this factory too. The convergence state
2366 * allocates a Vec array whose length comes from configuration, so it is
2367 * invoked here rather than by the caller, keeping every vector this run
2368 * owns created in one place. It depends only on option-parsed configuration
2369 * and on the vectors created above. */
2370 ierr = InitializeSolutionConvergenceState(simCtx); CHKERRQ(ierr);
2371
2372 LOG_ALLOW(GLOBAL, LOG_INFO, "All simulation vectors created and initialized.\n");
2373
2375 PetscFunctionReturn(0);
2376}
PetscErrorCode InitializeSolutionConvergenceState(SimCtx *simCtx)
Implementation of InitializeSolutionConvergenceState().
Definition setup.c:176
PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Allocates the accumulator state one window owns on one block.
PetscBool FieldStatisticsNeedsWorkspace(const struct SimCtx *simCtx)
Reports whether this process derives field statistics of any kind.
PicurvWindowDefinition definition
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
Vec lFriction_Velocity
Definition variables.h:1189
Vec lDiffusivityGradient
Definition variables.h:1201
Vec Wall_Stress
Definition variables.h:1193
Vec Qcrit_nodal
Q-criterion averaged to grid nodes; the field a .vts can place correctly.
Definition variables.h:1284
Vec lPostScalar
Definition variables.h:1219
Vec lCent
Definition variables.h:1244
Vec P_nodal
Definition variables.h:1281
UserCtx * user
Definition variables.h:768
Vec lIEta
Definition variables.h:1254
Vec lIZet
Definition variables.h:1254
Vec lNvert
Definition variables.h:1197
Vec Centz
Definition variables.h:1252
UserMG usermg
Definition variables.h:1082
Vec InflowFluctuation
Definition variables.h:1194
Vec lUcont_rm1
Definition variables.h:1207
Vec lKEta
Definition variables.h:1256
Vec Ucat_nodal
Definition variables.h:1282
Vec PostScalarNodal
Definition variables.h:1219
Vec DiffusivityGradient
Definition variables.h:1201
Vec lJCsi
Definition variables.h:1255
Vec Ucont
Definition variables.h:1197
Vec PostScalar
Definition variables.h:1219
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
Vec Qcrit
Definition variables.h:1283
Vec CellScalarAtCorner
Definition variables.h:1212
Vec Centx
Definition variables.h:1252
Vec lParticleCount
Definition variables.h:1276
Vec lUcont_o
Definition variables.h:1204
Vec CellVectorAtCorner
Definition variables.h:1213
Vec Ucat_o
Definition variables.h:1204
Vec lKZet
Definition variables.h:1256
Vec lNu_t
Definition variables.h:1259
Vec lCellScalarAtCorner
Definition variables.h:1212
Vec lJEta
Definition variables.h:1255
Vec lKCsi
Definition variables.h:1256
Vec ParticleCount
Definition variables.h:1276
Vec Ucont_o
Definition variables.h:1204
Vec lCenty
Definition variables.h:1253
Vec PostVectorNodal
Definition variables.h:1220
PetscInt mglevels
Definition variables.h:775
Vec lWall_Stress
Definition variables.h:1193
Vec Friction_Velocity
Definition variables.h:1189
Vec lJZet
Definition variables.h:1255
Vec Nvert_o
Definition variables.h:1204
Vec lCellVectorAtCorner
Definition variables.h:1213
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
Vec Psi_nodal
Definition variables.h:1285
Vec lPostVector
Definition variables.h:1220
Vec lCentx
Definition variables.h:1253
Vec Ucont_rm1
Definition variables.h:1207
Vec lUcont
Definition variables.h:1197
Vec Diffusivity
Definition variables.h:1200
Vec lICsi
Definition variables.h:1254
Vec lUcat
Definition variables.h:1197
Vec PostVector
Definition variables.h:1220
Vec lQcrit
Cell-centred Q-criterion and its ghosted copy for nodal averaging.
Definition variables.h:1283
Vec Nvert
Definition variables.h:1197
MGCtx * mgctx
Definition variables.h:778
Vec lDiffusivity
Definition variables.h:1200
Vec lNvert_o
Definition variables.h:1204
Vec Centy
Definition variables.h:1252
Vec lCentz
Definition variables.h:1253
Vec lInflowFluctuation
Inlet fluctuation filter state in the inlet faces' dummy planes.
Definition variables.h:1194
Vec Uch
Characteristic velocity for boundary conditions.
Definition variables.h:173
Context for Multigrid operations.
Definition variables.h:767
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
User-level context for managing the entire multigrid hierarchy.
Definition variables.h:774
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateLocalGhosts()

PetscErrorCode UpdateLocalGhosts ( UserCtx *  user,
FieldId  field_id 
)

Updates the local vector (including ghost points) from its corresponding global vector.

This function resolves the correct global vector, local vector, and DM from the authoritative field catalog and performs the standard PETSc DMGlobalToLocalBegin/End sequence. For registered single-face-family and component-staggered fields, it then repairs the adjacent periodic ghost in each normal direction so central differences see the correct neighboring face. Cell-centered fields and tangential face directions retain PETSc's native periodic wraparound. Includes optional debugging output (max norms before/after).

Parameters
userThe UserCtx structure containing the vectors and DMs.
field_idTyped identity of the catalogued field to update.
Returns
PetscErrorCode 0 on success, non-zero on failure.
Note
This function assumes the global vector associated with field_id has already been populated with the desired data (including any boundary conditions and periodic duplicate planes). It scatters that current global state into the local vector; it does not repair stale global periodic duplicate planes.
Wider QUICK-style normal ghost layers require a separate dedicated exchange; this function repairs the adjacent layer used by central stencils.

Updates the local vector (including ghost points) from its corresponding global vector.

Resolves the typed field view, performs the existing PETSc scatter, and applies the established periodic normal-face repair when needed.

Definition at line 2593 of file setup.c.

2594{
2595 PetscErrorCode ierr;
2596 PetscMPIInt rank;
2597 FieldView field_view;
2598 const char *field_name;
2599 Vec globalVec;
2600 Vec localVec;
2601 DM dm;
2602
2603 PetscFunctionBeginUser; // Use User version for application code
2605 rank = user->simCtx->rank;
2606 ierr = FieldGetView(user, field_id, &field_view); CHKERRQ(ierr);
2607 PetscCheck((field_view.descriptor->capabilities & FIELD_CAPABILITY_GHOST_UPDATE) != 0u,
2608 PETSC_COMM_SELF, PETSC_ERR_SUP,
2609 "Field '%s' does not support ghost updates.",
2610 field_view.descriptor->canonical_name);
2611 field_name = field_view.descriptor->canonical_name;
2612 globalVec = field_view.global_vec;
2613 localVec = field_view.local_vec;
2614 dm = field_view.dm;
2615
2616 LOG_ALLOW(GLOBAL, LOG_INFO, "Rank %d: Starting ghost update for field '%s'.\n", rank, field_name);
2617
2618 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Identified components for '%s': DM=%p, GlobalVec=%p, LocalVec=%p.\n",
2619 rank, field_name, (void*)dm, (void*)globalVec, (void*)localVec);
2620
2621 // --- 3. Optional Debugging: Norm Before Update ---
2622 // Use your logging convention check
2623 // if (get_log_level() >= LOG_LEVEL_DEBUG && is_function_allowed("UpdateLocalGhosts")) { // Example check
2624 if(get_log_level() >= LOG_DEBUG && is_function_allowed(__func__)){
2625 PetscReal norm_global_before;
2626 ierr = VecNorm(globalVec, NORM_INFINITY, &norm_global_before); CHKERRQ(ierr);
2627 LOG_ALLOW(GLOBAL, LOG_INFO,"Max norm '%s' (Global) BEFORE Ghost Update: %g\n", field_name, norm_global_before);
2628 // Optional: Norm of local vector before update (might contain old ghost values)
2629 // PetscReal norm_local_before;
2630 // ierr = VecNorm(localVec, NORM_INFINITY, &norm_local_before); CHKERRQ(ierr);
2631 // LOG_ALLOW(GLOBAL, LOG_DEBUG,"Max norm '%s' (Local) BEFORE Ghost Update: %g\n", field_name, norm_local_before);
2632 }
2633
2634 // --- 4. Perform the Global-to-Local Transfer (Ghost Update) ---
2635 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Calling DMGlobalToLocalBegin/End for '%s'.\n", rank, field_name);
2636 ierr = DMGlobalToLocalBegin(dm, globalVec, INSERT_VALUES, localVec); CHKERRQ(ierr);
2637 ierr = DMGlobalToLocalEnd(dm, globalVec, INSERT_VALUES, localVec); CHKERRQ(ierr);
2638 ierr = RepairPeriodicFieldGhosts(user, &field_view, localVec); CHKERRQ(ierr);
2639 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Completed DMGlobalToLocalBegin/End for '%s'.\n", rank, field_name);
2640
2641 // --- 5. Optional Debugging: Norm After Update ---
2642 // Use your logging convention check
2643 // if (get_log_level() >= LOG_LEVEL_DEBUG && is_function_allowed("UpdateLocalGhosts")) { // Example check
2644 if(get_log_level() >= LOG_DEBUG && is_function_allowed(__func__)){ // Using your specific check
2645 PetscReal norm_local_after;
2646 ierr = VecNorm(localVec, NORM_INFINITY, &norm_local_after); CHKERRQ(ierr);
2647 LOG_ALLOW(GLOBAL, LOG_INFO,"Max norm '%s' (Local) AFTER Ghost Update: %g\n", field_name, norm_local_after);
2648
2649 // --- 6. Optional Debugging: Specific Point Checks (Example for Ucat on Rank 0/1) ---
2650 // (Keep this conditional if it's only for specific debug scenarios)
2651 if (field_id == FIELD_ID_UCAT) { // Only do detailed checks for Ucat for now
2652 PetscMPIInt rank_test;
2653 rank_test = user->simCtx->rank;
2654
2655 // Get Local Info needed for indexing checks
2656 DMDALocalInfo info_check;
2657 info_check = user->info; // dm is user->da or user->fda, which share one decomposition
2658
2659 // Buffer for array pointer
2660 Cmpnts ***lUcat_arr_test = NULL;
2661 PetscErrorCode ierr_test = 0;
2662
2663 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Testing '%s' access immediately after ghost update...\n", rank_test, field_name);
2664 ierr_test = DMDAVecGetArrayDOFRead(dm, localVec, &lUcat_arr_test); // Use correct dm and localVec
2665
2666 if (ierr_test) {
2667 LOG_ALLOW(LOCAL, LOG_ERROR, "Rank %d: ERROR %d getting '%s' array after ghost update!\n", rank_test, ierr_test, field_name);
2668 } else if (!lUcat_arr_test) {
2669 LOG_ALLOW(LOCAL, LOG_ERROR, "Rank %d: ERROR NULL pointer getting '%s' array after ghost update!\n", rank_test, field_name);
2670 }
2671 else {
2672 // Check owned interior point (e.g., first interior point)
2673 PetscInt k_int = info_check.zs + (info_check.zm > 1 ? 1 : 0); // Global k index (at least zs+1 if possible)
2674 PetscInt j_int = info_check.ys + (info_check.ym > 1 ? 1 : 0); // Global j index
2675 PetscInt i_int = info_check.xs + (info_check.xm > 1 ? 1 : 0); // Global i index
2676 // Ensure indices are within global bounds if domain is very small
2677 //if (k_int >= info_check.mz-1) k_int = info_check.mz-2; if (k_int < 1) k_int = 1;
2678 //if (j_int >= info_check.my-1) j_int = info_check.my-2; if (j_int < 1) j_int = 1;
2679 // if (i_int >= info_check.mx-1) i_int = info_check.mx-2; if (i_int < 1) i_int = 1;
2680 // clamp k_int to [1 .. mz-2]
2681 if (k_int >= info_check.mz - 1) {
2682 k_int = info_check.mz - 2;
2683 }
2684 if (k_int < 1) {
2685 k_int = 1;
2686 }
2687
2688 // clamp j_int to [1 .. my-2]
2689 if (j_int >= info_check.my - 1) {
2690 j_int = info_check.my - 2;
2691 }
2692 if (j_int < 1) {
2693 j_int = 1;
2694 }
2695
2696 // clamp i_int to [1 .. mx-2]
2697 if (i_int >= info_check.mx - 1) {
2698 i_int = info_check.mx - 2;
2699 }
2700 if (i_int < 1) {
2701 i_int = 1;
2702 }
2703
2704 // Only attempt read if indices are actually owned (relevant for multi-rank)
2705 if (k_int >= info_check.zs && k_int < info_check.zs + info_check.zm &&
2706 j_int >= info_check.ys && j_int < info_check.ys + info_check.ym &&
2707 i_int >= info_check.xs && i_int < info_check.xs + info_check.xm)
2708 {
2709 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Attempting test read OWNED INTERIOR [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "] (Global)\n", rank_test, k_int, j_int, i_int);
2710 Cmpnts test_val_owned_interior = lUcat_arr_test[k_int][j_int][i_int];
2711 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: SUCCESS reading owned interior: x=%g\n", rank_test, test_val_owned_interior.x);
2712 } else {
2713 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Skipping interior test read for non-owned index [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "].\n", rank_test, k_int, j_int, i_int);
2714 }
2715
2716
2717 // Check owned boundary point (e.g., first owned point)
2718 PetscInt k_bnd = info_check.zs; // Global k index
2719 PetscInt j_bnd = info_check.ys; // Global j index
2720 PetscInt i_bnd = info_check.xs; // Global i index
2721 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Attempting test read OWNED BOUNDARY [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "] (Global)\n", rank_test, k_bnd, j_bnd, i_bnd);
2722 Cmpnts test_val_owned_boundary = lUcat_arr_test[k_bnd][j_bnd][i_bnd];
2723 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: SUCCESS reading owned boundary: x=%g\n", rank_test, test_val_owned_boundary.x);
2724
2725
2726 // Check ghost point (e.g., one layer below in k, if applicable)
2727 if (info_check.zs > 0) { // Only if there's a rank below
2728 PetscInt k_ghost = info_check.zs - 1;
2729 PetscInt j_ghost = info_check.ys; // Use start of owned y, simple example
2730 PetscInt i_ghost = info_check.xs; // Use start of owned x, simple example
2731 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Attempting test read GHOST [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "] (Global)\n", rank_test, k_ghost, j_ghost, i_ghost);
2732 Cmpnts test_val_ghost = lUcat_arr_test[k_ghost][j_ghost][i_ghost];
2733 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: SUCCESS reading ghost: x=%g\n", rank_test, test_val_ghost.x);
2734 } else {
2735 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Skipping ghost test read (zs=0).\n", rank_test);
2736 }
2737
2738 // Restore the array
2739 ierr_test = DMDAVecRestoreArrayDOFRead(dm, localVec, &lUcat_arr_test);
2740 if(ierr_test){ LOG_ALLOW(LOCAL, LOG_ERROR, "Rank %d: ERROR %d restoring '%s' array after test read!\n", rank_test, ierr_test, field_name); }
2741 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Finished testing '%s' access.\n", rank_test, field_name);
2742 }
2743 } // end if Ucat
2744 } // end debug logging check
2745
2746 LOG_ALLOW(GLOBAL, LOG_INFO, "Rank %d: Completed ghost update for field '%s'.\n", rank, field_name);
2748 PetscFunctionReturn(0);
2749}
@ FIELD_CAPABILITY_GHOST_UPDATE
unsigned int capabilities
const FieldDescriptor * descriptor
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
const char * canonical_name
@ FIELD_ID_UCAT
Non-owning runtime objects resolved for one field and UserCtx.
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
PetscErrorCode RepairPeriodicFieldGhosts(UserCtx *user, const FieldView *view, Vec local_vec)
Implementation of RepairPeriodicFieldGhosts().
Definition setup.c:2556
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscScalar x
Definition variables.h:145
DMDALocalInfo info
Definition variables.h:1169
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RepairPeriodicFieldGhosts()

PetscErrorCode RepairPeriodicFieldGhosts ( UserCtx *  user,
const FieldView *  view,
Vec  local_vec 
)

Applies a catalogued field's periodic normal-face ghost repair to a local vector.

The step UpdateLocalGhosts() runs after its scatter: for single-face-family and component-staggered fields, each active periodic face's adjacent normal ghost is rewritten from the deeper PETSc ghost; other fields are left unchanged. The result depends only on the local vector's scattered entries, so it may be reapplied after any partial rescatter of them.

Parameters
userBlock context owning the field's boundary metadata.
viewField view from FieldGetView(); its DM lays out local_vec.
local_vecLocal vector to repair: the field's own, or a scratch copy of it.
Returns
PetscErrorCode 0 on success.

Applies a catalogued field's periodic normal-face ghost repair to a local vector.

See also
RepairPeriodicFieldGhosts()

Definition at line 2556 of file setup.c.

2557{
2558 char face_direction = '\0';
2559 PetscBool component_staggered = PETSC_FALSE;
2560
2561 PetscFunctionBeginUser;
2563 switch (view->descriptor->sync_class) {
2564 case FIELD_SYNC_I_FACE:
2565 face_direction = 'i';
2566 break;
2567 case FIELD_SYNC_J_FACE:
2568 face_direction = 'j';
2569 break;
2570 case FIELD_SYNC_K_FACE:
2571 face_direction = 'k';
2572 break;
2574 component_staggered = PETSC_TRUE;
2575 break;
2577 break;
2578 default:
2579 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB,
2580 "Field '%s' has an invalid ghost synchronization class.", view->descriptor->canonical_name);
2581 }
2582 PetscCall(RepairPeriodicNormalFaceGhosts(user, view->dm, local_vec, view->descriptor->dof, face_direction,
2583 component_staggered));
2585 PetscFunctionReturn(0);
2586}
@ FIELD_SYNC_STANDARD
@ FIELD_SYNC_K_FACE
@ FIELD_SYNC_J_FACE
@ FIELD_SYNC_COMPONENT_STAGGERED
@ FIELD_SYNC_I_FACE
FieldSyncClass sync_class
static PetscErrorCode RepairPeriodicNormalFaceGhosts(UserCtx *user, DM dm, Vec local_vec, PetscInt dof, char face_direction, PetscBool component_staggered)
Repairs the adjacent normal ghost layer for periodic face-staggered data.
Definition setup.c:2386
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetupBoundaryConditions()

PetscErrorCode SetupBoundaryConditions ( SimCtx *  simCtx)

(Orchestrator) Sets up all boundary conditions for the simulation.

Parameters
simCtxSimulation context controlling the operation.
Returns
PetscErrorCode 0 on success.

(Orchestrator) Sets up all boundary conditions for the simulation.

See also
SetupBoundaryConditions()

Definition at line 2755 of file setup.c.

2756{
2757 PetscErrorCode ierr;
2758 PetscFunctionBeginUser;
2759
2761
2762 LOG_ALLOW(GLOBAL,LOG_INFO, "--- Setting up Boundary Conditions ---\n");
2763 // --- Phase 1: Parse and initialize BC configuration for all blocks ---
2764 LOG_ALLOW(GLOBAL,LOG_INFO,"Parsing BC configuration files and initializing boundary condition data structures.\n");
2765 UserCtx *user_finest = simCtx->usermg.mgctx[simCtx->usermg.mglevels-1].user;
2766 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
2767 LOG_ALLOW(GLOBAL,LOG_DEBUG, " -> Processing Block %" PetscInt_FMT ":\n", bi);
2768
2769 // --- Generate the filename for the current block ---
2770 const char *current_bc_filename = simCtx->bcs_files[bi];
2771 LOG_ALLOW(GLOBAL,LOG_DEBUG," -> Processing Block %" PetscInt_FMT " using config file '%s'\n", bi, current_bc_filename);
2772 // This will populate user_finest[bi].boundary_faces
2773
2774 //ierr = ParseAllBoundaryConditions(&user_finest[bi],current_bc_filename); CHKERRQ(ierr);
2775
2776 ierr = BoundarySystem_Initialize(&user_finest[bi], current_bc_filename); CHKERRQ(ierr);
2777 }
2778
2779 // Propogate BC Configuration to coarser levels.
2780 ierr = PropagateBoundaryConfigToCoarserLevels(simCtx); CHKERRQ(ierr);
2781
2782 // Validate the geometric contract before any metric consumes periodic geometry.
2783 for (PetscInt level = simCtx->usermg.mglevels - 1; level >= 0; level--) {
2784 UserCtx *level_users = simCtx->usermg.mgctx[level].user;
2785 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
2786 ierr = ValidatePeriodicGeometry(&level_users[bi]); CHKERRQ(ierr);
2787 }
2788 }
2789
2790 // --- Calculate Grid Metrics (requires BC configuration) ---
2791 // NOTE: This MUST be called here (after BC initialization but before inlet/outlet calculations) because:
2792 // 1. Periodic BC corrections in metric calculations need boundary_faces data to be populated
2793 // 2. Inlet/Outlet area calculations (below) require computed metrics (Csi, Eta, Zet) to be available
2794 // Previously this was in SetupGridAndSolvers, but that caused metrics to be computed without BC info.
2795 LOG_ALLOW(GLOBAL,LOG_INFO,"Computing grid metrics with boundary condition information.\n");
2796 ierr = CalculateAllGridMetrics(simCtx); CHKERRQ(ierr);
2797
2798 // --- Phase 2: Calculate inlet/outlet properties (requires computed metrics) ---
2799 LOG_ALLOW(GLOBAL,LOG_INFO,"Calculating inlet and outlet face properties.\n");
2800 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
2801 // Call the function to calculate the center of the inlet face & the inlet area, which may be used to calculate Boundary values.
2802 ierr = CalculateInletProperties(&user_finest[bi]); CHKERRQ(ierr);
2803
2804 // Call the function to calculate the center of the outlet face & the outlet area, which may be used to calculate Boundary values.
2805 ierr = CalculateOutletProperties(&user_finest[bi]); CHKERRQ(ierr);
2806 }
2807
2808 LOG_ALLOW(GLOBAL,LOG_INFO, "--- Boundary Conditions setup complete ---\n");
2809
2810
2812 PetscFunctionReturn(0);
2813}
PetscErrorCode BoundarySystem_Initialize(UserCtx *user, const char *bcs_filename)
Initializes the entire boundary system.
Definition Boundaries.c:412
PetscErrorCode PropagateBoundaryConfigToCoarserLevels(SimCtx *simCtx)
Propagates boundary condition configuration from finest to all coarser multigrid levels.
Definition Boundaries.c:530
PetscErrorCode CalculateAllGridMetrics(SimCtx *simCtx)
Orchestrates the calculation of all grid metrics.
Definition Metric.c:2267
PetscErrorCode CalculateOutletProperties(UserCtx *user)
Calculates the center and area of the primary OUTLET face.
Definition grid.c:1170
PetscErrorCode ValidatePeriodicGeometry(UserCtx *user)
Validates that configured geometric periodic seams match by translation.
Definition grid.c:450
PetscErrorCode CalculateInletProperties(UserCtx *user)
Calculates the center and area of the primary INLET face.
Definition grid.c:1119
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeSolutionConvergenceState()

PetscErrorCode InitializeSolutionConvergenceState ( SimCtx *  simCtx)

Allocates any runtime storage required by solution-convergence logging.

This helper is setup-owned because it allocates mode-specific buffers once the finest-level Eulerian vectors already exist. It does not compute or log any metrics; it only prepares storage for later use by LOG_SOLUTION_CONVERGENCE().

Allocation depends on the active solution-convergence mode:

  • steady/transient: no extra storage beyond counters
  • periodic_deterministic: one phase-aligned Ucat / P reference slot per configured period step and per block
  • statistical_steady: rolling scalar histories sized for two adjacent windows of mean_speed and mean_ke

The helper also resets the recorded-sample counter so warmup behavior starts from a clean state each time solver setup is rebuilt.

Parameters
[in,out]simCtxMaster simulation context owning the runtime storage.
Returns
PetscErrorCode 0 on success.

Allocates any runtime storage required by solution-convergence logging.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
InitializeSolutionConvergenceState()

Definition at line 176 of file setup.c.

177{
178 UserCtx *user = NULL;
179 PetscInt history_capacity = 0;
180
181 PetscFunctionBeginUser;
183 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be NULL.");
184 if (simCtx->exec_mode != EXEC_MODE_SOLVER) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
185 if (!simCtx->solutionConvergenceEnabled) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
186 if (!simCtx->usermg.mgctx) {
187 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
188 "Multigrid hierarchy must exist before initializing solution convergence storage.");
189 }
190
191 user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
192 if (!user) {
193 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
194 "Finest-level UserCtx must exist before initializing solution convergence storage.");
195 }
196
198
200 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
201 PetscCall(PetscCalloc1((size_t)simCtx->solutionConvergencePeriodSteps,
202 &user[bi].solutionConvergencePeriodicUcatRef));
203 PetscCall(PetscCalloc1((size_t)simCtx->solutionConvergencePeriodSteps,
204 &user[bi].solutionConvergencePeriodicPRef));
205 for (PetscInt phase = 0; phase < simCtx->solutionConvergencePeriodSteps; ++phase) {
206 PetscCall(VecDuplicate(user[bi].Ucat, &user[bi].solutionConvergencePeriodicUcatRef[phase]));
207 PetscCall(VecSet(user[bi].solutionConvergencePeriodicUcatRef[phase], 0.0));
208 PetscCall(VecDuplicate(user[bi].P, &user[bi].solutionConvergencePeriodicPRef[phase]));
209 PetscCall(VecSet(user[bi].solutionConvergencePeriodicPRef[phase], 0.0));
210 }
211 }
212 }
213
215 history_capacity = 2 * simCtx->solutionConvergenceWindowSteps;
216 PetscCall(PetscCalloc1((size_t)history_capacity, &simCtx->solutionConvergenceMeanSpeedHistory));
217 PetscCall(PetscCalloc1((size_t)history_capacity, &simCtx->solutionConvergenceMeanKEHistory));
218 }
219
221 PetscFunctionReturn(0);
222}
Here is the caller graph for this function:

◆ DestroySolutionConvergenceState()

PetscErrorCode DestroySolutionConvergenceState ( SimCtx *  simCtx)

Frees any runtime storage allocated for solution-convergence logging.

This helper is the cleanup counterpart to InitializeSolutionConvergenceState(). It releases periodic reference buffers and statistical-history arrays, then resets the associated pointers and counters. It is safe to call during teardown even if a given mode never allocated optional storage.

Parameters
[in,out]simCtxMaster simulation context owning the runtime storage.
Returns
PetscErrorCode 0 on success.

Frees any runtime storage allocated for solution-convergence logging.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
DestroySolutionConvergenceState()

Definition at line 230 of file setup.c.

231{
232 UserCtx *user = NULL;
233
234 PetscFunctionBeginUser;
236 if (!simCtx) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
237 if (simCtx->fieldStatisticsWindows) {
238 PetscCall(PetscFree(simCtx->fieldStatisticsWindows));
239 simCtx->fieldStatisticsWindows = NULL;
240 simCtx->fieldStatisticsWindowCount = 0;
241 }
242 if (!simCtx->usermg.mgctx) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
243
244 user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
245 if (user) {
246 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
247 if (user[bi].solutionConvergencePeriodicUcatRef) {
248 for (PetscInt phase = 0; phase < simCtx->solutionConvergencePeriodSteps; ++phase) {
249 if (user[bi].solutionConvergencePeriodicUcatRef[phase]) {
250 PetscCall(VecDestroy(&user[bi].solutionConvergencePeriodicUcatRef[phase]));
251 }
252 }
253 PetscCall(PetscFree(user[bi].solutionConvergencePeriodicUcatRef));
255 }
256 if (user[bi].solutionConvergencePeriodicPRef) {
257 for (PetscInt phase = 0; phase < simCtx->solutionConvergencePeriodSteps; ++phase) {
258 if (user[bi].solutionConvergencePeriodicPRef[phase]) {
259 PetscCall(VecDestroy(&user[bi].solutionConvergencePeriodicPRef[phase]));
260 }
261 }
262 PetscCall(PetscFree(user[bi].solutionConvergencePeriodicPRef));
263 user[bi].solutionConvergencePeriodicPRef = NULL;
264 }
265 }
266 }
267
269 PetscCall(PetscFree(simCtx->solutionConvergenceMeanSpeedHistory));
271 }
273 PetscCall(PetscFree(simCtx->solutionConvergenceMeanKEHistory));
275 }
277
279 PetscFunctionReturn(0);
280}
Vec * solutionConvergencePeriodicPRef
Definition variables.h:1209
Vec * solutionConvergencePeriodicUcatRef
Definition variables.h:1208
Here is the caller graph for this function:

◆ Allocate3DArrayScalar()

PetscErrorCode Allocate3DArrayScalar ( PetscReal ****  array,
PetscInt  nz,
PetscInt  ny,
PetscInt  nx 
)

Allocates a 3D array of PetscReal values using PetscCalloc.

This function dynamically allocates memory for a 3D array of PetscReal values with dimensions nz (layers) x ny (rows) x nx (columns). It uses PetscCalloc1 to ensure the memory is zero-initialized.

The allocation is done in three steps:

  1. Allocate an array of nz pointers (one for each layer).
  2. Allocate a contiguous block for nz*ny row pointers and assign each layer’s row pointers.
  3. Allocate a contiguous block for all nz*ny*nx PetscReal values.

This setup allows the array to be accessed as array[k][j][i], and the memory for the data is contiguous, which improves cache efficiency.

Parameters
[out]arrayPointer to the 3D array to be allocated.
[in]nzNumber of layers (z-direction).
[in]nyNumber of rows (y-direction).
[in]nxNumber of columns (x-direction).
Returns
PetscErrorCode 0 on success, nonzero on failure.

Allocates a 3D array of PetscReal values using PetscCalloc.

See also
Allocate3DArrayScalar()

Definition at line 2819 of file setup.c.

2820{
2821 PetscErrorCode ierr;
2822 PetscReal ***data;
2823 PetscReal *dataContiguous;
2824 PetscInt k, j;
2825
2826 PetscFunctionBegin;
2828 /* Step 1: Allocate memory for an array of nz layer pointers (zero-initialized) */
2829 ierr = PetscCalloc1(nz, &data); CHKERRQ(ierr);
2830
2831 /* Step 2: Allocate memory for all row pointers (nz * ny pointers) */
2832 ierr = PetscCalloc1(nz * ny, &data[0]); CHKERRQ(ierr);
2833 for (k = 1; k < nz; k++) {
2834 data[k] = data[0] + k * ny;
2835 }
2836
2837 /* Step 3: Allocate one contiguous block for all data elements (nz*ny*nx) */
2838 ierr = PetscCalloc1(nz * ny * nx, &dataContiguous); CHKERRQ(ierr);
2839
2840 /* Build the 3D pointer structure: each row pointer gets the correct segment of data */
2841 for (k = 0; k < nz; k++) {
2842 for (j = 0; j < ny; j++) {
2843 data[k][j] = dataContiguous + (k * ny + j) * nx;
2844 /* Memory is already zeroed by PetscCalloc1, so no manual initialization is needed */
2845 }
2846 }
2847 *array = data;
2849 PetscFunctionReturn(0);
2850}

◆ Deallocate3DArrayScalar()

PetscErrorCode Deallocate3DArrayScalar ( PetscReal ***  array,
PetscInt  nz,
PetscInt  ny 
)

Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.

This function frees the memory allocated for a 3D array of PetscReal values. It assumes the memory was allocated using Allocate3DArrayScalar, which allocated three separate memory blocks: one for the contiguous data, one for the row pointers, and one for the layer pointers.

Parameters
[in]arrayPointer to the 3D array to be deallocated.
[in]nzNumber of layers (z-direction).
[in]nyNumber of rows (y-direction).
Returns
PetscErrorCode 0 on success, nonzero on failure.

Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.

See also
Deallocate3DArrayScalar()

Definition at line 2856 of file setup.c.

2857{
2858 PetscErrorCode ierr;
2859 (void)nz;
2860 (void)ny;
2861
2862 PetscFunctionBegin;
2864 if (!array || !array[0] || !array[0][0] ) { // Added more robust check
2865 LOG_ALLOW(GLOBAL, LOG_WARNING, "Deallocate3DArrayScalar called with potentially unallocated or NULL array.\n");
2866 if (array) {
2867 if (array[0]) { // Check if row pointers might exist
2868 // Cannot safely access array[0][0] if array[0] might be invalid/freed
2869 // Standard deallocation below assumes valid pointers.
2870 ierr = PetscFree(array[0]); CHKERRQ(ierr); // Free row pointers if they exist
2871 }
2872 ierr = PetscFree(array); CHKERRQ(ierr); // Free layer pointers if they exist
2873 }
2875 PetscFunctionReturn(0);
2876 }
2877
2878 // --- Standard Deallocation (assuming valid allocation) ---
2879
2880 /* 1. Free the contiguous block of PetscReal values.
2881 The starting address was stored in array[0][0]. */
2882 ierr = PetscFree(array[0][0]); CHKERRQ(ierr); // Free the ACTUAL DATA
2883
2884 /* 2. Free the contiguous block of row pointers.
2885 The starting address was stored in array[0]. */
2886 ierr = PetscFree(array[0]); CHKERRQ(ierr); // Free the ROW POINTERS
2887
2888 /* 3. Free the layer pointer array.
2889 The starting address is 'array' itself. */
2890 ierr = PetscFree(array); CHKERRQ(ierr); // Free the LAYER POINTERS
2891
2893 PetscFunctionReturn(0);
2894}

◆ Allocate3DArrayVector()

PetscErrorCode Allocate3DArrayVector ( Cmpnts ****  array,
PetscInt  nz,
PetscInt  ny,
PetscInt  nx 
)

Allocates a contiguous 3D array of Cmpnts values.

The memory layout mirrors Allocate3DArrayScalar: layer pointers, row pointers, and contiguous payload are allocated such that indexing as array[k][j][i] is valid while keeping payload data contiguous.

Parameters
[out]arrayPointer to the 3D vector array to allocate.
[in]nzNumber of layers in the z-direction.
[in]nyNumber of rows in the y-direction.
[in]nxNumber of columns in the x-direction.
Returns
PetscErrorCode 0 on success, nonzero on failure.

Allocates a contiguous 3D array of Cmpnts values.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
Allocate3DArrayVector()

Definition at line 2902 of file setup.c.

2903{
2904 PetscErrorCode ierr;
2905 Cmpnts ***data;
2906 Cmpnts *dataContiguous;
2907 PetscInt k, j;
2908 PetscMPIInt rank;
2909
2910 PetscFunctionBegin;
2912
2913 rank = PetscGlobalRank;
2914
2915 /* Step 1: Allocate memory for nz layer pointers (zeroed) */
2916 ierr = PetscCalloc1(nz, &data); CHKERRQ(ierr);
2917
2918 LOG_ALLOW(LOCAL,LOG_DEBUG," [Rank %d] memory allocated for outermost layer (%" PetscInt_FMT " k-layer pointers).\n",rank,nz);
2919
2920 /* Step 2: Allocate memory for all row pointers (nz * ny pointers) */
2921 ierr = PetscCalloc1(nz * ny, &data[0]); CHKERRQ(ierr);
2922 for (k = 1; k < nz; k++) {
2923 data[k] = data[0] + k * ny;
2924 }
2925
2926 LOG_ALLOW(LOCAL,LOG_DEBUG,"[Rank %d] memory allocated for %" PetscInt_FMT "x%" PetscInt_FMT " row pointers.\n",rank,nz,ny);
2927
2928 /* Step 3: Allocate one contiguous block for nz*ny*nx Cmpnts structures (zeroed) */
2929 ierr = PetscCalloc1(nz * ny * nx, &dataContiguous); CHKERRQ(ierr);
2930
2931 LOG_ALLOW(GLOBAL,LOG_DEBUG,"[Rank %d] memory allocated for contigous block of %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT " Cmpnts structures).\n",rank,nz,ny,nx);
2932
2933 /* Build the 3D pointer structure for vector data */
2934 for (k = 0; k < nz; k++) {
2935 for (j = 0; j < ny; j++) {
2936 data[k][j] = dataContiguous + (k * ny + j) * nx;
2937 /* The PetscCalloc1 call has already initialized each Cmpnts to zero. */
2938 }
2939 }
2940
2941 LOG_ALLOW(GLOBAL,LOG_DEBUG,"[Rank %d] 3D pointer structure for vector data created. \n",rank);
2942
2943 *array = data;
2945 PetscFunctionReturn(0);
2946}

◆ Deallocate3DArrayVector()

PetscErrorCode Deallocate3DArrayVector ( Cmpnts ***  array,
PetscInt  nz,
PetscInt  ny 
)

Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.

This function frees the memory allocated for a 3D array of Cmpnts structures. It assumes the memory was allocated using Allocate3DArrayVector, which created three separate memory blocks: one for the contiguous vector data, one for the row pointers, and one for the layer pointers.

Parameters
[in]arrayPointer to the 3D array to be deallocated.
[in]nzNumber of layers in the z-direction.
[in]nyNumber of rows in the y-direction.
Returns
PetscErrorCode 0 on success, nonzero on failure.

Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
Deallocate3DArrayVector()

Definition at line 2954 of file setup.c.

2955{
2956 PetscErrorCode ierr;
2957 (void)nz;
2958 (void)ny;
2959
2960 PetscFunctionBegin;
2962 // If array is NULL or hasn't been allocated properly, just return.
2963 if (!array || !array[0] || !array[0][0] ) {
2964 LOG_ALLOW(GLOBAL, LOG_WARNING, "Deallocate3DArrayVector called with potentially unallocated or NULL array.\n");
2965 // Attempt to free what might exist, but be cautious
2966 if (array) {
2967 if (array[0]) { // Check if row pointers were allocated
2968 // We don't have a direct pointer to the contiguous data block
2969 // saved separately in this allocation scheme. The allocation relies
2970 // on array[0][0] pointing to it. If array[0] was freed first,
2971 // accessing array[0][0] is unsafe.
2972 // The allocation scheme where the contiguous data block is not
2973 // stored separately makes safe deallocation tricky if freeing
2974 // happens out of order or if parts are NULL.
2975
2976 // A SAFER ALLOCATION/DEALLOCATION would store the data pointer separately.
2977 // Given the current allocation scheme, the order MUST be:
2978 // 1. Free the data block (pointed to by array[0][0])
2979 // 2. Free the row pointer block (pointed to by array[0])
2980 // 3. Free the layer pointer block (pointed to by array)
2981
2982 // Let's assume the allocation was successful and pointers are valid.
2983 // Get pointer to the contiguous data block *before* freeing row pointers
2984 Cmpnts *dataContiguous = array[0][0];
2985 ierr = PetscFree(dataContiguous); CHKERRQ(ierr); // Free data block
2986
2987 // Now free the row pointers block
2988 ierr = PetscFree(array[0]); CHKERRQ(ierr); // Free row pointers
2989
2990 }
2991 // Finally, free the array of layer pointers
2992 ierr = PetscFree(array); CHKERRQ(ierr);
2993 }
2995 PetscFunctionReturn(0); // Return gracefully if input was NULL initially
2996 }
2997
2998
2999 // --- Standard Deallocation (assuming valid allocation) ---
3000
3001 /* 1. Free the contiguous block of Cmpnts structures.
3002 The starting address was stored in array[0][0] by Allocate3DArrayVector. */
3003 ierr = PetscFree(array[0][0]); CHKERRQ(ierr); // Free the ACTUAL DATA
3004
3005 /* 2. Free the contiguous block of row pointers.
3006 The starting address was stored in array[0]. */
3007 ierr = PetscFree(array[0]); CHKERRQ(ierr); // Free the ROW POINTERS
3008
3009 /* 3. Free the layer pointer array.
3010 The starting address is 'array' itself. */
3011 ierr = PetscFree(array); CHKERRQ(ierr); // Free the LAYER POINTERS
3012
3014 PetscFunctionReturn(0);
3015}

◆ GetOwnedCellRange()

PetscErrorCode GetOwnedCellRange ( const DMDALocalInfo *  info_nodes,
PetscInt  dim,
PetscInt *  xs_cell_global_out,
PetscInt *  xm_cell_local_out 
)

Determines the global starting index and number of CELLS owned by the current processor in a specified dimension.

Ownership is defined by the rank owning the cell's origin node (min i,j,k corner).

Parameters
[in]info_nodesPointer to the DMDALocalInfo struct obtained from the NODE-based DMDA (e.g., user->da or user->fda, assuming they have consistent nodal partitioning for defining cell origins).
[in]dimThe dimension to compute the range for (0 for x/i, 1 for y/j, 2 for z/k).
[out]xs_cell_global_outPointer to store the starting global cell index owned by this process.
[out]xm_cell_local_outPointer to store the number of owned cells in this dimension.
Returns
PetscErrorCode 0 on success.

Determines the global starting index and number of CELLS owned by the current processor in a specified dimension.

See also
GetOwnedCellRange()

Definition at line 3021 of file setup.c.

3025{
3026 PetscErrorCode ierr = 0; // Standard PETSc error code, not explicitly set here but good practice.
3027 PetscInt xs_node_global_rank; // Global index of the first node owned by this rank in the specified dimension.
3028 PetscInt num_nodes_owned_rank; // Number of nodes owned by this rank in this dimension (local count, excluding ghosts).
3029 PetscInt GlobalNodesInDim_from_info; // Total number of DA points in this dimension, from DMDALocalInfo.
3030
3031 PetscFunctionBeginUser;
3032
3033 // --- 1. Input Validation ---
3034 if (!info_nodes || !xs_cell_global_out || !xm_cell_local_out) {
3035 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null pointer passed to GetOwnedCellRange.");
3036 }
3037
3038 // --- 2. Extract Node Ownership and Global Dimension Information from DMDALocalInfo ---
3039 if (dim == 0) { // I-direction
3040 xs_node_global_rank = info_nodes->xs;
3041 num_nodes_owned_rank = info_nodes->xm;
3042 GlobalNodesInDim_from_info = info_nodes->mx;
3043 } else if (dim == 1) { // J-direction
3044 xs_node_global_rank = info_nodes->ys;
3045 num_nodes_owned_rank = info_nodes->ym;
3046 GlobalNodesInDim_from_info = info_nodes->my;
3047 } else if (dim == 2) { // K-direction
3048 xs_node_global_rank = info_nodes->zs;
3049 num_nodes_owned_rank = info_nodes->zm;
3050 GlobalNodesInDim_from_info = info_nodes->mz;
3051 } else {
3052 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT " in GetOwnedCellRange. Must be 0, 1, or 2.", dim);
3053 }
3054
3055 // --- 3. Correct for User-Defined Ghost Node ---
3056 // Per the function's contract (@warning), the DA size includes an extra, non-physical
3057 // node. We subtract 1 to get the true number of physical nodes for cell calculations.
3058 const PetscInt physical_nodes_in_dim = GlobalNodesInDim_from_info - 1;
3059
3060 // --- 4. Handle Edge Cases for Physical Domain Size ---
3061 // If the physical domain has 0 or 1 node, no cells can be formed.
3062 if (physical_nodes_in_dim <= 1) {
3063 *xs_cell_global_out = xs_node_global_rank; // Still report the rank's starting node
3064 *xm_cell_local_out = 0; // But 0 cells
3065 PetscFunctionReturn(0);
3066 }
3067
3068 // --- 5. Determine Cell Ownership Based on Corrected Node Ownership ---
3069 // The first cell this rank *could* define has its origin at the first node this rank owns.
3070 *xs_cell_global_out = xs_node_global_rank;
3071
3072 // If the rank owns no nodes in this dimension, it can't form any cell origins.
3073 if (num_nodes_owned_rank == 0) {
3074 *xm_cell_local_out = 0;
3075 } else {
3076 // --- BUG FIX APPLIED HERE ---
3077 // The previous logic incorrectly assumed a cell's end node (N_{k+1}) must be on the
3078 // same rank as its origin node (N_k). The correct logic is to find the intersection
3079 // between the nodes this rank owns and the nodes that are valid origins globally.
3080
3081 // The first node owned by the rank is its first potential origin.
3082 PetscInt first_owned_origin = xs_node_global_rank;
3083
3084 // The absolute last node owned by this rank. Any node up to and including this one
3085 // is a potential cell origin from this rank's perspective.
3086 PetscInt last_node_owned_by_rank = xs_node_global_rank + num_nodes_owned_rank - 1;
3087
3088 // The absolute last node in the entire PHYSICAL domain that can serve as a cell origin.
3089 // If there are `N` physical nodes (0 to N-1), this index is `N-2`.
3090 PetscInt last_possible_origin_global_idx = physical_nodes_in_dim - 2;
3091
3092 // The actual last origin this rank can provide is the *minimum* of what it owns
3093 // and what is globally possible. This correctly handles both ranks in the middle of
3094 // the domain and the very last rank.
3095 PetscInt actual_last_origin_this_rank_can_form = PetscMin(last_node_owned_by_rank, last_possible_origin_global_idx);
3096
3097 // If the first potential origin this rank owns is already beyond the actual last
3098 // origin it can form, then this rank forms no valid cell origins. This happens if
3099 // the rank only owns the very last physical node.
3100 if (first_owned_origin > actual_last_origin_this_rank_can_form) {
3101 *xm_cell_local_out = 0;
3102 } else {
3103 // The number of cells is the count of valid origins this rank owns.
3104 // (Count = Last Index - First Index + 1)
3105 *xm_cell_local_out = actual_last_origin_this_rank_can_form - first_owned_origin + 1;
3106 }
3107 }
3108
3109 PetscFunctionReturn(ierr);
3110}
Here is the caller graph for this function:

◆ GetPeriodicAxes()

static void GetPeriodicAxes ( const SimCtx *  simCtx,
PetscBool  periodic[3] 
)
inlinestatic

Which grid axes are periodic.

From the run's flags, which the loader derives from the boundary files and which selected DM_BOUNDARY_PERIODIC when the DMDAs were built. The loader refuses a case whose opposite faces or whose blocks disagree on periodicity, so the flags hold for every face, block and multigrid level.

Parameters
[in]simCtxSimulation context.
[out]periodicWhether the i, j and k axes are periodic.

Definition at line 361 of file setup.h.

362{
363 periodic[0] = (PetscBool)(simCtx->i_periodic != 0);
364 periodic[1] = (PetscBool)(simCtx->j_periodic != 0);
365 periodic[2] = (PetscBool)(simCtx->k_periodic != 0);
366}
Here is the caller graph for this function:

◆ GetOwnedInteriorCellBounds()

static void GetOwnedInteriorCellBounds ( const DMDALocalInfo *  info,
PetscInt  lo[3],
PetscInt  hi[3] 
)
inlinestatic

Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned range with the dummy layer at index 0 and at index m-1 removed.

lo[a] <= c < hi[a] along each axis. A periodic axis is treated like a walled one: its seam face at index 0 is not included, and callers that set it extend the range themselves.

Parameters
[in]infoLocal info of the block's da (or fda; they share the decomposition).
[out]loFirst owned interior index along i, j, k.
[out]hiOne past the last owned interior index along i, j, k.

Definition at line 378 of file setup.h.

379{
380 const PetscInt m[3] = {info->mx, info->my, info->mz};
381 const PetscInt start[3] = {info->xs, info->ys, info->zs};
382 const PetscInt end[3] = {info->xs + info->xm, info->ys + info->ym, info->zs + info->zm};
383
384 for (PetscInt a = 0; a < 3; a++) {
385 lo[a] = (start[a] == 0) ? 1 : start[a];
386 hi[a] = (end[a] == m[a]) ? m[a] - 1 : end[a];
387 }
388}
Here is the caller graph for this function:

◆ ComputeAndStoreNeighborRanks()

PetscErrorCode ComputeAndStoreNeighborRanks ( UserCtx *  user)

Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.

This function retrieves the neighbor information from the primary DMDA (user->da) and stores the face neighbors (xm, xp, ym, yp, zm, zp) in the user->neighbors structure. It assumes a standard PETSc ordering for the neighbors array returned by DMDAGetNeighbors. Logs warnings if the assumed indices seem incorrect (e.g., center rank mismatch).

Parameters
[in,out]userPointer to the UserCtx structure where neighbor info will be stored.
Returns
PetscErrorCode 0 on success, non-zero on failure.

Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.

See also
ComputeAndStoreNeighborRanks()

Definition at line 3116 of file setup.c.

3117{
3118 PetscErrorCode ierr;
3119 PetscMPIInt rank;
3120 PetscMPIInt size; // MPI communicator size
3121 const PetscMPIInt *neighbor_ranks_ptr; // Pointer to raw neighbor data from PETSc
3122
3123 PetscFunctionBeginUser;
3125 rank = PetscGlobalRank;
3126 size = PetscGlobalSize; // Get MPI size for validation
3127
3128 LOG_ALLOW(GLOBAL, LOG_INFO, "Rank %d: Computing DMDA neighbor ranks.\n", rank);
3129
3130 if (!user || !user->da) {
3131 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx or user->da is NULL in ComputeAndStoreNeighborRanks.");
3132 }
3133
3134 // Get the neighbor information from the DMDA
3135 // neighbor_ranks_ptr will point to an internal PETSc array of 27 ranks.
3136 ierr = DMDAGetNeighbors(user->da, &neighbor_ranks_ptr); CHKERRQ(ierr);
3137
3138 if (neighbor_ranks_ptr[13] != rank) {
3139 LOG_ALLOW(GLOBAL, LOG_WARNING, "Rank %d: DMDAGetNeighbors center index (13) is %d, expected current rank %d. Neighbor indexing might be non-standard or DMDA small.\n",
3140 rank, neighbor_ranks_ptr[13], rank);
3141 }
3142
3143 // All 27 entries, in DMDAGetNeighbors order (RANK_NEIGHBOR_INDEX). PETSc wraps a neighbour
3144 // across a DM_BOUNDARY_PERIODIC axis and marks one beyond any other boundary with a negative
3145 // rank, stored as MPI_PROC_NULL.
3146 for (PetscInt n = 0; n < 27; ++n) {
3147 const PetscMPIInt neighbor = neighbor_ranks_ptr[n];
3148 user->neighbors.rank[n] = (neighbor < 0 || neighbor >= size) ? MPI_PROC_NULL : neighbor;
3149 }
3150
3151 LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "[Rank %d] Stored face neighbours: xm=%d, xp=%d, ym=%d, yp=%d, zm=%d, zp=%d\n", rank,
3152 user->neighbors.rank[RANK_NEIGHBOR_INDEX(-1, 0, 0)], user->neighbors.rank[RANK_NEIGHBOR_INDEX(1, 0, 0)],
3153 user->neighbors.rank[RANK_NEIGHBOR_INDEX(0, -1, 0)], user->neighbors.rank[RANK_NEIGHBOR_INDEX(0, 1, 0)],
3154 user->neighbors.rank[RANK_NEIGHBOR_INDEX(0, 0, -1)], user->neighbors.rank[RANK_NEIGHBOR_INDEX(0, 0, 1)]);
3155 PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); // Ensure logs are flushed
3156
3157 // Note: neighbor_ranks_ptr memory is managed by PETSc, do not free it.
3159 PetscFunctionReturn(0);
3160}
#define RANK_NEIGHBOR_INDEX(di, dj, dk)
Index in RankNeighbors::rank of the neighbour offset (di, dj, dk), each -1, 0 or 1.
Definition variables.h:250
RankNeighbors neighbors
Definition variables.h:1174
PetscMPIInt rank[27]
Definition variables.h:259
Here is the caller graph for this function:

◆ SetDMDAProcLayout()

PetscErrorCode SetDMDAProcLayout ( DM  dm,
UserCtx *  user 
)

Sets the processor layout for a given DMDA based on PETSc options.

Reads the desired number of processors in x, y, and z directions using PETSc options (e.g., -dm_processors_x, -dm_processors_y, -dm_processors_z). If an option is not provided for a direction, PETSC_DECIDE is used for that direction. Applies the layout using DMDASetNumProcs.

Also stores the retrieved/decided values in user->procs_x/y/z if user context is provided.

Parameters
dmThe DMDA object to configure the layout for.
userPointer to the UserCtx structure (optional, used to store layout values).
Returns
PetscErrorCode 0 on success, non-zero on failure.

Sets the processor layout for a given DMDA based on PETSc options.

See also
SetDMDAProcLayout()

Definition at line 3166 of file setup.c.

3167{
3168 PetscErrorCode ierr;
3169 PetscMPIInt size, rank;
3170 PetscInt px = PETSC_DECIDE, py = PETSC_DECIDE, pz = PETSC_DECIDE;
3171 PetscBool px_set = PETSC_FALSE, py_set = PETSC_FALSE, pz_set = PETSC_FALSE;
3172 SimCtx *simCtx = user->simCtx;
3173
3174 // Set no.of processors in direction 1
3175 if(simCtx->da_procs_x) {
3176 px_set = PETSC_TRUE;
3177 px = simCtx->da_procs_x;
3178 }
3179 // Set no.of processors in direction 2
3180 if(simCtx->da_procs_y) {
3181 py_set = PETSC_TRUE;
3182 py = simCtx->da_procs_y;
3183 }
3184 // Set no.of processors in direction 1
3185 if(simCtx->da_procs_z) {
3186 pz_set = PETSC_TRUE;
3187 pz = simCtx->da_procs_z;
3188 }
3189
3190 PetscFunctionBeginUser;
3192 ierr = MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size); CHKERRQ(ierr);
3193 ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank); CHKERRQ(ierr);
3194 LOG_ALLOW(GLOBAL, LOG_INFO, "Rank %d: Configuring DMDA processor layout for %d total processes.\n", rank, size);
3195
3196 // --- Validate User Input (Optional but Recommended) ---
3197 // Check if specified processor counts multiply to the total MPI size
3198 if (px_set && py_set && pz_set) {
3199 if (px * py * pz != size) {
3200 SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_INCOMP,
3201 "Specified processor layout %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT " = %" PetscInt_FMT " does not match MPI size %d",
3202 px, py, pz, px * py * pz, size);
3203 }
3204 LOG_ALLOW(GLOBAL, LOG_INFO, "Using specified processor layout: %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT "\n", px, py, pz);
3205 } else if (px_set || py_set || pz_set) {
3206 // If only some are set, PETSC_DECIDE will be used for others
3207 LOG_ALLOW(GLOBAL, LOG_INFO, "Using partially specified processor layout: %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT " (PETSC_DECIDE for unspecified)\n", px, py, pz);
3208 } else {
3209 LOG_ALLOW(GLOBAL, LOG_INFO, "Using fully automatic processor layout (PETSC_DECIDE x PETSC_DECIDE x PETSC_DECIDE)\n");
3210 }
3211 // Additional checks: Ensure px, py, pz are positive if set
3212 if ((px_set && px <= 0) || (py_set && py <= 0) || (pz_set && pz <= 0)) {
3213 SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Specified processor counts must be positive.");
3214 }
3215
3216
3217 // --- Apply the layout to the DMDA ---
3218 ierr = DMDASetNumProcs(dm, px, py, pz); CHKERRQ(ierr);
3219 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Rank %d: DMDASetNumProcs called with px=%" PetscInt_FMT ", py=%" PetscInt_FMT ", pz=%" PetscInt_FMT ".\n", rank, px, py, pz);
3220
3221 // --- Store the values in UserCtx (Optional) ---
3222 // Note: If PETSC_DECIDE was used, PETSc calculates the actual values during DMSetUp.
3223 // We store the *requested* values here. To get the *actual* values used,
3224 // you would need to call DMDAGetInfo after DMSetUp.
3225 /*
3226 if (user) {
3227 user->procs_x = px;
3228 user->procs_y = py;
3229 user->procs_z = pz;
3230 }
3231 */
3233 PetscFunctionReturn(0);
3234}

◆ SetupDomainRankInfo()

PetscErrorCode SetupDomainRankInfo ( SimCtx *  simCtx)

Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchange.

This function orchestrates the following steps:

  1. Compute and store the neighbor ranks in the user context.
  2. Gather all local bounding boxes to rank 0.
  3. Broadcast the complete bounding box list to all ranks.

The final result is that each rank has access to its immediate neighbors and the bounding box information of all ranks.

Parameters
[in,out]simCtxPointer to initialized simulation context that owns all block UserCtx objects.
Returns
PetscErrorCode Returns 0 on success or non-zero PETSc error code.

Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchange.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
SetupDomainRankInfo()

Definition at line 3242 of file setup.c.

3243{
3244 PetscErrorCode ierr;
3245 PetscInt nblk = simCtx->block_number;
3246 PetscInt size = simCtx->size;
3247 BoundingBox *final_bboxlist = NULL;
3248
3249 PetscFunctionBeginUser;
3251
3252 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting full rank communication setup for %" PetscInt_FMT " block(s).\n", nblk);
3253
3254 UserCtx *user_finest = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
3255
3256 // --- Step 1: Compute neighbor ranks (unchanged) ---
3257 for (int bi = 0; bi < nblk; bi++) {
3258 ierr = ComputeAndStoreNeighborRanks(&user_finest[bi]); CHKERRQ(ierr);
3259 }
3260 LOG_ALLOW(GLOBAL, LOG_INFO, "Neighbor ranks computed and stored for all blocks.\n");
3261
3262 // --- Step 2: Allocate the final, unified list on ALL ranks ---
3263 // Every rank will build this list in parallel.
3264 ierr = PetscMalloc1(size * nblk, &final_bboxlist); CHKERRQ(ierr);
3265
3266 // --- Step 3: Loop through each block, gather then broadcast its bbox list ---
3267 for (int bi = 0; bi < nblk; bi++) {
3268 // This is a temporary pointer for the current block's list.
3269 BoundingBox *block_bboxlist = NULL;
3270
3271 LOG_ALLOW(GLOBAL, LOG_INFO, "Processing bounding boxes for block %d...\n", bi);
3272
3273 // A) GATHER: On rank 0, block_bboxlist is allocated and filled. On others, it's NULL.
3274 ierr = GatherAllBoundingBoxes(&user_finest[bi], &block_bboxlist); CHKERRQ(ierr);
3275 LOG_ALLOW(GLOBAL, LOG_DEBUG, " -> Gather complete for block %d.\n", bi);
3276
3277 // B) BROADCAST: On non-root ranks, block_bboxlist is allocated. Then, the data
3278 // from rank 0 is broadcast to all ranks. After this call, ALL ranks have
3279 // an identical, complete copy of the bounding boxes for the current block.
3280 ierr = BroadcastAllBoundingBoxes(&user_finest[bi], &block_bboxlist); CHKERRQ(ierr);
3281 LOG_ALLOW(GLOBAL, LOG_DEBUG, " -> Broadcast complete for block %d.\n", bi);
3282
3283 // C) ASSEMBLE: Every rank now copies the data for this block into the
3284 // correct segment of its final, unified list.
3285 for (int r = 0; r < size; r++) {
3286 // The layout is [r0b0, r1b0, ..., r(size-1)b0, r0b1, r1b1, ...]
3287 final_bboxlist[bi * size + r] = block_bboxlist[r];
3288 }
3289 LOG_ALLOW(GLOBAL, LOG_DEBUG, " -> Assembly into final list complete for block %d.\n", bi);
3290
3291 // D) CLEANUP: Free the temporary list for this block on ALL ranks before the next iteration.
3292 // Your helper functions use malloc, so we must use free.
3293 free(block_bboxlist);
3294 }
3295
3296 // --- Step 4: Assign the final pointer and run the last setup step ---
3297 simCtx->bboxlist = final_bboxlist;
3298 LOG_ALLOW(GLOBAL, LOG_INFO, "Final unified bboxlist created on all ranks and stored in SimCtx.\n");
3299
3300 ierr = SetupDomainCellDecompositionMap(&user_finest[0]); CHKERRQ(ierr);
3301 LOG_ALLOW(GLOBAL, LOG_INFO, "Domain Cell Composition set and broadcasted.\n");
3302
3303 LOG_ALLOW(GLOBAL, LOG_INFO, "SetupDomainRankInfo: Completed successfully.\n");
3304
3306 PetscFunctionReturn(0);
3307}
PetscErrorCode BroadcastAllBoundingBoxes(UserCtx *user, BoundingBox **bboxlist)
Broadcasts the bounding box information collected on rank 0 to all other ranks.
Definition grid.c:1071
PetscErrorCode GatherAllBoundingBoxes(UserCtx *user, BoundingBox **allBBoxes)
Gathers local bounding boxes from all MPI processes to rank 0.
Definition grid.c:1011
PetscErrorCode ComputeAndStoreNeighborRanks(UserCtx *user)
Implementation of ComputeAndStoreNeighborRanks().
Definition setup.c:3116
PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user)
Implementation of SetupDomainCellDecompositionMap().
Definition setup.c:3467
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Contra2Cart()

PetscErrorCode Contra2Cart ( UserCtx *  user)

Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on cell faces.

This function performs the transformation from a contravariant velocity representation (which is natural on a curvilinear grid) to a Cartesian (x,y,z) representation. For each interior computational cell owned by the rank, it performs the following:

  1. It averages the contravariant velocity components (U¹, U², U³) from the surrounding faces to get an estimate of the contravariant velocity at the cell center.
  2. It averages the metric vectors (Csi, Eta, Zet) from the surrounding faces to get an estimate of the metric tensor at the cell center. This tensor forms the transformation matrix.
  3. It solves the linear system [MetricTensor] * [ucat] = [ucont] for the Cartesian velocity vector ucat = (u,v,w) using Cramer's rule.
  4. The computed Cartesian velocity is stored only at independent owned cells in the global user->Ucat vector.

The function operates on local, ghosted versions of the input vectors (user->lUcont, user->lCsi, etc.) to ensure stencils are valid across processor boundaries.

Parameters
[in,out]userPointer to the UserCtx structure. The function reads from user->lUcont, user->lCsi, user->lEta, user->lZet, user->lNvert and writes to the global user->Ucat vector.
Returns
PetscErrorCode 0 on success.
Note
  • This function should be called AFTER user->lUcont and all local metric vectors (user->lCsi, etc.) have been populated with up-to-date ghost values via UpdateLocalGhosts.
  • It only computes Ucat for interior cells (not on physical boundaries) and for cells not marked as solid/blanked by user->lNvert.
  • The function performs no communication, does not synchronize periodic duplicate planes, and does not refresh user->lUcat.
  • Before stencil consumption, the caller must synchronize periodic cell values with SynchronizePeriodicCellFields(user, 1, {FIELD_ID_UCAT}) and then call UpdateLocalGhosts(user, FIELD_ID_UCAT). The latter remains necessary for the fully nonperiodic case because periodic synchronization is then a no-op.

Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on cell faces.

See also
Contra2Cart()

Definition at line 3313 of file setup.c.

3314{
3315 PetscErrorCode ierr;
3316 DMDALocalInfo info;
3317 Cmpnts ***lcsi_arr, ***leta_arr, ***lzet_arr; // Local metric arrays
3318 Cmpnts ***lucont_arr; // Local contravariant velocity array
3319 Cmpnts ***gucat_arr; // Global Cartesian velocity array
3320 PetscReal ***lnvert_arr; // Local Nvert array
3321 PetscReal ***laj_arr; // Local Jacobian Determinant inverse array
3322
3323 PetscFunctionBeginUser;
3325 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Starting Contravariant-to-Cartesian velocity transformation.\n");
3326
3327 // --- 1. Get DMDA Info and Check for Valid Inputs ---
3328 // All inputs (lUcont, lCsi, etc.) and outputs (Ucat) are on DMs from the UserCtx.
3329 // We get local info from fda, which governs the layout of most arrays here.
3330 info = user->info;
3331 if (!user->lUcont || !user->lCsi || !user->lEta || !user->lZet || !user->lNvert || !user->Ucat) {
3332 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Contra2Cart requires lUcont, lCsi/Eta/Zet, lNvert, and Ucat to be non-NULL.");
3333 }
3334
3335
3336 // --- 2. Get Read-Only Array Access to Local Input Vectors (with ghosts) ---
3337 ierr = DMDAVecGetArrayRead(user->fda, user->lUcont, &lucont_arr); CHKERRQ(ierr);
3338 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, &lcsi_arr); CHKERRQ(ierr);
3339 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, &leta_arr); CHKERRQ(ierr);
3340 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, &lzet_arr); CHKERRQ(ierr);
3341 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, &lnvert_arr); CHKERRQ(ierr);
3342 ierr = DMDAVecGetArrayRead(user->da, user->lAj, &laj_arr); CHKERRQ(ierr);
3343
3344 // --- 3. Get Write-Only Array Access to the Global Output Vector ---
3345 // We compute for local owned cells and write into the global vector.
3346 // PETSc handles mapping the global indices to the correct local memory locations.
3347 ierr = DMDAVecGetArray(user->fda, user->Ucat, &gucat_arr); CHKERRQ(ierr);
3348
3349
3350 // --- 4. Define Loop Bounds for INTERIOR Cells ---
3351 // We use adjusted bounds to avoid calculating Ucat on the physical domain boundaries,
3352 // as these are typically set explicitly by boundary condition functions.
3353 // The stencils use indices like i-1, j-1, k-1, so we must start loops at least at index 1.
3354 PetscInt i_start = (info.xs == 0) ? info.xs + 1 : info.xs;
3355 PetscInt i_end = (info.xs + info.xm == info.mx) ? info.xs + info.xm - 1 : info.xs + info.xm;
3356
3357 PetscInt j_start = (info.ys == 0) ? info.ys + 1 : info.ys;
3358 PetscInt j_end = (info.ys + info.ym == info.my) ? info.ys + info.ym - 1 : info.ys + info.ym;
3359
3360 PetscInt k_start = (info.zs == 0) ? info.zs + 1 : info.zs;
3361 PetscInt k_end = (info.zs + info.zm == info.mz) ? info.zs + info.zm - 1 : info.zs + info.zm;
3362
3363 // --- 5. Main Computation Loop ---
3364 // Loops over the GLOBAL indices of interior cells owned by this rank.
3365 for (PetscInt k_cell = k_start; k_cell < k_end; ++k_cell) {
3366 for (PetscInt j_cell = j_start; j_cell < j_end; ++j_cell) {
3367 for (PetscInt i_cell = i_start; i_cell < i_end; ++i_cell) {
3368
3369 // Check if the cell is a fluid cell (not solid/blanked)
3370 // if (lnvert_arr[k_cell][j_cell][i_cell] > 0.1) continue; // Skip solid/blanked cells
3371
3372 const Cmpnts centre = {0.5, 0.5, 0.5};
3373 ierr = ContravariantToCartesianInCell(lucont_arr, lcsi_arr, leta_arr, lzet_arr, i_cell, j_cell, k_cell,
3374 centre, &gucat_arr[k_cell][j_cell][i_cell]); CHKERRQ(ierr);
3375 }
3376 }
3377 }
3378
3379 // --- 6. Restore Array Access ---
3380 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcont, &lucont_arr); CHKERRQ(ierr);
3381 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, &lcsi_arr); CHKERRQ(ierr);
3382 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, &leta_arr); CHKERRQ(ierr);
3383 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, &lzet_arr); CHKERRQ(ierr);
3384 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, &lnvert_arr); CHKERRQ(ierr);
3385 ierr = DMDAVecRestoreArrayRead(user->da, user->lAj, &laj_arr); CHKERRQ(ierr);
3386 ierr = DMDAVecRestoreArray(user->fda, user->Ucat, &gucat_arr); CHKERRQ(ierr);
3387
3388 LOG_ALLOW(GLOBAL, LOG_INFO, "Completed Contravariant-to-Cartesian velocity transformation. \n");
3390 PetscFunctionReturn(0);
3391}
static PetscErrorCode ContravariantToCartesianInCell(Cmpnts ***lucont, Cmpnts ***lcsi, Cmpnts ***leta, Cmpnts ***lzet, PetscInt i, PetscInt j, PetscInt k, Cmpnts w, Cmpnts *ucat)
Cartesian velocity at a point of one cell from the cell's face fluxes.
Definition setup.h:503
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ContravariantToCartesianInCell()

static PetscErrorCode ContravariantToCartesianInCell ( Cmpnts ***  lucont,
Cmpnts ***  lcsi,
Cmpnts ***  leta,
Cmpnts ***  lzet,
PetscInt  i,
PetscInt  j,
PetscInt  k,
Cmpnts  w,
Cmpnts *  ucat 
)
inlinestatic

Cartesian velocity at a point of one cell from the cell's face fluxes.

Each contravariant flux (U^1, U^2, U^3) and each face-area vector row (Csi, Eta, Zet) is interpolated linearly between the cell's two faces of that family, at the fraction w.x, w.y, w.z of the way from the minimum face, and S_i . u = U^i is solved by Cramer's rule. With w = (1/2, 1/2, 1/2) this is the cell-centre value Contra2Cart() stores. The flux through each face family varies linearly along that family's own axis, so on a cell whose face-area vectors do not vary along their own axis (any rectilinear cell) the velocity's divergence is the cell's discrete flux divergence, and zero when the fluxes are divergence-free. It is inline and has no profiling hook: it runs once per cell or particle, inside Contra2Cart()'s loop on the solver's hot path.

Parameters
[in]lucontGhosted local Ucont array.
[in]lcsiGhosted local Csi array.
[in]letaGhosted local Eta array.
[in]lzetGhosted local Zet array.
[in]iCell index in cell-centred array numbering (physical cell i - 1).
[in]jAs i, for the j direction.
[in]kAs i, for the k direction.
[in]wPosition in the cell, each component in [0, 1] from the minimum face.
[out]ucatCartesian velocity at that position.
Returns
PetscErrorCode 0 on success; PETSC_ERR_FLOP_COUNT when the face-area vectors are degenerate.

Definition at line 503 of file setup.h.

505{
506 PetscFunctionBeginUser;
507 // Transformation matrix [mat]: the face-area vectors at the point, each family
508 // interpolated between the cell's two faces of that family.
509 PetscReal mat[3][3];
510
511 mat[0][0] = (1.0 - w.x) * lcsi[k][j][i-1].x + w.x * lcsi[k][j][i].x;
512 mat[0][1] = (1.0 - w.x) * lcsi[k][j][i-1].y + w.x * lcsi[k][j][i].y;
513 mat[0][2] = (1.0 - w.x) * lcsi[k][j][i-1].z + w.x * lcsi[k][j][i].z;
514
515 mat[1][0] = (1.0 - w.y) * leta[k][j-1][i].x + w.y * leta[k][j][i].x;
516 mat[1][1] = (1.0 - w.y) * leta[k][j-1][i].y + w.y * leta[k][j][i].y;
517 mat[1][2] = (1.0 - w.y) * leta[k][j-1][i].z + w.y * leta[k][j][i].z;
518
519 mat[2][0] = (1.0 - w.z) * lzet[k-1][j][i].x + w.z * lzet[k][j][i].x;
520 mat[2][1] = (1.0 - w.z) * lzet[k-1][j][i].y + w.z * lzet[k][j][i].y;
521 mat[2][2] = (1.0 - w.z) * lzet[k-1][j][i].z + w.z * lzet[k][j][i].z;
522
523 // Contravariant velocity vector `q` at the point, interpolated the same way.
524 PetscReal q[3];
525 q[0] = (1.0 - w.x) * lucont[k][j][i-1].x + w.x * lucont[k][j][i].x; // U¹
526 q[1] = (1.0 - w.y) * lucont[k][j-1][i].y + w.y * lucont[k][j][i].y; // U²
527 q[2] = (1.0 - w.z) * lucont[k-1][j][i].z + w.z * lucont[k][j][i].z; // U³
528
529 // Solve the 3x3 system `mat * ucat = q` using Cramer's rule.
530 PetscReal det = mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) -
531 mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) +
532 mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]);
533
534 if (PetscAbsReal(det) < 1.0e-18) {
535 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FLOP_COUNT, "Transformation matrix determinant is near zero at cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") \n", i, j, k);
536 }
537
538 PetscReal det_inv = 1.0 / det;
539
540 PetscReal det0 = q[0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) -
541 q[1] * (mat[0][1] * mat[2][2] - mat[0][2] * mat[2][1]) +
542 q[2] * (mat[0][1] * mat[1][2] - mat[0][2] * mat[1][1]);
543
544 PetscReal det1 = -q[0] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) +
545 q[1] * (mat[0][0] * mat[2][2] - mat[0][2] * mat[2][0]) -
546 q[2] * (mat[0][0] * mat[1][2] - mat[0][2] * mat[1][0]);
547
548 PetscReal det2 = q[0] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]) -
549 q[1] * (mat[0][0] * mat[2][1] - mat[0][1] * mat[2][0]) +
550 q[2] * (mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]);
551
552 ucat->x = det0 * det_inv;
553 ucat->y = det1 * det_inv;
554 ucat->z = det2 * det_inv;
555 PetscFunctionReturn(0);
556}
PetscScalar z
Definition variables.h:145
PetscScalar y
Definition variables.h:145
Here is the caller graph for this function:

◆ Cart2Contra()

PetscErrorCode Cart2Contra ( UserCtx *  user)

Convert the ghosted Cartesian velocity field to contravariant face fluxes.

Interpolates user->lUcat to each logical face and dots it with the corresponding face-area metric vector. Writes independent entries of user->Ucont. Periodic and physical endpoint values in user->lUcat must be finalized and its MPI ghosts current before entry. The resulting Ucont is not synchronized; callers must use the staggered-field workflow before stencil use.

Parameters
[in,out]userUserCtx for the block; Ucont is written in place.
Returns
PetscErrorCode 0 on success.

Convert the ghosted Cartesian velocity field to contravariant face fluxes.

Definition at line 3396 of file setup.c.

3397{
3398 PetscErrorCode ierr;
3399 DMDALocalInfo info;
3400 const Cmpnts ***ucat_arr, ***csi_arr, ***eta_arr, ***zet_arr;
3401 Cmpnts ***ucont_arr;
3402
3403 PetscFunctionBeginUser;
3405
3406 info = user->info;
3407 ierr = DMDAVecGetArrayRead(user->fda, user->lUcat, &ucat_arr); CHKERRQ(ierr);
3408 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, &csi_arr); CHKERRQ(ierr);
3409 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, &eta_arr); CHKERRQ(ierr);
3410 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, &zet_arr); CHKERRQ(ierr);
3411 ierr = DMDAVecGetArray(user->fda, user->Ucont, &ucont_arr); CHKERRQ(ierr);
3412
3413 const PetscInt i_start = PetscMax(info.xs, 1);
3414 const PetscInt j_start = PetscMax(info.ys, 1);
3415 const PetscInt k_start = PetscMax(info.zs, 1);
3416 const PetscInt i_end = PetscMin(info.xs + info.xm, info.mx - 1);
3417 const PetscInt j_end = PetscMin(info.ys + info.ym, info.my - 1);
3418 const PetscInt k_end = PetscMin(info.zs + info.zm, info.mz - 1);
3419
3420 for (PetscInt k = k_start; k < k_end; k++) {
3421 for (PetscInt j = j_start; j < j_end; j++) {
3422 for (PetscInt i = i_start; i < i_end; i++) {
3423 const Cmpnts u_xi = {
3424 0.5 * (ucat_arr[k][j][i].x + ucat_arr[k][j][i + 1].x),
3425 0.5 * (ucat_arr[k][j][i].y + ucat_arr[k][j][i + 1].y),
3426 0.5 * (ucat_arr[k][j][i].z + ucat_arr[k][j][i + 1].z)
3427 };
3428 const Cmpnts u_eta = {
3429 0.5 * (ucat_arr[k][j][i].x + ucat_arr[k][j + 1][i].x),
3430 0.5 * (ucat_arr[k][j][i].y + ucat_arr[k][j + 1][i].y),
3431 0.5 * (ucat_arr[k][j][i].z + ucat_arr[k][j + 1][i].z)
3432 };
3433 const Cmpnts u_zeta = {
3434 0.5 * (ucat_arr[k][j][i].x + ucat_arr[k + 1][j][i].x),
3435 0.5 * (ucat_arr[k][j][i].y + ucat_arr[k + 1][j][i].y),
3436 0.5 * (ucat_arr[k][j][i].z + ucat_arr[k + 1][j][i].z)
3437 };
3438 ucont_arr[k][j][i].x = csi_arr[k][j][i].x * u_xi.x + csi_arr[k][j][i].y * u_xi.y + csi_arr[k][j][i].z * u_xi.z;
3439 ucont_arr[k][j][i].y = eta_arr[k][j][i].x * u_eta.x + eta_arr[k][j][i].y * u_eta.y + eta_arr[k][j][i].z * u_eta.z;
3440 ucont_arr[k][j][i].z = zet_arr[k][j][i].x * u_zeta.x + zet_arr[k][j][i].y * u_zeta.y + zet_arr[k][j][i].z * u_zeta.z;
3441 }
3442 }
3443 }
3444
3445 ierr = DMDAVecRestoreArray(user->fda, user->Ucont, &ucont_arr); CHKERRQ(ierr);
3446 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, &zet_arr); CHKERRQ(ierr);
3447 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, &eta_arr); CHKERRQ(ierr);
3448 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, &csi_arr); CHKERRQ(ierr);
3449 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcat, &ucat_arr); CHKERRQ(ierr);
3450
3452 PetscFunctionReturn(0);
3453}
Here is the caller graph for this function:

◆ SetupDomainCellDecompositionMap()

PetscErrorCode SetupDomainCellDecompositionMap ( UserCtx *  user)

Creates and distributes a map of the domain's cell decomposition to all ranks.

This function is a critical part of the simulation setup. It determines the global cell ownership for each MPI rank and makes this information available to all other ranks. This "decomposition map" is essential for the robust "Walk and Handoff" particle migration strategy, allowing any rank to quickly identify the owner of a target cell.

The process involves:

  1. Each rank gets its own node ownership information from the DMDA.
  2. It converts this node information into cell ownership ranges using the GetOwnedCellRange helper function.
  3. It participates in an MPI_Allgather collective operation to build a complete array (user->RankCellInfoMap) containing the ownership information for every rank.

This function should be called once during initialization after the primary DMDA (user->da) has been set up.

Parameters
[in,out]userPointer to the UserCtx structure. The function will allocate and populate user->RankCellInfoMap and set user->num_ranks.
Returns
PetscErrorCode 0 on success, or a non-zero PETSc error code on failure. Errors can occur if input pointers are NULL or if MPI communication fails.

Creates and distributes a map of the domain's cell decomposition to all ranks.

See also
SetupDomainCellDecompositionMap()

Definition at line 3467 of file setup.c.

3468{
3469 PetscErrorCode ierr;
3470 DMDALocalInfo local_node_info;
3471 RankCellInfo my_cell_info;
3472 PetscMPIInt rank, size;
3473
3474 PetscFunctionBeginUser;
3476
3477 // --- 1. Input Validation and MPI Info ---
3478 if (!user) {
3479 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx pointer is NULL in SetupDomainCellDecompositionMap.");
3480 }
3481 if (!user->da) {
3482 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "user->da is not initialized in SetupDomainCellDecompositionMap.");
3483 }
3484
3485 rank = PetscGlobalRank;
3486 size = PetscGlobalSize;
3487
3488 LOG_ALLOW(GLOBAL, LOG_INFO, "Setting up domain cell decomposition map for %d ranks.\n", size);
3489
3490 // --- 2. Determine Local Cell Ownership ---
3491 // Get the local node ownership information from the primary DMDA.
3492 local_node_info = user->info;
3493
3494 // Use the robust helper function to convert node ownership to cell ownership.
3495 // A cell's index is defined by its origin node.
3496
3497 ierr = GetOwnedCellRange(&local_node_info, 0, &my_cell_info.xs_cell, &my_cell_info.xm_cell); CHKERRQ(ierr);
3498 ierr = GetOwnedCellRange(&local_node_info, 1, &my_cell_info.ys_cell, &my_cell_info.ym_cell); CHKERRQ(ierr);
3499 ierr = GetOwnedCellRange(&local_node_info, 2, &my_cell_info.zs_cell, &my_cell_info.zm_cell); CHKERRQ(ierr);
3500
3501 // Log the calculated local ownership for debugging purposes.
3502 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d] Owns cells: i[%" PetscInt_FMT ", %" PetscInt_FMT "), j[%" PetscInt_FMT ", %" PetscInt_FMT "), k[%" PetscInt_FMT ", %" PetscInt_FMT ")\n",
3503 rank, my_cell_info.xs_cell, my_cell_info.xs_cell + my_cell_info.xm_cell,
3504 my_cell_info.ys_cell, my_cell_info.ys_cell + my_cell_info.ym_cell,
3505 my_cell_info.zs_cell, my_cell_info.zs_cell + my_cell_info.zm_cell);
3506
3507 // --- 3. Allocate and Distribute the Global Map ---
3508 // Allocate memory for the global map that will hold information from all ranks.
3509 ierr = PetscMalloc1(size, &user->RankCellInfoMap); CHKERRQ(ierr);
3510
3511 // Perform the collective communication to gather the `RankCellInfo` struct from every rank.
3512 // Each rank sends its `my_cell_info` and receives the complete array in `user->RankCellInfoMap`.
3513 // We use MPI_BYTE to ensure portability across different systems and struct padding.
3514 ierr = MPI_Allgather(&my_cell_info, sizeof(RankCellInfo), MPI_BYTE,
3515 user->RankCellInfoMap, sizeof(RankCellInfo), MPI_BYTE,
3516 PETSC_COMM_WORLD); CHKERRQ(ierr);
3517 ierr = DMDAGetInfo(user->da, NULL, NULL, NULL, NULL, &user->RankCellInfoProcs[0], &user->RankCellInfoProcs[1],
3518 &user->RankCellInfoProcs[2], NULL, NULL, NULL, NULL, NULL, NULL); CHKERRQ(ierr);
3519
3520 LOG_ALLOW(GLOBAL, LOG_INFO, "Domain cell decomposition map created and distributed successfully.\n");
3521
3523 PetscFunctionReturn(0);
3524}
PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
Implementation of GetOwnedCellRange().
Definition setup.c:3021
PetscInt ys_cell
Definition variables.h:264
PetscInt xs_cell
Definition variables.h:264
PetscInt zm_cell
Definition variables.h:265
PetscInt zs_cell
Definition variables.h:264
PetscInt RankCellInfoProcs[3]
DMDA process grid (m, n, p) of RankCellInfoMap: rank i + m (j + n k).
Definition variables.h:1275
PetscInt xm_cell
Definition variables.h:265
RankCellInfo * RankCellInfoMap
Definition variables.h:1274
PetscInt ym_cell
Definition variables.h:265
A lean struct to hold the global cell ownership range for a single MPI rank.
Definition variables.h:263
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BinarySearchInt64()

PetscErrorCode BinarySearchInt64 ( PetscInt  n,
const PetscInt64  arr[],
PetscInt64  key,
PetscBool *  found 
)

Performs a binary search for a key in a sorted array of PetscInt64.

This is a standard binary search algorithm implemented as a PETSc-style helper function. It efficiently determines if a given key exists within a sorted array.

Parameters
[in]nThe number of elements in the array.
[in]arrA pointer to the sorted array of PetscInt64 values to be searched.
[in]keyThe PetscInt64 value to search for.
[out]foundA pointer to a PetscBool that will be set to PETSC_TRUE if the key is found, and PETSC_FALSE otherwise.
Returns
PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
Note
The input array arr must be sorted in ascending order for the algorithm to work correctly.

Performs a binary search for a key in a sorted array of PetscInt64.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
BinarySearchInt64()

Definition at line 3532 of file setup.c.

3533{
3534 PetscInt low = 0, high = n - 1;
3535
3536 PetscFunctionBeginUser;
3538
3539 // --- 1. Input Validation ---
3540 if (!found) {
3541 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output pointer 'found' is NULL in PetscBinarySearchInt64.");
3542 }
3543 if (n > 0 && !arr) {
3544 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input array 'arr' is NULL for n > 0.");
3545 }
3546
3547 // Initialize output
3548 *found = PETSC_FALSE;
3549
3550 // --- 2. Binary Search Algorithm ---
3551 while (low <= high) {
3552 // Use this form to prevent potential integer overflow on very large arrays
3553 PetscInt mid = low + (high - low) / 2;
3554
3555 if (arr[mid] == key) {
3556 *found = PETSC_TRUE; // Key found!
3557 break; // Exit the loop
3558 }
3559
3560 if (arr[mid] < key) {
3561 low = mid + 1; // Search in the right half
3562 } else {
3563 high = mid - 1; // Search in the left half
3564 }
3565 }
3566
3568 PetscFunctionReturn(0);
3569}
Here is the caller graph for this function:

◆ ComputeDivergence()

PetscErrorCode ComputeDivergence ( UserCtx *  user)

Computes the discrete divergence of the contravariant velocity field.

This diagnostic/kernel routine evaluates continuity residuals on the local block and writes the resulting divergence field into the configured output vector(s).

Parameters
[in,out]userBlock-level context containing velocity and metric fields.
Returns
PetscErrorCode 0 on success.

Computes the discrete divergence of the contravariant velocity field.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
ComputeDivergence()

Definition at line 3599 of file setup.c.

3600{
3601 PetscErrorCode ierr;
3602 DM da = user->da, fda = user->fda;
3603 DMDALocalInfo info = user->info;
3604
3605 PetscInt ti = user->simCtx->step;
3606
3607 PetscInt xs = info.xs, xe = info.xs + info.xm;
3608 PetscInt ys = info.ys, ye = info.ys + info.ym;
3609 PetscInt zs = info.zs, ze = info.zs + info.zm;
3610 PetscInt mx = info.mx, my = info.my, mz = info.mz;
3611
3612 PetscInt lxs, lys, lzs, lxe, lye, lze;
3613 PetscInt i, j, k;
3614
3615 Vec Div;
3616 PetscReal ***div, ***aj, ***nvert;
3617 Cmpnts ***ucont;
3618 PetscReal maxdiv;
3619
3620 lxs = xs; lxe = xe;
3621 lys = ys; lye = ye;
3622 lzs = zs; lze = ze;
3623
3624 if (xs==0) lxs = xs+1;
3625 if (ys==0) lys = ys+1;
3626 if (zs==0) lzs = zs+1;
3627
3628 if (xe==mx) lxe = xe-1;
3629 if (ye==my) lye = ye-1;
3630 if (ze==mz) lze = ze-1;
3631
3632 PetscFunctionBeginUser;
3634
3635 DMDAVecGetArray(fda,user->lUcont, &ucont);
3636 DMDAVecGetArray(da, user->lAj, &aj);
3637 VecDuplicate(user->P, &Div);
3638 DMDAVecGetArray(da, Div, &div);
3639 DMDAVecGetArray(da, user->lNvert, &nvert);
3640
3641 for (k=lzs; k<lze; k++) {
3642 for (j=lys; j<lye; j++) {
3643 for (i=lxs; i<lxe; i++) {
3644 maxdiv = fabs((ucont[k][j][i].x - ucont[k][j][i-1].x +
3645 ucont[k][j][i].y - ucont[k][j-1][i].y +
3646 ucont[k][j][i].z - ucont[k-1][j][i].z)*aj[k][j][i]);
3647 if (nvert[k][j][i] + nvert[k+1][j][i] + nvert[k-1][j][i] +
3648 nvert[k][j+1][i] + nvert[k][j-1][i] +
3649 nvert[k][j][i+1] + nvert[k][j][i-1] > 0.1) maxdiv = 0.;
3650 div[k][j][i] = maxdiv;
3651
3652 }
3653 }
3654 }
3655
3656 if (zs==0) {
3657 k=0;
3658 for (j=ys; j<ye; j++) {
3659 for (i=xs; i<xe; i++) {
3660 div[k][j][i] = 0.;
3661 }
3662 }
3663 }
3664
3665 if (ze == mz) {
3666 k=mz-1;
3667 for (j=ys; j<ye; j++) {
3668 for (i=xs; i<xe; i++) {
3669 div[k][j][i] = 0.;
3670 }
3671 }
3672 }
3673
3674 if (xs==0) {
3675 i=0;
3676 for (k=zs; k<ze; k++) {
3677 for (j=ys; j<ye; j++) {
3678 div[k][j][i] = 0.;
3679 }
3680 }
3681 }
3682
3683 if (xe==mx) {
3684 i=mx-1;
3685 for (k=zs; k<ze; k++) {
3686 for (j=ys; j<ye; j++) {
3687 div[k][j][i] = 0;
3688 }
3689 }
3690 }
3691
3692 if (ys==0) {
3693 j=0;
3694 for (k=zs; k<ze; k++) {
3695 for (i=xs; i<xe; i++) {
3696 div[k][j][i] = 0.;
3697 }
3698 }
3699 }
3700
3701 if (ye==my) {
3702 j=my-1;
3703 for (k=zs; k<ze; k++) {
3704 for (i=xs; i<xe; i++) {
3705 div[k][j][i] = 0.;
3706 }
3707 }
3708 }
3709 DMDAVecRestoreArray(da, Div, &div);
3710 PetscInt MaxFlatIndex;
3711
3712 VecMax(Div, &MaxFlatIndex, &maxdiv);
3713
3714 LOG_ALLOW(GLOBAL,LOG_INFO,"[Step %" PetscInt_FMT "]] The Maximum Divergence is %e at flat index %" PetscInt_FMT ".\n",ti,maxdiv,MaxFlatIndex);
3715
3716 user->simCtx->MaxDivFlatArg = MaxFlatIndex;
3717 user->simCtx->MaxDiv = maxdiv;
3718
3719 /* The owning rank finds the location; every rank (rank 0 writes the continuity log) gets it. */
3720 PetscInt max_location[3] = {-1, -1, -1};
3721 for (k=zs; k<ze; k++) {
3722 for (j=ys; j<ye; j++) {
3723 for (i=xs; i<xe; i++) {
3724 if (Gidx(i,j,k,user) == MaxFlatIndex) {
3725 max_location[0] = k; max_location[1] = j; max_location[2] = i;
3726 }
3727 }
3728 }
3729 }
3730 ierr = MPI_Allreduce(MPI_IN_PLACE, max_location, 3, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3731 user->simCtx->MaxDivz = max_location[0];
3732 user->simCtx->MaxDivy = max_location[1];
3733 user->simCtx->MaxDivx = max_location[2];
3734 LOG_ALLOW(GLOBAL,LOG_INFO,"[Step %" PetscInt_FMT "] The Maximum Divergence(%e) is at location [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "]. \n", ti, maxdiv, max_location[0], max_location[1], max_location[2]);
3735
3736
3737 DMDAVecRestoreArray(da, user->lNvert, &nvert);
3738 DMDAVecRestoreArray(fda, user->lUcont, &ucont);
3739 DMDAVecRestoreArray(da, user->lAj, &aj);
3740 VecDestroy(&Div);
3741
3743 PetscFunctionReturn(0);
3744}
static PetscInt Gidx(PetscInt i, PetscInt j, PetscInt k, UserCtx *user)
Convert logical indices into the flattened global index used by setup helpers.
Definition setup.c:3575
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TransformScalarDerivativesToPhysical()

void TransformScalarDerivativesToPhysical ( PetscReal  jacobian,
Cmpnts  csi_metrics,
Cmpnts  eta_metrics,
Cmpnts  zet_metrics,
PetscReal  dPhi_dcsi,
PetscReal  dPhi_deta,
PetscReal  dPhi_dzet,
Cmpnts *  gradPhi 
)

Transforms scalar derivatives from computational space to physical space.

using the chain rule. Formula: dPhi/dx = J * ( dPhi/dCsi * dCsi/dx + dPhi/dEta * dEta/dx + ... )

Parameters
jacobianLocal mapping Jacobian determinant.
csi_metricsPhysical gradient of the xi coordinate.
eta_metricsPhysical gradient of the eta coordinate.
zet_metricsPhysical gradient of the zeta coordinate.
dPhi_dcsiScalar derivative in the xi direction.
dPhi_detaScalar derivative in the eta direction.
dPhi_dzetScalar derivative in the zeta direction.
[out]gradPhiPhysical Cartesian scalar gradient.

Transforms scalar derivatives from computational space to physical space.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
TransformScalarDerivativesToPhysical()

Definition at line 3753 of file setup.c.

3761{
3763 // Gradient X component
3764 gradPhi->x = jacobian * (dPhi_dcsi * csi_metrics.x + dPhi_deta * eta_metrics.x + dPhi_dzet * zet_metrics.x);
3765
3766 // Gradient Y component
3767 gradPhi->y = jacobian * (dPhi_dcsi * csi_metrics.y + dPhi_deta * eta_metrics.y + dPhi_dzet * zet_metrics.y);
3768
3769 // Gradient Z component
3770 gradPhi->z = jacobian * (dPhi_dcsi * csi_metrics.z + dPhi_deta * eta_metrics.z + dPhi_dzet * zet_metrics.z);
3772}
Here is the caller graph for this function:

◆ ComputeScalarFieldDerivatives()

PetscErrorCode ComputeScalarFieldDerivatives ( UserCtx *  user,
PetscInt  i,
PetscInt  j,
PetscInt  k,
PetscReal ***  field_data,
Cmpnts *  grad 
)

Computes the gradient of a cell-centered SCALAR field at a specific grid point.

Parameters
userBlock metric context.
iCell index in the xi direction.
jCell index in the eta direction.
kCell index in the zeta direction.
field_dataGhosted scalar values indexed as [k][j][i].
[out]gradPhysical Cartesian gradient at the requested cell.
Returns
PetscErrorCode 0 on success.

Computes the gradient of a cell-centered SCALAR field at a specific grid point.

See also
ComputeScalarFieldDerivatives()

Definition at line 3799 of file setup.c.

3801{
3802 PetscErrorCode ierr;
3803 Cmpnts ***csi, ***eta, ***zet;
3804 PetscReal ***jac;
3805 PetscReal d_csi, d_eta, d_zet;
3806
3807 PetscFunctionBeginUser;
3809
3810 // 1. Get read-only access to metrics
3811 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
3812 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
3813 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
3814 ierr = DMDAVecGetArrayRead(user->da, user->lAj, &jac); CHKERRQ(ierr);
3815
3816 // 2. Compute derivatives in computational space (Central Difference)
3817 // Assumes ghosts are available at i+/-1
3818 d_csi = 0.5 * (field_data[k][j][i+1] - field_data[k][j][i-1]);
3819 d_eta = 0.5 * (field_data[k][j+1][i] - field_data[k][j-1][i]);
3820 d_zet = 0.5 * (field_data[k+1][j][i] - field_data[k-1][j][i]);
3821
3822 // 3. Transform to physical space
3824 csi[k][j][i], eta[k][j][i], zet[k][j][i],
3825 d_csi, d_eta, d_zet,
3826 grad);
3827
3828 // 4. Restore arrays
3829 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
3830 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
3831 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
3832 ierr = DMDAVecRestoreArrayRead(user->da, user->lAj, &jac); CHKERRQ(ierr);
3833
3835 PetscFunctionReturn(0);
3836}
void TransformScalarDerivativesToPhysical(PetscReal jacobian, Cmpnts csi_metrics, Cmpnts eta_metrics, Cmpnts zet_metrics, PetscReal dPhi_dcsi, PetscReal dPhi_deta, PetscReal dPhi_dzet, Cmpnts *gradPhi)
Implementation of TransformScalarDerivativesToPhysical().
Definition setup.c:3753
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeVectorFieldDerivatives()

PetscErrorCode ComputeVectorFieldDerivatives ( UserCtx *  user,
PetscInt  i,
PetscInt  j,
PetscInt  k,
Cmpnts ***  field_data,
Cmpnts *  dudx,
Cmpnts *  dvdx,
Cmpnts *  dwdx 
)

Computes the derivatives of a cell-centered vector field at a specific grid point.

This function orchestrates the calculation of spatial derivatives. It first computes the derivatives in computational space (d/dcsi, d/deta, d/dzet) using a central difference scheme and then transforms them into physical space (d/dx, d/dy, d/dz).

Parameters
userBlock metric context.
iCell index in the xi direction.
jCell index in the eta direction.
kCell index in the zeta direction.
field_dataGhosted Cartesian vector values indexed as [k][j][i].
[out]dudxGradient of the x velocity component.
[out]dvdxGradient of the y velocity component.
[out]dwdxGradient of the z velocity component.
Returns
PetscErrorCode 0 on success.

Computes the derivatives of a cell-centered vector field at a specific grid point.

See also
ComputeVectorFieldDerivatives()

Definition at line 3842 of file setup.c.

3844{
3845 PetscErrorCode ierr;
3846 Cmpnts ***csi, ***eta, ***zet;
3847 PetscReal ***jac;
3848 PetscFunctionBeginUser;
3849
3850 // 1. Get read-only access to the necessary metric data arrays
3851 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
3852 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
3853 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
3854 ierr = DMDAVecGetArrayRead(user->da, user->lAj, &jac); CHKERRQ(ierr);
3855
3856 // 2. Calculate derivatives in computational space using central differencing
3857 Cmpnts deriv_csi, deriv_eta, deriv_zet;
3858 deriv_csi.x = (field_data[k][j][i+1].x - field_data[k][j][i-1].x) * 0.5;
3859 deriv_csi.y = (field_data[k][j][i+1].y - field_data[k][j][i-1].y) * 0.5;
3860 deriv_csi.z = (field_data[k][j][i+1].z - field_data[k][j][i-1].z) * 0.5;
3861
3862 deriv_eta.x = (field_data[k][j+1][i].x - field_data[k][j-1][i].x) * 0.5;
3863 deriv_eta.y = (field_data[k][j+1][i].y - field_data[k][j-1][i].y) * 0.5;
3864 deriv_eta.z = (field_data[k][j+1][i].z - field_data[k][j-1][i].z) * 0.5;
3865
3866 deriv_zet.x = (field_data[k+1][j][i].x - field_data[k-1][j][i].x) * 0.5;
3867 deriv_zet.y = (field_data[k+1][j][i].y - field_data[k-1][j][i].y) * 0.5;
3868 deriv_zet.z = (field_data[k+1][j][i].z - field_data[k-1][j][i].z) * 0.5;
3869
3870 // 3. Transform derivatives to physical space
3871 TransformDerivativesToPhysical(jac[k][j][i], csi[k][j][i], eta[k][j][i], zet[k][j][i],
3872 deriv_csi, deriv_eta, deriv_zet,
3873 dudx, dvdx, dwdx);
3874
3875 // 4. Restore access to the PETSc data arrays
3876 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
3877 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
3878 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
3879 ierr = DMDAVecRestoreArrayRead(user->da, user->lAj, &jac); CHKERRQ(ierr);
3880
3881 PetscFunctionReturn(0);
3882}
static void TransformDerivativesToPhysical(PetscReal jacobian, Cmpnts csi_metrics, Cmpnts eta_metrics, Cmpnts zet_metrics, Cmpnts deriv_csi, Cmpnts deriv_eta, Cmpnts deriv_zet, Cmpnts *dudx, Cmpnts *dvdx, Cmpnts *dwdx)
Transform contravariant vector derivatives into physical Cartesian derivatives.
Definition setup.c:3777
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LESConfigSetDefaults()

PetscErrorCode LESConfigSetDefaults ( LESConfig *  config)

Installs the shipped defaults for every LES closure parameter.

One definition of the defaults, shared by the control-file ingress and by test fixtures, so the two cannot drift apart. It lives with the rest of the context construction because defaults are ingress, not closure behaviour, and because the postprocessor builds a simulation context without linking the LES module.

Local averaging and clamped limiting are the defaults because they are the only settings valid on arbitrary geometry; cases with homogeneous directions or an interest in backscatter opt into the alternatives.

Parameters
[out]configConfiguration block to populate.
Returns
PetscErrorCode 0 on success, or PETSC_ERR_ARG_NULL for a null argument.

Installs the shipped defaults for every LES closure parameter.

Full API contract is documented with the header declaration in include/setup.h.

See also
LESConfigSetDefaults()

Definition at line 288 of file setup.c.

289{
290 PetscFunctionBeginUser;
292 PetscCheck(config != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
293 "LES configuration destination cannot be NULL.");
294
295 config->dynamic_frequency = 1;
296 config->constant_cs = 0.03;
297 // Vreman (2004) recommends c = 2.5 Cs^2, 0.07 for Cs = 0.17; Nicoud & Ducros (1999)
298 // calibrate C_w near 0.5-0.6 against the same isotropic decay. Both are calibrations
299 // from isotropic turbulence, not universal values.
300 config->vreman_coefficient = 0.07;
301 config->wale_coefficient = 0.5;
304 config->test_filter_width_ratio = 2.0;
305 // Local averaging makes no homogeneity claim, so it is the only default that is
306 // correct on every geometry. Homogeneous and global averaging are opted into.
308 config->averaging_direction[0] = PETSC_FALSE;
309 config->averaging_direction[1] = PETSC_FALSE;
310 config->averaging_direction[2] = PETSC_FALSE;
311 config->clip_mode = LES_CLIP_CLAMP;
312 // Roughly twice the physical Smagorinsky constant: high enough to catch a
313 // diverging coefficient, low enough that it does not shape the distribution.
314 config->max_cs = 0.3;
315 config->min_viscosity_ratio = 0.0;
316 config->yoshizawa_ci = 0.09;
317 config->diagnostics_enabled = PETSC_FALSE;
318 config->diagnostics_cadence = 1;
319
321 PetscFunctionReturn(0);
322}
PetscReal yoshizawa_ci
Yoshizawa constant for the reported SGS kinetic energy.
Definition variables.h:677
PetscInt dynamic_frequency
Recompute the dynamic coefficient every N steps.
Definition variables.h:665
LESFilterWidthModel filter_width_model
How the grid filter width Delta is derived per cell.
Definition variables.h:669
LESTestFilterKernel test_filter_kernel
Discrete test-filter stencil.
Definition variables.h:670
@ LES_CLIP_CLAMP
Definition variables.h:653
@ LES_TEST_FILTER_VOLUME_WEIGHTED_BOX
Definition variables.h:627
PetscReal max_cs
Ceiling on Cs under LES_CLIP_CLAMP.
Definition variables.h:675
LESClipMode clip_mode
Admissible range for the coefficient.
Definition variables.h:674
PetscBool averaging_direction[3]
Averaged-over logical directions (xi, eta, zeta).
Definition variables.h:673
PetscReal wale_coefficient
Model constant C_w for WALE (Nicoud & Ducros 1999).
Definition variables.h:668
PetscInt diagnostics_cadence
Steps between diagnostic rows.
Definition variables.h:679
PetscReal min_viscosity_ratio
Enforce nu + nu_t >= ratio * nu.
Definition variables.h:676
@ LES_AVERAGING_LOCAL
Definition variables.h:640
PetscBool diagnostics_enabled
Append per-step coefficient statistics to the run log directory.
Definition variables.h:678
PetscReal constant_cs
Fixed Cs for CONSTANT_SMAGORINSKY; unused by the dynamic model.
Definition variables.h:666
PetscReal test_filter_width_ratio
Test-to-grid ratio per filtered direction; alpha is its square for the box, ratio^(4/3) for Simpson.
Definition variables.h:671
LESAveragingMode averaging_mode
Averaging set for the Germano contractions.
Definition variables.h:672
PetscReal vreman_coefficient
Model constant c for VREMAN (Vreman 2004: 2.5 Cs^2).
Definition variables.h:667
@ LES_FILTER_WIDTH_CUBE_ROOT_VOLUME
Definition variables.h:615
Here is the caller graph for this function:

◆ DestroyUserVectors()

PetscErrorCode DestroyUserVectors ( UserCtx *  user)

Destroys all PETSc Vec objects within a single UserCtx structure.

This helper function systematically destroys the Vec objects stored in a UserCtx. The vectors are organized into functional groups for clarity:

  • Primary flow fields (Ucont, Ucat, P, Nvert)
  • Solver work vectors (Phi)
  • Time-stepping vectors (Ucont_o, Ucont_rm1, etc.)
  • Grid metrics (cell-centered, face-centered, coordinates)
  • Turbulence vectors (Nu_t, CS, lFriction_Velocity)
  • Particle vectors (ParticleCount, Psi)
  • Boundary condition vectors (Ubcs, Uch)
  • Post-processing vectors (P_nodal, Qcrit)
  • And more...

All destroys are protected with NULL checks to handle conditional allocations safely.

Parameters
[in,out]userPointer to the UserCtx containing the vectors to destroy.
Returns
PetscErrorCode 0 on success.

Destroys all PETSc Vec objects within a single UserCtx structure.

See also
DestroyUserVectors()

Definition at line 3894 of file setup.c.

3895{
3896 PetscErrorCode ierr;
3897 PetscFunctionBeginUser;
3899
3900 // --- Group A: Primary Flow Fields (Always allocated at all levels) ---
3901 if (user->Ucont) { ierr = VecDestroy(&user->Ucont); CHKERRQ(ierr); }
3902 if (user->lUcont) { ierr = VecDestroy(&user->lUcont); CHKERRQ(ierr); }
3903 if (user->Ucat) { ierr = VecDestroy(&user->Ucat); CHKERRQ(ierr); }
3904 if (user->lUcat) { ierr = VecDestroy(&user->lUcat); CHKERRQ(ierr); }
3905 if (user->P) { ierr = VecDestroy(&user->P); CHKERRQ(ierr); }
3906 if (user->lP) { ierr = VecDestroy(&user->lP); CHKERRQ(ierr); }
3907 if (user->Nvert) { ierr = VecDestroy(&user->Nvert); CHKERRQ(ierr); }
3908 if (user->lNvert) { ierr = VecDestroy(&user->lNvert); CHKERRQ(ierr); }
3909
3910 // --- Group A2: Derived Flow Fields (Conditional) ---
3911 if(user->Diffusivity) {ierr = VecDestroy(&user->Diffusivity); CHKERRQ(ierr);}
3912 if(user->lDiffusivity){ierr = VecDestroy(&user->lDiffusivity); CHKERRQ(ierr);}
3913 if(user->DiffusivityGradient){ierr = VecDestroy(&user->DiffusivityGradient); CHKERRQ(ierr);}
3914 if(user->lDiffusivityGradient){ierr = VecDestroy(&user->lDiffusivityGradient); CHKERRQ(ierr);}
3915
3916 // --- Group B: Solver Work Vectors (All levels) ---
3917 if (user->Phi) { ierr = VecDestroy(&user->Phi); CHKERRQ(ierr); }
3918 if (user->lPhi) { ierr = VecDestroy(&user->lPhi); CHKERRQ(ierr); }
3919
3920 // --- Group C: Time-Stepping Vectors (Finest level only) ---
3921 if (user->Ucont_o) { ierr = VecDestroy(&user->Ucont_o); CHKERRQ(ierr); }
3922 if (user->Ucont_rm1) { ierr = VecDestroy(&user->Ucont_rm1); CHKERRQ(ierr); }
3923 if (user->Ucat_o) { ierr = VecDestroy(&user->Ucat_o); CHKERRQ(ierr); }
3924 if (user->P_o) { ierr = VecDestroy(&user->P_o); CHKERRQ(ierr); }
3925 if (user->Nvert_o) { ierr = VecDestroy(&user->Nvert_o); CHKERRQ(ierr); }
3926 if (user->lUcont_o) { ierr = VecDestroy(&user->lUcont_o); CHKERRQ(ierr); }
3927 if (user->lUcont_rm1) { ierr = VecDestroy(&user->lUcont_rm1); CHKERRQ(ierr); }
3928 if (user->lNvert_o) { ierr = VecDestroy(&user->lNvert_o); CHKERRQ(ierr); }
3929
3930 // --- Group D: Grid Metrics - Face Centered (All levels) ---
3931 if (user->Csi) { ierr = VecDestroy(&user->Csi); CHKERRQ(ierr); }
3932 if (user->Eta) { ierr = VecDestroy(&user->Eta); CHKERRQ(ierr); }
3933 if (user->Zet) { ierr = VecDestroy(&user->Zet); CHKERRQ(ierr); }
3934 if (user->Aj) { ierr = VecDestroy(&user->Aj); CHKERRQ(ierr); }
3935 if (user->lCsi) { ierr = VecDestroy(&user->lCsi); CHKERRQ(ierr); }
3936 if (user->lEta) { ierr = VecDestroy(&user->lEta); CHKERRQ(ierr); }
3937 if (user->lZet) { ierr = VecDestroy(&user->lZet); CHKERRQ(ierr); }
3938 if (user->lAj) { ierr = VecDestroy(&user->lAj); CHKERRQ(ierr); }
3939
3940 // --- Group E: Grid Metrics - Face Centered (All levels) ---
3941 if (user->ICsi) { ierr = VecDestroy(&user->ICsi); CHKERRQ(ierr); }
3942 if (user->IEta) { ierr = VecDestroy(&user->IEta); CHKERRQ(ierr); }
3943 if (user->IZet) { ierr = VecDestroy(&user->IZet); CHKERRQ(ierr); }
3944 if (user->JCsi) { ierr = VecDestroy(&user->JCsi); CHKERRQ(ierr); }
3945 if (user->JEta) { ierr = VecDestroy(&user->JEta); CHKERRQ(ierr); }
3946 if (user->JZet) { ierr = VecDestroy(&user->JZet); CHKERRQ(ierr); }
3947 if (user->KCsi) { ierr = VecDestroy(&user->KCsi); CHKERRQ(ierr); }
3948 if (user->KEta) { ierr = VecDestroy(&user->KEta); CHKERRQ(ierr); }
3949 if (user->KZet) { ierr = VecDestroy(&user->KZet); CHKERRQ(ierr); }
3950 if (user->IAj) { ierr = VecDestroy(&user->IAj); CHKERRQ(ierr); }
3951 if (user->JAj) { ierr = VecDestroy(&user->JAj); CHKERRQ(ierr); }
3952 if (user->KAj) { ierr = VecDestroy(&user->KAj); CHKERRQ(ierr); }
3953 if (user->lICsi) { ierr = VecDestroy(&user->lICsi); CHKERRQ(ierr); }
3954 if (user->lIEta) { ierr = VecDestroy(&user->lIEta); CHKERRQ(ierr); }
3955 if (user->lIZet) { ierr = VecDestroy(&user->lIZet); CHKERRQ(ierr); }
3956 if (user->lJCsi) { ierr = VecDestroy(&user->lJCsi); CHKERRQ(ierr); }
3957 if (user->lJEta) { ierr = VecDestroy(&user->lJEta); CHKERRQ(ierr); }
3958 if (user->lJZet) { ierr = VecDestroy(&user->lJZet); CHKERRQ(ierr); }
3959 if (user->lKCsi) { ierr = VecDestroy(&user->lKCsi); CHKERRQ(ierr); }
3960 if (user->lKEta) { ierr = VecDestroy(&user->lKEta); CHKERRQ(ierr); }
3961 if (user->lKZet) { ierr = VecDestroy(&user->lKZet); CHKERRQ(ierr); }
3962 if (user->lIAj) { ierr = VecDestroy(&user->lIAj); CHKERRQ(ierr); }
3963 if (user->lJAj) { ierr = VecDestroy(&user->lJAj); CHKERRQ(ierr); }
3964 if (user->lKAj) { ierr = VecDestroy(&user->lKAj); CHKERRQ(ierr); }
3965
3966 // --- Group F: Cell/Face Coordinates and Grid Spacing (All levels) ---
3967 if (user->Cent) { ierr = VecDestroy(&user->Cent); CHKERRQ(ierr); }
3968 if (user->lCent) { ierr = VecDestroy(&user->lCent); CHKERRQ(ierr); }
3969 ierr = MetricDestroyFacePlanes(user); CHKERRQ(ierr);
3970 if (user->Centx) { ierr = VecDestroy(&user->Centx); CHKERRQ(ierr); }
3971 if (user->Centy) { ierr = VecDestroy(&user->Centy); CHKERRQ(ierr); }
3972 if (user->Centz) { ierr = VecDestroy(&user->Centz); CHKERRQ(ierr); }
3973 if (user->lCentx) { ierr = VecDestroy(&user->lCentx); CHKERRQ(ierr); }
3974 if (user->lCenty) { ierr = VecDestroy(&user->lCenty); CHKERRQ(ierr); }
3975 if (user->lCentz) { ierr = VecDestroy(&user->lCentz); CHKERRQ(ierr); }
3976
3977 // --- Group G: Turbulence Model Vectors (Finest level, conditional on les) ---
3978 if (user->Nu_t) { ierr = VecDestroy(&user->Nu_t); CHKERRQ(ierr); }
3979 if (user->lNu_t) { ierr = VecDestroy(&user->lNu_t); CHKERRQ(ierr); }
3980 if (user->CS) { ierr = VecDestroy(&user->CS); CHKERRQ(ierr); }
3981 if (user->lCs) { ierr = VecDestroy(&user->lCs); CHKERRQ(ierr); }
3982 if (user->Wall_Stress) { ierr = VecDestroy(&user->Wall_Stress); CHKERRQ(ierr); }
3983 if (user->lWall_Stress) { ierr = VecDestroy(&user->lWall_Stress); CHKERRQ(ierr); }
3984 if (user->InflowFluctuation) { ierr = VecDestroy(&user->InflowFluctuation); CHKERRQ(ierr); }
3985 if (user->lInflowFluctuation) { ierr = VecDestroy(&user->lInflowFluctuation); CHKERRQ(ierr); }
3986 if (user->Friction_Velocity) { ierr = VecDestroy(&user->Friction_Velocity); CHKERRQ(ierr); }
3987 if (user->lFriction_Velocity) { ierr = VecDestroy(&user->lFriction_Velocity); CHKERRQ(ierr); }
3988
3989 // --- Group H: Particle Vectors (Finest level, conditional on np > 0) ---
3990 if (user->ParticleCount) { ierr = VecDestroy(&user->ParticleCount); CHKERRQ(ierr); }
3991 if (user->lParticleCount) { ierr = VecDestroy(&user->lParticleCount); CHKERRQ(ierr); }
3992 if (user->Psi) { ierr = VecDestroy(&user->Psi); CHKERRQ(ierr); }
3993 if (user->lPsi) { ierr = VecDestroy(&user->lPsi); CHKERRQ(ierr); }
3994
3995 // --- Group I: Boundary Condition Vectors (All levels) ---
3996 if (user->Bcs.Ubcs) { ierr = VecDestroy(&user->Bcs.Ubcs); CHKERRQ(ierr); }
3997 if (user->Bcs.Uch) { ierr = VecDestroy(&user->Bcs.Uch); CHKERRQ(ierr); }
3998
3999 // --- Group J: Post-Processing Vectors (Finest level, postprocessor mode) ---
4000 if (user->P_nodal) { ierr = VecDestroy(&user->P_nodal); CHKERRQ(ierr); }
4001 if (user->Ucat_nodal) { ierr = VecDestroy(&user->Ucat_nodal); CHKERRQ(ierr); }
4002 if (user->Qcrit) { ierr = VecDestroy(&user->Qcrit); CHKERRQ(ierr); }
4003 if (user->lQcrit) { ierr = VecDestroy(&user->lQcrit); CHKERRQ(ierr); }
4004 if (user->Qcrit_nodal) { ierr = VecDestroy(&user->Qcrit_nodal); CHKERRQ(ierr); }
4005 if (user->Psi_nodal) { ierr = VecDestroy(&user->Psi_nodal); CHKERRQ(ierr); }
4006
4007 // --- Group K: Interpolation Vectors (Lazy allocation) ---
4008 if (user->fieldStatisticsStorage) {
4009 SimCtx *stats_ctx = user->simCtx;
4010 const PetscInt window_count = stats_ctx ? stats_ctx->fieldStatisticsWindowCount : 0;
4011 for (PetscInt w = 0; w < window_count; ++w) {
4012 ierr = PicurvWindowStorageDestroy(&user->fieldStatisticsStorage[w]); CHKERRQ(ierr);
4013 }
4014 ierr = PetscFree(user->fieldStatisticsStorage); CHKERRQ(ierr);
4015 user->fieldStatisticsStorage = NULL;
4016 }
4017 if (user->CellScalarAtCorner) { ierr = VecDestroy(&user->CellScalarAtCorner); CHKERRQ(ierr); }
4018 if (user->lCellScalarAtCorner) { ierr = VecDestroy(&user->lCellScalarAtCorner); CHKERRQ(ierr); }
4019 if (user->CellVectorAtCorner) { ierr = VecDestroy(&user->CellVectorAtCorner); CHKERRQ(ierr); }
4020 if (user->PostScalar) { ierr = VecDestroy(&user->PostScalar); CHKERRQ(ierr); }
4021 if (user->lPostScalar) { ierr = VecDestroy(&user->lPostScalar); CHKERRQ(ierr); }
4022 if (user->PostScalarNodal) { ierr = VecDestroy(&user->PostScalarNodal); CHKERRQ(ierr); }
4023 if (user->PostVector) { ierr = VecDestroy(&user->PostVector); CHKERRQ(ierr); }
4024 if (user->lPostVector) { ierr = VecDestroy(&user->lPostVector); CHKERRQ(ierr); }
4025 if (user->PostVectorNodal) { ierr = VecDestroy(&user->PostVectorNodal); CHKERRQ(ierr); }
4026 if (user->lCellVectorAtCorner) { ierr = VecDestroy(&user->lCellVectorAtCorner); CHKERRQ(ierr); }
4027
4028 // --- Group L: Implicit Solver Workspaces (kept for the run by the momentum solvers) ---
4029 if (user->Rhs) { ierr = VecDestroy(&user->Rhs); CHKERRQ(ierr); }
4030 if (user->dUcont) { ierr = VecDestroy(&user->dUcont); CHKERRQ(ierr); }
4031 if (user->pUcont) { ierr = VecDestroy(&user->pUcont); CHKERRQ(ierr); }
4032 if (user->pRhs) { ierr = VecDestroy(&user->pRhs); CHKERRQ(ierr); }
4033
4034 // --- Group M: Poisson Solver Vectors (kept for the run by PoissonSolver_Multigrid) ---
4035 if (user->B) { ierr = VecDestroy(&user->B); CHKERRQ(ierr); }
4036 if (user->R) { ierr = VecDestroy(&user->R); CHKERRQ(ierr); }
4037
4038 LOG_ALLOW(LOCAL, LOG_DEBUG, "All vectors destroyed for UserCtx.\n");
4040 PetscFunctionReturn(0);
4041}
PetscErrorCode MetricDestroyFacePlanes(UserCtx *user)
Frees the face-plane fields MetricComputeFacePlanes() built, if any.
Definition Metric.c:355
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
Vec pUcont
Definition variables.h:1207
Vec dUcont
Definition variables.h:1207
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DestroyUserContext()

PetscErrorCode DestroyUserContext ( UserCtx *  user)

Destroys all resources allocated within a single UserCtx structure.

This function cleans up all memory and PETSc objects associated with a single UserCtx (grid level). It calls the helper functions and destroys remaining objects in the proper dependency order:

  1. Boundary conditions (handlers and their data)
  2. All PETSc vectors (via DestroyUserVectors)
  3. Matrix and solver objects (A, MR, MP, ksp, nullsp)
  4. Application ordering (AO)
  5. Distributed mesh objects (DMs) - most derived first
  6. Raw PetscMalloc'd arrays (RankCellInfoMap)

This function should be called for each UserCtx in the multigrid hierarchy.

Parameters
[in,out]userPointer to the UserCtx to be destroyed.
Returns
PetscErrorCode 0 on success.

Destroys all resources allocated within a single UserCtx structure.

See also
DestroyUserContext()

Definition at line 4046 of file setup.c.

4047{
4048 PetscErrorCode ierr;
4049 PetscFunctionBeginUser;
4051
4052 if (!user) {
4053 LOG_ALLOW(LOCAL, LOG_WARNING, "DestroyUserContext called with NULL user pointer.\n");
4055 PetscFunctionReturn(0);
4056 }
4057
4058 LOG_ALLOW(LOCAL, LOG_INFO, "Destroying UserCtx at level %" PetscInt_FMT "...\n", user->thislevel);
4059
4060 // --- Step 1: Destroy Boundary Condition System ---
4061 // This handles all BC handlers and their private data.
4062 ierr = BoundarySystem_Destroy(user); CHKERRQ(ierr);
4063 LOG_ALLOW(LOCAL, LOG_DEBUG, " Boundary system destroyed.\n");
4064
4065 // --- Step 2: Destroy All Vectors ---
4066 // Handles ~74 Vec objects with proper NULL checking.
4067 ierr = DestroyUserVectors(user); CHKERRQ(ierr);
4068 LOG_ALLOW(LOCAL, LOG_DEBUG, " All vectors destroyed.\n");
4069
4070 // --- Step 3: Destroy Matrix and Solver Objects ---
4071 // Destroy pressure-Poisson matrices and solver.
4072 if (user->A) {
4073 ierr = MatDestroy(&user->A); CHKERRQ(ierr);
4074 LOG_ALLOW(LOCAL, LOG_DEBUG, " Matrix A destroyed.\n");
4075 }
4076 if (user->MR) {
4077 ierr = MatDestroy(&user->MR); CHKERRQ(ierr);
4078 LOG_ALLOW(LOCAL, LOG_DEBUG, " Matrix MR destroyed.\n");
4079 }
4080 if (user->MP) {
4081 ierr = MatDestroy(&user->MP); CHKERRQ(ierr);
4082 LOG_ALLOW(LOCAL, LOG_DEBUG, " Matrix MP destroyed.\n");
4083 }
4084 if (user->ksp) {
4085 ierr = KSPDestroy(&user->ksp); CHKERRQ(ierr);
4086 LOG_ALLOW(LOCAL, LOG_DEBUG, " KSP solver destroyed.\n");
4087 }
4088 if (user->nullsp) {
4089 ierr = MatNullSpaceDestroy(&user->nullsp); CHKERRQ(ierr);
4090 LOG_ALLOW(LOCAL, LOG_DEBUG, " MatNullSpace destroyed.\n");
4091 }
4092
4093 // --- Step 4: Destroy Application Ordering ---
4094 if (user->ao) {
4095 ierr = AODestroy(&user->ao); CHKERRQ(ierr);
4096 LOG_ALLOW(LOCAL, LOG_DEBUG, " AO destroyed.\n");
4097 }
4098
4099 // --- Step 5: Destroy DM Objects ---
4100 // Destroy in reverse order of dependency: post_swarm, swarm, fda6, fda, da
4101 if (user->post_swarm) {
4102 ierr = DMDestroy(&user->post_swarm); CHKERRQ(ierr);
4103 LOG_ALLOW(LOCAL, LOG_DEBUG, " post_swarm DM destroyed.\n");
4104 }
4105 if (user->swarm) {
4106 ierr = DMDestroy(&user->swarm); CHKERRQ(ierr);
4107 LOG_ALLOW(LOCAL, LOG_DEBUG, " swarm DM destroyed.\n");
4108 }
4109 if (user->fda6) {
4110 ierr = DMDestroy(&user->fda6); CHKERRQ(ierr);
4111 LOG_ALLOW(LOCAL, LOG_DEBUG, " fda6 DM destroyed.\n");
4112 }
4113 if (user->da) {
4114 ierr = DMDestroy(&user->da); CHKERRQ(ierr);
4115 LOG_ALLOW(LOCAL, LOG_DEBUG, " da DM destroyed.\n");
4116 }
4117
4118 // --- Step 6: Free PetscMalloc'd Arrays ---
4119 // Free arrays allocated with PetscMalloc1
4120 if (user->RankCellInfoMap) {
4121 ierr = PetscFree(user->RankCellInfoMap); CHKERRQ(ierr);
4122 user->RankCellInfoMap = NULL;
4123 LOG_ALLOW(LOCAL, LOG_DEBUG, " RankCellInfoMap freed.\n");
4124 }
4125
4126 LOG_ALLOW(LOCAL, LOG_INFO, "UserCtx at level %" PetscInt_FMT " fully destroyed.\n", user->thislevel);
4128 PetscFunctionReturn(0);
4129}
PetscErrorCode BoundarySystem_Destroy(UserCtx *user)
Cleans up and destroys all boundary system resources.
PetscErrorCode DestroyUserVectors(UserCtx *user)
Implementation of DestroyUserVectors().
Definition setup.c:3894
MatNullSpace nullsp
Definition variables.h:1228
DM post_swarm
Definition variables.h:1280
PetscInt thislevel
Definition variables.h:1269
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FinalizeSimulation()

PetscErrorCode FinalizeSimulation ( SimCtx *  simCtx)

Main cleanup function for the entire simulation context.

This function is responsible for destroying ALL memory and PETSc objects allocated during the simulation, including:

  • All UserCtx structures in the multigrid hierarchy (via DestroyUserContext)
  • The multigrid management structures (UserMG, MGCtx array)
  • All SimCtx-level objects (logviewer, dm_swarm, bboxlist, string arrays, etc.)
  • The SimCtx allocation itself.

This function should be called ONCE at the end of the simulation, after all computation is complete, but BEFORE PetscFinalize().

Call order in main:

  1. [Simulation runs]
  2. ProfilingFinalize(simCtx);
  3. FinalizeSimulation(simCtx); <- This function
  4. PetscFinalize();
Parameters
[in,out]simCtxPointer to the master SimulationContext to be destroyed. The pointer is invalid after this call returns.
Returns
PetscErrorCode 0 on success.

Main cleanup function for the entire simulation context.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/setup.h.

See also
FinalizeSimulation()

Definition at line 4137 of file setup.c.

4138{
4139 PetscErrorCode ierr;
4140 PetscFunctionBeginUser;
4142
4143 if (!simCtx) {
4144 LOG_ALLOW(GLOBAL, LOG_WARNING, "FinalizeSimulation called with NULL SimCtx pointer.\n");
4146 PetscFunctionReturn(0);
4147 }
4148
4149 LOG_ALLOW(GLOBAL, LOG_INFO, "========================================\n");
4150 LOG_ALLOW(GLOBAL, LOG_INFO, "Beginning simulation memory cleanup...\n");
4151 LOG_ALLOW(GLOBAL, LOG_INFO, "========================================\n");
4152
4153 // ============================================================================
4154 // PHASE 1: DESTROY MULTIGRID HIERARCHY (All UserCtx structures)
4155 // ============================================================================
4156
4157 ierr = DestroySolutionConvergenceState(simCtx); CHKERRQ(ierr);
4158 ierr = DestroyFieldStatisticsConfig(simCtx); CHKERRQ(ierr);
4159 ierr = ParticleFieldPlanDestroy(&simCtx->particleFieldPlan); CHKERRQ(ierr);
4160 ierr = ParticleInletsDestroy(simCtx); CHKERRQ(ierr);
4161 ierr = AnalyticalFieldDestroy(simCtx); CHKERRQ(ierr);
4162 ierr = VerificationFieldsDestroy(simCtx); CHKERRQ(ierr);
4163
4164 if (simCtx->usermg.mgctx) {
4165 LOG_ALLOW(GLOBAL, LOG_INFO, "Destroying multigrid hierarchy (%" PetscInt_FMT " levels)...\n",
4166 simCtx->usermg.mglevels);
4167
4168 // Destroy each UserCtx from finest to coarsest (reverse order is safer)
4169 for (PetscInt level = simCtx->usermg.mglevels - 1; level >= 0; level--) {
4170 UserCtx *user = simCtx->usermg.mgctx[level].user;
4171 if (user) {
4172 LOG_ALLOW(LOCAL, LOG_INFO, " Destroying level %" PetscInt_FMT " of %" PetscInt_FMT "...\n",
4173 level, simCtx->usermg.mglevels - 1);
4174 ierr = DestroyUserContext(user); CHKERRQ(ierr);
4175
4176 // Free the UserCtx structure itself
4177 ierr = PetscFree(user); CHKERRQ(ierr);
4178 simCtx->usermg.mgctx[level].user = NULL;
4179 }
4180
4181 // Destroy the MGCtx-level packer DM
4182 if (simCtx->usermg.mgctx[level].packer) {
4183 ierr = DMDestroy(&simCtx->usermg.mgctx[level].packer); CHKERRQ(ierr);
4184 LOG_ALLOW(LOCAL, LOG_DEBUG, " MGCtx[%" PetscInt_FMT "].packer destroyed.\n", level);
4185 }
4186 }
4187
4188 // Free the MGCtx array itself
4189 ierr = PetscFree(simCtx->usermg.mgctx); CHKERRQ(ierr);
4190 simCtx->usermg.mgctx = NULL;
4191 LOG_ALLOW(GLOBAL, LOG_INFO, "All multigrid levels destroyed.\n");
4192 }
4193
4194 // ============================================================================
4195 // PHASE 2: DESTROY USERMG-LEVEL OBJECTS
4196 // ============================================================================
4197
4198 if (simCtx->usermg.packer) {
4199 ierr = DMDestroy(&simCtx->usermg.packer); CHKERRQ(ierr);
4200 LOG_ALLOW(LOCAL, LOG_DEBUG, "UserMG.packer DM destroyed.\n");
4201 }
4202
4203 if (simCtx->usermg.snespacker) {
4204 ierr = SNESDestroy(&simCtx->usermg.snespacker); CHKERRQ(ierr);
4205 LOG_ALLOW(LOCAL, LOG_DEBUG, "UserMG.snespacker SNES destroyed.\n");
4206 }
4207
4208 // ============================================================================
4209 // PHASE 3: DESTROY SIMCTX-LEVEL OBJECTS
4210 // ============================================================================
4211
4212 LOG_ALLOW(GLOBAL, LOG_INFO, "Destroying SimCtx-level objects...\n");
4213
4214 // --- PetscViewer for logging ---
4215 if (simCtx->logviewer) {
4216 ierr = PetscViewerDestroy(&simCtx->logviewer); CHKERRQ(ierr);
4217 LOG_ALLOW(LOCAL, LOG_DEBUG, " logviewer destroyed.\n");
4218 }
4219
4220 // --- Particle System DM ---
4221 if (simCtx->dm_swarm) {
4222 ierr = DMDestroy(&simCtx->dm_swarm); CHKERRQ(ierr);
4223 LOG_ALLOW(LOCAL, LOG_DEBUG, " dm_swarm destroyed.\n");
4224 }
4225
4226 // --- BoundingBox List (Array of BoundingBox structs) ---
4227 if (simCtx->bboxlist) {
4228 ierr = PetscFree(simCtx->bboxlist); CHKERRQ(ierr);
4229 simCtx->bboxlist = NULL;
4230 LOG_ALLOW(LOCAL, LOG_DEBUG, " bboxlist freed.\n");
4231 }
4232
4233 // --- Boundary Condition Files (Array of strings) ---
4234 if (simCtx->bcs_files) {
4235 for (PetscInt i = 0; i < simCtx->num_bcs_files; i++) {
4236 if (simCtx->bcs_files[i]) {
4237 ierr = PetscFree(simCtx->bcs_files[i]); CHKERRQ(ierr);
4238 }
4239 }
4240 ierr = PetscFree(simCtx->bcs_files); CHKERRQ(ierr);
4241 simCtx->bcs_files = NULL;
4242 LOG_ALLOW(LOCAL, LOG_DEBUG, " bcs_files array freed (%" PetscInt_FMT " files).\n", simCtx->num_bcs_files);
4243 }
4244
4245 // --- Post-Processing Parameters ---
4246 // pps is allocated with PetscNew and contains only static char arrays and basic types.
4247 // No internal dynamic allocations need to be freed.
4248 if (simCtx->pps) {
4249 ierr = PetscFree(simCtx->pps); CHKERRQ(ierr);
4250 simCtx->pps = NULL;
4251 LOG_ALLOW(LOCAL, LOG_DEBUG, " PostProcessParams freed.\n");
4252 }
4253
4254 // --- IBM/FSI Objects ---
4255 // Note: These are initialized to NULL and currently have no dedicated destroy functions.
4256 // If these modules are extended with cleanup routines, call them here.
4257 if (simCtx->ibm != NULL) {
4258 LOG_ALLOW(GLOBAL, LOG_WARNING, " WARNING: simCtx->ibm is non-NULL but no destroy function exists. Potential memory leak.\n");
4259 }
4260 if (simCtx->ibmv != NULL) {
4261 LOG_ALLOW(GLOBAL, LOG_WARNING, " WARNING: simCtx->ibmv is non-NULL but no destroy function exists. Potential memory leak.\n");
4262 }
4263 if (simCtx->fsi != NULL) {
4264 LOG_ALLOW(GLOBAL, LOG_WARNING, " WARNING: simCtx->fsi is non-NULL but no destroy function exists. Potential memory leak.\n");
4265 }
4266
4267 // --- Logging Allowed Functions (Array of strings) ---
4268 // Note: The logging system maintains its own copy via set_allowed_functions(),
4269 // so freeing simCtx->allowedFuncs will NOT affect LOG_ALLOW functionality.
4270 if (simCtx->allowedFuncs) {
4271 for (PetscInt i = 0; i < simCtx->nAllowed; i++) {
4272 if (simCtx->allowedFuncs[i]) {
4273 ierr = PetscFree(simCtx->allowedFuncs[i]); CHKERRQ(ierr);
4274 }
4275 }
4276 ierr = PetscFree(simCtx->allowedFuncs); CHKERRQ(ierr);
4277 simCtx->allowedFuncs = NULL;
4278 LOG_ALLOW(LOCAL, LOG_DEBUG, " allowedFuncs array freed (%" PetscInt_FMT " functions).\n", simCtx->nAllowed);
4279 }
4280
4281 ierr = PetscFree(simCtx->tracePIDs); CHKERRQ(ierr);
4282 simCtx->nTracePIDs = 0;
4283
4284 // --- Profiling Critical Functions (Array of strings) ---
4285 if (simCtx->profilingSelectedFuncs) {
4286 for (PetscInt i = 0; i < simCtx->nProfilingSelectedFuncs; i++) {
4287 if (simCtx->profilingSelectedFuncs[i]) {
4288 ierr = PetscFree(simCtx->profilingSelectedFuncs[i]); CHKERRQ(ierr);
4289 }
4290 }
4291 ierr = PetscFree(simCtx->profilingSelectedFuncs); CHKERRQ(ierr);
4292 simCtx->profilingSelectedFuncs = NULL;
4293 LOG_ALLOW(LOCAL, LOG_DEBUG, " profilingSelectedFuncs array freed (%" PetscInt_FMT " functions).\n", simCtx->nProfilingSelectedFuncs);
4294 }
4295 if (simCtx->profilingHelpers) {
4296 for (PetscInt i = 0; i < simCtx->nProfilingHelpers; i++) {
4297 ierr = PetscFree(simCtx->profilingHelpers[i]); CHKERRQ(ierr);
4298 }
4299 ierr = PetscFree(simCtx->profilingHelpers); CHKERRQ(ierr);
4300 simCtx->nProfilingHelpers = 0;
4301 }
4302
4303 // ============================================================================
4304 // PHASE 4: FINAL SUMMARY
4305 // ============================================================================
4306
4307 LOG_ALLOW(GLOBAL, LOG_INFO, "========================================\n");
4308 LOG_ALLOW(GLOBAL, LOG_INFO, "Simulation cleanup completed successfully.\n");
4309 LOG_ALLOW(GLOBAL, LOG_INFO, "All PETSc objects have been destroyed.\n");
4310 LOG_ALLOW(GLOBAL, LOG_INFO, "========================================\n");
4311
4312 ierr = PetscFree(simCtx); CHKERRQ(ierr);
4314 PetscFunctionReturn(0);
4315}
PetscErrorCode AnalyticalFieldDestroy(SimCtx *simCtx)
Release what AnalyticalSolutionEngine() keeps from step to step, if anything.
PetscErrorCode ParticleFieldPlanDestroy(ParticleFieldPlan **plan)
Free a plan and its compiled expressions.
PetscErrorCode ParticleInletsDestroy(SimCtx *simCtx)
Release what ParticleInletsCreate() and InjectParticlesAtInlets() allocated.
PetscErrorCode DestroyUserContext(UserCtx *user)
Implementation of DestroyUserContext().
Definition setup.c:4046
PetscErrorCode DestroySolutionConvergenceState(SimCtx *simCtx)
Implementation of DestroySolutionConvergenceState().
Definition setup.c:230
PetscErrorCode DestroyFieldStatisticsConfig(SimCtx *simCtx)
Releases the window definitions resolved by ParseFieldStatisticsConfig() and the ensembles resolved b...
DM packer
Definition variables.h:779
SNES snespacker
Definition variables.h:780
DM packer
Definition variables.h:770
PetscErrorCode VerificationFieldsDestroy(SimCtx *simCtx)
Releases the compiled verification fields.
Here is the call graph for this function:
Here is the caller graph for this function: