PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions
io.h File Reference

Public interface for data input/output routines. More...

#include "variables.h"
#include "logging.h"
#include "Boundaries.h"
Include dependency graph for io.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PetscErrorCode ReadGridGenerationInputs (UserCtx *user)
 Parses command-line options for a programmatically generated grid for a SINGLE block.
 
PetscErrorCode ReadGridFile (UserCtx *user)
 Sets grid dimensions from a file for a SINGLE block using a one-time read cache.
 
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.
 
PetscBool ShouldWriteDataOutput (const SimCtx *simCtx, PetscInt completed_step)
 Returns whether full field/restart output should be written for the.
 
PetscErrorCode WriteCheckpointBundle (SimCtx *simCtx, const char *reason)
 Write and atomically publish one complete checkpoint bundle.
 
PetscErrorCode ReadSimulationFields (UserCtx *user, PetscInt ti)
 Reads binary field data for velocity, pressure, and other required vectors.
 
PetscErrorCode RestoreFieldStatisticsState (SimCtx *simCtx, PetscInt ti)
 Restores field-statistics window state and accumulators from a checkpoint.
 
PetscErrorCode ReadFieldData (UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
 Reads data for a specific field from a file into the provided vector.
 
PetscErrorCode WriteFieldData (UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
 Writes data from a specific PETSc vector to a file.
 
PetscErrorCode WriteSimulationFields (UserCtx *user, const char *checkpoint_directory)
 Writes simulation fields to files.
 
PetscErrorCode WriteSwarmField (UserCtx *user, const char *field_name, const char *ext)
 Writes data from a specific field in a PETSc Swarm to a file.
 
PetscErrorCode WriteSwarmIntField (UserCtx *user, const char *field_name, const char *ext)
 Writes integer data from a specific PETSc Swarm field to a file.
 
PetscErrorCode WriteAllSwarmFields (UserCtx *user, const char *checkpoint_directory)
 Writes a predefined set of PETSc Swarm fields to files.
 
PetscInt ReadDataFileToArray (const char *filename, double **data_out, PetscInt *Nout, MPI_Comm comm)
 Reads a simple ASCII data file containing one numeric value per line.
 
PetscErrorCode CreateVTKFileFromMetadata (const char *filename, const VTKMetaData *meta, MPI_Comm comm)
 Creates a VTK file from prepared metadata and field payloads.
 
PetscErrorCode ReadSwarmField (UserCtx *user, const char *field_name, const char *ext)
 Reads data from a file into a specified field of a PETSc DMSwarm.
 
PetscErrorCode ReadSwarmIntField (UserCtx *user, const char *field_name, const char *ext)
 Reads integer swarm data by using ReadFieldData and casting the result.
 
PetscErrorCode ReadAllSwarmFields (UserCtx *user, PetscInt ti)
 Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.
 
PetscErrorCode ReadCheckpointParticleCount (UserCtx *user, PetscInt ti, PetscInt *particle_count)
 Read the particle count from a validated committed checkpoint.
 
PetscErrorCode DisplayBanner (SimCtx *simCtx)
 Displays a structured banner summarizing the simulation configuration.
 
PetscErrorCode StringToBCFace (const char *str, BCFace *face_out)
 Converts a face-token string (e.g., "-Xi", "+Eta") to the internal BCFace enum.
 
PetscErrorCode StringToBCType (const char *str, BCType *type_out)
 Converts a mathematical BC type string (e.g., "PERIODIC", "WALL") to BCType.
 
PetscErrorCode StringToBCHandlerType (const char *str, BCHandlerType *handler_out)
 Converts a BC handler token (implementation strategy) to BCHandlerType.
 
PetscErrorCode ValidateBCHandlerForBCType (BCType type, BCHandlerType handler)
 Validates that a selected handler is compatible with a mathematical BC type.
 
void FreeBC_ParamList (BC_Param *head)
 Frees an entire linked list of boundary-condition parameters.
 
PetscErrorCode GetBCParamReal (BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
 Searches a BC_Param linked list for a key and returns its value as a double.
 
PetscErrorCode GetBCParamBool (BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
 Searches a BC_Param linked list for a key and returns its value as a bool.
 
PetscErrorCode GetBCParamString (BC_Param *params, const char *key, const char **value_out, PetscBool *found)
 Searches a BC_Param linked list for a key and returns its value as a string.
 
PetscErrorCode GetDrivenSeamFluxFlag (BC_Param *params, PetscBool *value_out, PetscBool *found)
 Read the driven-flow seam-flux flag, accepting its deprecated apply_trim spelling.
 
PetscErrorCode ParseAllBoundaryConditions (UserCtx *user, const char *bcs_input_filename)
 Parses the boundary conditions file to configure the type, handler, and any associated parameters for all 6 global faces of the domain.
 
PetscErrorCode DeterminePeriodicity (SimCtx *simCtx)
 Scans all block-specific boundary condition files to determine a globally consistent periodicity for each dimension, reusing the core type parser.
 
void TrimWhitespace (char *str)
 Removes leading and trailing ASCII whitespace from a mutable string.
 
PetscBool CheckpointFieldIsEnabled (const SimCtx *simCtx, const FieldDescriptor *descriptor)
 Return whether a catalogued field belongs in the current checkpoint.
 
PetscErrorCode PicurvPhysicalTime (const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
 Convert a solver time to physical seconds, t * L_ref / U_ref.
 
PetscErrorCode PicurvFieldReferenceScale (SimCtx *simCtx, const char *field_name, PetscReal *scale, char *description, size_t description_length)
 Physical scale one field is multiplied by to leave non-dimensional form.
 
PetscErrorCode ParsePostProcessingSettings (SimCtx *simCtx)
 Initializes post-processing settings from a config file and command-line overrides.
 
PetscErrorCode ParseScalingInformation (SimCtx *simCtx)
 Parses physical scaling parameters from command-line options.
 

Detailed Description

Public interface for data input/output routines.

This header declares functions responsible for parsing grid geometry information, either from command-line options for programmatically generated grids or by reading the header of a grid definition file.

Definition in file io.h.

Function Documentation

◆ ReadGridGenerationInputs()

PetscErrorCode ReadGridGenerationInputs ( UserCtx *  user)

Parses command-line options for a programmatically generated grid for a SINGLE block.

This function reads all per-block array options related to grid geometry, such as dimensions (-im), domain bounds (-xMins), and stretching ratios (-rxs). It then populates the fields of the provided UserCtx struct using its internal block index user->_this.

Parameters
userPointer to the UserCtx for a specific block. The function will populate the geometric fields (IM, Min_X, rx, etc.) within this struct.
Returns
PetscErrorCode 0 on success, or a PETSc error code on failure.

Parses command-line options for a programmatically generated grid for a SINGLE block.

See also
ReadGridGenerationInputs()

Definition at line 537 of file io.c.

538{
539 PetscErrorCode ierr;
540 SimCtx *simCtx = user->simCtx;
541 PetscInt nblk = simCtx->block_number;
542 PetscInt block_index = user->_this;
543 PetscBool found;
544
545 // Temporary arrays to hold the parsed values for ALL blocks
546 PetscInt *IMs = NULL, *JMs = NULL, *KMs = NULL, *cgrids = NULL;
547 PetscReal *xMins = NULL, *xMaxs = NULL, *rxs = NULL;
548 PetscReal *yMins = NULL, *yMaxs = NULL, *rys = NULL;
549 PetscReal *zMins = NULL, *zMaxs = NULL, *rzs = NULL;
550
551 PetscFunctionBeginUser;
553
554 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Reading generated grid inputs for block %" PetscInt_FMT ".\n", simCtx->rank, block_index);
555
556 if (block_index >= nblk) {
557 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Block index %" PetscInt_FMT " is out of range for nblk=%" PetscInt_FMT "", block_index, nblk);
558 }
559
560 // --- Allocate temporary storage for all array options ---
561 ierr = PetscMalloc4(nblk, &IMs, nblk, &JMs, nblk, &KMs, nblk, &cgrids); CHKERRQ(ierr);
562 ierr = PetscMalloc6(nblk, &xMins, nblk, &xMaxs, nblk, &rxs, nblk, &yMins, nblk, &yMaxs, nblk, &rys); CHKERRQ(ierr);
563 ierr = PetscMalloc3(nblk, &zMins, nblk, &zMaxs, nblk, &rzs); CHKERRQ(ierr);
564
565 // --- Set default values for the temporary arrays ---
566 for (PetscInt i = 0; i < nblk; ++i) {
567 IMs[i] = 10; JMs[i] = 10; KMs[i] = 10; cgrids[i] = 0;
568 xMins[i] = 0.0; xMaxs[i] = 1.0; rxs[i] = 1.0;
569 yMins[i] = 0.0; yMaxs[i] = 1.0; rys[i] = 1.0;
570 zMins[i] = 0.0; zMaxs[i] = 1.0; rzs[i] = 1.0;
571 }
572
573 // --- Parse the array options from the command line / control file ---
574 PetscInt count;
575 count = nblk; ierr = PetscOptionsGetIntArray(NULL, NULL, "-im", IMs, &count, &found); CHKERRQ(ierr);
576 count = nblk; ierr = PetscOptionsGetIntArray(NULL, NULL, "-jm", JMs, &count, &found); CHKERRQ(ierr);
577 count = nblk; ierr = PetscOptionsGetIntArray(NULL, NULL, "-km", KMs, &count, &found); CHKERRQ(ierr);
578 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-xMins", xMins, &count, &found); CHKERRQ(ierr);
579 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-xMaxs", xMaxs, &count, &found); CHKERRQ(ierr);
580 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-rxs", rxs, &count, &found); CHKERRQ(ierr);
581 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-yMins", yMins, &count, &found); CHKERRQ(ierr);
582 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-yMaxs", yMaxs, &count, &found); CHKERRQ(ierr);
583 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-rys", rys, &count, &found); CHKERRQ(ierr);
584 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-zMins", zMins, &count, &found); CHKERRQ(ierr);
585 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-zMaxs", zMaxs, &count, &found); CHKERRQ(ierr);
586 count = nblk; ierr = PetscOptionsGetRealArray(NULL, NULL, "-rzs", rzs, &count, &found); CHKERRQ(ierr);
587 count = nblk; ierr = PetscOptionsGetIntArray(NULL, NULL, "-cgrids", cgrids, &count, &found); CHKERRQ(ierr);
588
589 /* Domain bounds are supplied in physical units, exactly like a `.picgrid`. A file
590 * grid is divided by the reference length when the conductor publishes it as an
591 * asset; a programmatically generated one has no such staging step, so the same
592 * division happens here. Without it this mode alone would take non-dimensional
593 * input while post-processing multiplied its coordinates back by L_ref, inflating
594 * the reported geometry whenever length_ref differed from one. */
595 const PetscReal length_ref = simCtx->scaling.L_ref;
596
597 PetscCheck(length_ref > 0.0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
598 "Reference length L_ref must be positive to non-dimensionalize the "
599 "programmatic domain bounds. Got %g", (double)length_ref);
600
601 // --- Assign the parsed values to the specific UserCtx struct passed in ---
602 user->IM = IMs[block_index];
603 user->JM = JMs[block_index];
604 user->KM = KMs[block_index];
605 user->Min_X = xMins[block_index] / length_ref;
606 user->Max_X = xMaxs[block_index] / length_ref;
607 user->rx = rxs[block_index];
608 user->Min_Y = yMins[block_index] / length_ref;
609 user->Max_Y = yMaxs[block_index] / length_ref;
610 user->ry = rys[block_index];
611 user->Min_Z = zMins[block_index] / length_ref;
612 user->Max_Z = zMaxs[block_index] / length_ref;
613 user->rz = rzs[block_index];
614 user->cgrid = cgrids[block_index];
615
616 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Block %" PetscInt_FMT " grid generation inputs set: IM=%" PetscInt_FMT ", JM=%" PetscInt_FMT ", KM=%" PetscInt_FMT "\n",
617 simCtx->rank, block_index, user->IM, user->JM, user->KM);
618 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Block %" PetscInt_FMT " bounds after L_ref=%.4g: X=[%.4g, %.4g], "
619 "Y=[%.4g, %.4g], Z=[%.4g, %.4g]\n",
620 simCtx->rank, block_index, (double)length_ref,
621 user->Min_X, user->Max_X, user->Min_Y, user->Max_Y, user->Min_Z, user->Max_Z);
622
623 // --- Clean up temporary storage ---
624 ierr = PetscFree4(IMs, JMs, KMs, cgrids); CHKERRQ(ierr);
625 ierr = PetscFree6(xMins, xMaxs, rxs, yMins, yMaxs, rys); CHKERRQ(ierr);
626 ierr = PetscFree3(zMins, zMaxs, rzs); CHKERRQ(ierr);
627
629 PetscFunctionReturn(0);
630}
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#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
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscMPIInt rank
Definition variables.h:919
PetscInt cgrid
Definition variables.h:1177
PetscInt block_number
Definition variables.h:1009
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal Min_X
Definition variables.h:1172
PetscInt KM
Definition variables.h:1171
PetscReal L_ref
Definition variables.h:898
PetscInt _this
Definition variables.h:1175
PetscReal ry
Definition variables.h:1176
PetscReal Max_Y
Definition variables.h:1172
PetscReal rz
Definition variables.h:1176
ScalingCtx scaling
Definition variables.h:1003
PetscInt JM
Definition variables.h:1171
PetscReal Min_Z
Definition variables.h:1172
PetscReal Max_X
Definition variables.h:1172
PetscReal Min_Y
Definition variables.h:1172
PetscInt IM
Definition variables.h:1171
PetscReal rx
Definition variables.h:1176
PetscReal Max_Z
Definition variables.h:1172
The master context for the entire simulation.
Definition variables.h:916
Here is the caller graph for this function:

◆ ReadGridFile()

PetscErrorCode ReadGridFile ( UserCtx *  user)

Sets grid dimensions from a file for a SINGLE block using a one-time read cache.

This function uses a static-variable pattern to ensure the grid file header is read only once, collectively, by all processes on the first call. Subsequent calls simply retrieve the pre-loaded and broadcasted data for the specified block.

Parameters
userPointer to the UserCtx for a specific block. This function will populate the IM, JM, and KM fields.
Returns
PetscErrorCode 0 on success, or a PETSc error code on failure.

Sets grid dimensions from a file for a SINGLE block using a one-time read cache.

See also
ReadGridFile()

Definition at line 636 of file io.c.

637{
638 PetscErrorCode ierr;
639 SimCtx *simCtx = user->simCtx;
640 PetscInt block_index = user->_this;
641
642 PetscFunctionBeginUser;
644
645 // --- One-Time Read and Broadcast Logic ---
647 LOG_ALLOW(GLOBAL, LOG_INFO, "First call to ReadGridFile. Reading and broadcasting grid file header from '%s'...\n", simCtx->grid_file);
648 PetscMPIInt rank = simCtx->rank;
649 PetscInt nblk = simCtx->block_number;
650
651 if (rank == 0) {
652 FILE *fd = fopen(simCtx->grid_file, "r");
653 if (!fd) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Cannot open file: %s", simCtx->grid_file);
654
655 // Read and validate the canonical PICGRID header.
656 char firstTok[32] = {0};
657 if (fscanf(fd, "%31s", firstTok) != 1)
658 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Empty grid file: %s", simCtx->grid_file);
659 if (strcmp(firstTok, "PICGRID") != 0)
660 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
661 "Grid file %s must begin with the canonical PICGRID header.", simCtx->grid_file);
662 if (fscanf(fd, "%" PetscInt_FMT, &g_nblk_from_file) != 1)
663 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Expected number of blocks after \"PICGRID\" in %s", simCtx->grid_file);
664 if (g_nblk_from_file != nblk) {
665 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Mismatch: -nblk is %" PetscInt_FMT " but grid file specifies %" PetscInt_FMT " blocks.", nblk, g_nblk_from_file);
666 }
667
668 ierr = PetscMalloc3(nblk, &g_IMs_from_file, nblk, &g_JMs_from_file, nblk, &g_KMs_from_file); CHKERRQ(ierr);
669 for (PetscInt i = 0; i < nblk; ++i) {
670 if (fscanf(fd, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", &g_IMs_from_file[i], &g_JMs_from_file[i], &g_KMs_from_file[i]) != 3) {
671 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Expected 3 integers for block %" PetscInt_FMT " in %s", i, simCtx->grid_file);
672 }
673 }
674 fclose(fd);
675 }
676
677 // Broadcast nblk to verify (optional, good practice)
678 ierr = MPI_Bcast(&g_nblk_from_file, 1, MPIU_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
679
680 // Allocate on other ranks before receiving the broadcast
681 if (rank != 0) {
682 ierr = PetscMalloc3(nblk, &g_IMs_from_file, nblk, &g_JMs_from_file, nblk, &g_KMs_from_file); CHKERRQ(ierr);
683 }
684
685 // Broadcast the data arrays
686 ierr = MPI_Bcast(g_IMs_from_file, nblk, MPIU_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
687 ierr = MPI_Bcast(g_JMs_from_file, nblk, MPIU_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
688 ierr = MPI_Bcast(g_KMs_from_file, nblk, MPIU_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
689
690 g_file_has_been_read = PETSC_TRUE;
691 LOG_ALLOW(GLOBAL, LOG_INFO, "Grid file header read and broadcast complete.\n");
692 }
693
694 // --- Per-Block Assignment Logic (runs on every call) ---
695 user->IM = g_IMs_from_file[block_index];
696 user->JM = g_JMs_from_file[block_index];
697 user->KM = g_KMs_from_file[block_index];
698
699 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Set file inputs for Block %" PetscInt_FMT ": IM=%" PetscInt_FMT ", JM=%" PetscInt_FMT ", KM=%" PetscInt_FMT "\n",
700 simCtx->rank, block_index, user->IM, user->JM, user->KM);
701
703 PetscFunctionReturn(0);
704}
static PetscInt * g_IMs_from_file
Caches the IM dimensions for all blocks read from the grid file.
Definition io.c:37
static PetscInt g_nblk_from_file
Stores the number of blocks read from the grid file.
Definition io.c:35
static PetscBool g_file_has_been_read
A flag to ensure the grid file is read only once.
Definition io.c:43
static PetscInt * g_KMs_from_file
Caches the KM dimensions for all blocks read from the grid file.
Definition io.c:41
static PetscInt * g_JMs_from_file
Caches the JM dimensions for all blocks read from the grid file.
Definition io.c:39
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
char grid_file[PETSC_MAX_PATH_LEN]
Definition variables.h:1012
Here is the caller graph for this function:

◆ VerifyPathExistence()

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.

This function centralizes the logic for checking arbitrary paths. Only Rank 0 performs the filesystem check, and the result is broadcast to all other processes. This ensures collective and synchronized decision-making across all ranks. It is intended for configuration files, source directories, etc., where the path is known completely.

Parameters
[in]pathThe full path to the file or directory to check.
[in]is_dirPETSC_TRUE if checking for a directory, PETSC_FALSE for a file.
[in]is_optionalPETSC_TRUE if the path is optional (results in a warning), PETSC_FALSE if mandatory (results in an error).
[in]descriptionA user-friendly description of the path for logging (e.g., "Grid file").
[out]existsThe result of the check (identical on all ranks).
Returns
PetscErrorCode

A parallel-safe helper to verify the existence of a generic file or directory path.

See also
VerifyPathExistence()

Definition at line 1202 of file io.c.

1203{
1204 PetscErrorCode ierr;
1205 PetscMPIInt rank;
1206 MPI_Comm comm = PETSC_COMM_WORLD;
1207
1208 PetscFunctionBeginUser;
1210 ierr = MPI_Comm_rank(comm, &rank); CHKERRQ(ierr);
1211
1212 if (rank == 0) {
1213 if (is_dir) {
1214 ierr = PetscTestDirectory(path, 'r', exists); CHKERRQ(ierr);
1215 } else {
1216 ierr = PetscTestFile(path, 'r', exists); CHKERRQ(ierr);
1217 }
1218
1219 if (!(*exists)) {
1220 if (is_optional) {
1221 LOG_ALLOW(GLOBAL, LOG_INFO, "Optional %s not found at: %s (using defaults/ignoring).\n", description, path);
1222 } else {
1223 LOG_ALLOW(GLOBAL, LOG_ERROR, "Mandatory %s not found at: %s\n", description, path);
1224 }
1225 } else {
1226 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Found %s: %s\n", description, path);
1227 }
1228 }
1229
1230 // Broadcast the result from Rank 0
1231 PetscMPIInt exists_int = (rank == 0) ? (PetscMPIInt)(*exists) : 0;
1232 ierr = MPI_Bcast(&exists_int, 1, MPI_INT, 0, comm); CHKERRMPI(ierr);
1233 *exists = (PetscBool)exists_int;
1234
1235 // Collective error for mandatory files
1236 if (!(*exists) && !is_optional) {
1237 SETERRQ(comm, PETSC_ERR_FILE_OPEN, "Mandatory %s not found. Rank 0 expected it at '%s'. Check path and permissions.", description, path);
1238 }
1239
1241 PetscFunctionReturn(0);
1242}
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
Here is the caller graph for this function:

◆ ShouldWriteDataOutput()

PetscBool ShouldWriteDataOutput ( const SimCtx *  simCtx,
PetscInt  completed_step 
)

Returns whether full field/restart output should be written for the.

completed timestep.

Parameters
simCtxSimulation context controlling the operation.
completed_stepCompleted step index used by the decision helper.
Returns
PetscBool indicating the result of ShouldWriteDataOutput().

Returns whether full field/restart output should be written for the.

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

See also
ShouldWriteDataOutput()

Definition at line 521 of file io.c.

522{
524 if (!simCtx) {
526 return PETSC_FALSE;
527 }
529 return (PetscBool)(simCtx->tiout > 0 && completed_step > 0 && completed_step % simCtx->tiout == 0);
530}
PetscInt tiout
Definition variables.h:928
Here is the caller graph for this function:

◆ WriteCheckpointBundle()

PetscErrorCode WriteCheckpointBundle ( SimCtx *  simCtx,
const char *  reason 
)

Write and atomically publish one complete checkpoint bundle.

Parameters
[in,out]simCtxSimulation context owning all enabled checkpoint state.
[in]reasonStable lifecycle reason such as initial, cadence, final, or signal.
Returns
Zero on success or a PETSc/MPI/filesystem error.

Write and atomically publish one complete checkpoint bundle.

Definition at line 2501 of file io.c.

2502{
2503 UserCtx *user = NULL;
2504 char checkpoints_root[PETSC_MAX_PATH_LEN];
2505 char final_directory[PETSC_MAX_PATH_LEN];
2506 char temporary_directory[PETSC_MAX_PATH_LEN];
2507 char nested_directory[PETSC_MAX_PATH_LEN];
2508 char commit_path[PETSC_MAX_PATH_LEN];
2509 char geometry_digest[65] = "";
2510 char manifest_digest[65] = "";
2511 PetscBool final_exists = PETSC_FALSE;
2512 PetscInt particle_count = 0;
2513 PetscMPIInt writer_pid = 0;
2514
2515 PetscFunctionBeginUser;
2517 PetscCheck(simCtx != NULL && reason != NULL && reason[0] != '\0',
2518 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
2519 "Simulation context and checkpoint reason are required.");
2520 // io.write_initial_checkpoint / io.write_final_checkpoint can turn off the run's boundary
2521 // bundles; cadence and signal bundles are always written.
2522 if ((simCtx->skipInitialCheckpoint && (strcmp(reason, "initial") == 0 || strcmp(reason, "branch_start") == 0)) ||
2523 (simCtx->skipFinalCheckpoint && strcmp(reason, "final") == 0)) {
2524 LOG_ALLOW(GLOBAL, LOG_INFO, "Skipping the %s checkpoint at step %" PetscInt_FMT " (io.write_%s_checkpoint is false).\n",
2525 reason, simCtx->step, strcmp(reason, "final") == 0 ? "final" : "initial");
2527 PetscFunctionReturn(0);
2528 }
2529 user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
2530 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
2531 "Finest-level fields must exist before checkpoint output.");
2532
2533 PetscCall(PetscSNPrintf(checkpoints_root, sizeof(checkpoints_root), "%s/%s",
2535 PetscCall(FormatCheckpointStepDirectory(simCtx->output_dir, simCtx->step,
2536 final_directory, sizeof(final_directory)));
2537 PetscCall(PetscTestDirectory(final_directory, 'r', &final_exists));
2538 if (final_exists) {
2539 PetscReal saved_time = 0.0;
2540 PetscCall(ValidateCheckpointBundle(simCtx, user, final_directory, simCtx->step,
2541 &saved_time, NULL, NULL, NULL, NULL));
2542 PetscCheck(PetscAbsReal(saved_time - simCtx->ti) <=
2543 10.0 * PETSC_MACHINE_EPSILON * PetscMax(1.0, PetscAbsReal(simCtx->ti)),
2544 PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
2545 "Committed checkpoint step %" PetscInt_FMT " has time %.17g, current state has time %.17g.",
2546 simCtx->step, (double)saved_time, (double)simCtx->ti);
2547 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Checkpoint step %" PetscInt_FMT " is already committed; skipping duplicate write.\n",
2548 simCtx->step);
2550 PetscFunctionReturn(0);
2551 }
2552
2553 if (simCtx->rank == 0) writer_pid = (PetscMPIInt)getpid();
2554 PetscCallMPI(MPI_Bcast(&writer_pid, 1, MPI_INT, 0, PETSC_COMM_WORLD));
2555 PetscCall(PetscSNPrintf(temporary_directory, sizeof(temporary_directory),
2556 "%s/.step_%0*" PetscInt_FMT ".incomplete.%d",
2557 checkpoints_root, PICURV_CHECKPOINT_STEP_WIDTH,
2558 simCtx->step, (int)writer_pid));
2559 PetscCall(CreateCheckpointDirectoryCollective(simCtx, checkpoints_root));
2560 PetscCall(CreateCheckpointDirectoryCollective(simCtx, temporary_directory));
2561 PetscCall(PetscSNPrintf(nested_directory, sizeof(nested_directory), "%s/%s",
2562 temporary_directory, PICURV_EULERIAN_DIRECTORY));
2563 PetscCall(CreateCheckpointDirectoryCollective(simCtx, nested_directory));
2564 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2565 PetscCall(PetscSNPrintf(nested_directory, sizeof(nested_directory),
2566 "%s/%s/block_%04" PetscInt_FMT,
2567 temporary_directory, PICURV_EULERIAN_DIRECTORY, block));
2568 PetscCall(CreateCheckpointDirectoryCollective(simCtx, nested_directory));
2569 }
2570 if (ParticlesEnabled(simCtx)) {
2571 PetscCall(PetscSNPrintf(nested_directory, sizeof(nested_directory), "%s/%s",
2572 temporary_directory, PICURV_PARTICLE_DIRECTORY));
2573 PetscCall(CreateCheckpointDirectoryCollective(simCtx, nested_directory));
2574 PetscCall(DMSwarmGetSize(user->swarm, &particle_count));
2575 }
2576 if (FieldStatisticsIsActive(simCtx)) {
2577 PetscCall(FormatStatisticsPath(temporary_directory, -1, -1, NULL,
2578 nested_directory, sizeof(nested_directory)));
2579 PetscCall(CreateCheckpointDirectoryCollective(simCtx, nested_directory));
2580 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
2581 PetscCall(FormatStatisticsPath(temporary_directory, window, -1, NULL,
2582 nested_directory, sizeof(nested_directory)));
2583 PetscCall(CreateCheckpointDirectoryCollective(simCtx, nested_directory));
2584 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2585 PetscCall(FormatStatisticsPath(temporary_directory, window, block, NULL,
2586 nested_directory, sizeof(nested_directory)));
2587 PetscCall(CreateCheckpointDirectoryCollective(simCtx, nested_directory));
2588 }
2589 }
2590 }
2591
2592 PetscCall(ComputeCheckpointGeometrySHA256(simCtx, user, geometry_digest));
2593 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2594 PetscCall(WriteSimulationFields(&user[block], temporary_directory));
2595 }
2596 if (ParticlesEnabled(simCtx)) PetscCall(WriteAllSwarmFields(user, temporary_directory));
2597 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2598 PetscCall(WriteStatisticsFields(&user[block], temporary_directory));
2599 }
2600 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
2601
2602 PetscCall(WriteCheckpointManifest(simCtx, user, temporary_directory, reason,
2603 geometry_digest, particle_count, manifest_digest));
2604 if (simCtx->rank == 0) {
2605 FILE *commit_file = NULL;
2606
2607 PetscCall(PetscSNPrintf(commit_path, sizeof(commit_path), "%s/COMMITTED", temporary_directory));
2608 commit_file = fopen(commit_path, "w");
2609 PetscCheck(commit_file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
2610 "Unable to create checkpoint commit marker '%s'.", commit_path);
2611 PetscCheck(fprintf(commit_file, "%s\n", manifest_digest) > 0 &&
2612 fflush(commit_file) == 0 && fsync(fileno(commit_file)) == 0,
2613 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2614 "Unable to write checkpoint commit marker '%s'.", commit_path);
2615 PetscCheck(fclose(commit_file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2616 "Unable to close checkpoint commit marker '%s'.", commit_path);
2617 PetscCheck(rename(temporary_directory, final_directory) == 0,
2618 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2619 "Unable to commit checkpoint '%s': %s", final_directory, strerror(errno));
2620 }
2621 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
2623 "Committed checkpoint step %" PetscInt_FMT " at t=%.17g (%s): %s\n",
2624 simCtx->step, (double)simCtx->ti, reason, final_directory);
2626 PetscFunctionReturn(0);
2627}
#define PICURV_CHECKPOINT_STEP_WIDTH
Definition io.c:28
#define PICURV_CHECKPOINTS_DIRECTORY
Definition io.c:24
PetscErrorCode WriteAllSwarmFields(UserCtx *user, const char *checkpoint_directory)
Implementation of WriteAllSwarmFields().
Definition io.c:2155
static PetscErrorCode FormatStatisticsPath(const char *root, PetscInt window, PetscInt block, const char *payload_name, char *path, size_t path_size)
Format any level of the statistics subtree, from the root down to one payload.
Definition io.c:105
#define PICURV_PARTICLE_DIRECTORY
Definition io.c:26
static PetscErrorCode FormatCheckpointStepDirectory(const char *root, PetscInt step, char *path, size_t path_size)
Format the canonical directory name for one completed step.
Definition io.c:271
PetscErrorCode WriteSimulationFields(UserCtx *user, const char *checkpoint_directory)
Implementation of WriteSimulationFields().
Definition io.c:1954
static PetscErrorCode CreateCheckpointDirectoryCollective(const SimCtx *simCtx, const char *path)
Create one directory on rank zero and report failures collectively.
Definition io.c:303
static PetscErrorCode ComputeCheckpointGeometrySHA256(SimCtx *simCtx, UserCtx *user, char digest_hex[65])
Compute and cache a rank-count-independent hash of the active grid geometry.
Definition io.c:200
static PetscErrorCode ValidateCheckpointBundle(SimCtx *simCtx, UserCtx *user, const char *checkpoint_directory, PetscInt expected_step, PetscReal *physical_time, PetscInt *particle_count, PetscBool *particles_saved, PetscBool *les_saved, PetscBool *inflow_saved)
Validate a committed bundle and return selected authoritative metadata; a NULL user skips the geometr...
Definition io.c:325
static PetscErrorCode WriteStatisticsFields(UserCtx *user, const char *checkpoint_directory)
Write every window's accumulator payloads for one block into a bundle.
Definition io.c:1989
#define PICURV_EULERIAN_DIRECTORY
Definition io.c:25
static PetscErrorCode WriteCheckpointManifest(SimCtx *simCtx, UserCtx *user, const char *checkpoint_directory, const char *reason, const char *geometry_digest, PetscInt particle_count, char manifest_digest[65])
Write the complete manifest after every payload has closed successfully.
Definition io.c:2246
PetscBool FieldStatisticsIsActive(const struct SimCtx *simCtx)
Reports whether this run has live field-statistics state.
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
UserCtx * user
Definition variables.h:768
UserMG usermg
Definition variables.h:1082
char output_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:940
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
PetscBool skipFinalCheckpoint
io.write_final_checkpoint false: no end-of-run bundle.
Definition variables.h:930
PetscInt mglevels
Definition variables.h:775
PetscBool skipInitialCheckpoint
io.write_initial_checkpoint false: no initial/branch_start bundle.
Definition variables.h:929
PetscInt step
Definition variables.h:924
MGCtx * mgctx
Definition variables.h:778
PetscReal ti
Definition variables.h:925
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadSimulationFields()

PetscErrorCode ReadSimulationFields ( UserCtx *  user,
PetscInt  ti 
)

Reads binary field data for velocity, pressure, and other required vectors.

Validates one committed checkpoint bundle and reads every enabled Eulerian checkpoint field through the field catalog.

Parameters
[in,out]userPointer to the UserCtx structure containing the simulation context.
[in]tiCheckpoint step resolved below the configured source root.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Reads binary field data for velocity, pressure, and other required vectors.

See also
ReadSimulationFields()

Definition at line 1387 of file io.c.

1388{
1389 SimCtx *simCtx = user->simCtx;
1390 const char *source_path = NULL;
1391 char checkpoint_directory[PETSC_MAX_PATH_LEN];
1392 PetscReal checkpoint_time = 0.0;
1393 PetscBool particles_saved = PETSC_FALSE;
1394 PetscBool les_saved = PETSC_FALSE;
1395 PetscBool inflow_saved = PETSC_FALSE;
1396
1397 PetscFunctionBeginUser;
1399 if(simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR){
1400 source_path = simCtx->pps->source_dir;
1401 } else if(simCtx->exec_mode == EXEC_MODE_SOLVER){
1402 source_path = simCtx->restart_dir;
1403 } else{
1404 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Invalid execution mode for reading simulation fields.");
1405 }
1406
1407 PetscCall(ResolveCheckpointStepDirectory(source_path, ti,
1408 checkpoint_directory, sizeof(checkpoint_directory)));
1409 PetscCall(ValidateCheckpointBundle(simCtx, user - user->_this,
1410 checkpoint_directory, ti, &checkpoint_time, NULL,
1411 &particles_saved, &les_saved, &inflow_saved));
1412 PetscCheck(!(ParticlesEnabled(simCtx) && !strcmp(simCtx->particleRestartMode, "load")) || particles_saved,
1413 PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
1414 "Particle restart_mode=load was requested, but checkpoint step %" PetscInt_FMT
1415 " contains no particle state.", ti);
1416 if (simCtx->exec_mode == EXEC_MODE_SOLVER && user->_this == 0) {
1417 simCtx->ti = checkpoint_time;
1418 if (ti == simCtx->StartStep) simCtx->StartTime = checkpoint_time;
1419 PetscCall(RestoreDrivenFluxTarget(simCtx, user, checkpoint_directory));
1420 }
1421
1422 LOG_ALLOW(GLOBAL, LOG_INFO, "Reading Eulerian checkpoint fields for block %" PetscInt_FMT " from '%s'.\n",
1423 user->_this, checkpoint_directory);
1424 PetscCall(PetscSNPrintf(simCtx->_io_context_buffer, sizeof(simCtx->_io_context_buffer),
1425 "%s/%s/block_%04" PetscInt_FMT,
1426 checkpoint_directory, PICURV_EULERIAN_DIRECTORY, user->_this));
1427 simCtx->current_io_directory = simCtx->_io_context_buffer;
1428
1429 for (PetscInt raw_id = 0; raw_id < FIELD_ID_COUNT; ++raw_id) {
1430 const FieldDescriptor *descriptor = NULL;
1431 FieldView view;
1432
1433 PetscCall(FieldGetDescriptor((FieldId)raw_id, &descriptor));
1434 if (!CheckpointFieldIsEnabled(simCtx, descriptor)) continue;
1435 /* A solver restart that reseeds particles (restart_mode init) must not restore the
1436 averages of the particles it discards; post-processing shows what was saved. */
1437 if ((descriptor->availability & FIELD_AVAILABILITY_PARTICLES) &&
1438 (!particles_saved ||
1439 (simCtx->exec_mode == EXEC_MODE_SOLVER && strcmp(simCtx->particleRestartMode, "load")))) continue;
1440 if ((descriptor->availability & FIELD_AVAILABILITY_LES_DYNAMIC) && !les_saved) continue;
1441 /* Wall-model state is derived, not carried: the first boundary pass of the
1442 restarted run recomputes it from the restored velocity field. Writing it keeps
1443 it available to postprocessing; reading it would only tie a restart to whether
1444 the source checkpoint happened to have a wall model enabled. */
1445 if (descriptor->availability & FIELD_AVAILABILITY_WALL_MODEL) continue;
1446 if ((descriptor->availability & FIELD_AVAILABILITY_TURBULENCE) &&
1447 !(simCtx->les && les_saved)) continue;
1448 /* An inlet whose checkpoint holds no filter state starts its filter afresh. */
1449 if ((descriptor->availability & FIELD_AVAILABILITY_INFLOW_FLUCTUATION) && !inflow_saved) continue;
1451 PetscCall(FieldGetView(user, descriptor->id, &view));
1452 PetscCall(ReadFieldData(user, descriptor->canonical_name, view.global_vec, "dat"));
1453 /* A dimensionalizing post-processor scales each field as it is loaded, so a field
1454 is scaled exactly once per load: one that this step skipped keeps its earlier,
1455 already scaled, value instead of being scaled again. */
1456 if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR && simCtx->pps && simCtx->pps->dimensionalize) {
1457 PetscReal scale = 1.0;
1458
1459 PetscCall(PicurvFieldReferenceScale(simCtx, descriptor->canonical_name, &scale, NULL, 0));
1460 if (scale != 1.0) PetscCall(VecScale(view.global_vec, scale));
1461 }
1462 if (view.local_vec) PetscCall(UpdateLocalGhosts(user, descriptor->id));
1463 }
1464 simCtx->restartHistoryAvailable = PETSC_TRUE;
1465 simCtx->current_io_directory = NULL;
1467 PetscFunctionReturn(0);
1468}
@ FIELD_AVAILABILITY_WALL_MODEL
@ FIELD_AVAILABILITY_PARTICLES
@ FIELD_AVAILABILITY_TURBULENCE
@ FIELD_AVAILABILITY_LES_DYNAMIC
@ FIELD_AVAILABILITY_INFLOW_FLUCTUATION
unsigned int availability
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
const char * canonical_name
PetscErrorCode FieldGetDescriptor(FieldId field_id, const FieldDescriptor **descriptor)
Return immutable metadata for a valid field identifier.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_COUNT
Immutable metadata for one field identity.
Non-owning runtime objects resolved for one field and UserCtx.
PetscErrorCode PicurvFieldReferenceScale(SimCtx *simCtx, const char *field_name, PetscReal *scale, char *description, size_t description_length)
Implementation of PicurvFieldReferenceScale().
Definition io.c:3006
static PetscErrorCode RestoreDrivenFluxTarget(SimCtx *simCtx, UserCtx *user, const char *checkpoint_directory)
Restore a latched driven-flow flux target from a checkpoint manifest.
Definition io.c:1334
PetscBool CheckpointFieldIsEnabled(const SimCtx *simCtx, const FieldDescriptor *descriptor)
Implementation of CheckpointFieldIsEnabled().
Definition io.c:75
PetscErrorCode ReadFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Implementation of ReadFieldData().
Definition io.c:1248
static PetscErrorCode ResolveCheckpointStepDirectory(const char *source_root, PetscInt step, char *path, size_t path_size)
Resolve either an exact bundle or a run/output root to one step bundle.
Definition io.c:284
str source_path(str source)
Extract a repository path from a path-or-symbol source declaration.
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
PetscReal StartTime
Definition variables.h:932
PetscBool dimensionalize
Whether derived output leaves non-dimensional form, from global_operations.dimensionalize.
Definition variables.h:828
PetscBool inflowFluctuationsRestored
That state was read from the restart checkpoint.
Definition variables.h:1044
PetscInt StartStep
Definition variables.h:926
char * current_io_directory
Definition variables.h:944
char particleRestartMode[16]
Definition variables.h:1056
char source_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:795
PostProcessParams * pps
Definition variables.h:1131
@ EXEC_MODE_SOLVER
Definition variables.h:888
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
char _io_context_buffer[PETSC_MAX_PATH_LEN]
Definition variables.h:943
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
ExecutionMode exec_mode
Definition variables.h:937
PetscBool restartHistoryAvailable
Definition variables.h:947
char restart_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:939
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RestoreFieldStatisticsState()

PetscErrorCode RestoreFieldStatisticsState ( SimCtx *  simCtx,
PetscInt  ti 
)

Restores field-statistics window state and accumulators from a checkpoint.

Resumes every configured window from the bundle at ti when continuation was requested, per 7. Checkpoints, Restart, and Continuation. Window scalars come from the bundle manifest and accumulator payloads through the same natural-ordering vector reader Eulerian fields use, so a restart on a different MPI rank count restores identical state.

Does nothing when statistics are disabled, no window is configured, or continuation was not requested. Anything else is fatal rather than silently zeroed: a window count mismatch, a renamed window, a changed definition hash, a requested end earlier than the represented span, or missing state.

Under EXEC_MODE_RESTART_CHECK it needs no grid: it validates the bundle and every window against the manifest, skipping only the geometry comparison and the payload reads, and returns. The CLI runs that before staging a carried restart, so an incompatible window is refused before a job is queued.

Parameters
[in,out]simCtxSimulation context carrying the windows and accumulators.
[in]tiStep whose committed bundle supplies the state.
Returns
Zero on success, or a PETSc error when continuation cannot be honored.

Restores field-statistics window state and accumulators from a checkpoint.

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

See also
RestoreFieldStatisticsState()

Definition at line 1604 of file io.c.

1605{
1606 UserCtx *user = NULL;
1607 PetscOptions options = NULL;
1608 char checkpoint_directory[PETSC_MAX_PATH_LEN];
1609 char metadata_path[PETSC_MAX_PATH_LEN];
1610 const char *source_path = NULL;
1611 PetscInt saved_window_count = 0;
1612 PetscReal checkpoint_time = 0.0;
1613 PetscBool found = PETSC_FALSE;
1614
1615 PetscFunctionBeginUser;
1617 PetscCheck(simCtx != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be NULL.");
1618 if (!FieldStatisticsIsActive(simCtx)) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1619 if (!simCtx->fieldStatisticsContinue) {
1621 "Statistics continuation was not requested; %" PetscInt_FMT " window(s) start from zero.\n",
1624 PetscFunctionReturn(0);
1625 }
1626
1627 /* A restart check runs before setup: it validates everything the metadata holds and
1628 * stops before the payloads, which need the grid. */
1629 if (simCtx->exec_mode != EXEC_MODE_RESTART_CHECK) {
1630 user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1631 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
1632 "Finest-level fields must exist before statistics state is restored.");
1633 }
1635 : simCtx->restart_dir;
1636 PetscCheck(source_path != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
1637 "No checkpoint source directory is set for the current execution mode.");
1638 PetscCall(ResolveCheckpointStepDirectory(source_path, ti,
1639 checkpoint_directory, sizeof(checkpoint_directory)));
1640 PetscCall(ValidateCheckpointBundle(simCtx, user, checkpoint_directory, ti,
1641 &checkpoint_time, NULL, NULL, NULL, NULL));
1642 PetscCall(PetscSNPrintf(metadata_path, sizeof(metadata_path), "%s/checkpoint.meta",
1643 checkpoint_directory));
1644
1645 PetscCall(PetscOptionsCreate(&options));
1646 PetscCall(PetscOptionsInsertFile(PETSC_COMM_WORLD, options, metadata_path, PETSC_TRUE));
1647 PetscCall(PetscOptionsGetInt(options, NULL, "-checkpoint_statistics_window_count",
1648 &saved_window_count, &found));
1649 /* Missing state for a requested continuation is fatal and never silently
1650 * zeroed: resuming from zero would report a converged average built from a
1651 * fraction of the samples its metadata claims. */
1652 PetscCheck(found && saved_window_count == simCtx->fieldStatisticsWindowCount,
1653 PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
1654 "Statistics continuation requested, but checkpoint '%s' holds %" PetscInt_FMT
1655 " window(s) and this run configures %" PetscInt_FMT ".",
1656 checkpoint_directory, found ? saved_window_count : 0,
1657 simCtx->fieldStatisticsWindowCount);
1658
1659 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
1660 PetscCall(ReadStatisticsWindowState(options, window, metadata_path, checkpoint_time,
1661 simCtx->dt, simCtx->exec_mode,
1662 &simCtx->fieldStatisticsWindows[window]));
1663 }
1664 PetscCall(PetscOptionsDestroy(&options));
1665 if (!user) {
1666 LOG_ALLOW(GLOBAL, LOG_INFO, "Statistics continuation check passed: %" PetscInt_FMT " window(s) can continue from '%s'.\n",
1667 simCtx->fieldStatisticsWindowCount, checkpoint_directory);
1669 PetscFunctionReturn(0);
1670 }
1671
1672 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
1673 PetscCheck(user[block].fieldStatisticsStorage != NULL, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
1674 "Statistics accumulators were not allocated for block %" PetscInt_FMT ".", block);
1675 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
1676 const PicurvWindowDefinition *definition = &simCtx->fieldStatisticsWindows[window].definition;
1677 const PicurvWindowStorage *storage = &user[block].fieldStatisticsStorage[window];
1678 PetscInt payload_count = 0;
1679
1680 PetscCall(FormatStatisticsPath(checkpoint_directory, window, block, NULL,
1681 simCtx->_io_context_buffer,
1682 sizeof(simCtx->_io_context_buffer)));
1683 simCtx->current_io_directory = simCtx->_io_context_buffer;
1684 PetscCall(PicurvWindowStoragePayloadCount(storage, &payload_count));
1685 for (PetscInt index = 0; index < payload_count; ++index) {
1687
1688 PetscCall(PicurvWindowStoragePayload(&user[block], definition, storage, index, &payload));
1689 PetscCall(ReadFieldData(&user[block], payload.name, payload.vec, "dat"));
1690 }
1691 }
1692 simCtx->current_io_directory = NULL;
1693 }
1694
1695 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
1696 const PicurvWindow *state = &simCtx->fieldStatisticsWindows[window];
1697
1699 "Statistics window '%s' continued from '%s': state %s, %" PetscInt_FMT " sample(s), "
1700 "total weight %.6g, represented time %.6g, restart segment %" PetscInt_FMT ".\n",
1701 state->definition.name, checkpoint_directory,
1703 (double)state->total_weight, (double)state->represented_time,
1704 state->restart_count);
1705 }
1707 PetscFunctionReturn(0);
1708}
static PetscErrorCode ReadStatisticsWindowState(PetscOptions options, PetscInt window, const char *metadata_path, PetscReal checkpoint_time, PetscReal step_size, ExecutionMode exec_mode, PicurvWindow *state)
Restore one window's scalar bookkeeping from a validated manifest.
Definition io.c:1472
Vec vec
Borrowed accumulator vector; never owned by the caller.
PetscErrorCode PicurvWindowStoragePayload(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt index, PicurvStatisticsPayload *payload)
Resolves one enumerated payload of a window's storage.
char name[96]
File basename, no extension.
PetscErrorCode PicurvWindowStoragePayloadCount(const PicurvWindowStorage *storage, PetscInt *count)
Reports how many checkpointable vectors one window's storage holds.
One checkpointable accumulator vector, resolved by enumeration index.
Independent accumulator state for one window on one block.
PetscInt sample_count
PicurvWindowState state
PetscInt restart_count
Restart segments this state descends from.
PetscReal total_weight
const char * PicurvWindowStateName(PicurvWindowState state)
Returns a stable human-readable name for a window state.
PicurvWindowDefinition definition
PetscReal represented_time
Physical time the window covers.
Runtime state of one window.
The scientifically immutable definition of one window.
PetscReal dt
Definition variables.h:933
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
@ EXEC_MODE_RESTART_CHECK
Definition variables.h:890
PetscBool fieldStatisticsContinue
Definition variables.h:995
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadFieldData()

PetscErrorCode ReadFieldData ( UserCtx *  user,
const char *  field_name,
Vec  field_vec,
const char *  ext 
)

Reads data for a specific field from a file into the provided vector.

This function uses the field name to construct the file path and reads the data from the corresponding file into the provided PETSc vector.

Parameters
[in]userPointer to the UserCtx structure containing simulation context.
[in]field_nameName of the field (e.g., "ufield", "vfield", "pfield").
[out]field_vecPETSc vector to store the field data.
[in]extFile extension (e.g., "dat").
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Reads data for a specific field from a file into the provided vector.

See also
ReadFieldData()

Definition at line 1248 of file io.c.

1252{
1253 PetscErrorCode ierr;
1254 char filename[PETSC_MAX_PATH_LEN];
1255 MPI_Comm comm;
1256 PetscMPIInt rank,size;
1257 SimCtx *simCtx = user->simCtx;
1258
1259
1260 PetscFunctionBeginUser;
1262
1263 if(!simCtx->current_io_directory){
1264 SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "I/O context directory was not set before calling ReadFieldData().");
1265 }
1266
1267
1268 ierr = PetscObjectGetComm((PetscObject)field_vec,&comm);CHKERRQ(ierr);
1269 ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
1270 ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
1271
1272 const char *source_path = simCtx->current_io_directory;
1273 ierr = PetscSNPrintf(filename, sizeof(filename), "%s/%s.%s",
1274 source_path, field_name, ext); CHKERRQ(ierr);
1275 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Attempting to read <%s> on rank %d/%d\n", filename,(int)rank,(int)size);
1276
1277 // Rank 0 checks the file exists, so a missing one is named; VecLoad checks its length.
1278 PetscBool found = PETSC_FALSE;
1279 if (rank == 0) { ierr = PetscTestFile(filename, 'r', &found); CHKERRQ(ierr); }
1280 ierr = MPI_Bcast(&found, 1, MPIU_BOOL, 0, comm); CHKERRMPI(ierr);
1281 if (!found) SETERRQ(comm, PETSC_ERR_FILE_OPEN, "Restart/Source file not found: %s", filename);
1282
1283 // Every rank reads its own part (MPI-IO). A DMDA payload is in natural order and is read into a
1284 // natural vector, then permuted; any other vector (a swarm field) is in rank order and is read
1285 // into a vector of its layout, then copied, since loading into a DMSwarm view could resize it.
1286 DM dm = NULL;
1287 Vec staged = NULL;
1288 PetscViewer viewer = NULL;
1289 ierr = FieldVecDMDA(field_vec, &dm); CHKERRQ(ierr);
1290 const PetscBool natural = (PetscBool)(dm != NULL);
1291 if (natural) { ierr = DMDACreateNaturalVector(dm, &staged); CHKERRQ(ierr); }
1292 else { ierr = VecDuplicate(field_vec, &staged); CHKERRQ(ierr); }
1293 ierr = OpenFieldPayloadViewer(comm, filename, FILE_MODE_READ, &viewer); CHKERRQ(ierr);
1294 ierr = VecLoad(staged, viewer);
1295 if (ierr) {
1296 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);
1297 ierr = VecDestroy(&staged); CHKERRQ(ierr);
1298 SETERRQ(comm, PETSC_ERR_FILE_UNEXPECTED, "Could not load '%s' into field '%s'.", filename, field_name);
1299 }
1300 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);
1301 if (natural) {
1302 ierr = DMDANaturalToGlobalBegin(dm, staged, INSERT_VALUES, field_vec); CHKERRQ(ierr);
1303 ierr = DMDANaturalToGlobalEnd(dm, staged, INSERT_VALUES, field_vec); CHKERRQ(ierr);
1304 } else {
1305 ierr = VecCopy(staged, field_vec); CHKERRQ(ierr);
1306 }
1307 ierr = VecDestroy(&staged); CHKERRQ(ierr);
1308
1309 LOG_ALLOW(GLOBAL,LOG_INFO, "Loaded <%s>\n",filename);
1310
1312 PetscFunctionReturn(0);
1313}
static PetscErrorCode FieldVecDMDA(Vec field_vec, DM *dmda)
The DMDA a vector belongs to, or NULL for a vector of any other layout (a swarm field).
Definition io.c:137
static PetscErrorCode OpenFieldPayloadViewer(MPI_Comm comm, const char *filename, PetscFileMode mode, PetscViewer *viewer)
Open a PETSc binary viewer for one field payload, reading or writing through MPI-IO.
Definition io.c:182
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteFieldData()

PetscErrorCode WriteFieldData ( UserCtx *  user,
const char *  field_name,
Vec  field_vec,
const char *  ext 
)

Writes data from a specific PETSc vector to a file.

This function uses the field name to construct the file path and writes the data from the provided PETSc vector to the corresponding file.

Parameters
[in]userPointer to the UserCtx structure containing simulation context.
[in]field_nameName of the field (e.g., "ufield", "vfield", "pfield").
[in]field_vecPETSc vector containing the field data to write.
[in]extFile extension (e.g., "dat").
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Writes data from a specific PETSc vector to a file.

See also
WriteFieldData()

Definition at line 1901 of file io.c.

1905{
1906 MPI_Comm comm;
1907 Vec natural_vec = NULL, ordered_vec = NULL;
1908 PetscViewer viewer;
1909 char filename[PETSC_MAX_PATH_LEN];
1910 SimCtx *simCtx=user->simCtx;
1911
1912 PetscFunctionBeginUser;
1914
1915 if(!simCtx->current_io_directory){
1916 SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "I/O context directory was not set before calling WriteFieldData().");
1917 }
1918
1919 /* ------------------------------------------------------------ */
1920 /* Basic communicator information */
1921 /* ------------------------------------------------------------ */
1922 PetscCall(PetscObjectGetComm((PetscObject)field_vec,&comm));
1923
1924 PetscCall(PetscSNPrintf(filename, sizeof(filename), "%s/%s.%s",
1925 simCtx->current_io_directory, field_name, ext));
1926
1927 // Every rank writes its own part of the file (MPI-IO), the same file a sequential write
1928 // makes - the header, then the values in natural order - so no rank gathers or relays the
1929 // field: at 1e9 particles a field is tens of GB.
1930 PetscCall(NaturalOrderedVector(field_vec, &natural_vec, &ordered_vec));
1931 if ((int)get_log_level() >= (int)LOG_DEBUG) {
1932 PetscReal vmin, vmax;
1933
1934 PetscCall(VecMin(ordered_vec, NULL, &vmin));
1935 PetscCall(VecMax(ordered_vec, NULL, &vmax));
1936 LOG_ALLOW(GLOBAL,LOG_DEBUG, " <%s> range = [%.4e … %.4e]\n", field_name,(double)vmin,(double)vmax);
1937 }
1938 PetscCall(OpenFieldPayloadViewer(comm, filename, FILE_MODE_WRITE, &viewer));
1939 PetscCall(VecView(ordered_vec, viewer));
1940 PetscCall(PetscViewerDestroy(&viewer));
1941 PetscCall(VecDestroy(&natural_vec));
1942 LOG_ALLOW(GLOBAL, LOG_INFO, "Wrote <%s>\n", filename);
1943
1945 PetscFunctionReturn(0);
1946}
static PetscErrorCode NaturalOrderedVector(Vec field_vec, Vec *natural_vec, Vec *ordered_vec)
Express a vector in decomposition-independent natural ordering.
Definition io.c:156
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteSimulationFields()

PetscErrorCode WriteSimulationFields ( UserCtx *  user,
const char *  checkpoint_directory 
)

Writes simulation fields to files.

This function writes contravariant velocity, Cartesian velocity, pressure, and node state fields to their respective binary files. It also conditionally writes LES model fields when those models are enabled.

Parameters
[in]userPointer to the UserCtx structure containing simulation context.
[in]checkpoint_directoryRoot of the in-progress checkpoint bundle.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Writes simulation fields to files.

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

See also
WriteSimulationFields()

Definition at line 1954 of file io.c.

1955{
1956 SimCtx *simCtx = user->simCtx;
1957
1958 PetscFunctionBeginUser;
1960 PetscCheck(checkpoint_directory != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1961 "Checkpoint destination cannot be NULL.");
1962 PetscCall(PetscSNPrintf(simCtx->_io_context_buffer, sizeof(simCtx->_io_context_buffer),
1963 "%s/%s/block_%04" PetscInt_FMT,
1964 checkpoint_directory, PICURV_EULERIAN_DIRECTORY, user->_this));
1965 simCtx->current_io_directory = simCtx->_io_context_buffer;
1966
1967 if (simCtx->les) {
1968 // The constant model holds no coefficient field to stage.
1969 if (simCtx->les == DYNAMIC_SMAGORINSKY) {
1970 PetscCall(CopyOwnedLocalScalarToGlobal(user->da, user->lCs, user->CS));
1971 }
1972 PetscCall(CopyOwnedLocalScalarToGlobal(user->da, user->lNu_t, user->Nu_t));
1973 }
1974 for (PetscInt raw_id = 0; raw_id < FIELD_ID_COUNT; ++raw_id) {
1975 const FieldDescriptor *descriptor = NULL;
1976 FieldView view;
1977
1978 PetscCall(FieldGetDescriptor((FieldId)raw_id, &descriptor));
1979 if (!CheckpointFieldIsEnabled(simCtx, descriptor)) continue;
1980 PetscCall(FieldGetView(user, descriptor->id, &view));
1981 PetscCall(WriteFieldData(user, descriptor->canonical_name, view.global_vec, "dat"));
1982 }
1983 simCtx->current_io_directory = NULL;
1985 PetscFunctionReturn(0);
1986}
static PetscErrorCode CopyOwnedLocalScalarToGlobal(DM dm, Vec local_vec, Vec global_vec)
Copies the owned entries of a ghosted scalar DMDA vector to its global vector.
Definition io.c:52
PetscErrorCode WriteFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Implementation of WriteFieldData().
Definition io.c:1901
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
Vec lNu_t
Definition variables.h:1259
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteSwarmField()

PetscErrorCode WriteSwarmField ( UserCtx *  user,
const char *  field_name,
const char *  ext 
)

Writes data from a specific field in a PETSc Swarm to a file.

This function retrieves the Swarm from the UserCtx (i.e., user->swarm) and creates a global PETSc vector from the specified Swarm field. It then calls the existing WriteFieldData() function to handle the actual I/O operation. After writing the data, the function destroys the temporary global vector to avoid memory leaks.

Parameters
[in]userPointer to the UserCtx structure containing simulation context and the PetscSwarm (as user->swarm).
[in]field_nameName of the Swarm field to be written (e.g., "my_field").
[in]extFile extension (e.g., "dat", "bin").
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.
Note
Compatible with PETSc 3.14.4.

Writes data from a specific field in a PETSc Swarm to a file.

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

See also
WriteSwarmField()

Definition at line 2031 of file io.c.

2032{
2033 PetscErrorCode ierr;
2034 Vec fieldVec;
2035 DM swarm;
2036
2037 PetscFunctionBeginUser; /* PETSc macro indicating start of function */
2039
2040 /*
2041 * 1) Retrieve the PetscSwarm from the user context.
2042 * Ensure user->swarm is initialized and not NULL.
2043 */
2044 swarm = user->swarm;
2045
2046 /*
2047 * 2) Create a global vector from the specified swarm field.
2048 * This function is available in PETSc 3.14.4.
2049 * It provides a read/write "view" of the swarm field as a global Vec.
2050 */
2052 "Attempting to create global vector from field: %s\n",
2053 field_name);
2054 ierr = DMSwarmCreateGlobalVectorFromField(swarm, field_name, &fieldVec);CHKERRQ(ierr);
2055
2056 /*
2057 * 3) Use your existing WriteFieldData() to write the global vector to a file.
2058 * The field name, time index, and extension are passed along for naming.
2059 */
2061 "Calling WriteFieldData for field: %s\n",
2062 field_name);
2063 ierr = WriteFieldData(user, field_name, fieldVec, ext);CHKERRQ(ierr);
2064
2065 /*
2066 * 4) Destroy the global vector once the data is successfully written.
2067 * This step is crucial for avoiding memory leaks.
2068 * DMSwarmDestroyGlobalVectorFromField() is also available in PETSc 3.14.4.
2069 */
2071 "Destroying the global vector for field: %s\n",
2072 field_name);
2073 ierr = DMSwarmDestroyGlobalVectorFromField(swarm, field_name, &fieldVec);CHKERRQ(ierr);
2074
2075 /* Log and return success. */
2077 "Successfully wrote swarm data for field: %s\n",
2078 field_name);
2079
2081 PetscFunctionReturn(0); /* PETSc macro indicating end of function */
2082}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteSwarmIntField()

PetscErrorCode WriteSwarmIntField ( UserCtx *  user,
const char *  field_name,
const char *  ext 
)

Writes integer data from a specific PETSc Swarm field to a file.

This function is designed for swarm fields that store integer data (e.g., DMSwarm_CellID), which cannot be converted to a standard PETSc Vec of PetscScalars. It accesses the raw data pointer for the field on each rank using DMSwarmGetField(), writes the local data to a rank-specific binary file, and then restores the field access.

Parameters
[in]userPointer to the UserCtx structure containing the PetscSwarm.
[in]field_nameName of the integer Swarm field to be written.
[in]extFile extension (e.g., "dat", "bin").
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Writes integer data from a specific PETSc Swarm field to a file.

See also
WriteSwarmIntField()

Definition at line 2088 of file io.c.

2089{
2090 PetscErrorCode ierr;
2091 DM swarm = user->swarm;
2092 Vec temp_vec; // Temporary Vec to hold casted data
2093 PetscInt nlocal, nglobal,bs,i;
2094 PetscDataType field_type;
2095 void *field_array_void;
2096 PetscScalar *scalar_array; // Pointer to the temporary Vec's scalar data
2097
2098 PetscFunctionBeginUser;
2100
2101 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Casting '%s' to Vec for writing.\n", field_name);
2102
2103 // Get the swarm field properties
2104 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
2105 ierr = DMSwarmGetSize(swarm, &nglobal); CHKERRQ(ierr);
2106 ierr = DMSwarmGetField(swarm, field_name, &bs, &field_type, &field_array_void); CHKERRQ(ierr);
2107 PetscCheck(field_type == PETSC_INT || field_type == PETSC_INT64,
2108 PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2109 "Swarm field '%s' must use PETSC_INT or PETSC_INT64 for integer output, not %s.",
2110 field_name, PetscDataTypes[field_type]);
2111
2112 // Create Temporary parallel Vec wit the CORRECT layout
2113 ierr = VecCreate(PETSC_COMM_WORLD, &temp_vec); CHKERRQ(ierr);
2114 ierr = VecSetType(temp_vec, VECMPI); CHKERRQ(ierr);
2115 ierr = VecSetSizes(temp_vec, nlocal*bs, nglobal*bs); CHKERRQ(ierr);
2116 ierr = VecSetUp(temp_vec); CHKERRQ(ierr);
2117
2118 // Defining Vector field to mandatory field 'position'
2119 DMSwarmVectorDefineField(swarm,ParticleFieldName(PARTICLE_FIELD_ID_POSITION));
2120
2121 ierr = VecGetArray(temp_vec, &scalar_array); CHKERRQ(ierr);
2122
2123 if (field_type == PETSC_INT64) {
2124 PetscInt64 *int64_array = (PetscInt64 *)field_array_void;
2125 // Perform the cast from PetscInt64 to PetscScalar
2126 for (i = 0; i < nlocal*bs; i++) {
2127 scalar_array[i] = (PetscScalar)int64_array[i];
2128 }
2129 }else{
2130 PetscInt *int_array = (PetscInt *)field_array_void;
2131 //Perform the cast from PetscInt to PetscScalar
2132 for (i = 0; i < nlocal*bs; i++) {
2133 scalar_array[i] = (PetscScalar)int_array[i];
2134 }
2135 }
2136
2137 // Restore access to both arrays
2138 ierr = VecRestoreArray(temp_vec, &scalar_array); CHKERRQ(ierr);
2139 ierr = DMSwarmRestoreField(swarm, field_name, &bs, NULL, &field_array_void); CHKERRQ(ierr);
2140
2141 // Call your existing writer with the temporary, populated Vec
2142 ierr = WriteFieldData(user, field_name, temp_vec, ext); CHKERRQ(ierr);
2143
2144 // Clean up
2145 ierr = VecDestroy(&temp_vec); CHKERRQ(ierr);
2146
2148 PetscFunctionReturn(0);
2149}
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_POSITION
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteAllSwarmFields()

PetscErrorCode WriteAllSwarmFields ( UserCtx *  user,
const char *  checkpoint_directory 
)

Writes a predefined set of PETSc Swarm fields to files.

This function iterates through checkpoint-capable particle catalog entries and delegates each payload to the existing generic swarm writer.

This function will only execute if particles are enabled in the simulation (i.e., user->simCtx->np > 0 and user->swarm is not NULL).

Parameters
[in]userPointer to the UserCtx structure containing the simulation context and the PetscSwarm.
[in]checkpoint_directoryRoot of the in-progress checkpoint bundle.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Writes a predefined set of PETSc Swarm fields to files.

See also
WriteAllSwarmFields()

Definition at line 2155 of file io.c.

2156{
2157 SimCtx *simCtx = user->simCtx;
2158
2159 PetscFunctionBeginUser;
2161
2162 // If no swarm is configured or there are no particles, do nothing and return.
2163 if (!user->swarm || !ParticlesEnabled(simCtx)) {
2165 PetscFunctionReturn(0);
2166 }
2167
2168 PetscCheck(checkpoint_directory != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
2169 "Checkpoint destination cannot be NULL.");
2170 PetscCall(PetscSNPrintf(simCtx->_io_context_buffer, sizeof(simCtx->_io_context_buffer),
2171 "%s/%s", checkpoint_directory, PICURV_PARTICLE_DIRECTORY));
2172 simCtx->current_io_directory = simCtx->_io_context_buffer;
2173
2174 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
2175 const ParticleFieldDescriptor *descriptor = NULL;
2176
2177 PetscCall(ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor));
2178 if (!(descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_CHECKPOINT)) continue;
2179 if (descriptor->data_type == PETSC_INT || descriptor->data_type == PETSC_INT64) {
2180 PetscCall(WriteSwarmIntField(user, descriptor->canonical_name, "dat"));
2181 } else {
2182 PetscCall(WriteSwarmField(user, descriptor->canonical_name, "dat"));
2183 }
2184 }
2185
2186 simCtx->current_io_directory = NULL;
2187
2189 PetscFunctionReturn(0);
2190}
PetscErrorCode WriteSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
Implementation of WriteSwarmIntField().
Definition io.c:2088
PetscErrorCode WriteSwarmField(UserCtx *user, const char *field_name, const char *ext)
Implementation of WriteSwarmField().
Definition io.c:2031
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_COUNT
@ PARTICLE_FIELD_CAPABILITY_CHECKPOINT
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
Immutable metadata for one persistent particle field.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadDataFileToArray()

PetscInt ReadDataFileToArray ( const char *  filename,
double **  data_out,
PetscInt *  Nout,
MPI_Comm  comm 
)

Reads a simple ASCII data file containing one numeric value per line.

This helper performs rank-0 file I/O, broadcasts the parsed result to the rest of the communicator, and returns a replicated array on every rank.

Parameters
filenamePath to the input data file.
data_outOutput pointer to the allocated scalar array.
NoutOutput pointer storing the number of values read.
commMPI communicator used for the coordinated read/broadcast sequence.
Returns
Integer value produced by ReadDataFileToArray().

Reads a simple ASCII data file containing one numeric value per line.

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

See also
ReadDataFileToArray()

Definition at line 3300 of file io.c.

3304{
3306 /* STEP 0: Prepare local variables & log function entry */
3307 PetscMPIInt rank, size;
3308 PetscErrorCode ierr;
3309 FILE *fp = NULL;
3310 PetscInt N = 0; /* number of lines/values read on rank 0 */
3311 double *array = NULL; /* pointer to local array on each rank */
3312 PetscInt fileExistsFlag = 0; /* 0 = doesn't exist, 1 = does exist */
3313
3315 "Start reading from file: %s\n",
3316 filename);
3317
3318 /* Basic error checking: data_out, Nout must be non-null. */
3319 if (!filename || !data_out || !Nout) {
3321 "Null pointer argument provided.\n");
3323 return 1;
3324 }
3325
3326 /* Determine rank/size for coordinating I/O. */
3327 MPI_Comm_rank(comm, &rank);
3328 MPI_Comm_size(comm, &size);
3329
3330 /* STEP 1: On rank 0, check if file can be opened. */
3331 if (!rank) {
3332 fp = fopen(filename, "r");
3333 if (fp) {
3334 fileExistsFlag = 1;
3335 fclose(fp);
3336 }
3337 }
3338
3339 /* STEP 2: Broadcast file existence to all ranks. */
3340 // In ReadDataFileToArray:
3341 ierr = MPI_Bcast(&fileExistsFlag, 1, MPIU_INT, 0, comm); CHKERRQ(ierr);
3342
3343 if (!fileExistsFlag) {
3344 /* If file does not exist, log & return. */
3345 if (!rank) {
3347 "File '%s' not found.\n",
3348 filename);
3349 }
3351 return 2;
3352 }
3353
3354 /* STEP 3: Rank 0 re-opens and reads the file, counting lines, etc. */
3355 if (!rank) {
3356 fp = fopen(filename, "r");
3357 if (!fp) {
3359 "File '%s' could not be opened for reading.\n",
3360 filename);
3362 return 3;
3363 }
3364
3365 /* (3a) Count lines first. */
3366 {
3367 char line[256];
3368 while (fgets(line, sizeof(line), fp)) {
3369 N++;
3370 }
3371 }
3372
3374 "File '%s' has %" PetscInt_FMT " lines.\n",
3375 filename, N);
3376
3377 /* (3b) Allocate array on rank 0. */
3378 array = (double*)malloc(N * sizeof(double));
3379 if (!array) {
3380 fclose(fp);
3382 "malloc failed for array.\n");
3384 return 4;
3385 }
3386
3387 /* (3c) Rewind & read values into array. */
3388 rewind(fp);
3389 {
3390 PetscInt i = 0;
3391 char line[256];
3392 while (fgets(line, sizeof(line), fp)) {
3393 double val;
3394 if (sscanf(line, "%lf", &val) == 1) {
3395 array[i++] = val;
3396 }
3397 }
3398 }
3399 fclose(fp);
3400
3402 "Successfully read %" PetscInt_FMT " values from '%s'.\n",
3403 N, filename);
3404 }
3405
3406 /* STEP 4: Broadcast the integer N to all ranks. */
3407 ierr = MPI_Bcast(&N, 1, MPIU_INT, 0, comm); CHKERRQ(ierr);
3408
3409 /* STEP 5: Each rank allocates an array to receive the broadcast if rank>0. */
3410 if (rank) {
3411 array = (double*)malloc(N * sizeof(double));
3412 if (!array) {
3414 "malloc failed on rank %d.\n",
3415 rank);
3417 return 5;
3418 }
3419 }
3420
3421 /* STEP 6: Broadcast the actual data from rank 0 to all. */
3422 ierr = MPI_Bcast(array, N, MPI_DOUBLE, 0, comm); CHKERRQ(ierr);
3423
3424 /* STEP 7: Assign outputs on all ranks. */
3425 *data_out = array;
3426 *Nout = N;
3427
3429 "Done. Provided array of length=%" PetscInt_FMT " to all ranks.\n",
3430 N);
3432 return 0; /* success */
3433}
#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
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30

◆ CreateVTKFileFromMetadata()

PetscErrorCode CreateVTKFileFromMetadata ( const char *  filename,
const VTKMetaData *  meta,
MPI_Comm  comm 
)

Creates a VTK file from prepared metadata and field payloads.

This helper dispatches to the structured-grid or polydata writer based on the metadata contents and emits the assembled VTK file on the requested communicator.

Parameters
filenamePath to the output VTK file.
metaVTK metadata describing the output geometry and field payloads.
commMPI communicator used by the write operation.
Returns
Integer value produced by CreateVTKFileFromMetadata().

Creates a VTK file from prepared metadata and field payloads.

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

See also
CreateVTKFileFromMetadata()

Definition at line 172 of file vtk_io.c.

173{
174 static const char footer[] = "\n </AppendedData>\n</VTKFile>\n";
175 const PetscBool structured = (PetscBool)(meta->fileType == VTK_STRUCTURED);
176 char tmp_filename[PETSC_MAX_PATH_LEN];
177 PetscMPIInt rank;
178 long long header_bytes = 0; /* -1: rank 0 could not write the header */
179 MPI_File fh;
180 MPI_Offset position;
181 PetscInt blocks = 0, local_points = 1, boffset = 0;
182 struct VTKBlock { PetscInt components; MPI_Datatype type; size_t size; const void *data; } block[MAX_POINT_DATA_FIELDS + 3];
183
184 PetscFunctionBeginUser;
186 PetscCheck(structured || meta->fileType == VTK_POLYDATA, comm, PETSC_ERR_ARG_WRONG, "Unknown VTK file type.");
187 PetscCallMPI(MPI_Comm_rank(comm, &rank));
188 PetscCall(PetscSNPrintf(tmp_filename, sizeof(tmp_filename), "%s.tmp", filename));
189
190 /* The appended blocks, in the order the header declares them. */
191 block[blocks++] = (struct VTKBlock){3, MPIU_SCALAR, sizeof(PetscScalar), meta->coords};
192 for (PetscInt f = 0; f < meta->num_point_data_fields; ++f)
193 block[blocks++] = (struct VTKBlock){meta->point_data_fields[f].num_components, MPIU_SCALAR, sizeof(PetscScalar),
194 meta->point_data_fields[f].data};
195 if (!structured) {
196 block[blocks++] = (struct VTKBlock){1, MPIU_INT, sizeof(PetscInt), meta->connectivity};
197 block[blocks++] = (struct VTKBlock){1, MPIU_INT, sizeof(PetscInt), meta->offsets};
198 }
199 for (int d = 0; d < (structured ? 3 : 1); ++d) local_points *= meta->local_size[d];
200
201 if (rank == 0) {
202 FILE *fp = fopen(tmp_filename, "wb");
203 if (!fp || WriteVTKFileHeader(fp, meta, &boffset)) header_bytes = -1;
204 else header_bytes = (long long)ftell(fp);
205 if (fp && fclose(fp)) header_bytes = -1;
206 }
207 PetscCallMPI(MPI_Bcast(&header_bytes, 1, MPI_LONG_LONG, 0, comm));
208 PetscCheck(header_bytes >= 0, comm, PETSC_ERR_FILE_OPEN, "Could not write the VTK header of '%s'.", tmp_filename);
209
210 /* Rank 0 writes each block's byte count; every rank writes its own points into the block. */
211 PetscCallMPI(MPI_File_open(comm, tmp_filename, MPI_MODE_WRONLY, MPI_INFO_NULL, &fh));
212 position = (MPI_Offset)header_bytes;
213 for (PetscInt b = 0; b < blocks; ++b) {
214 const uint64_t bytes = (uint64_t)block[b].components * (uint64_t)meta->npoints * block[b].size;
215 MPI_Datatype point, view;
216 PetscMPIInt count;
217
218 PetscCallMPI(MPI_File_set_view(fh, 0, MPI_BYTE, MPI_BYTE, "native", MPI_INFO_NULL));
219 if (rank == 0) PetscCallMPI(MPI_File_write_at(fh, position, &bytes, (int)sizeof(bytes), MPI_BYTE, MPI_STATUS_IGNORE));
220 position += (MPI_Offset)sizeof(bytes);
221
222 PetscCallMPI(MPI_Type_contiguous((PetscMPIInt)block[b].components, block[b].type, &point));
223 PetscCallMPI(MPI_Type_commit(&point));
224 view = point;
225 if (structured && local_points > 0) {
226 const PetscMPIInt sizes[3] = {(PetscMPIInt)meta->mz, (PetscMPIInt)meta->my, (PetscMPIInt)meta->mx};
227 const PetscMPIInt subsizes[3] = {(PetscMPIInt)meta->local_size[2], (PetscMPIInt)meta->local_size[1], (PetscMPIInt)meta->local_size[0]};
228 const PetscMPIInt starts[3] = {(PetscMPIInt)meta->local_start[2], (PetscMPIInt)meta->local_start[1], (PetscMPIInt)meta->local_start[0]};
229 PetscCallMPI(MPI_Type_create_subarray(3, sizes, subsizes, starts, MPI_ORDER_C, point, &view));
230 PetscCallMPI(MPI_Type_commit(&view));
231 }
232 PetscCallMPI(MPI_File_set_view(fh, position, point, view, "native", MPI_INFO_NULL));
233 PetscCall(PetscMPIIntCast(local_points, &count));
234 if (structured) PetscCallMPI(MPI_File_write_all(fh, block[b].data, count, point, MPI_STATUS_IGNORE));
235 else PetscCallMPI(MPI_File_write_at_all(fh, (MPI_Offset)meta->local_start[0], block[b].data, count, point, MPI_STATUS_IGNORE));
236 if (view != point) PetscCallMPI(MPI_Type_free(&view));
237 PetscCallMPI(MPI_Type_free(&point));
238 position += (MPI_Offset)bytes;
239 }
240 PetscCallMPI(MPI_File_set_view(fh, 0, MPI_BYTE, MPI_BYTE, "native", MPI_INFO_NULL));
241 if (rank == 0) PetscCallMPI(MPI_File_write_at(fh, position, footer, (int)strlen(footer), MPI_BYTE, MPI_STATUS_IGNORE));
242 PetscCallMPI(MPI_File_close(&fh));
243 if (rank == 0) PetscCheck(rename(tmp_filename, filename) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
244 "Could not move '%s' to '%s'.", tmp_filename, filename);
245 LOG_ALLOW(GLOBAL, LOG_INFO, "Wrote VTK file '%s'.\n", filename);
247 PetscFunctionReturn(0);
248}
#define MAX_POINT_DATA_FIELDS
Defines the maximum number of data fields for VTK point data.
Definition variables.h:787
PetscInt npoints
Definition variables.h:874
PetscInt num_components
Definition variables.h:854
PetscInt num_point_data_fields
Definition variables.h:879
PetscInt local_size[3]
Definition variables.h:876
PetscInt local_start[3]
Definition variables.h:875
PetscInt * connectivity
Definition variables.h:880
PetscInt * offsets
Definition variables.h:881
VTKFileType fileType
Definition variables.h:872
PetscScalar * data
Definition variables.h:855
PetscScalar * coords
Definition variables.h:877
VTKFieldInfo point_data_fields[20]
Definition variables.h:878
PetscInt mz
Definition variables.h:873
PetscInt my
Definition variables.h:873
PetscInt mx
Definition variables.h:873
@ VTK_POLYDATA
Definition variables.h:861
@ VTK_STRUCTURED
Definition variables.h:860
static PetscErrorCode WriteVTKFileHeader(FILE *fp, const VTKMetaData *meta, PetscInt *boffset)
Open a VTK XML document and write its file-level header.
Definition vtk_io.c:115
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadSwarmField()

PetscErrorCode ReadSwarmField ( UserCtx *  user,
const char *  field_name,
const char *  ext 
)

Reads data from a file into a specified field of a PETSc DMSwarm.

This function is the counterpart to WriteSwarmField(). It creates a global PETSc vector that references the specified DMSwarm field, uses ReadFieldData() to read the data from a file, and then destroys the global vector reference.

Parameters
[in]userPointer to the UserCtx structure (containing user->swarm).
[in]field_nameName of the DMSwarm field to read into (must be previously declared/allocated).
[in]extFile extension (e.g., "dat" or "bin").
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.
Note
Compatible with PETSc 3.14.x.

Reads data from a file into a specified field of a PETSc DMSwarm.

See also
ReadSwarmField()

Definition at line 1714 of file io.c.

1715{
1716 PetscErrorCode ierr;
1717 DM swarm;
1718 Vec fieldVec;
1719
1720 PetscFunctionBegin;
1722
1723 swarm = user->swarm;
1724
1725 LOG_ALLOW(GLOBAL,LOG_DEBUG," ReadSwarmField Begins \n");
1726
1727 /* 2) Create a global vector that references the specified Swarm field. */
1728 ierr = DMSwarmCreateGlobalVectorFromField(swarm, field_name, &fieldVec);CHKERRQ(ierr);
1729
1730 LOG_ALLOW(GLOBAL,LOG_DEBUG," Vector created from Field \n");
1731
1732 /* 3) Use the ReadFieldData() function to read data into fieldVec. */
1733 ierr = ReadFieldData(user, field_name, fieldVec, ext);CHKERRQ(ierr);
1734
1735 /* 4) Destroy the global vector reference. */
1736 ierr = DMSwarmDestroyGlobalVectorFromField(swarm, field_name, &fieldVec);CHKERRQ(ierr);
1737
1739 PetscFunctionReturn(0);
1740}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadSwarmIntField()

PetscErrorCode ReadSwarmIntField ( UserCtx *  user,
const char *  field_name,
const char *  ext 
)

Reads integer swarm data by using ReadFieldData and casting the result.

This function is the counterpart to WriteSwarmIntField. It reads a file containing floating-point data (that was originally integer) into a temporary Vec and then casts it back to the integer swarm field. It works by:

  1. Creating a temporary parallel Vec.
  2. Calling the standard ReadFieldData() to populate this Vec.
  3. Accessing the local data of both the Vec and the swarm field.
  4. Populating the swarm's integer field by casting each PetscScalar back to a PetscInt.
  5. Destroying the temporary Vec.
Parameters
[in]userPointer to the UserCtx structure.
[in]field_nameName of the integer Swarm field to be read.
[in]extFile extension.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Reads integer swarm data by using ReadFieldData and casting the result.

See also
ReadSwarmIntField()

Definition at line 1746 of file io.c.

1747{
1748 PetscErrorCode ierr;
1749 DM swarm = user->swarm;
1750 Vec temp_vec;
1751 PetscInt nlocal, nglobal, bs, i;
1752 PetscDataType field_type;
1753 const PetscScalar *scalar_array; // Read-only pointer from the temp Vec
1754 void *field_array_void;
1755
1756
1757 PetscFunctionBeginUser;
1759
1760 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Reading '%s' via temporary Vec.\n", field_name);
1761
1762 // Get the properties of the swarm field to determine the expected layout
1763 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
1764 ierr = DMSwarmGetSize(swarm, &nglobal); CHKERRQ(ierr);
1765 // We get the block size but not the data pointer yet
1766 ierr = DMSwarmGetField(swarm, field_name, &bs, &field_type, NULL); CHKERRQ(ierr);
1767 ierr = DMSwarmRestoreField(swarm, field_name, &bs, NULL, NULL); CHKERRQ(ierr);
1768 PetscCheck(field_type == PETSC_INT || field_type == PETSC_INT64,
1769 PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
1770 "Swarm field '%s' must use PETSC_INT or PETSC_INT64 for integer restart input, not %s.",
1771 field_name, PetscDataTypes[field_type]);
1772
1773 // Create a temporary Vec with the CORRECT layout to receive the data
1774 ierr = VecCreate(PETSC_COMM_WORLD, &temp_vec); CHKERRQ(ierr);
1775 ierr = VecSetType(temp_vec, VECMPI); CHKERRQ(ierr);
1776 ierr = VecSetSizes(temp_vec, nlocal * bs, nglobal * bs); CHKERRQ(ierr);
1777 ierr = VecSetBlockSize(temp_vec, bs); CHKERRQ(ierr);
1778 ierr = VecSetUp(temp_vec); CHKERRQ(ierr);
1779
1780 // Call your existing reader to populate the temporary Vec
1781 ierr = ReadFieldData(user, field_name, temp_vec, ext); CHKERRQ(ierr);
1782
1783 // Get local pointers
1784 ierr = VecGetArrayRead(temp_vec, &scalar_array); CHKERRQ(ierr);
1785 ierr = DMSwarmGetField(swarm, field_name, NULL, NULL, &field_array_void); CHKERRQ(ierr);
1786
1787 // Perform the cast back, using the correct loop size (nlocal * bs)
1788 if (field_type == PETSC_INT64) {
1789 PetscInt64 *int64_array = (PetscInt64 *)field_array_void;
1790 for (i = 0; i < nlocal * bs; i++) {
1791 int64_array[i] = (PetscInt64)scalar_array[i];
1792 }
1793 } else {
1794 PetscInt *int_array = (PetscInt *)field_array_void;
1795 for (i = 0; i < nlocal * bs; i++) {
1796 int_array[i] = (PetscInt)scalar_array[i];
1797 }
1798 }
1799
1800 // Restore access
1801 ierr = DMSwarmRestoreField(swarm, field_name, NULL, NULL, &field_array_void); CHKERRQ(ierr);
1802 ierr = VecRestoreArrayRead(temp_vec, &scalar_array); CHKERRQ(ierr);
1803
1804 // 6. Clean up
1805 ierr = VecDestroy(&temp_vec); CHKERRQ(ierr);
1806
1808 PetscFunctionReturn(0);
1809}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadAllSwarmFields()

PetscErrorCode ReadAllSwarmFields ( UserCtx *  user,
PetscInt  ti 
)

Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.

This function is analogous to ReadSimulationFields() but targets a DMSwarm. Each Swarm field is read from a separate file using ReadSwarmField().

Parameters
[in,out]userPointer to the UserCtx structure containing the DMSwarm (user->swarm).
[in]tiTime index for constructing the file name.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.

See also
ReadAllSwarmFields()

Definition at line 1815 of file io.c.

1816{
1817 PetscInt nGlobal;
1818 SimCtx *simCtx = user->simCtx;
1819 const char *source_path = NULL;
1820 char checkpoint_directory[PETSC_MAX_PATH_LEN];
1821
1822 PetscFunctionBeginUser;
1824 PetscCall(DMSwarmGetSize(user->swarm, &nGlobal));
1825 LOG_ALLOW(GLOBAL, LOG_INFO, "Reading DMSwarm fields for timestep %" PetscInt_FMT " (swarm size is %" PetscInt_FMT ").\n", ti, nGlobal);
1826
1827 if (nGlobal == 0) {
1828 LOG_ALLOW(GLOBAL, LOG_INFO, "Swarm is empty for timestep %" PetscInt_FMT ". Nothing to read.\n", ti);
1830 PetscFunctionReturn(0);
1831 }
1832
1833 // First, determine the top-level source directory based on the execution mode.
1834 if (simCtx->exec_mode == EXEC_MODE_SOLVER) {
1835 source_path = simCtx->restart_dir;
1836 } else if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) {
1837 source_path = simCtx->pps->source_dir;
1838 } else {
1839 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "Invalid execution mode for reading simulation fields.");
1840 }
1841
1842 PetscCall(ResolveCheckpointStepDirectory(source_path, ti,
1843 checkpoint_directory, sizeof(checkpoint_directory)));
1844 PetscCall(PetscSNPrintf(simCtx->_io_context_buffer, sizeof(simCtx->_io_context_buffer),
1845 "%s/%s", checkpoint_directory, PICURV_PARTICLE_DIRECTORY));
1846 simCtx->current_io_directory = simCtx->_io_context_buffer;
1847
1848 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
1849 const ParticleFieldDescriptor *descriptor = NULL;
1850
1851 PetscCall(ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor));
1852 if (!(descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_CHECKPOINT)) continue;
1853 if (descriptor->data_type == PETSC_INT || descriptor->data_type == PETSC_INT64) {
1854 PetscCall(ReadSwarmIntField(user, descriptor->canonical_name, "dat"));
1855 } else {
1856 PetscCall(ReadSwarmField(user, descriptor->canonical_name, "dat"));
1857 }
1858 }
1859
1860 simCtx->current_io_directory = NULL;
1861
1862 LOG_ALLOW(GLOBAL, LOG_INFO, "Finished reading DMSwarm fields for timestep %" PetscInt_FMT ".\n", ti);
1864 PetscFunctionReturn(0);
1865}
PetscErrorCode ReadSwarmField(UserCtx *user, const char *field_name, const char *ext)
Implementation of ReadSwarmField().
Definition io.c:1714
PetscErrorCode ReadSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
Implementation of ReadSwarmIntField().
Definition io.c:1746
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadCheckpointParticleCount()

PetscErrorCode ReadCheckpointParticleCount ( UserCtx *  user,
PetscInt  ti,
PetscInt *  particle_count 
)

Read the particle count from a validated committed checkpoint.

Parameters
[in,out]userSimulation context and active grid used for validation.
[in]tiCheckpoint step resolved below the configured source root.
[out]particle_countNumber of particles recorded by the bundle.
Returns
Zero on success or a checkpoint-validation error.

Read the particle count from a validated committed checkpoint.

Definition at line 1868 of file io.c.

1869{
1870 SimCtx *simCtx = NULL;
1871 const char *source_path = NULL;
1872 char checkpoint_directory[PETSC_MAX_PATH_LEN];
1873 PetscBool particles_saved = PETSC_FALSE;
1874
1875 PetscFunctionBeginUser;
1877 PetscCheck(user != NULL && particle_count != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1878 "Simulation context and particle-count output are required.");
1879 simCtx = user->simCtx;
1880 if (simCtx->exec_mode == EXEC_MODE_SOLVER) source_path = simCtx->restart_dir;
1881 else if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) source_path = simCtx->pps->source_dir;
1882 else SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
1883 "Invalid execution mode for reading checkpoint particle metadata.");
1884
1885 PetscCall(ResolveCheckpointStepDirectory(source_path, ti,
1886 checkpoint_directory, sizeof(checkpoint_directory)));
1887 PetscCall(ValidateCheckpointBundle(simCtx, user - user->_this,
1888 checkpoint_directory, ti, NULL, particle_count,
1889 &particles_saved, NULL, NULL));
1890 PetscCheck(particles_saved, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
1891 "Checkpoint step %" PetscInt_FMT " contains no particle state.", ti);
1893 PetscFunctionReturn(0);
1894}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DisplayBanner()

PetscErrorCode DisplayBanner ( SimCtx *  simCtx)

Displays a structured banner summarizing the simulation configuration.

This function prints effective key simulation parameters to standard output on MPI rank 0. It retrieves global domain bounds and block metadata from simCtx, and suppresses settings that do not apply to the selected mode. For example, Initial Pseudo-CFL (Courant) appears only for the Dual Time Picard–Jameson RK momentum solver; it is not a Newton–Krylov control. The report also identifies active logging, profiling, runtime-memory, and solution-convergence modes so the startup log records the effective observability contract.

Parameters
[in]simCtxPointer to the master simulation context.
Returns
PetscErrorCode Returns 0 on success.

Displays a structured banner summarizing the simulation configuration.

Reports only configuration that applies to the selected run mode. In particular, pseudo-CFL is a Dual Time Picard–Jameson RK control and is deliberately omitted for explicit and Newton–Krylov momentum solves.

Definition at line 2635 of file io.c.

2636{
2637 PetscErrorCode ierr;
2638 PetscMPIInt rank;
2639 Cmpnts global_min_coords, global_max_coords;
2640 PetscReal StartTime;
2641 PetscInt StartStep,StepsToRun,total_num_particles;
2642 PetscMPIInt num_mpi_procs;
2643 const char *log_level_name;
2644 const char *convergence_mode_name;
2645
2646 // SimCtx *simCtx = user->simCtx;
2647 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
2648 num_mpi_procs = simCtx->size;
2649 StartTime = simCtx->StartTime;
2650 StartStep = simCtx->StartStep;
2651 StepsToRun = simCtx->StepsToRun;
2652 total_num_particles = simCtx->np;
2653 BoundingBox *bboxlist_on_rank0 = simCtx->bboxlist;
2654
2655
2656 PetscFunctionBeginUser;
2658
2659 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "DisplayBanner - UserCtx pointer is NULL.");
2660 switch (get_log_level()) {
2661 case LOG_ERROR: log_level_name = "ERROR"; break;
2662 case LOG_WARNING: log_level_name = "WARNING"; break;
2663 case LOG_INFO: log_level_name = "INFO"; break;
2664 case LOG_DEBUG: log_level_name = "DEBUG"; break;
2665 case LOG_TRACE: log_level_name = "TRACE"; break;
2666 case LOG_VERBOSE: log_level_name = "VERBOSE"; break;
2667 default: log_level_name = "UNKNOWN"; break;
2668 }
2669 switch (simCtx->solutionConvergenceMode) {
2670 case SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC: convergence_mode_name = "STEADY_DETERMINISTIC"; break;
2671 case SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC: convergence_mode_name = "PERIODIC_DETERMINISTIC"; break;
2672 case SOLUTION_CONVERGENCE_STATISTICAL_STEADY: convergence_mode_name = "STATISTICAL_STEADY"; break;
2673 case SOLUTION_CONVERGENCE_TRANSIENT: convergence_mode_name = "TRANSIENT"; break;
2674 default: convergence_mode_name = "UNKNOWN"; break;
2675 }
2676 global_min_coords = user->bbox.min_coords;
2677 global_max_coords = user->bbox.max_coords;
2678 rank = simCtx->rank;
2679
2680 if (rank == 0) {
2681 // If global_domain_bbox is not pre-populated in UserCtx, compute it here from bboxlist_on_rank0
2682 // This assumes bboxlist_on_rank0 is valid and contains all local bounding boxes on rank 0.
2683 if (bboxlist_on_rank0 && num_mpi_procs > 0) {
2684 global_min_coords = bboxlist_on_rank0[0].min_coords;
2685 global_max_coords = bboxlist_on_rank0[0].max_coords;
2686 for (PetscMPIInt p = 1; p < num_mpi_procs; ++p) {
2687 global_min_coords.x = PetscMin(global_min_coords.x, bboxlist_on_rank0[p].min_coords.x);
2688 global_min_coords.y = PetscMin(global_min_coords.y, bboxlist_on_rank0[p].min_coords.y);
2689 global_min_coords.z = PetscMin(global_min_coords.z, bboxlist_on_rank0[p].min_coords.z);
2690 global_max_coords.x = PetscMax(global_max_coords.x, bboxlist_on_rank0[p].max_coords.x);
2691 global_max_coords.y = PetscMax(global_max_coords.y, bboxlist_on_rank0[p].max_coords.y);
2692 global_max_coords.z = PetscMax(global_max_coords.z, bboxlist_on_rank0[p].max_coords.z);
2693 }
2694 // Optionally store this in user->global_domain_bbox if it's useful elsewhere
2695 // user->global_domain_bbox.min_coords = global_min_coords;
2696 // user->global_domain_bbox.max_coords = global_max_coords;
2697 } else {
2698 // Fallback or warning if bboxlist is not available for global calculation
2699 LOG_ALLOW(LOCAL, LOG_WARNING, "(Rank 0) - bboxlist not provided or num_mpi_procs <=0; using user->bbox for domain bounds.\n");
2700 // global_min_coords = user->bbox.min_coords; // Use local bbox of rank 0 as fallback
2701 // global_max_coords = user->bbox.max_coords;
2702 }
2703
2704 ierr = PetscPrintf(PETSC_COMM_SELF, "\n"); CHKERRQ(ierr);
2705 ierr = PetscPrintf(PETSC_COMM_SELF, "=============================================================\n"); CHKERRQ(ierr);
2706 ierr = PetscPrintf(PETSC_COMM_SELF, " CASE SUMMARY \n"); CHKERRQ(ierr);
2707 ierr = PetscPrintf(PETSC_COMM_SELF, "=============================================================\n"); CHKERRQ(ierr);
2708 ierr = PetscPrintf(PETSC_COMM_SELF, " Grid Points : %" PetscInt_FMT " X %" PetscInt_FMT " X %" PetscInt_FMT "\n", user->IM, user->JM, user->KM); CHKERRQ(ierr);
2709 ierr = PetscPrintf(PETSC_COMM_SELF, " Cells : %" PetscInt_FMT " X %" PetscInt_FMT " X %" PetscInt_FMT "\n", user->IM - 1, user->JM - 1, user->KM - 1); CHKERRQ(ierr);
2710 ierr = PetscPrintf(PETSC_COMM_SELF, " Global Domain Bounds (X) : %.6f to %.6f\n", (double)global_min_coords.x, (double)global_max_coords.x); CHKERRQ(ierr);
2711 ierr = PetscPrintf(PETSC_COMM_SELF, " Global Domain Bounds (Y) : %.6f to %.6f\n", (double)global_min_coords.y, (double)global_max_coords.y); CHKERRQ(ierr);
2712 ierr = PetscPrintf(PETSC_COMM_SELF, " Global Domain Bounds (Z) : %.6f to %.6f\n", (double)global_min_coords.z, (double)global_max_coords.z); CHKERRQ(ierr);
2713 ierr = PetscPrintf(PETSC_COMM_SELF, " Periodic Axes (BC-derived) : I=%s, J=%s, K=%s\n",
2714 simCtx->i_periodic ? "YES" : "NO",
2715 simCtx->j_periodic ? "YES" : "NO",
2716 simCtx->k_periodic ? "YES" : "NO"); CHKERRQ(ierr);
2717 for (PetscInt axis = 0; axis < 3; axis++) {
2718 if (!user->periodic_translation_valid[axis]) continue;
2719 ierr = PetscPrintf(PETSC_COMM_SELF,
2720 " Periodic %c Translation : (%.6e, %.6e, %.6e)\n",
2721 "IJK"[axis],
2722 (double)user->periodic_translation[axis].x,
2723 (double)user->periodic_translation[axis].y,
2724 (double)user->periodic_translation[axis].z); CHKERRQ(ierr);
2725 }
2726 if(strcmp(simCtx->eulerianSource,"load")==0 || strcmp(simCtx->eulerianSource,"solve")==0){
2727 ierr = PetscPrintf(PETSC_COMM_SELF, "-------------------- Boundary Conditions --------------------\n"); CHKERRQ(ierr);
2728 const int face_name_width = 17; // Adjusted for longer names (Zeta,Eta,Xi)
2729 for (PetscInt i_face = 0; i_face < 6; ++i_face) {
2730 BCFace current_face = (BCFace)i_face;
2731 // The BCFaceToString will now return the Xi, Eta, Zeta versions
2732 const char* face_str = BCFaceToString(current_face);
2733 const char* bc_type_str = BCTypeToString(user->boundary_faces[current_face].mathematical_type);
2734 const char* bc_handler_type_str = BCHandlerTypeToString(user->boundary_faces[current_face].handler_type);
2735 if(user->boundary_faces[current_face].mathematical_type == INLET){
2737 PetscReal source_id = -1.0;
2738 const char *source_file = NULL;
2739 PetscBool found, found_file;
2740 ierr = GetBCParamReal(user->boundary_faces[current_face].params,"source_id",&source_id,&found); CHKERRQ(ierr);
2741 ierr = GetBCParamString(user->boundary_faces[current_face].params,"source_file",&source_file,&found_file); CHKERRQ(ierr);
2742 if (found_file && source_file) {
2743 ierr = PetscPrintf(PETSC_COMM_SELF, " Face %-*s : %s - %s - source_file=%s\n",
2744 face_name_width, face_str, bc_type_str, bc_handler_type_str, source_file); CHKERRQ(ierr);
2745 } else {
2746 ierr = PetscPrintf(PETSC_COMM_SELF, " Face %-*s : %s - %s - source -face_source_%d\n",
2747 face_name_width, face_str, bc_type_str, bc_handler_type_str, (int)source_id); CHKERRQ(ierr);
2748 }
2749 }
2751 PetscBool trimflag,foundtrimflag;
2752 ierr = GetDrivenSeamFluxFlag(user->boundary_faces[current_face].params,&trimflag,&foundtrimflag); CHKERRQ(ierr);
2753 ierr = PetscPrintf(PETSC_COMM_SELF, " Face %-*s : %s - %s - [from initial state] - %s\n",
2754 face_name_width, face_str, bc_type_str, bc_handler_type_str,trimflag?"Enforce seam flux":"Seam flux not enforced"); CHKERRQ(ierr);
2756 PetscReal flux;
2757 PetscBool trimflag,foundflux,foundtrimflag;
2758 ierr = GetBCParamReal(user->boundary_faces[current_face].params,"target_flux",&flux,&foundflux); CHKERRQ(ierr);
2759 ierr = GetDrivenSeamFluxFlag(user->boundary_faces[current_face].params,&trimflag,&foundtrimflag); CHKERRQ(ierr);
2760 ierr = PetscPrintf(PETSC_COMM_SELF, " Face %-*s : %s - %s - [%.4f] - %s\n",
2761 face_name_width, face_str, bc_type_str, bc_handler_type_str,flux,trimflag?"Enforce seam flux":"Seam flux not enforced"); CHKERRQ(ierr);
2762 } else{
2763 ierr = PetscPrintf(PETSC_COMM_SELF, " Face %-*s : %s - %s\n",
2764 face_name_width, face_str, bc_type_str,bc_handler_type_str); CHKERRQ(ierr);
2765 }
2766 }
2767 }
2768 ierr = PetscPrintf(PETSC_COMM_SELF, "-------------------------------------------------------------\n"); CHKERRQ(ierr);
2769 ierr = PetscPrintf(PETSC_COMM_SELF, " Run Mode : %s\n", simCtx->OnlySetup ? "SETUP ONLY" : "Full Simulation"); CHKERRQ(ierr);
2770 ierr = PetscPrintf(PETSC_COMM_SELF, " Start Time : %.4f\n", (double)StartTime); CHKERRQ(ierr);
2771 ierr = PetscPrintf(PETSC_COMM_SELF, " Timestep Size : %.4f\n", (double)simCtx->dt); CHKERRQ(ierr);
2772 ierr = PetscPrintf(PETSC_COMM_SELF, " Starting Step : %" PetscInt_FMT "\n", StartStep); CHKERRQ(ierr);
2773 ierr = PetscPrintf(PETSC_COMM_SELF, " Total Steps to Run : %" PetscInt_FMT "\n", StepsToRun); CHKERRQ(ierr);
2774 ierr = PetscPrintf(PETSC_COMM_SELF, " Ending Step : %" PetscInt_FMT "\n", StartStep + StepsToRun); CHKERRQ(ierr);
2775 if (simCtx->tiout > 0) {
2776 ierr = PetscPrintf(PETSC_COMM_SELF, " Field/Restart Cadence : every %" PetscInt_FMT " step(s)\n", simCtx->tiout); CHKERRQ(ierr);
2777 } else {
2778 ierr = PetscPrintf(PETSC_COMM_SELF, " Field/Restart Cadence : DISABLED\n"); CHKERRQ(ierr);
2779 }
2780 /* Recorded whether or not statistics are configured, so a log says plainly
2781 * whether monitoring was active rather than leaving its absence ambiguous. */
2782 if (FieldStatisticsIsActive(simCtx) && simCtx->statisticsConsoleOutputFreq > 0) {
2783 ierr = PetscPrintf(PETSC_COMM_SELF, " Statistics Console Cadence : every %" PetscInt_FMT " step(s), %" PetscInt_FMT " window(s)\n",
2784 simCtx->statisticsConsoleOutputFreq, simCtx->fieldStatisticsWindowCount); CHKERRQ(ierr);
2785 } else if (FieldStatisticsIsActive(simCtx)) {
2786 ierr = PetscPrintf(PETSC_COMM_SELF, " Statistics Console Cadence : DISABLED (%" PetscInt_FMT " window(s) accumulating)\n",
2787 simCtx->fieldStatisticsWindowCount); CHKERRQ(ierr);
2788 } else {
2789 ierr = PetscPrintf(PETSC_COMM_SELF, " Statistics Console Cadence : DISABLED (no window configured)\n"); CHKERRQ(ierr);
2790 }
2791 ierr = PetscPrintf(PETSC_COMM_SELF, " Immersed Boundary : %s\n", simCtx->immersed ? "ENABLED" : "DISABLED"); CHKERRQ(ierr);
2792 if (simCtx->walltimeGuardEnabled) {
2793 ierr = PetscPrintf(
2794 PETSC_COMM_SELF,
2795 " Runtime Walltime Guard : %s (warmup=%" PetscInt_FMT ", multiplier=%.2f, min=%.1f s, alpha=%.2f)\n",
2796 simCtx->walltimeGuardActive ? "ENABLED" : "CONFIGURED BUT INACTIVE",
2797 simCtx->walltimeGuardWarmupSteps,
2798 (double)simCtx->walltimeGuardMultiplier,
2799 (double)simCtx->walltimeGuardMinSeconds,
2800 (double)simCtx->walltimeGuardEstimatorAlpha
2801 ); CHKERRQ(ierr);
2802 } else {
2803 ierr = PetscPrintf(PETSC_COMM_SELF, " Runtime Walltime Guard : DISABLED\n"); CHKERRQ(ierr);
2804 }
2805 ierr = PetscPrintf(PETSC_COMM_SELF, " Console Log Level : %s\n", log_level_name); CHKERRQ(ierr);
2806 ierr = PetscPrintf(PETSC_COMM_SELF, " Profiling Timestep Output : %s\n", simCtx->profilingTimestepMode); CHKERRQ(ierr);
2807 ierr = PetscPrintf(PETSC_COMM_SELF, " Profiling Final Summary : %s\n", simCtx->profilingFinalSummary ? "ENABLED" : "DISABLED"); CHKERRQ(ierr);
2808 if (simCtx->runtimeMemoryLogEnabled) {
2809 ierr = PetscPrintf(PETSC_COMM_SELF, " Runtime Memory Log : ENABLED (Runtime_Memory.csv)\n"); CHKERRQ(ierr);
2810 } else {
2811 ierr = PetscPrintf(PETSC_COMM_SELF, " Runtime Memory Log : DISABLED\n"); CHKERRQ(ierr);
2812 }
2813 ierr = PetscPrintf(PETSC_COMM_SELF, " Solution Convergence Log : %s\n",
2814 simCtx->solutionConvergenceEnabled ? "ENABLED" : "DISABLED"); CHKERRQ(ierr);
2815 ierr = PetscPrintf(PETSC_COMM_SELF, " Number of MPI Processes : %d\n", num_mpi_procs); CHKERRQ(ierr);
2816 ierr = PetscPrintf(PETSC_COMM_WORLD," Number of Particles : %" PetscInt_FMT "\n", total_num_particles); CHKERRQ(ierr);
2817 if (ParticlesEnabled(simCtx)) {
2818 const char *particle_init_str = ParticleInitializationToString(simCtx->ParticleInitialization);
2819
2820 if (simCtx->particleConsoleOutputFreq > 0) {
2821 ierr = PetscPrintf(PETSC_COMM_SELF, " Particle Console Cadence : every %" PetscInt_FMT " step(s)\n", simCtx->particleConsoleOutputFreq); CHKERRQ(ierr);
2822 } else {
2823 ierr = PetscPrintf(PETSC_COMM_SELF, " Particle Console Cadence : DISABLED\n"); CHKERRQ(ierr);
2824 }
2825 ierr = PetscPrintf(PETSC_COMM_SELF, " Particle Log Row Sampling : every %" PetscInt_FMT " particle(s)\n", simCtx->LoggingFrequency); CHKERRQ(ierr);
2826 if (simCtx->nTracePIDs > 0) {
2827 ierr = PetscPrintf(PETSC_COMM_SELF, " Traced Particles :"); CHKERRQ(ierr);
2828 for (PetscInt t = 0; t < simCtx->nTracePIDs; ++t) {
2829 ierr = PetscPrintf(PETSC_COMM_SELF, " %lld", (long long)simCtx->tracePIDs[t]); CHKERRQ(ierr);
2830 }
2831 ierr = PetscPrintf(PETSC_COMM_SELF, "\n"); CHKERRQ(ierr);
2832 }
2833 if (simCtx->StartStep > 0) {
2834 ierr = PetscPrintf(PETSC_COMM_SELF, " Particle Restart Mode : %s\n", simCtx->particleRestartMode); CHKERRQ(ierr);
2835 }
2836 ierr = PetscPrintf(PETSC_COMM_SELF, " Particle Initialization Mode: %s\n", particle_init_str); CHKERRQ(ierr);
2837 ierr = PetscPrintf(PETSC_COMM_SELF, " Particle Boundary Policy :"); CHKERRQ(ierr);
2838 for (PetscInt i_face = 0; i_face < 6; ++i_face) {
2839 ierr = PetscPrintf(PETSC_COMM_SELF, " %s=%s", BCFaceToString((BCFace)i_face),
2840 ParticleBoundaryPolicyToString(user->boundary_faces[i_face].particle_policy)); CHKERRQ(ierr);
2841 }
2842 ierr = PetscPrintf(PETSC_COMM_SELF, "\n"); CHKERRQ(ierr);
2843 ierr = PetscPrintf(PETSC_COMM_SELF, " Interpolation Method : %s\n",
2844 InterpolationMethodToString(simCtx->interpolationMethod)); CHKERRQ(ierr);
2846 if (user->inletFaceDefined) {
2847 ierr = PetscPrintf(PETSC_COMM_SELF, " Particles Initialized At : %s (Enum Val: %d)\n", BCFaceToString(user->identifiedInletBCFace), user->identifiedInletBCFace); CHKERRQ(ierr);
2848 } else {
2849 ierr = PetscPrintf(PETSC_COMM_SELF, " Particles Initialized At : --- (No INLET face identified)\n"); CHKERRQ(ierr);
2850 }
2851 }
2852 }
2853 if(strcmp(simCtx->eulerianSource,"solve")==0 || strcmp(simCtx->eulerianSource,"load")==0){
2854 ierr = PetscPrintf(PETSC_COMM_WORLD," Reynolds Number : %le\n", simCtx->ren); CHKERRQ(ierr);
2855 //ierr = PetscPrintf(PETSC_COMM_WORLD," Von-Neumann Number : %le\n", simCtx->vnn); CHKERRQ(ierr);
2856 if(strcmp(simCtx->eulerianSource,"solve")==0){
2857 //ierr = PetscPrintf(PETSC_COMM_WORLD," Stanton Number : %le\n", simCtx->st); CHKERRQ(ierr);
2858 ierr = PetscPrintf(PETSC_COMM_WORLD," Momentum Equation Solver : %s\n", MomentumSolverTypeToString(simCtx->mom_solver_type)); CHKERRQ(ierr);
2860 ierr = PetscPrintf(PETSC_COMM_WORLD," Initial Pseudo-CFL (Courant): %le\n", simCtx->pseudo_cfl); CHKERRQ(ierr);
2861 ierr = PetscPrintf(PETSC_COMM_WORLD," Pseudo-CFL Range : [%le, %le]\n", simCtx->min_pseudo_cfl, simCtx->max_pseudo_cfl); CHKERRQ(ierr);
2862 ierr = PetscPrintf(PETSC_COMM_WORLD," Pseudo-CFL Adaptation : growth=%le, reduction=%le, backtrack=%s\n",
2864 simCtx->no_pseudo_cfl_backtrack ? "DISABLED" : "ENABLED"); CHKERRQ(ierr);
2865 ierr = PetscPrintf(PETSC_COMM_WORLD," Pseudo-Time Iteration Limit : %" PetscInt_FMT "\n", simCtx->mom_max_pseudo_steps); CHKERRQ(ierr);
2866 } else if (simCtx->mom_solver_type == MOMENTUM_SOLVER_NEWTON_KRYLOV) {
2867 ierr = PetscPrintf(PETSC_COMM_WORLD," Newton-Krylov PETSc Controls: SNES/KSP options (mom_nk_*)\n"); CHKERRQ(ierr);
2868 ierr = PetscPrintf(PETSC_COMM_WORLD," Newton-Krylov History Log : %s\n", simCtx->mom_nk_monitor_history ? "ENABLED" : "DISABLED"); CHKERRQ(ierr);
2869 } else if (simCtx->mom_solver_type == MOMENTUM_SOLVER_EXPLICIT_RK) {
2870 ierr = PetscPrintf(PETSC_COMM_WORLD," Pseudo-Time Controller : NOT APPLICABLE\n"); CHKERRQ(ierr);
2871 }
2872 ierr = PetscPrintf(PETSC_COMM_WORLD," Solution Convergence Mode : %s\n", convergence_mode_name); CHKERRQ(ierr);
2874 ierr = PetscPrintf(PETSC_COMM_WORLD," Convergence Period : %" PetscInt_FMT " step(s)\n", simCtx->solutionConvergencePeriodSteps); CHKERRQ(ierr);
2876 ierr = PetscPrintf(PETSC_COMM_WORLD," Convergence Window : %" PetscInt_FMT " step(s)\n", simCtx->solutionConvergenceWindowSteps); CHKERRQ(ierr);
2877 }
2878 ierr = PetscPrintf(PETSC_COMM_WORLD," Large Eddy Simulation Model : %s\n", LESModelToString(simCtx->les)); CHKERRQ(ierr);
2879 if (simCtx->les != NO_LES_MODEL) {
2880 const LESConfig *les = &simCtx->les_config;
2881
2882 /* Reported with the user-facing spellings, so a line here can be
2883 matched against the case file that produced it. */
2884 if (simCtx->les == VREMAN) {
2885 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Filter Width : per direction (cell edges; filter_width unused)\n"); CHKERRQ(ierr);
2886 } else {
2887 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Filter Width : %s\n",
2888 LESFilterWidthModelToString(les->filter_width_model)); CHKERRQ(ierr);
2889 }
2890 if (simCtx->les == VREMAN) {
2891 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Vreman Coefficient : %.4f (no coefficient field)\n",
2892 (double)les->vreman_coefficient); CHKERRQ(ierr);
2893 } else if (simCtx->les == WALE) {
2894 ierr = PetscPrintf(PETSC_COMM_WORLD," LES WALE Coefficient : %.4f (no coefficient field)\n",
2895 (double)les->wale_coefficient); CHKERRQ(ierr);
2896 } else if (simCtx->les == CONSTANT_SMAGORINSKY) {
2897 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Smagorinsky Constant : %.4f (no coefficient field)\n",
2898 (double)les->constant_cs); CHKERRQ(ierr);
2899 } else {
2900 char directions[8] = "";
2901 PetscInt used = 0;
2902
2903 if (les->averaging_direction[0]) directions[used++] = 'i';
2904 if (les->averaging_direction[1]) directions[used++] = 'j';
2905 if (les->averaging_direction[2]) directions[used++] = 'k';
2906 directions[used] = '\0';
2907
2908 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Test Filter : %s (width ratio %.3f)\n",
2910 (double)les->test_filter_width_ratio); CHKERRQ(ierr);
2911 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Dynamic Update Cadence : every %d step(s)\n",
2912 (int)les->dynamic_frequency); CHKERRQ(ierr);
2913 /* An empty direction list under homogeneous averaging is not a
2914 missing answer: the directions are derived from periodicity at
2915 the first update, once the block is known. */
2916 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Coefficient Averaging : %s%s%s\n",
2918 used > 0 ? " over " : "",
2919 used > 0 ? directions : ""); CHKERRQ(ierr);
2920 if (les->clip_mode == LES_CLIP_CLAMP) {
2921 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Coefficient Limiting : clamp (max Cs %.3f)\n",
2922 (double)les->max_cs); CHKERRQ(ierr);
2923 } else {
2924 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Coefficient Limiting : %s\n",
2925 LESClipModeToString(les->clip_mode)); CHKERRQ(ierr);
2926 }
2927 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Total Viscosity Floor : %.3f x molecular\n",
2928 (double)les->min_viscosity_ratio); CHKERRQ(ierr);
2929 }
2930 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Gradient (Clark) Term : %s\n",
2931 simCtx->les_gradient_model ? "ENABLED" : "DISABLED"); CHKERRQ(ierr);
2932 if (les->diagnostics_enabled) {
2933 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Coefficient Diagnostics : ENABLED (les_coefficient.csv, every %d step(s))\n",
2934 (int)les->diagnostics_cadence); CHKERRQ(ierr);
2935 /* The Yoshizawa coefficient scales only the reported subgrid kinetic
2936 energy, so it belongs with the diagnostics line rather than above it. */
2937 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Yoshizawa Coefficient : %.4f (subgrid energy estimate)\n",
2938 (double)les->yoshizawa_ci); CHKERRQ(ierr);
2939 } else {
2940 ierr = PetscPrintf(PETSC_COMM_WORLD," LES Coefficient Diagnostics : DISABLED\n"); CHKERRQ(ierr);
2941 }
2942 }
2943 /* Reported independently of the LES closure, because a wall function is
2944 configured independently of it. */
2945 if (simCtx->wallfunction) {
2946 /* Only the log law has a roughness term. Printing the height beside a
2947 model that discards it would report a control that is not in force. */
2949 ierr = PetscPrintf(PETSC_COMM_WORLD," Wall Function Model : %s (roughness height %.3e)\n",
2951 (double)simCtx->wall_roughness_height); CHKERRQ(ierr);
2952 } else {
2953 ierr = PetscPrintf(PETSC_COMM_WORLD," Wall Function Model : %s (smooth wall; no roughness term)\n",
2955 }
2956 } else {
2957 ierr = PetscPrintf(PETSC_COMM_WORLD," Wall Function Model : DISABLED\n"); CHKERRQ(ierr);
2958 }
2959 }
2960 if (strcmp(simCtx->eulerianSource, "load") == 0) {
2961 ierr = PetscPrintf(PETSC_COMM_SELF, " Eulerian State Source : load (%s)\n",
2962 simCtx->restart_dir); CHKERRQ(ierr);
2963 } else if (simCtx->StartStep > 0) {
2964 ierr = PetscPrintf(PETSC_COMM_SELF, " Eulerian State Source : restart step %" PetscInt_FMT " (%s)\n",
2965 simCtx->StartStep, simCtx->restart_dir); CHKERRQ(ierr);
2966 } else {
2967 ierr = PetscPrintf(PETSC_COMM_SELF, " Eulerian State Source : initial condition (Source)\n"); CHKERRQ(ierr);
2968 if (simCtx->initialConditionStaged) {
2969 ierr = PetscPrintf(PETSC_COMM_SELF,
2970 " Initial Velocity File : field=%s directory=%s\n",
2971 simCtx->initialConditionField == IC_FIELD_UCAT ? "Ucat" : "Ucont",
2972 simCtx->initialConditionDirectory); CHKERRQ(ierr);
2973 }
2974 }
2975 } else if(strcmp(simCtx->eulerianSource,"analytical")==0){
2976 ierr = PetscPrintf(PETSC_COMM_WORLD," Eulerian State Source : analytical (Source)\n"); CHKERRQ(ierr);
2977 }
2978 ierr = PetscPrintf(PETSC_COMM_SELF, "=============================================================\n"); CHKERRQ(ierr);
2979 ierr = PetscPrintf(PETSC_COMM_SELF, "\n"); CHKERRQ(ierr);
2980 }
2982 PetscFunctionReturn(0);
2983}
PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
Implementation of GetBCParamReal().
Definition io.c:819
PetscErrorCode GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found)
Implementation of GetDrivenSeamFluxFlag().
Definition io.c:888
PetscErrorCode GetBCParamString(BC_Param *params, const char *key, const char **value_out, PetscBool *found)
Implementation of GetBCParamString().
Definition io.c:859
const char * LESTestFilterKernelToString(LESTestFilterKernel kernel)
Returns the user-facing name of an LES test-filter kernel.
Definition logging.c:727
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Converts a BCHandlerType enum to its string representation.
Definition logging.c:888
const char * ParticleBoundaryPolicyToString(ParticleBoundaryPolicy policy)
Returns the configuration token for a particle boundary policy.
Definition logging.c:850
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
const char * WallFunctionModelToString(WallFunctionModel model)
Returns the user-facing name of a wall-function model.
Definition logging.c:786
const char * LESFilterWidthModelToString(LESFilterWidthModel model)
Returns the user-facing name of an LES grid-filter-width model.
Definition logging.c:704
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
const char * LESAveragingModeToString(LESAveragingMode mode)
Returns the user-facing name of an LES coefficient-averaging mode.
Definition logging.c:746
const char * InterpolationMethodToString(InterpolationMethod method)
Returns the display name of a grid-to-particle interpolation method.
Definition logging.c:869
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
const char * LESModelToString(LESModelType LESFlag)
Returns the canonical log token for an LES model selector.
Definition logging.c:682
const char * LESClipModeToString(LESClipMode mode)
Returns the user-facing name of an LES coefficient-limiting mode.
Definition logging.c:766
const char * MomentumSolverTypeToString(MomentumSolverType SolverFlag)
Returns the canonical log token for a momentum-solver selector.
Definition logging.c:808
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:662
@ VREMAN
Definition variables.h:587
@ NO_LES_MODEL
Definition variables.h:584
@ WALE
Definition variables.h:588
@ CONSTANT_SMAGORINSKY
Definition variables.h:585
PetscBool mom_nk_monitor_history
Definition variables.h:975
@ INLET
Definition variables.h:323
PetscReal yoshizawa_ci
Yoshizawa constant for the reported SGS kinetic energy.
Definition variables.h:677
PetscBool inletFaceDefined
Definition variables.h:1183
PetscBool profilingFinalSummary
Definition variables.h:1107
PetscInt dynamic_frequency
Recompute the dynamic coefficient every N steps.
Definition variables.h:665
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
LESFilterWidthModel filter_width_model
How the grid filter width Delta is derived per cell.
Definition variables.h:669
PetscInt statisticsConsoleOutputFreq
Definition variables.h:991
BCFace identifiedInletBCFace
Definition variables.h:1184
PetscBool walltimeGuardActive
Definition variables.h:1110
LESTestFilterKernel test_filter_kernel
Discrete test-filter stencil.
Definition variables.h:670
LESConfig les_config
Parameters of the LES closure selected by les.
Definition variables.h:1046
PetscReal pseudo_cfl_reduction_factor
Definition variables.h:966
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
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
PetscReal min_pseudo_cfl
Definition variables.h:967
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
PetscReal ren
Definition variables.h:965
BCHandlerType handler_type
Definition variables.h:427
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
PetscBool solutionConvergenceEnabled
Definition variables.h:980
@ LES_CLIP_CLAMP
Definition variables.h:653
PetscInt StepsToRun
Definition variables.h:927
char profilingTimestepMode[32]
Definition variables.h:1106
WallFunctionModel
Selects the wall model applied on WALL faces.
Definition variables.h:600
@ WALL_FUNCTION_LOG_LAW
Definition variables.h:602
PetscInt np
Definition variables.h:1049
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 no_pseudo_cfl_backtrack
Definition variables.h:969
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
PetscBool OnlySetup
Definition variables.h:934
@ 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
PetscScalar x
Definition variables.h:145
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
InterpolationMethod interpolationMethod
Definition variables.h:1055
PetscReal max_pseudo_cfl
Definition variables.h:967
BoundingBox * bboxlist
Definition variables.h:1053
PetscInt les_gradient_model
Add the Clark gradient (tensor-diffusivity) term to the viscous flux.
Definition variables.h:1045
ParticleBoundaryPolicy particle_policy
What a particle crossing this face becomes (BC param particle_policy).
Definition variables.h:428
BC_Param * params
Definition variables.h:429
char eulerianSource[PETSC_MAX_PATH_LEN]
Definition variables.h:938
PetscBool walltimeGuardEnabled
Definition variables.h:1109
PetscReal wall_roughness_height
Definition variables.h:1004
ParticleInitializationType ParticleInitialization
Definition variables.h:1054
PetscScalar z
Definition variables.h:145
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
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
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
PetscInt solutionConvergenceWindowSteps
Definition variables.h:983
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
PetscReal pseudo_cfl_growth_factor
Definition variables.h:966
LESAveragingMode averaging_mode
Averaging set for the Germano contractions.
Definition variables.h:672
PetscInt64 * tracePIDs
Sorted, distinct IDs of the particles whose every stage is reported (-picurv_trace_particles); NULL w...
Definition variables.h:1088
PetscInt particleConsoleOutputFreq
Definition variables.h:931
PetscBool initialConditionStaged
Definition variables.h:977
PetscInt i_periodic
Definition variables.h:1010
PetscReal vreman_coefficient
Model constant c for VREMAN (Vreman 2004: 2.5 Cs^2).
Definition variables.h:667
PetscInt mom_max_pseudo_steps
Definition variables.h:959
PetscScalar y
Definition variables.h:145
@ IC_FIELD_UCAT
Definition variables.h:202
PetscMPIInt size
Definition variables.h:920
Cmpnts periodic_translation[3]
Definition variables.h:1178
@ 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
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
BCType mathematical_type
Definition variables.h:426
SolutionConvergenceMode solutionConvergenceMode
Definition variables.h:981
InitialConditionField initialConditionField
Definition variables.h:978
BoundingBox bbox
Definition variables.h:1173
MomentumSolverType mom_solver_type
Definition variables.h:958
PetscInt immersed
Definition variables.h:950
PetscReal pseudo_cfl
Definition variables.h:965
PetscInt LoggingFrequency
Definition variables.h:1087
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Every user-selectable parameter of the LES closure.
Definition variables.h:664
Here is the call graph for this function:
Here is the caller graph for this function:

◆ StringToBCFace()

PetscErrorCode StringToBCFace ( const char *  str,
BCFace *  face_out 
)

Converts a face-token string (e.g., "-Xi", "+Eta") to the internal BCFace enum.

Parameters
[in]strInput token from configuration.
[out]face_outParsed enum value on success.
Returns
PetscErrorCode 0 on success, non-zero for invalid tokens or null pointers.

Converts a face-token string (e.g., "-Xi", "+Eta") to the internal BCFace enum.

See also
StringToBCFace()

Definition at line 736 of file io.c.

736 {
738 if (strcasecmp(str, "-Xi") == 0) *face_out = BC_FACE_NEG_X;
739 else if (strcasecmp(str, "+Xi") == 0) *face_out = BC_FACE_POS_X;
740 else if (strcasecmp(str, "-Eta") == 0) *face_out = BC_FACE_NEG_Y;
741 else if (strcasecmp(str, "+Eta") == 0) *face_out = BC_FACE_POS_Y;
742 else if (strcasecmp(str, "-Zeta") == 0) *face_out = BC_FACE_NEG_Z;
743 else if (strcasecmp(str, "+Zeta") == 0) *face_out = BC_FACE_POS_Z;
744 else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown face specifier: %s", str);
746 return 0;
747}
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
Here is the caller graph for this function:

◆ StringToBCType()

PetscErrorCode StringToBCType ( const char *  str,
BCType *  type_out 
)

Converts a mathematical BC type string (e.g., "PERIODIC", "WALL") to BCType.

Parameters
[in]strInput token from configuration.
[out]type_outParsed enum value on success.
Returns
PetscErrorCode 0 on success, non-zero for invalid tokens or null pointers.

Converts a mathematical BC type string (e.g., "PERIODIC", "WALL") to BCType.

See also
StringToBCType()

Definition at line 753 of file io.c.

753 {
755 if (strcasecmp(str, "WALL") == 0) *type_out = WALL;
756 else if (strcasecmp(str, "SYMMETRY") == 0)
757 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE,
758 "The SYMMETRY boundary type is retired: a symmetry plane is a free-slip wall, "
759 "so use type WALL with handler free_slip.");
760 else if (strcasecmp(str, "INLET") == 0) *type_out = INLET;
761 else if (strcasecmp(str, "OUTLET") == 0) *type_out = OUTLET;
762 else if (strcasecmp(str, "PERIODIC") == 0) *type_out = PERIODIC;
763 // ... add other BCTypes here ...
764 else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown BC Type string: %s", str);
766 return 0;
767}
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
Here is the caller graph for this function:

◆ StringToBCHandlerType()

PetscErrorCode StringToBCHandlerType ( const char *  str,
BCHandlerType *  handler_out 
)

Converts a BC handler token (implementation strategy) to BCHandlerType.

Parameters
[in]strInput handler token from configuration.
[out]handler_outParsed enum value on success.
Returns
PetscErrorCode 0 on success, non-zero for invalid tokens or null pointers.

Converts a BC handler token (implementation strategy) to BCHandlerType.

See also
StringToBCHandlerType()

Definition at line 773 of file io.c.

773 {
775 if (strcasecmp(str, "noslip") == 0) *handler_out = BC_HANDLER_WALL_NOSLIP;
776 else if (strcasecmp(str, "free_slip") == 0) *handler_out = BC_HANDLER_WALL_FREE_SLIP;
777 else if (strcasecmp(str, "moving") == 0) *handler_out = BC_HANDLER_WALL_MOVING;
778 else if (strcasecmp(str, "conservation") == 0) *handler_out = BC_HANDLER_OUTLET_CONSERVATION;
779 else if (strcasecmp(str, "prescribed_velocity") == 0) *handler_out = BC_HANDLER_INLET_PRESCRIBED_VELOCITY;
780 else if (strcasecmp(str,"geometric") == 0) *handler_out = BC_HANDLER_PERIODIC_GEOMETRIC;
781 else if (strcasecmp(str,"constant_flux") == 0) *handler_out = BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX;
782 else if (strcasecmp(str,"initial_flux") == 0) *handler_out = BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX;
783 // ... add other BCHandlerTypes here ...
784 else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown BC Handler string: %s", str);
786 return 0;
787}
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
@ BC_HANDLER_WALL_NOSLIP
Definition variables.h:345
@ BC_HANDLER_OUTLET_CONSERVATION
Definition variables.h:350
@ BC_HANDLER_WALL_FREE_SLIP
Definition variables.h:347
Here is the caller graph for this function:

◆ ValidateBCHandlerForBCType()

PetscErrorCode ValidateBCHandlerForBCType ( BCType  type,
BCHandlerType  handler 
)

Validates that a selected handler is compatible with a mathematical BC type.

Parameters
[in]typeMathematical BC type (e.g., WALL, PERIODIC).
[in]handlerSelected handler implementation enum.
Returns
PetscErrorCode 0 if compatible, non-zero if the combination is invalid.

Validates that a selected handler is compatible with a mathematical BC type.

See also
ValidateBCHandlerForBCType()

Definition at line 793 of file io.c.

793 {
795 switch (type) {
796 case OUTLET:
797 if(handler != BC_HANDLER_OUTLET_CONSERVATION) { PROFILE_FUNCTION_END; return PETSC_ERR_ARG_WRONG; }
798 break;
799 case WALL:
800 if (handler != BC_HANDLER_WALL_NOSLIP && handler != BC_HANDLER_WALL_FREE_SLIP &&
801 handler != BC_HANDLER_WALL_MOVING) { PROFILE_FUNCTION_END; return PETSC_ERR_ARG_WRONG; }
802 break;
803 case INLET:
804 if (handler != BC_HANDLER_INLET_PRESCRIBED_VELOCITY) { PROFILE_FUNCTION_END; return PETSC_ERR_ARG_WRONG; }
805 break;
806 case PERIODIC:
808 // ... add other validation cases here ...
809 default: break;
810 }
812 return 0; // Combination is valid
813}
Here is the caller graph for this function:

◆ FreeBC_ParamList()

void FreeBC_ParamList ( BC_Param *  head)

Frees an entire linked list of boundary-condition parameters.

Parameters
[in,out]headHead pointer of the BC_Param list to destroy.

Frees an entire linked list of boundary-condition parameters.

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

See also
FreeBC_ParamList()

Definition at line 719 of file io.c.

719 {
721 BC_Param *current = head;
722 while (current != NULL) {
723 BC_Param *next = current->next;
724 PetscFree(current->key);
725 PetscFree(current->value);
726 PetscFree(current);
727 current = next;
728 }
730}
struct BC_Param_s * next
Definition variables.h:375
char * key
Definition variables.h:373
char * value
Definition variables.h:374
A node in a linked list for storing key-value parameters from the bcs.dat file.
Definition variables.h:372
Here is the caller graph for this function:

◆ GetBCParamReal()

PetscErrorCode GetBCParamReal ( BC_Param *  params,
const char *  key,
PetscReal *  value_out,
PetscBool *  found 
)

Searches a BC_Param linked list for a key and returns its value as a double.

Parameters
paramsThe head of the BC_Param linked list.
keyThe key to search for (case-insensitive).
[out]value_outThe found value, converted to a PetscReal.
[out]foundSet to PETSC_TRUE if the key was found, PETSC_FALSE otherwise.
Returns
0 on success.

Searches a BC_Param linked list for a key and returns its value as a double.

See also
GetBCParamReal()

Definition at line 819 of file io.c.

820{
821 const char *text = NULL;
822
823 PetscFunctionBeginUser;
825 *value_out = 0.0;
826 PetscCall(GetBCParamString(params, key, &text, found));
827 if (*found) *value_out = atof(text);
829 PetscFunctionReturn(0); // It's not an error to not find the key.
830}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetBCParamBool()

PetscErrorCode GetBCParamBool ( BC_Param *  params,
const char *  key,
PetscBool *  value_out,
PetscBool *  found 
)

Searches a BC_Param linked list for a key and returns its value as a bool.

Parameters
paramsThe head of the BC_Param linked list.
keyThe key to search for (case-insensitive).
[out]value_outThe found value, converted to a PetscBool.
[out]foundSet to PETSC_TRUE if the key was found, PETSC_FALSE otherwise.
Returns
0 on success.

Searches a BC_Param linked list for a key and returns its value as a bool.

See also
GetBCParamBool()

Definition at line 836 of file io.c.

837{
838 const char *text = NULL;
839
840 PetscFunctionBeginUser;
842 *value_out = PETSC_FALSE;
843 PetscCall(GetBCParamString(params, key, &text, found));
844 // FALSE unless the value is one of the "true" strings, including for a key with no value.
845 if (*found && text &&
846 (strcasecmp(text, "true") == 0 || strcmp(text, "1") == 0 || strcasecmp(text, "yes") == 0)) {
847 *value_out = PETSC_TRUE;
848 }
850 PetscFunctionReturn(0); // It's not an error to not find the key.
851}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetBCParamString()

PetscErrorCode GetBCParamString ( BC_Param *  params,
const char *  key,
const char **  value_out,
PetscBool *  found 
)

Searches a BC_Param linked list for a key and returns its value as a string.

Parameters
paramsThe head of the BC_Param linked list.
keyThe key to search for (case-insensitive).
[out]value_outBorrowed pointer to the matching value string, or NULL if absent.
[out]foundSet to PETSC_TRUE if the key was found, PETSC_FALSE otherwise.
Returns
0 on success.

Searches a BC_Param linked list for a key and returns its value as a string.

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

See also
GetBCParamString()

Definition at line 859 of file io.c.

860{
861 PetscFunctionBeginUser;
863 *found = PETSC_FALSE;
864 *value_out = NULL;
865 if (!key) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); } // No key to search for
866 for (BC_Param *param = params; param; param = param->next) {
867 if (strcasecmp(param->key, key) == 0) {
868 *value_out = param->value;
869 *found = PETSC_TRUE;
870 break;
871 }
872 }
874 PetscFunctionReturn(0);
875}
Here is the caller graph for this function:

◆ GetDrivenSeamFluxFlag()

PetscErrorCode GetDrivenSeamFluxFlag ( BC_Param *  params,
PetscBool *  value_out,
PetscBool *  found 
)

Read the driven-flow seam-flux flag, accepting its deprecated apply_trim spelling.

Parameters
[in]paramsParameter list for the face.
[out]value_outResolved flag value.
[out]foundWhether either spelling was present.
Returns
PetscErrorCode 0 on success.

Read the driven-flow seam-flux flag, accepting its deprecated apply_trim spelling.

The option was originally spelled apply_trim, which said that something was trimmed but not what or why. The canonical name is now enforce_seam_flux. Generated bcs.run files carry the canonical name, but a hand-written or archived one may still use the old spelling, so both are accepted here and the canonical name wins. The argument contract lives with the header declaration in include/io.h.

See also
GetDrivenSeamFluxFlag()

Definition at line 888 of file io.c.

889{
890 PetscErrorCode ierr;
891 PetscFunctionBeginUser;
893
894 ierr = GetBCParamBool(params, "enforce_seam_flux", value_out, found); CHKERRQ(ierr);
895 if (!*found) {
896 ierr = GetBCParamBool(params, "apply_trim", value_out, found); CHKERRQ(ierr);
897 }
899 PetscFunctionReturn(0);
900}
PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
Implementation of GetBCParamBool().
Definition io.c:836
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ParseAllBoundaryConditions()

PetscErrorCode ParseAllBoundaryConditions ( UserCtx *  user,
const char *  bcs_input_filename 
)

Parses the boundary conditions file to configure the type, handler, and any associated parameters for all 6 global faces of the domain.

This function performs the following steps:

  1. On MPI rank 0, it reads the specified configuration file line-by-line.
  2. It parses each line for <Face> <Type> <Handler> [param=value]... format.
  3. It validates the parsed strings and stores the configuration, including a linked list of parameters, in a temporary array.
  4. It then serializes this configuration and broadcasts it to all other MPI ranks.
  5. All ranks (including rank 0) then deserialize the broadcasted data to populate their local user->boundary_faces array identically.
  6. It also sets the particle inlet lookup fields in UserCtx.
Parameters
[in,out]userThe main UserCtx struct where the final configuration for all ranks will be stored.
[in]bcs_input_filenameThe path to the boundary conditions configuration file.
Returns
PetscErrorCode 0 on success, error code on failure.

Parses the boundary conditions file to configure the type, handler, and any associated parameters for all 6 global faces of the domain.

See also
ParseAllBoundaryConditions()

Definition at line 911 of file io.c.

912{
913 PetscErrorCode ierr;
914 PetscMPIInt rank;
915
916 // Temporary storage for rank 0 to build the configuration before broadcasting.
917 BoundaryFaceConfig configs_rank0[6];
918
919 PetscFunctionBeginUser;
921 rank = PetscGlobalRank;
922
923 if (rank == 0) {
924 FILE *file;
925 char line_buffer[1024];
926
927 // Initialize the temporary config array with safe defaults on rank 0.
928 for (int i = 0; i < 6; i++) {
929 configs_rank0[i].face_id = (BCFace)i;
930 configs_rank0[i].mathematical_type = WALL;
931 configs_rank0[i].handler_type = BC_HANDLER_WALL_NOSLIP;
932 configs_rank0[i].params = NULL;
933 configs_rank0[i].handler = NULL; // Handler object is not created here.
934 }
935
936 LOG_ALLOW(GLOBAL, LOG_INFO, "Parsing BC configuration from '%s' on rank 0... \n", bcs_input_filename);
937 file = fopen(bcs_input_filename, "r");
938 if (!file) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Could not open BCs file '%s'.", bcs_input_filename);
939
940 while (fgets(line_buffer, sizeof(line_buffer), file)) {
941 char *current_pos = line_buffer;
942 while (isspace((unsigned char)*current_pos)) current_pos++; // Skip leading whitespace
943 if (*current_pos == '#' || *current_pos == '\0' || *current_pos == '\n' || *current_pos == '\r') continue;
944
945 char *face_str = strtok(current_pos, " \t\n\r");
946 char *type_str = strtok(NULL, " \t\n\r");
947 char *handler_str = strtok(NULL, " \t\n\r");
948
949 if (!face_str || !type_str || !handler_str) {
950 LOG_ALLOW(GLOBAL, LOG_WARNING, "Malformed line in bcs.dat, skipping: %s \n", line_buffer);
951 continue;
952 }
953
954 BCFace face_enum;
955 BCType type_enum;
956 BCHandlerType handler_enum;
957 const char* handler_name_for_log;
958
959 // --- Convert strings to enums and validate ---
960 ierr = StringToBCFace(face_str, &face_enum); CHKERRQ(ierr);
961 ierr = StringToBCType(type_str, &type_enum); CHKERRQ(ierr);
962 ierr = StringToBCHandlerType(handler_str, &handler_enum); CHKERRQ(ierr);
963 ierr = ValidateBCHandlerForBCType(type_enum, handler_enum);
964 if (ierr) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Validation failed: Handler '%s' is not valid for Type '%s' on Face '%s'.\n", handler_str, type_str, face_str);
965
966 // Store the core types for the corresponding face
967 configs_rank0[face_enum].mathematical_type = type_enum;
968 configs_rank0[face_enum].handler_type = handler_enum;
969 handler_name_for_log = BCHandlerTypeToString(handler_enum); // Assumes this utility exists
970 LOG_ALLOW(GLOBAL, LOG_DEBUG, " Parsed Face '%s': Type=%s, Handler=%s \n", face_str, type_str, handler_name_for_log);
971
972 // --- Parse optional key=value parameters for this face ---
973 FreeBC_ParamList(configs_rank0[face_enum].params); // Clear any previous (default) params
974 configs_rank0[face_enum].params = NULL;
975 BC_Param **param_next_ptr = &configs_rank0[face_enum].params; // Pointer to the 'next' pointer to build the list
976
977 char* token;
978 while ((token = strtok(NULL, " \t\n\r")) != NULL) {
979 char* equals_ptr = strchr(token, '=');
980 if (!equals_ptr) {
981 LOG_ALLOW(GLOBAL, LOG_WARNING, "Malformed parameter '%s' on face '%s', skipping. \n", token, face_str);
982 continue;
983 }
984
985 *equals_ptr = '\0'; // Temporarily split the string at '=' to separate key and value
986 char* key_str = token;
987 char* value_str = equals_ptr + 1;
988
989 BC_Param *new_param;
990 ierr = PetscMalloc1(1, &new_param); CHKERRQ(ierr);
991 ierr = PetscStrallocpy(key_str, &new_param->key); CHKERRQ(ierr);
992 ierr = PetscStrallocpy(value_str, &new_param->value); CHKERRQ(ierr);
993 new_param->next = NULL;
994
995 *param_next_ptr = new_param;
996 param_next_ptr = &new_param->next;
997 LOG_ALLOW(GLOBAL, LOG_TRACE, " - Found param: [%s] = [%s] \n", new_param->key, new_param->value);
998 }
999 }
1000 fclose(file);
1001 }
1002
1003 // =========================================================================
1004 // BROADCASTING THE CONFIGURATION FROM RANK 0
1005 // =========================================================================
1006 // This is a critical step to ensure all processes have the same configuration.
1007
1008 LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "Rank %d broadcasting/receiving BC configuration.\n", rank);
1009
1010 for (int i = 0; i < 6; i++) {
1011 // --- Broadcast simple enums ---
1012 if (rank == 0) {
1013 user->boundary_faces[i] = configs_rank0[i]; // Rank 0 populates its final struct
1014 }
1015 ierr = MPI_Bcast(&user->boundary_faces[i].mathematical_type, 1, MPI_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
1016 ierr = MPI_Bcast(&user->boundary_faces[i].handler_type, 1, MPI_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
1017
1018 // --- Serialize and Broadcast the parameter linked list ---
1019 PetscInt n_params = 0;
1020 if (rank == 0) { // On rank 0, count the number of parameters to send
1021 for (BC_Param *p = user->boundary_faces[i].params; p; p = p->next) n_params++;
1022 }
1023 ierr = MPI_Bcast(&n_params, 1, MPIU_INT, 0, PETSC_COMM_WORLD);CHKERRQ(ierr);
1024
1025 if (rank != 0) { // Non-root ranks need to receive and build the list
1026 FreeBC_ParamList(user->boundary_faces[i].params); // Ensure list is empty before building
1027 user->boundary_faces[i].params = NULL;
1028 }
1029
1030 BC_Param **param_next_ptr = &user->boundary_faces[i].params;
1031
1032 for (int j = 0; j < n_params; j++) {
1033 char key_buf[256] = {0}, val_buf[256] = {0};
1034 if (rank == 0) {
1035 // On rank 0, navigate to the j-th param and copy its data to buffers
1036 BC_Param *p = user->boundary_faces[i].params;
1037 for (int k = 0; k < j; k++) p = p->next;
1038 strncpy(key_buf, p->key, 255);
1039 strncpy(val_buf, p->value, 255);
1040 }
1041
1042 ierr = MPI_Bcast(key_buf, 256, MPI_CHAR, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
1043 ierr = MPI_Bcast(val_buf, 256, MPI_CHAR, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
1044
1045 if (rank != 0) {
1046 // On non-root ranks, deserialize: create a new node and append it
1047 BC_Param *new_param;
1048 ierr = PetscMalloc1(1, &new_param); CHKERRQ(ierr);
1049 ierr = PetscStrallocpy(key_buf, &new_param->key); CHKERRQ(ierr);
1050 ierr = PetscStrallocpy(val_buf, &new_param->value); CHKERRQ(ierr);
1051 new_param->next = NULL;
1052 *param_next_ptr = new_param;
1053 param_next_ptr = &new_param->next;
1054 } else {
1055 // On rank 0, just advance the pointer for the next iteration
1056 param_next_ptr = &((*param_next_ptr)->next);
1057 }
1058 }
1059 user->boundary_faces[i].face_id = (BCFace)i; // Ensure face_id is set on all ranks
1060 }
1061
1062 // --- Set particle inlet lookup fields used by the particle system ---
1063 user->inletFaceDefined = PETSC_FALSE;
1064 for (int i=0; i<6; i++) {
1065
1066 if (user->boundary_faces[i].mathematical_type == INLET && !user->inletFaceDefined) {
1067 user->inletFaceDefined = PETSC_TRUE;
1068 user->identifiedInletBCFace = (BCFace)i;
1069 LOG_ALLOW(GLOBAL, LOG_INFO, "Inlet face for particle initialization identified as Face %d.\n", i);
1070 break; // Found the first one, stop looking
1071 }
1072 }
1073
1074
1075 if (rank == 0) {
1076 // Rank 0 can now free the linked lists it created for the temporary storage.
1077 // As written, user->boundary_faces was populated directly on rank 0, so no extra free is needed.
1078 // for(int i=0; i<6; i++) FreeBC_ParamList(configs_rank0[i].params); // This would be needed if we used configs_rank0 exclusively
1079 }
1080
1082 PetscFunctionReturn(0);
1083}
PetscErrorCode StringToBCHandlerType(const char *str, BCHandlerType *handler_out)
Implementation of StringToBCHandlerType().
Definition io.c:773
PetscErrorCode ValidateBCHandlerForBCType(BCType type, BCHandlerType handler)
Implementation of ValidateBCHandlerForBCType().
Definition io.c:793
PetscErrorCode StringToBCFace(const char *str, BCFace *face_out)
Implementation of StringToBCFace().
Definition io.c:736
void FreeBC_ParamList(BC_Param *head)
Implementation of FreeBC_ParamList().
Definition io.c:719
PetscErrorCode StringToBCType(const char *str, BCType *type_out)
Implementation of StringToBCType().
Definition io.c:753
#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
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
BoundaryCondition * handler
Definition variables.h:430
Holds the complete configuration for one of the six boundary faces.
Definition variables.h:424
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DeterminePeriodicity()

PetscErrorCode DeterminePeriodicity ( SimCtx *  simCtx)

Scans all block-specific boundary condition files to determine a globally consistent periodicity for each dimension, reusing the core type parser.

This is a lightweight pre-parser intended to be called before DMDA creation. It ensures that the periodicity setting is consistent across all blocks, which is a physical requirement for the domain.

  1. It collectively verifies that the mandatory BCS file for each block exists.
  2. On MPI rank 0, it then iterates through the files.
  3. For each line, it attempts to convert the type string to a BCType enum using the standard StringToBCType helper.
  4. If the conversion is successful AND the type is PERIODIC, it flags the corresponding face.
  5. If the conversion fails (e.g., for "WALL", "INLET", etc.), the error is cleared and the line is simply ignored, as it's not relevant to periodicity.
  6. It validates consistency (e.g., -Xi and +Xi match) and ensures all block files specify the same global periodicity.
  7. It broadcasts the final three flags (as integers 0 or 1) to all MPI ranks.
  8. All ranks update the i_periodic, j_periodic, and k_periodic fields in their SimCtx.
Parameters
[in,out]simCtxThe master SimCtx struct, containing the bcs_files list and where the final periodicity flags will be stored.
Returns
PetscErrorCode 0 on success, error code on failure.

Scans all block-specific boundary condition files to determine a globally consistent periodicity for each dimension, reusing the core type parser.

See also
DeterminePeriodicity()

Definition at line 1096 of file io.c.

1097{
1098 PetscErrorCode ierr;
1099 PetscMPIInt rank;
1100 PetscInt periodic_flags[3] = {0, 0, 0}; // Index 0:I, 1:J, 2:K
1101
1102 PetscFunctionBeginUser;
1104 rank = simCtx->rank;
1105
1106 // --- Part 1: Collectively verify all BCS files exist before proceeding ---
1107 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
1108 const char *bcs_filename = simCtx->bcs_files[bi];
1109 if (!bcs_filename) SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_NULL, "BCS filename for block %" PetscInt_FMT " is not set in SimCtx.", bi);
1110 char desc_buf[256];
1111 PetscBool file_exists;
1112 snprintf(desc_buf, sizeof(desc_buf), "BCS file for block %" PetscInt_FMT "", bi);
1113 ierr = VerifyPathExistence(bcs_filename, PETSC_FALSE, PETSC_FALSE, desc_buf, &file_exists); CHKERRQ(ierr);
1114 }
1115
1116 // --- Part 2: Rank 0 does the parsing, since we know all files exist ---
1117 if (rank == 0) {
1118 PetscBool global_is_periodic[3] = {PETSC_FALSE, PETSC_FALSE, PETSC_FALSE};
1119 PetscBool is_set = PETSC_FALSE;
1120
1121 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
1122 const char *bcs_filename = simCtx->bcs_files[bi];
1123 FILE *file = fopen(bcs_filename, "r");
1124
1125 PetscBool face_is_periodic[6] = {PETSC_FALSE};
1126 char line_buffer[1024];
1127
1128 while (fgets(line_buffer, sizeof(line_buffer), file)) {
1129 char *current_pos = line_buffer;
1130 while (isspace((unsigned char)*current_pos)) current_pos++;
1131 if (*current_pos == '#' || *current_pos == '\0' || *current_pos == '\n') continue;
1132
1133 // --- Tokenize the line exactly like the main parser ---
1134 char *face_str = strtok(current_pos, " \t\n\r");
1135 char *type_str = strtok(NULL, " \t\n\r");
1136
1137 // If the line doesn't have at least two tokens, we can't determine the type.
1138 if (!face_str || !type_str) continue;
1139
1140 // --- Perform a direct, non-erroring check on the mathematical type string ---
1141 if (strcasecmp(type_str, "PERIODIC") == 0) {
1142 BCFace face_enum;
1143 // A malformed face string on a periodic line IS a fatal error.
1144 ierr = StringToBCFace(face_str, &face_enum); CHKERRQ(ierr);
1145 face_is_periodic[face_enum] = PETSC_TRUE;
1146 }
1147 // Any other type_str (e.g., "WALL", "INLET") is correctly and silently ignored.
1148 }
1149 fclose(file);
1150
1151 // --- Validate consistency within this file ---
1152 if (face_is_periodic[BC_FACE_NEG_X] != face_is_periodic[BC_FACE_POS_X])
1153 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Inconsistent X-periodicity in file '%s' for block %" PetscInt_FMT ". Both -Xi and +Xi must be periodic or neither.", bcs_filename, bi);
1154 if (face_is_periodic[BC_FACE_NEG_Y] != face_is_periodic[BC_FACE_POS_Y])
1155 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Inconsistent Y-periodicity in file '%s' for block %" PetscInt_FMT ". Both -Eta and +Eta must be periodic or neither.", bcs_filename, bi);
1156 if (face_is_periodic[BC_FACE_NEG_Z] != face_is_periodic[BC_FACE_POS_Z])
1157 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Inconsistent Z-periodicity in file '%s' for block %" PetscInt_FMT ". Both -Zeta and +Zeta must be periodic or neither.", bcs_filename, bi);
1158
1159 PetscBool local_is_periodic[3] = {face_is_periodic[BC_FACE_NEG_X], face_is_periodic[BC_FACE_NEG_Y], face_is_periodic[BC_FACE_NEG_Z]};
1160
1161 // --- Validate consistency across block files ---
1162 if (!is_set) {
1163 global_is_periodic[0] = local_is_periodic[0];
1164 global_is_periodic[1] = local_is_periodic[1];
1165 global_is_periodic[2] = local_is_periodic[2];
1166 is_set = PETSC_TRUE;
1167 } else {
1168 if (global_is_periodic[0] != local_is_periodic[0] || global_is_periodic[1] != local_is_periodic[1] || global_is_periodic[2] != local_is_periodic[2]) {
1169 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1170 "Periodicity mismatch between blocks. Block 0 requires (I:%d, J:%d, K:%d), but block %" PetscInt_FMT " (file '%s') has (I:%d, J:%d, K:%d).",
1171 (int)global_is_periodic[0], (int)global_is_periodic[1], (int)global_is_periodic[2],
1172 bi, bcs_filename,
1173 (int)local_is_periodic[0], (int)local_is_periodic[1], (int)local_is_periodic[2]);
1174 }
1175 }
1176 } // end loop over blocks
1177
1178 periodic_flags[0] = (global_is_periodic[0]) ? 1 : 0;
1179 periodic_flags[1] = (global_is_periodic[1]) ? 1 : 0;
1180 periodic_flags[2] = (global_is_periodic[2]) ? 1 : 0;
1181
1182 LOG_ALLOW(GLOBAL, LOG_INFO, "Global periodicity determined: I-periodic=%" PetscInt_FMT ", J-periodic=%" PetscInt_FMT ", K-periodic=%" PetscInt_FMT "\n",
1183 periodic_flags[0], periodic_flags[1], periodic_flags[2]);
1184 }
1185
1186 // --- Part 3: Broadcast the final flags from rank 0 to all other ranks ---
1187 ierr = MPI_Bcast(periodic_flags, 3, MPIU_INT, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
1188
1189 // --- All ranks now update their SimCtx ---
1190 simCtx->i_periodic = periodic_flags[0];
1191 simCtx->j_periodic = periodic_flags[1];
1192 simCtx->k_periodic = periodic_flags[2];
1193
1195 PetscFunctionReturn(0);
1196}
PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists)
Implementation of VerifyPathExistence().
Definition io.c:1202
char ** bcs_files
Definition variables.h:1015
PetscInt k_periodic
Definition variables.h:1010
PetscInt j_periodic
Definition variables.h:1010
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TrimWhitespace()

void TrimWhitespace ( char *  str)

Removes leading and trailing ASCII whitespace from a mutable string.

Parameters
[in,out]strNUL-terminated string compacted in place.

Removes leading and trailing ASCII whitespace from a mutable string.

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

See also
TrimWhitespace()

Definition at line 486 of file io.c.

486 {
488 if (!str) { PROFILE_FUNCTION_END; return; }
489 if (str[0] == '\0') { PROFILE_FUNCTION_END; return; }
490
491 char *start = str;
492 // Find the first non-whitespace character
493 while (isspace((unsigned char)*start)) {
494 start++;
495 }
496
497 // Find the end of the string
498 char *end = str + strlen(str) - 1;
499 // Move backwards from the end to find the last non-whitespace character
500 while (end > start && isspace((unsigned char)*end)) {
501 end--;
502 }
503
504 // Null-terminate after the last non-whitespace character
505 *(end + 1) = '\0';
506
507 // If there was leading whitespace, shift the string to the left
508 if (str != start) {
509 memmove(str, start, (end - start) + 2); // +2 to include the new null terminator
510 }
512}
Here is the caller graph for this function:

◆ CheckpointFieldIsEnabled()

PetscBool CheckpointFieldIsEnabled ( const SimCtx *  simCtx,
const FieldDescriptor *  descriptor 
)

Return whether a catalogued field belongs in the current checkpoint.

A checkpointed field whose subsystem is active (turbulence, dynamic LES, particles, wall model). These are exactly the fields a checkpoint read can load, so consumers of loaded state use the same predicate.

Parameters
[in]simCtxRun context whose active subsystems decide availability.
[in]descriptorCatalog entry to test.
Returns
PETSC_TRUE when the field is checkpointed in this run.

Return whether a catalogued field belongs in the current checkpoint.

Definition at line 75 of file io.c.

76{
78 const unsigned int availability = descriptor ? descriptor->availability : FIELD_AVAILABILITY_ALWAYS;
79
80 if (!simCtx || !descriptor || !(descriptor->capabilities & FIELD_CAPABILITY_CHECKPOINT)) { PROFILE_HELPER_END; return PETSC_FALSE; }
81 if ((availability & FIELD_AVAILABILITY_TURBULENCE) && !simCtx->les) { PROFILE_HELPER_END; return PETSC_FALSE; }
82 if ((availability & FIELD_AVAILABILITY_LES_DYNAMIC) && simCtx->les != DYNAMIC_SMAGORINSKY) { PROFILE_HELPER_END; return PETSC_FALSE; }
83 if ((availability & FIELD_AVAILABILITY_PARTICLES) && !ParticlesEnabled(simCtx)) { PROFILE_HELPER_END; return PETSC_FALSE; }
84 if ((availability & FIELD_AVAILABILITY_WALL_MODEL) && !simCtx->wallfunction) { PROFILE_HELPER_END; return PETSC_FALSE; }
85 if ((availability & FIELD_AVAILABILITY_INFLOW_FLUCTUATION) && !simCtx->inflowFluctuations) { PROFILE_HELPER_END; return PETSC_FALSE; }
87 return PETSC_TRUE;
88}
@ FIELD_CAPABILITY_CHECKPOINT
@ FIELD_AVAILABILITY_ALWAYS
unsigned int capabilities
PetscBool inflowFluctuations
Some inlet adds synthetic fluctuations; their filter state is checkpointed.
Definition variables.h:1043
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvPhysicalTime()

PetscErrorCode PicurvPhysicalTime ( const SimCtx *  simCtx,
PetscReal  solver_time,
PetscReal *  physical 
)

Convert a solver time to physical seconds, t * L_ref / U_ref.

Runtime diagnostics record solver time; each also reports this physical time so a history can be plotted in seconds without the case's scales at hand.

Parameters
[in]simCtxContext carrying the reference scales.
[in]solver_timeTime in solver units.
[out]physicalTime in seconds.
Returns
Zero on success.

Convert a solver time to physical seconds, t * L_ref / U_ref.

Definition at line 2986 of file io.c.

2987{
2988 const FieldDimension time_dimension = FIELD_DIM_TIME;
2989 PetscReal scale = 1.0;
2990
2991 PetscFunctionBeginUser;
2993 PetscCheck(simCtx && physical, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
2994 "Context and physical-time output are required.");
2995 PetscCall(FieldDimensionReferenceScale(&simCtx->scaling, time_dimension, &scale));
2996 *physical = solver_time * scale;
2998 PetscFunctionReturn(0);
2999}
PetscErrorCode FieldDimensionReferenceScale(const ScalingCtx *scaling, FieldDimension dimension, PetscReal *scale)
Return the factor that turns a solver value of one dimension into physical units.
#define FIELD_DIM_TIME
Physical dimension as exponents of the reference length, velocity, and density.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvFieldReferenceScale()

PetscErrorCode PicurvFieldReferenceScale ( SimCtx *  simCtx,
const char *  field_name,
PetscReal *  scale,
char *  description,
size_t  description_length 
)

Physical scale one field is multiplied by to leave non-dimensional form.

Each field's dimension is recorded once, on its entry in the Eulerian or particle field catalog; this resolves a name against both and applies the run's reference scales. Field dimensionalization, derived field statistics, and anything else needing a physical scale read it from here.

Parameters
[in]simCtxContext carrying the resolved reference scales.
[in]field_nameCase-insensitive catalogued field name or alias.
[out]scaleMultiplicative factor.
[out]descriptionOptional human-readable dimension, may be NULL.
[in]description_lengthCapacity of description.
Returns
0 on success; PETSC_ERR_ARG_UNKNOWN_TYPE for a name in neither catalog, and PETSC_ERR_ARG_WRONGSTATE for a field without a fixed dimension (bookkeeping, or staging storage whose dimension is its source's).

Physical scale one field is multiplied by to leave non-dimensional form.

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

See also
PicurvFieldReferenceScale()

Definition at line 3006 of file io.c.

3009{
3010 FieldDimension dimension;
3011 FieldId field_id = FIELD_ID_INVALID;
3013 PetscBool found = PETSC_FALSE;
3014
3015 PetscFunctionBeginUser;
3017 PetscCheck(simCtx && field_name && scale, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
3018 "Context, field name, and output scale are required.");
3019
3020 /* The dimension is a property of the field, recorded on its catalog entry. */
3021 PetscCall(FieldTryIdFromName(field_name, &field_id, &found));
3022 if (found) {
3023 const FieldDescriptor *descriptor = NULL;
3024
3025 PetscCall(FieldGetDescriptor(field_id, &descriptor));
3026 dimension = descriptor->dimension;
3027 } else {
3028 const ParticleFieldDescriptor *descriptor = NULL;
3029
3030 PetscCall(ParticleFieldTryIdFromName(field_name, &particle_id, &found));
3031 PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE,
3032 "Field '%s' is in neither the Eulerian nor the particle field catalog.", field_name);
3033 PetscCall(ParticleFieldGetDescriptor(particle_id, &descriptor));
3034 dimension = descriptor->dimension;
3035 }
3036 PetscCheck(dimension.kind == FIELD_DIMENSION_FIXED, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
3037 "Field '%s' has no fixed physical dimension, so it has no reference scale.", field_name);
3038 PetscCall(FieldDimensionReferenceScale(&simCtx->scaling, dimension, scale));
3039 if (description && description_length) {
3040 PetscCall(FieldDimensionLabel(dimension, description, description_length));
3041 }
3043 PetscFunctionReturn(0);
3044}
@ FIELD_DIMENSION_FIXED
The exponents are the field's dimension.
PetscErrorCode FieldTryIdFromName(const char *field_name, FieldId *field_id, PetscBool *found)
Look a name up without treating an unknown name as an error.
FieldDimension dimension
FieldDimensionKind kind
PetscErrorCode FieldDimensionLabel(FieldDimension dimension, char *label, size_t length)
Write a printable form of a dimension, such as L^2 U or dimensionless.
@ FIELD_ID_INVALID
@ PARTICLE_FIELD_ID_INVALID
PetscErrorCode ParticleFieldTryIdFromName(const char *field_name, ParticleFieldId *field_id, PetscBool *found)
Look a name up without treating an unknown name as an error.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ParsePostProcessingSettings()

PetscErrorCode ParsePostProcessingSettings ( SimCtx *  simCtx)

Initializes post-processing settings from a config file and command-line overrides.

This function establishes the configuration for a post-processing run by:

  1. Setting hardcoded default values in the PostProcessParams struct.
  2. Reading a configuration file to override the defaults.
  3. Parsing command-line options (-startTime, -endTime, etc.) which can override both the defaults and the file settings.
Parameters
simCtxThe pointer to the simulation context that contains the postprocessing file and struct.
Returns
PetscErrorCode

Initializes post-processing settings from a config file and command-line overrides.

See also
ParsePostProcessingSettings()

Definition at line 3051 of file io.c.

3052{
3053 FILE *file;
3054 char line[1024];
3055 PetscBool startTimeSet, endTimeSet, timeStepSet;
3056
3057 PetscFunctionBeginUser;
3059
3060 if (!simCtx || !simCtx->pps) {
3061 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_NULL, "SimCtx or its pps member is NULL in ParsePostProcessingSettings.");
3062 }
3063
3064 char *configFile = simCtx->PostprocessingControlFile;
3065 PostProcessParams *pps = simCtx->pps;
3066
3067
3068 // --- 1. Set Sane Defaults First ---
3069 pps->startTime = 0;
3070 pps->endTime = 0;
3071 pps->timeStep = 1;
3072 pps->step_list_file[0] = '\0';
3073 pps->outputParticles = PETSC_FALSE;
3074 pps->particle_output_freq = simCtx->LoggingFrequency; // Default to logging frequency;
3075 strcpy(pps->process_pipeline, "");
3076 strcpy(pps->output_fields_instantaneous, "Ucat,P");
3077 strcpy(pps->output_prefix, "Field");
3078 strcpy(pps->particle_output_prefix,"Particle");
3079 strcpy(pps->particle_fields,"velocity,CellID,weight,pid");
3080 strcpy(pps->particle_pipeline,"");
3081 strncpy(pps->statistics_pipeline, "", MAX_PIPELINE_LENGTH - 1);
3082 strncpy(pps->statistics_output_prefix, "Stats", MAX_FILENAME_LENGTH - 1);
3083 strcpy(pps->particleExt,"dat"); // The input file format for particles.
3084 strcpy(pps->eulerianExt,"dat"); // The input file format for Eulerian fields.
3085 /* The postprocessor's own decomposition: the control file carries the solve's, which
3086 * fits a different rank count, so the postprocessor reads only this one. */
3087 pps->da_procs[0] = pps->da_procs[1] = pps->da_procs[2] = PETSC_DECIDE;
3088 /* A negative source step means "the last step this recipe covers", so a recipe
3089 * that does not name one still derives from a bundle that exists. */
3090 pps->field_statistics_windows[0] = '\0';
3091 strcpy(pps->field_statistics_outputs, "mean,reynolds_stress,rms,tke,flux");
3092 strcpy(pps->field_statistics_formats, "vtk");
3093 strcpy(pps->field_statistics_output_prefix, "Field");
3094 pps->dimensionalize = PETSC_FALSE;
3097 pps->reference[0] = pps->reference[1] = pps->reference[2] = 1;
3098 strncpy(pps->source_dir, simCtx->output_dir, sizeof(pps->source_dir) - 1);
3099 pps->source_dir[sizeof(pps->source_dir) - 1] = '\0'; // Ensure null-termination
3100
3101 // --- 2. Parse the Configuration File (overrides defaults) ---
3102 file = fopen(configFile, "r");
3103 if (file) {
3104 LOG_ALLOW(GLOBAL, LOG_INFO, "Parsing post-processing config file: %s\n", configFile);
3105 while (fgets(line, sizeof(line), file)) {
3106 char *key, *value, *comment;
3107 comment = strchr(line, '#'); if (comment) *comment = '\0';
3108 TrimWhitespace(line); if (strlen(line) == 0) continue;
3109 key = strtok(line, "="); value = strtok(NULL, "=");
3110 if (key && value) {
3111 TrimWhitespace(key); TrimWhitespace(value);
3112 if (strcmp(key, "startTime") == 0) pps->startTime = atoi(value);
3113 else if (strcmp(key, "endTime") == 0) pps->endTime = atoi(value);
3114 else if (strcmp(key, "timeStep") == 0) pps->timeStep = atoi(value);
3115 else if (strcmp(key, "step_list_file") == 0) {
3116 strncpy(pps->step_list_file, value, sizeof(pps->step_list_file) - 1);
3117 pps->step_list_file[sizeof(pps->step_list_file) - 1] = '\0';
3118 }
3119 else if (strcmp(key, "output_particles") == 0) {
3120 if (strcasecmp(value, "true") == 0) pps->outputParticles = PETSC_TRUE;
3121 }
3122 else if (strcasecmp(key, "process_pipeline") == 0) {
3123 strncpy(pps->process_pipeline, value, MAX_PIPELINE_LENGTH - 1);
3124 pps->process_pipeline[MAX_PIPELINE_LENGTH - 1] = '\0'; // Ensure null-termination
3125 } else if (strcasecmp(key, "field_statistics_windows") == 0) {
3126 strncpy(pps->field_statistics_windows, value, MAX_FIELD_LIST_LENGTH - 1);
3128 } else if (strcasecmp(key, "field_statistics_formats") == 0) {
3129 strncpy(pps->field_statistics_formats, value, MAX_FIELD_LIST_LENGTH - 1);
3131 } else if (strcasecmp(key, "field_statistics_outputs") == 0) {
3132 strncpy(pps->field_statistics_outputs, value, MAX_FIELD_LIST_LENGTH - 1);
3134 } else if (strcasecmp(key, "field_statistics_source_step") == 0) {
3135 pps->field_statistics_source_step = atoi(value);
3136 } else if (strcasecmp(key, "field_statistics_homogeneous") == 0) {
3137 pps->field_statistics_homogeneous[0] = (PetscBool)(strchr(value, 'i') != NULL);
3138 pps->field_statistics_homogeneous[1] = (PetscBool)(strchr(value, 'j') != NULL);
3139 pps->field_statistics_homogeneous[2] = (PetscBool)(strchr(value, 'k') != NULL);
3140 } else if (strncasecmp(key, "field_statistics_ensemble_", 26) == 0) {
3141 /* Ensembles are defined with the run windows' option families, so the
3142 * window parser reads them; the recipe line becomes that option. */
3143 char option[MAX_FILENAME_LENGTH + 2];
3144
3145 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s", key));
3146 PetscCall(PetscOptionsSetValue(NULL, option, value));
3147 } else if (strcasecmp(key, "da_processors") == 0) {
3148 PetscInt parsed[3];
3149 PetscCheck(sscanf(value, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT,
3150 &parsed[0], &parsed[1], &parsed[2]) == 3
3151 && parsed[0] > 0 && parsed[1] > 0 && parsed[2] > 0,
3152 PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
3153 "Post recipe da_processors must be three positive integers, got '%s'.", value);
3154 for (PetscInt axis = 0; axis < 3; ++axis) pps->da_procs[axis] = parsed[axis];
3155 } else if (strcasecmp(key, "dimensionalize") == 0) {
3156 pps->dimensionalize = (PetscBool)(strcasecmp(value, "true") == 0
3157 || strcmp(value, "1") == 0);
3158 } else if (strcasecmp(key, "field_statistics_output_prefix") == 0) {
3159 strncpy(pps->field_statistics_output_prefix, value,
3160 sizeof(pps->field_statistics_output_prefix) - 1);
3162 sizeof(pps->field_statistics_output_prefix) - 1] = '\0';
3163 } else if (strcasecmp(key, "output_fields_instantaneous") == 0) {
3164 strncpy(pps->output_fields_instantaneous, value, MAX_FIELD_LIST_LENGTH - 1);
3166 } else if (strcasecmp(key, "output_prefix") == 0) {
3167 strncpy(pps->output_prefix, value, MAX_FILENAME_LENGTH - 1);
3168 pps->output_prefix[MAX_FILENAME_LENGTH - 1] = '\0';
3169 } else if (strcasecmp(key, "particle_output_prefix") == 0) {
3170 strncpy(pps->particle_output_prefix, value, MAX_FILENAME_LENGTH - 1);
3172 } else if (strcasecmp(key, "particle_fields_instantaneous") == 0) {
3173 strncpy(pps->particle_fields, value, MAX_FIELD_LIST_LENGTH - 1);
3174 pps->particle_fields[MAX_FIELD_LIST_LENGTH - 1] = '\0';
3175 } else if (strcasecmp(key, "particle_pipeline") == 0) {
3176 strncpy(pps->particle_pipeline, value, MAX_PIPELINE_LENGTH - 1);
3177 pps->particle_pipeline[MAX_PIPELINE_LENGTH - 1] = '\0';
3178 } else if (strcasecmp(key, "particle_output_freq") == 0) {
3179 pps->particle_output_freq = atoi(value);
3180 } else if (strcasecmp(key, "statistics_pipeline") == 0) {
3181 strncpy(pps->statistics_pipeline, value, MAX_PIPELINE_LENGTH - 1);
3183 } else if (strcasecmp(key, "statistics_output_prefix") == 0) {
3184 strncpy(pps->statistics_output_prefix, value, MAX_FILENAME_LENGTH - 1);
3186 } else if (strcasecmp(key, "particleExt") == 0) {
3187 strncpy(pps->particleExt, value, sizeof(pps->particleExt) - 1);
3188 pps->particleExt[sizeof(pps->particleExt) - 1] = '\0';
3189 } else if (strcasecmp(key, "eulerianExt") == 0) {
3190 strncpy(pps->eulerianExt, value, sizeof(pps->eulerianExt) - 1);
3191 pps->eulerianExt[sizeof(pps->eulerianExt) - 1] = '\0';
3192 } else if (strcmp(key, "reference_ip") == 0) {pps->reference[0] = atoi(value);
3193 } else if (strcmp(key, "reference_jp") == 0) {pps->reference[1] = atoi(value);
3194 } else if (strcmp(key, "reference_kp") == 0) {pps->reference[2] = atoi(value);
3195 } else if (strcasecmp(key, "source_directory") == 0) {
3196 strncpy(pps->source_dir, value, sizeof(pps->source_dir) - 1);
3197 pps->source_dir[sizeof(pps->source_dir) - 1] = '\0';
3198 } else if (strcasecmp(key, "spectra_signature") == 0) {
3199 /* Spectra are computed by the conductor's Python stage, not here. The
3200 key exists so a change to the spectra recipe reaches the recipe
3201 fingerprint each step's output record carries; this executable has
3202 no use for it and accepting it silently keeps the log free of a
3203 warning that would appear on every post-processing run. */
3204 } else {
3205 LOG_ALLOW(GLOBAL, LOG_WARNING, "Unknown key '%s' in post-processing config file. Ignoring.\n", key);
3206 }
3207 // Add parsing for pipeline, fields, etc. in later phases
3208 }
3209 }
3210 fclose(file);
3211 } else {
3212 LOG_ALLOW(GLOBAL, LOG_INFO, "Could not open post-processing config file '%s'. Using defaults and command-line overrides.\n", configFile);
3213 }
3214
3215 // --- 3. Parse Command-Line Options (overrides file settings and defaults) ---
3216 PetscOptionsGetInt(NULL, NULL, "-startTime", &pps->startTime, &startTimeSet);
3217 PetscOptionsGetInt(NULL, NULL, "-endTime", &pps->endTime, &endTimeSet);
3218 PetscCall(PetscOptionsGetInt(NULL, NULL, "-timeStep", &pps->timeStep, &timeStepSet));
3219 PetscCheck(pps->timeStep > 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
3220 "Post-processing timeStep must be positive (got %" PetscInt_FMT "). "
3221 "For one checkpoint, set startTime=endTime and timeStep=1.", pps->timeStep);
3222 PetscOptionsGetBool(NULL, NULL, "-output_particles", &pps->outputParticles, NULL);
3223
3224 if(pps->endTime==-1){
3225 pps->endTime = simCtx->StartStep + simCtx->StepsToRun; // Total steps if endTime is set to -1.
3226 }
3227
3228 // If only startTime is given on command line, run for a single step
3229 if (startTimeSet && !endTimeSet) {
3230 pps->endTime = pps->startTime;
3231 }
3232
3233 LOG_ALLOW(GLOBAL, LOG_INFO, "Post-processing configured to run from t=%" PetscInt_FMT " to t=%" PetscInt_FMT " with step %" PetscInt_FMT ". Particle output: %s.\n",
3234 pps->startTime, pps->endTime, pps->timeStep, pps->outputParticles ? "TRUE" : "FALSE");
3235
3236 LOG_ALLOW(GLOBAL, LOG_INFO, "Process Pipeline: %s\n", pps->process_pipeline);
3237 LOG_ALLOW(GLOBAL, LOG_INFO, "Instantaneous Output Fields: %s\n", pps->output_fields_instantaneous);
3238 LOG_ALLOW(GLOBAL, LOG_INFO, "Output Prefix: %s\n", pps->output_prefix);
3239 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Output Prefix: %s\n", pps->particle_output_prefix);
3240 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Fields: %s\n", pps->particle_fields);
3241 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Pipeline: %s\n", pps->particle_pipeline);
3242 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Output Frequency: %" PetscInt_FMT "\n", pps->particle_output_freq);
3243 LOG_ALLOW(GLOBAL, LOG_INFO, "Post input extensions: Eulerian='.%s', Particle='.%s'\n", pps->eulerianExt, pps->particleExt);
3244 PetscCall(ParsePostStatisticsEnsembles(simCtx));
3245
3247 PetscFunctionReturn(0);
3248}
void TrimWhitespace(char *str)
Implementation of TrimWhitespace().
Definition io.c:486
PetscErrorCode ParsePostStatisticsEnsembles(SimCtx *simCtx)
Resolves the statistics ensembles a post-processing recipe defines.
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 field_statistics_output_prefix[PETSC_MAX_PATH_LEN]
Analysis prefix for CSV summaries; VTK continues to use output_prefix.
Definition variables.h:826
#define MAX_FIELD_LIST_LENGTH
Definition variables.h:784
#define MAX_PIPELINE_LENGTH
Definition variables.h:783
char step_list_file[PETSC_MAX_PATH_LEN]
File listing the exact steps to process, one per line; empty uses the time controls.
Definition variables.h:802
PetscInt reference[3]
Definition variables.h:844
PetscInt timeStep
Definition variables.h:800
#define MAX_FILENAME_LENGTH
Definition variables.h:785
char statistics_pipeline[1024]
e.g.
Definition variables.h:815
char field_statistics_formats[1024]
Comma-separated formats: vtk for derived fields, csv for the convergence history.
Definition variables.h:824
char output_fields_instantaneous[1024]
Definition variables.h:807
char eulerianExt[8]
Definition variables.h:840
char particle_pipeline[1024]
Definition variables.h:809
PetscInt da_procs[3]
Postprocessor MPI decomposition (i, j, k) from the recipe; PETSC_DECIDE where unset.
Definition variables.h:845
char process_pipeline[1024]
Definition variables.h:806
PetscInt particle_output_freq
Definition variables.h:812
char particle_fields[1024]
Definition variables.h:810
PetscBool outputParticles
Definition variables.h:803
PetscInt field_statistics_source_step
Committed step supplying the state; negative means the step being processed.
Definition variables.h:830
char particleExt[8]
Definition variables.h:841
char field_statistics_windows[1024]
Comma-separated window names to derive; empty disables the pipeline.
Definition variables.h:820
char field_statistics_outputs[1024]
Comma-separated outputs: mean, reynolds_stress, rms, tke, flux, point_variance.
Definition variables.h:822
PetscInt startTime
Definition variables.h:798
PetscBool field_statistics_homogeneous[3]
Directions profiles merge over, in (i, j, k) order; none selected writes no profile.
Definition variables.h:832
char PostprocessingControlFile[PETSC_MAX_PATH_LEN]
Definition variables.h:1130
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:

◆ ParseScalingInformation()

PetscErrorCode ParseScalingInformation ( SimCtx *  simCtx)

Parses physical scaling parameters from command-line options.

This function reads the reference length, velocity, and density from the PETSc options database (provided via -scaling_L_ref, etc.). It populates the simCtx->scaling struct and calculates the derived reference pressure. It sets default values of 1.0 for a fully non-dimensional case if the options are not provided.

Parameters
[in,out]simCtxThe simulation context whose 'scaling' member will be populated.
Returns
PetscErrorCode

Parses physical scaling parameters from command-line options.

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

See also
ParseScalingInformation()

Definition at line 3256 of file io.c.

3257{
3258 PetscErrorCode ierr;
3259 PetscBool flg;
3260
3261 PetscFunctionBeginUser;
3263
3264 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx is NULL in ParseScalingInformation");
3265
3266 // --- 1. Set default values to 1.0 ---
3267 // This represents a purely non-dimensional run if no scaling is provided.
3268 simCtx->scaling.L_ref = 1.0;
3269 simCtx->scaling.U_ref = 1.0;
3270 simCtx->scaling.rho_ref = 1.0;
3271
3272 // --- 2. Read overrides from the command line / control file ---
3273 ierr = PetscOptionsGetReal(NULL, NULL, "-scaling_L_ref", &simCtx->scaling.L_ref, &flg); CHKERRQ(ierr);
3274 ierr = PetscOptionsGetReal(NULL, NULL, "-scaling_U_ref", &simCtx->scaling.U_ref, &flg); CHKERRQ(ierr);
3275 ierr = PetscOptionsGetReal(NULL, NULL, "-scaling_rho_ref", &simCtx->scaling.rho_ref, &flg); CHKERRQ(ierr);
3276
3277 // --- 3. Calculate derived scaling factors ---
3278 // Check for division by zero to be safe, though U_ref should be positive.
3279 if (simCtx->scaling.U_ref <= 0.0) {
3280 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Reference velocity U_ref must be positive. Got %g", (double)simCtx->scaling.U_ref);
3281 }
3282 simCtx->scaling.P_ref = simCtx->scaling.rho_ref * simCtx->scaling.U_ref * simCtx->scaling.U_ref;
3283
3284 // --- 4. Log the final, effective scales for verification ---
3285 LOG(GLOBAL, LOG_INFO, "---------------- Physical Scales Initialized -----------------\n");
3286 LOG(GLOBAL, LOG_INFO, " L_ref: %.4f, U_ref: %.4f, rho_ref: %.4f, P_ref: %.4f\n",
3287 simCtx->scaling.L_ref, simCtx->scaling.U_ref, simCtx->scaling.rho_ref, simCtx->scaling.P_ref);
3288 LOG(GLOBAL, LOG_INFO, "--------------------------------------------------------------\n");
3289
3291 PetscFunctionReturn(0);
3292}
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
PetscReal P_ref
Definition variables.h:901
PetscReal rho_ref
Definition variables.h:900
PetscReal U_ref
Definition variables.h:899
Here is the caller graph for this function: