PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
io.c
Go to the documentation of this file.
1/**
2 * @file io.c
3 * @brief Implementation of data input/output routines, focusing on grid configuration.
4 *
5 * This module provides functions to parse grid geometry information, either from
6 * command-line options for programmatically generated grids or by reading the
7 * header of a grid definition file.
8 */
9
10#include "io.h"
11#include "checksum.h"
12#include "field_catalog.h"
15#include "statistics_config.h"
16
17#include <errno.h>
18#include <stdlib.h>
19#include <sys/stat.h>
20#include <unistd.h>
21
22#define PICURV_CHECKPOINT_FORMAT "picurv-checkpoint"
23#define PICURV_CHECKPOINT_VERSION 1
24#define PICURV_CHECKPOINTS_DIRECTORY "checkpoints"
25#define PICURV_EULERIAN_DIRECTORY "eulerian"
26#define PICURV_PARTICLE_DIRECTORY "particles"
27#define PICURV_STATISTICS_DIRECTORY "statistics"
28#define PICURV_CHECKPOINT_STEP_WIDTH 12
29
30// =============================================================================
31// STATIC (PRIVATE) VARIABLES FOR ONE-TIME FILE READ
32// =============================================================================
33
34/** @brief Stores the number of blocks read from the grid file. */
35static PetscInt g_nblk_from_file = 0;
36/** @brief Caches the IM dimensions for all blocks read from the grid file. */
37static PetscInt* g_IMs_from_file = NULL;
38/** @brief Caches the JM dimensions for all blocks read from the grid file. */
39static PetscInt* g_JMs_from_file = NULL;
40/** @brief Caches the KM dimensions for all blocks read from the grid file. */
41static PetscInt* g_KMs_from_file = NULL;
42/** @brief A flag to ensure the grid file is read only once. */
43static PetscBool g_file_has_been_read = PETSC_FALSE;
44
45/**
46 * @brief Copies the owned entries of a ghosted scalar DMDA vector to its global vector.
47 *
48 * DMLocalToGlobal with INSERT_VALUES is unsupported for multidirection-periodic
49 * DMDAs in PETSc. Explicitly copying only the uniquely owned region preserves
50 * INSERT semantics without reducing duplicate periodic ghost entries.
51 */
52static PetscErrorCode CopyOwnedLocalScalarToGlobal(DM dm, Vec local_vec, Vec global_vec)
53{
54 DMDALocalInfo info;
55 const PetscScalar ***local_array = NULL;
56 PetscScalar ***global_array = NULL;
57
58 PetscFunctionBeginUser;
60
61 PetscCall(DMDAGetLocalInfo(dm, &info));
62 PetscCall(DMDAVecGetArrayRead(dm, local_vec, &local_array));
63 PetscCall(DMDAVecGetArray(dm, global_vec, &global_array));
64 for (PetscInt k = info.zs; k < info.zs + info.zm; ++k)
65 for (PetscInt j = info.ys; j < info.ys + info.ym; ++j)
66 for (PetscInt i = info.xs; i < info.xs + info.xm; ++i)
67 global_array[k][j][i] = local_array[k][j][i];
68 PetscCall(DMDAVecRestoreArray(dm, global_vec, &global_array));
69 PetscCall(DMDAVecRestoreArrayRead(dm, local_vec, &local_array));
71 PetscFunctionReturn(0);
72}
73
74/** @brief Implementation of \ref CheckpointFieldIsEnabled(). */
75PetscBool CheckpointFieldIsEnabled(const SimCtx *simCtx, const FieldDescriptor *descriptor)
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}
89
90/**
91 * @brief Format any level of the statistics subtree, from the root down to one payload.
92 *
93 * This is the only place the statistics layout is written down. The directory
94 * creator, the payload writer, the manifest inventory, and the restart reader all
95 * ask for the level they need, so a path cannot be built one way and looked for
96 * another.
97 *
98 * Statistics payloads are block scoped exactly as Eulerian payloads are, with a
99 * window level above the block level, so a multiblock run keeps one accumulator tree
100 * per block under each window.
101 *
102 * Pass @p root NULL for a bundle-relative path, and stop early by passing a negative
103 * @p window or @p block, or a NULL @p payload_name.
104 */
105static PetscErrorCode FormatStatisticsPath(const char *root, PetscInt window, PetscInt block,
106 const char *payload_name, char *path, size_t path_size)
107{
108 size_t used = 0;
109
110 PetscFunctionBeginUser;
112 PetscCheck(path != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output path is required.");
113 if (root) PetscCall(PetscSNPrintf(path, path_size, "%s/%s", root, PICURV_STATISTICS_DIRECTORY));
114 else PetscCall(PetscSNPrintf(path, path_size, "%s", PICURV_STATISTICS_DIRECTORY));
115 if (window < 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
116
117 PetscCall(PetscStrlen(path, &used));
118 PetscCall(PetscSNPrintf(path + used, path_size - used, "/window_%04" PetscInt_FMT, window));
119 if (block < 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
120
121 PetscCall(PetscStrlen(path, &used));
122 PetscCall(PetscSNPrintf(path + used, path_size - used, "/block_%04" PetscInt_FMT, block));
123 if (!payload_name) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
124
125 PetscCall(PetscStrlen(path, &used));
126 PetscCall(PetscSNPrintf(path + used, path_size - used, "/%s.dat", payload_name));
128 PetscFunctionReturn(0);
129}
130
131/**
132 * @brief The DMDA a vector belongs to, or NULL for a vector of any other layout (a swarm field).
133 * @param[in] field_vec Vector.
134 * @param[out] dmda Its DMDA, or NULL.
135 * @return PETSc error code.
136 */
137static inline PetscErrorCode FieldVecDMDA(Vec field_vec, DM *dmda)
138{
139 DM dm = NULL;
140 const char *dm_type = NULL;
141
142 PetscFunctionBeginUser;
143 *dmda = NULL;
144 PetscCall(VecGetDM(field_vec, &dm));
145 if (dm) PetscCall(DMGetType(dm, &dm_type));
146 if (dm_type && !strcmp(dm_type, DMDA)) *dmda = dm;
147 PetscFunctionReturn(0);
148}
149
150/**
151 * @brief Express a vector in decomposition-independent natural ordering.
152 * @details A DMDA vector is permuted into a new natural vector; any other vector (a swarm
153 * field, for one) is already ordered rank by rank and is returned as is, with
154 * *natural_vec left NULL. The caller destroys *natural_vec.
155 */
156static PetscErrorCode NaturalOrderedVector(Vec field_vec, Vec *natural_vec, Vec *ordered_vec)
157{
158 DM dm = NULL;
159
160 PetscFunctionBeginUser;
162 *natural_vec = NULL;
163 *ordered_vec = field_vec;
164 PetscCall(FieldVecDMDA(field_vec, &dm));
165 if (dm) {
166 PetscCall(DMDACreateNaturalVector(dm, natural_vec));
167 PetscCall(DMDAGlobalToNaturalBegin(dm, field_vec, INSERT_VALUES, *natural_vec));
168 PetscCall(DMDAGlobalToNaturalEnd(dm, field_vec, INSERT_VALUES, *natural_vec));
169 *ordered_vec = *natural_vec;
170 }
172 PetscFunctionReturn(0);
173}
174
175/**
176 * @brief Open a PETSc binary viewer for one field payload, reading or writing through MPI-IO.
177 * @details Every rank reads or writes its own contiguous part of the file collectively, instead
178 * of rank 0 relaying each rank's share; the file is the same PETSc binary file (header,
179 * then the values in vector order) either way. No `.info` sidecar is read or written.
180 * PETSc's own `-viewer_binary_mpiio false` switches to the rank-0 relay for both.
181 */
182static PetscErrorCode OpenFieldPayloadViewer(MPI_Comm comm, const char *filename, PetscFileMode mode, PetscViewer *viewer)
183{
184 PetscBool use_mpiio = PETSC_TRUE;
185
186 PetscFunctionBeginUser;
188 PetscCall(PetscOptionsGetBool(NULL, NULL, "-viewer_binary_mpiio", &use_mpiio, NULL));
189 PetscCall(PetscViewerCreate(comm, viewer));
190 PetscCall(PetscViewerSetType(*viewer, PETSCVIEWERBINARY));
191 PetscCall(PetscViewerFileSetMode(*viewer, mode));
192 PetscCall(PetscViewerBinarySetUseMPIIO(*viewer, use_mpiio));
193 PetscCall(PetscViewerBinarySetSkipInfo(*viewer, PETSC_TRUE));
194 PetscCall(PetscViewerFileSetName(*viewer, filename));
196 PetscFunctionReturn(0);
197}
198
199/** @brief Compute and cache a rank-count-independent hash of the active grid geometry. */
200static PetscErrorCode ComputeCheckpointGeometrySHA256(SimCtx *simCtx, UserCtx *user, char digest_hex[65])
201{
202 PicurvSHA256Context hash_context;
203 char metadata[256];
204
205 PetscFunctionBeginUser;
207 PetscCheck(simCtx != NULL && user != NULL && digest_hex != NULL,
208 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Geometry hash inputs cannot be NULL.");
209 if (simCtx->checkpointGeometryHashReady) {
210 PetscCall(PetscStrncpy(digest_hex, simCtx->checkpointGeometrySHA256, 65));
212 PetscFunctionReturn(0);
213 }
214
215 if (simCtx->rank == 0) PicurvSHA256Init(&hash_context);
216 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
217 FieldView coordinates;
218 Vec natural_vec = NULL, ordered_vec = NULL;
219 const PetscScalar *values = NULL;
220 PetscInt value_count = 0, local_count = 0, max_count = 0;
221 PetscMPIInt size;
222
223 // The hash covers the coordinates in natural order. Each rank holds a contiguous run of
224 // that order, so rank 0 hashes its own and then each rank's in turn, holding one rank's
225 // share at a time: the bytes hashed are those of the whole gathered vector.
226 PetscCall(FieldGetView(&user[block], FIELD_ID_COORDINATES, &coordinates));
227 PetscCall(NaturalOrderedVector(coordinates.global_vec, &natural_vec, &ordered_vec));
228 PetscCall(VecGetSize(ordered_vec, &value_count));
229 PetscCall(VecGetLocalSize(ordered_vec, &local_count));
230 PetscCall(VecGetArrayRead(ordered_vec, &values));
231 size = simCtx->size;
232 PetscCallMPI(MPI_Allreduce(&local_count, &max_count, 1, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD));
233 if (simCtx->rank == 0) {
234 PetscScalar *chunk = NULL;
235 size_t metadata_length = 0;
236
237 PetscCall(PetscSNPrintf(metadata, sizeof(metadata),
238 "block=%" PetscInt_FMT ";im=%" PetscInt_FMT ";jm=%" PetscInt_FMT
239 ";km=%" PetscInt_FMT ";periodic=%d,%d,%d;",
240 block, user[block].IM, user[block].JM, user[block].KM,
241 (int)simCtx->i_periodic, (int)simCtx->j_periodic, (int)simCtx->k_periodic));
242 PetscCall(PetscStrlen(metadata, &metadata_length));
243 PicurvSHA256Update(&hash_context, metadata, metadata_length);
244 PicurvSHA256Update(&hash_context, &value_count, sizeof(value_count));
245 PicurvSHA256Update(&hash_context, values, (size_t)local_count * sizeof(*values));
246 PetscCall(PetscMalloc1(max_count + 1, &chunk));
247 for (PetscMPIInt r = 1; r < size; ++r) {
248 PetscInt count = 0;
249 PetscCallMPI(MPI_Recv(&count, 1, MPIU_INT, r, 0, PETSC_COMM_WORLD, MPI_STATUS_IGNORE));
250 PetscCallMPI(MPI_Recv(chunk, (int)count, MPIU_SCALAR, r, 1, PETSC_COMM_WORLD, MPI_STATUS_IGNORE));
251 PicurvSHA256Update(&hash_context, chunk, (size_t)count * sizeof(*chunk));
252 }
253 PetscCall(PetscFree(chunk));
254 } else {
255 PetscCallMPI(MPI_Send(&local_count, 1, MPIU_INT, 0, 0, PETSC_COMM_WORLD));
256 PetscCallMPI(MPI_Send((void *)values, (int)local_count, MPIU_SCALAR, 0, 1, PETSC_COMM_WORLD));
257 }
258 PetscCall(VecRestoreArrayRead(ordered_vec, &values));
259 PetscCall(VecDestroy(&natural_vec));
260 }
261
262 if (simCtx->rank == 0) PicurvSHA256FinalHex(&hash_context, digest_hex);
263 PetscCallMPI(MPI_Bcast(digest_hex, 65, MPI_CHAR, 0, PETSC_COMM_WORLD));
264 PetscCall(PetscStrncpy(simCtx->checkpointGeometrySHA256, digest_hex, 65));
265 simCtx->checkpointGeometryHashReady = PETSC_TRUE;
267 PetscFunctionReturn(0);
268}
269
270/** @brief Format the canonical directory name for one completed step. */
271static PetscErrorCode FormatCheckpointStepDirectory(const char *root, PetscInt step, char *path, size_t path_size)
272{
273 PetscFunctionBeginUser;
275 PetscCheck(root != NULL && path != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
276 "Checkpoint root and output path are required.");
277 PetscCall(PetscSNPrintf(path, path_size, "%s/%s/step_%0*" PetscInt_FMT,
280 PetscFunctionReturn(0);
281}
282
283/** @brief Resolve either an exact bundle or a run/output root to one step bundle. */
284static PetscErrorCode ResolveCheckpointStepDirectory(const char *source_root, PetscInt step,
285 char *path, size_t path_size)
286{
287 char metadata_path[PETSC_MAX_PATH_LEN];
288 PetscBool exact_bundle = PETSC_FALSE;
289
290 PetscFunctionBeginUser;
292 PetscCheck(source_root != NULL && path != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
293 "Checkpoint source and output path are required.");
294 PetscCall(PetscSNPrintf(metadata_path, sizeof(metadata_path), "%s/checkpoint.meta", source_root));
295 PetscCall(PetscTestFile(metadata_path, 'r', &exact_bundle));
296 if (exact_bundle) PetscCall(PetscStrncpy(path, source_root, path_size));
297 else PetscCall(FormatCheckpointStepDirectory(source_root, step, path, path_size));
299 PetscFunctionReturn(0);
300}
301
302/** @brief Create one directory on rank zero and report failures collectively. */
303static PetscErrorCode CreateCheckpointDirectoryCollective(const SimCtx *simCtx, const char *path)
304{
305 PetscMPIInt create_failed = 0;
306
307 PetscFunctionBeginUser;
309 PetscCheck(simCtx != NULL && path != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
310 "Simulation context and directory path are required.");
311 if (simCtx->rank == 0 && mkdir(path, 0777) != 0) {
312 struct stat directory_stat;
313 if (errno != EEXIST || stat(path, &directory_stat) != 0 || !S_ISDIR(directory_stat.st_mode)) {
314 create_failed = 1;
315 }
316 }
317 PetscCallMPI(MPI_Bcast(&create_failed, 1, MPI_INT, 0, PETSC_COMM_WORLD));
318 PetscCheck(!create_failed, PETSC_COMM_WORLD, PETSC_ERR_FILE_OPEN,
319 "Unable to create checkpoint directory '%s'.", path);
321 PetscFunctionReturn(0);
322}
323
324/** @brief Validate a committed bundle and return selected authoritative metadata; a NULL @p user skips the geometry comparison. */
325static PetscErrorCode ValidateCheckpointBundle(SimCtx *simCtx, UserCtx *user,
326 const char *checkpoint_directory,
327 PetscInt expected_step,
328 PetscReal *physical_time,
329 PetscInt *particle_count,
330 PetscBool *particles_saved,
331 PetscBool *les_saved,
332 PetscBool *inflow_saved)
333{
334 char metadata_path[PETSC_MAX_PATH_LEN];
335 char commit_path[PETSC_MAX_PATH_LEN];
336 char expected_digest[65] = "";
337 char actual_digest[65] = "";
338 char format[64] = "";
339 char saved_geometry_digest[65] = "";
340 char current_geometry_digest[65] = "";
341 PetscOptions options = NULL;
342 PetscInt version = 0;
343 PetscInt saved_step = -1;
344 PetscInt payload_count = 0;
345 PetscInt saved_particle_count = 0;
346 PetscReal saved_time = 0.0;
347 PetscBool saved_particles = PETSC_FALSE;
348 PetscBool saved_les = PETSC_FALSE;
349 PetscBool saved_inflow = PETSC_FALSE;
350 PetscBool found = PETSC_FALSE;
351 FILE *commit_file = NULL;
352
353 PetscFunctionBeginUser;
355 PetscCheck(simCtx != NULL && checkpoint_directory != NULL,
356 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Checkpoint validation inputs cannot be NULL.");
357 PetscCall(PetscSNPrintf(metadata_path, sizeof(metadata_path), "%s/checkpoint.meta", checkpoint_directory));
358 PetscCall(PetscSNPrintf(commit_path, sizeof(commit_path), "%s/COMMITTED", checkpoint_directory));
359
360 PetscCall(PetscTestFile(metadata_path, 'r', &found));
361 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_OPEN,
362 "Checkpoint metadata is missing: %s", metadata_path);
363 PetscCall(PetscTestFile(commit_path, 'r', &found));
364 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_OPEN,
365 "Checkpoint is not committed: %s", checkpoint_directory);
366
367 commit_file = fopen(commit_path, "r");
368 PetscCheck(commit_file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
369 "Unable to read checkpoint commit marker '%s'.", commit_path);
370 PetscCheck(fgets(expected_digest, sizeof(expected_digest), commit_file) != NULL,
371 PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
372 "Checkpoint commit marker '%s' is empty.", commit_path);
373 PetscCheck(fclose(commit_file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
374 "Unable to close checkpoint commit marker '%s'.", commit_path);
375 TrimWhitespace(expected_digest);
376 PetscCheck(strlen(expected_digest) == 64, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
377 "Checkpoint commit marker '%s' does not contain a SHA-256 digest.", commit_path);
378 PetscCall(PicurvSHA256File(metadata_path, actual_digest));
379 PetscCheck(!strcmp(expected_digest, actual_digest), PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
380 "Checkpoint metadata hash mismatch in '%s'.", checkpoint_directory);
381
382 PetscCall(PetscOptionsCreate(&options));
383 PetscCall(PetscOptionsInsertFile(PETSC_COMM_WORLD, options, metadata_path, PETSC_TRUE));
384 PetscCall(PetscOptionsGetString(options, NULL, "-checkpoint_format", format, sizeof(format), &found));
385 PetscCheck(found && !strcmp(format, PICURV_CHECKPOINT_FORMAT), PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
386 "Unsupported checkpoint format '%s' in '%s'.", found ? format : "<missing>", metadata_path);
387 PetscCall(PetscOptionsGetInt(options, NULL, "-checkpoint_version", &version, &found));
388 PetscCheck(found && version == PICURV_CHECKPOINT_VERSION, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
389 "Unsupported checkpoint version %" PetscInt_FMT " in '%s'; expected %d.",
390 version, metadata_path, PICURV_CHECKPOINT_VERSION);
391 /* PETSc binary files store sizes as PetscInt, so a payload is readable only by a build with
392 the same index width; a checkpoint written before the width was recorded is 32-bit. */
393 {
394 PetscInt index_bytes = 4;
395 PetscCall(PetscOptionsGetInt(options, NULL, "-checkpoint_petsc_index_bytes", &index_bytes, NULL));
396 PetscCheck(index_bytes == (PetscInt)sizeof(PetscInt), PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
397 "Checkpoint '%s' was written by a PETSc with %" PetscInt_FMT "-byte indices; this build uses "
398 "%d-byte indices. Restart or post-process it with a PICurv built on a %" PetscInt_FMT "-bit-index PETSc.",
399 checkpoint_directory, index_bytes, (int)sizeof(PetscInt), 8 * index_bytes);
400 }
401 PetscCall(PetscOptionsGetInt(options, NULL, "-checkpoint_step", &saved_step, &found));
402 PetscCheck(found && saved_step == expected_step, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
403 "Checkpoint step is %" PetscInt_FMT ", expected %" PetscInt_FMT ".",
404 saved_step, expected_step);
405 PetscCall(PetscOptionsGetReal(options, NULL, "-checkpoint_time", &saved_time, &found));
406 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
407 "Checkpoint '%s' does not record physical time.", metadata_path);
408 PetscCall(PetscOptionsGetString(options, NULL, "-checkpoint_geometry_sha256",
409 saved_geometry_digest, sizeof(saved_geometry_digest), &found));
410 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
411 "Checkpoint '%s' does not record geometry identity.", metadata_path);
412 /* Without a grid (a restart check before setup) there is no active geometry to compare. */
413 if (user) {
414 PetscCall(ComputeCheckpointGeometrySHA256(simCtx, user, current_geometry_digest));
415 PetscCheck(!strcmp(saved_geometry_digest, current_geometry_digest), PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
416 "Checkpoint geometry/layout does not match the active grid.");
417 }
418
419 PetscCall(PetscOptionsGetInt(options, NULL, "-checkpoint_payload_count", &payload_count, &found));
420 PetscCheck(found && payload_count > 0, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
421 "Checkpoint '%s' has no payload inventory.", metadata_path);
422 PetscCall(PetscOptionsGetInt(options, NULL, "-checkpoint_particle_count",
423 &saved_particle_count, &found));
424 PetscCheck(found && saved_particle_count >= 0, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
425 "Checkpoint '%s' has no valid particle count.", metadata_path);
426 PetscCall(PetscOptionsGetBool(options, NULL, "-checkpoint_particles", &saved_particles, &found));
427 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
428 "Checkpoint '%s' does not record particle-state availability.", metadata_path);
429 PetscCall(PetscOptionsGetBool(options, NULL, "-checkpoint_les", &saved_les, &found));
430 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
431 "Checkpoint '%s' does not record LES-state availability.", metadata_path);
432 /* Absent from checkpoints written before inlets had synthetic fluctuations: none saved. */
433 PetscCall(PetscOptionsGetBool(options, NULL, "-checkpoint_inflow_fluctuation", &saved_inflow, NULL));
434 for (PetscInt payload = 0; payload < payload_count; ++payload) {
435 char option_name[96];
436 char relative_path[PETSC_MAX_PATH_LEN];
437 char payload_path[PETSC_MAX_PATH_LEN];
438 long long expected_bytes = -1;
439 char expected_bytes_text[64];
440 struct stat payload_stat;
441
442 PetscCall(PetscSNPrintf(option_name, sizeof(option_name),
443 "-checkpoint_payload_%" PetscInt_FMT "_path", payload));
444 PetscCall(PetscOptionsGetString(options, NULL, option_name,
445 relative_path, sizeof(relative_path), &found));
446 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
447 "Checkpoint payload %" PetscInt_FMT " has no path.", payload);
448 PetscCall(PetscSNPrintf(option_name, sizeof(option_name),
449 "-checkpoint_payload_%" PetscInt_FMT "_bytes", payload));
450 PetscCall(PetscOptionsGetString(options, NULL, option_name,
451 expected_bytes_text, sizeof(expected_bytes_text), &found));
452 if (found) expected_bytes = strtoll(expected_bytes_text, NULL, 10);
453 PetscCheck(found && expected_bytes >= 0, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
454 "Checkpoint payload %" PetscInt_FMT " has no valid byte size.", payload);
455 PetscCall(PetscSNPrintf(payload_path, sizeof(payload_path), "%s/%s",
456 checkpoint_directory, relative_path));
457 PetscCheck(stat(payload_path, &payload_stat) == 0 && S_ISREG(payload_stat.st_mode),
458 PETSC_COMM_WORLD, PETSC_ERR_FILE_OPEN,
459 "Checkpoint payload is missing: %s", payload_path);
460 PetscCheck((long long)payload_stat.st_size == expected_bytes,
461 PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
462 "Checkpoint payload '%s' is %lld bytes; expected %lld.",
463 payload_path, (long long)payload_stat.st_size, expected_bytes);
464 }
465 PetscCall(PetscOptionsDestroy(&options));
466 if (physical_time) *physical_time = saved_time;
467 if (particle_count) *particle_count = saved_particle_count;
468 if (particles_saved) *particles_saved = saved_particles;
469 if (les_saved) *les_saved = saved_les;
470 if (inflow_saved) *inflow_saved = saved_inflow;
472 PetscFunctionReturn(0);
473}
474
475
476// =============================================================================
477// PUBLIC FUNCTION IMPLEMENTATIONS
478// =============================================================================
479
480/**
481 * @brief Implementation of \ref TrimWhitespace().
482 * @details Full API contract (arguments, ownership, side effects) is documented with
483 * the header declaration in `include/io.h`.
484 * @see TrimWhitespace()
485 */
486void TrimWhitespace(char *str) {
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}
513
514/**
515 * @brief Implementation of \ref ShouldWriteDataOutput().
516 * @details Full API contract (arguments, ownership, side effects) is documented with
517 * the header declaration in `include/io.h`.
518 * @see ShouldWriteDataOutput()
519 */
520
521PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step)
522{
524 if (!simCtx) {
526 return PETSC_FALSE;
527 }
529 return (PetscBool)(simCtx->tiout > 0 && completed_step > 0 && completed_step % simCtx->tiout == 0);
530}
531
532
533/**
534 * @brief Implementation of \ref ReadGridGenerationInputs().
535 * @see ReadGridGenerationInputs()
536 */
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}
631
632/**
633 * @brief Implementation of \ref ReadGridFile().
634 * @see ReadGridFile()
635 */
636PetscErrorCode ReadGridFile(UserCtx *user)
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}
705
706
707//================================================================================
708//
709// PRIVATE HELPER FUNCTIONS
710//
711//================================================================================
712
713/**
714 * @brief Implementation of \ref FreeBC_ParamList().
715 * @details Full API contract (arguments, ownership, side effects) is documented with
716 * the header declaration in `include/io.h`.
717 * @see FreeBC_ParamList()
718 */
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}
731
732/**
733 * @brief Implementation of \ref StringToBCFace().
734 * @see StringToBCFace()
735 */
736PetscErrorCode StringToBCFace(const char* str, BCFace* face_out) {
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}
748
749/**
750 * @brief Implementation of \ref StringToBCType().
751 * @see StringToBCType()
752 */
753PetscErrorCode StringToBCType(const char* str, BCType* type_out) {
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}
768
769/**
770 * @brief Implementation of \ref StringToBCHandlerType().
771 * @see StringToBCHandlerType()
772 */
773PetscErrorCode StringToBCHandlerType(const char* str, BCHandlerType* handler_out) {
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}
788
789/**
790 * @brief Implementation of \ref ValidateBCHandlerForBCType().
791 * @see ValidateBCHandlerForBCType()
792 */
793PetscErrorCode ValidateBCHandlerForBCType(BCType type, BCHandlerType handler) {
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}
814
815/**
816 * @brief Implementation of \ref GetBCParamReal().
817 * @see GetBCParamReal()
818 */
819PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
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}
831
832/**
833 * @brief Implementation of \ref GetBCParamBool().
834 * @see GetBCParamBool()
835 */
836PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
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}
852
853/**
854 * @brief Implementation of \ref GetBCParamString().
855 * @details Full API contract (arguments, ownership, side effects) is documented with
856 * the header declaration in `include/io.h`.
857 * @see GetBCParamString()
858 */
859PetscErrorCode GetBCParamString(BC_Param *params, const char *key, const char **value_out, PetscBool *found)
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}
876
877/**
878 * @brief Implementation of \ref GetDrivenSeamFluxFlag().
879 * @details The option was originally spelled `apply_trim`, which said that
880 * something was trimmed but not what or why. The canonical name is now
881 * `enforce_seam_flux`. Generated `bcs.run` files carry the canonical
882 * name, but a hand-written or archived one may still use the old
883 * spelling, so both are accepted here and the canonical name wins.
884 * The argument contract lives with the header declaration in
885 * `include/io.h`.
886 * @see GetDrivenSeamFluxFlag()
887 */
888PetscErrorCode GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found)
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}
901
902//================================================================================
903//
904// PUBLIC PARSING FUNCTION
905//
906//================================================================================
907/**
908 * @brief Implementation of \ref ParseAllBoundaryConditions().
909 * @see ParseAllBoundaryConditions()
910 */
911PetscErrorCode ParseAllBoundaryConditions(UserCtx *user, const char *bcs_input_filename)
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}
1084
1085//================================================================================
1086//
1087// PRIVATE HELPER FUNCTIONS
1088//
1089//================================================================================
1090
1091// ... (existing helper functions like FreeBC_ParamList, StringToBCFace, etc.) ...
1092/**
1093 * @brief Implementation of \ref DeterminePeriodicity().
1094 * @see DeterminePeriodicity()
1095 */
1096PetscErrorCode DeterminePeriodicity(SimCtx *simCtx)
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}
1197
1198/**
1199 * @brief Implementation of \ref VerifyPathExistence().
1200 * @see VerifyPathExistence()
1201 */
1202PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists)
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}
1243
1244/**
1245 * @brief Implementation of \ref ReadFieldData().
1246 * @see ReadFieldData()
1247 */
1248PetscErrorCode ReadFieldData(UserCtx *user,
1249 const char *field_name,
1250 Vec field_vec,
1251 const char *ext)
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}
1314
1315
1316/**
1317 * @brief Restore a latched driven-flow flux target from a checkpoint manifest.
1318 *
1319 * @details Only `initial_flux` needs this. Its target is derived from the field
1320 * the run originally started with, so re-measuring it after a restart
1321 * would silently retarget the controller at whatever the flux had
1322 * drifted to. `constant_flux` reads its target from the bcs file on
1323 * every run and is deliberately left alone, so that editing
1324 * `target_flux` between segments still takes effect.
1325 *
1326 * Checkpoints written before this metadata existed simply have no
1327 * entry; the controller then falls back to re-measuring and says so.
1328 *
1329 * @param[in,out] simCtx Simulation context receiving the target.
1330 * @param[in] user Block context, for its boundary handler types.
1331 * @param[in] checkpoint_directory Directory holding the validated manifest.
1332 * @return PetscErrorCode 0 on success.
1333 */
1334static PetscErrorCode RestoreDrivenFluxTarget(SimCtx *simCtx, UserCtx *user,
1335 const char *checkpoint_directory)
1336{
1337 char metadata_path[PETSC_MAX_PATH_LEN];
1338 PetscOptions options = NULL;
1339 PetscBool uses_initial_flux = PETSC_FALSE;
1340 PetscBool saved_latched = PETSC_FALSE;
1341 PetscBool found = PETSC_FALSE;
1342 PetscReal saved_target = 0.0;
1343
1344 PetscFunctionBeginUser;
1346
1347 for (PetscInt face = 0; face < 6; ++face) {
1349 uses_initial_flux = PETSC_TRUE;
1350 break;
1351 }
1352 }
1353 if (!uses_initial_flux) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1354
1355 PetscCall(PetscSNPrintf(metadata_path, sizeof(metadata_path),
1356 "%s/checkpoint.meta", checkpoint_directory));
1357 PetscCall(PetscOptionsCreate(&options));
1358 PetscCall(PetscOptionsInsertFile(PETSC_COMM_WORLD, options, metadata_path, PETSC_TRUE));
1359 PetscCall(PetscOptionsGetBool(options, NULL, "-checkpoint_driven_flux_latched", &saved_latched, &found));
1360 if (found && saved_latched) {
1361 PetscCall(PetscOptionsGetReal(options, NULL, "-checkpoint_driven_flux_target", &saved_target, &found));
1362 } else {
1363 found = PETSC_FALSE;
1364 }
1365 PetscCall(PetscOptionsDestroy(&options));
1366
1367 if (found) {
1368 simCtx->targetVolumetricFlux = saved_target;
1369 simCtx->drivenFluxTargetLatched = PETSC_TRUE;
1371 "Driven Flow: restored latched target volumetric flux %.6e from checkpoint '%s'.\n",
1372 (double)saved_target, checkpoint_directory);
1373 } else {
1375 "Driven Flow: checkpoint '%s' records no latched flux target; the initial_flux "
1376 "controller will re-measure it from the restarted field.\n", checkpoint_directory);
1377 }
1378
1380 PetscFunctionReturn(0);
1381}
1382
1383/**
1384 * @brief Implementation of \ref ReadSimulationFields().
1385 * @see ReadSimulationFields()
1386 */
1387PetscErrorCode ReadSimulationFields(UserCtx *user,PetscInt ti)
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}
1469
1470
1471/** @brief Restore one window's scalar bookkeeping from a validated manifest. */
1472static PetscErrorCode ReadStatisticsWindowState(PetscOptions options, PetscInt window,
1473 const char *metadata_path, PetscReal checkpoint_time,
1474 PetscReal step_size, ExecutionMode exec_mode,
1475 PicurvWindow *state)
1476{
1477 char option_name[128];
1478 char saved_name[PICURV_WINDOW_NAME_LENGTH] = "";
1479 char saved_digest[65] = "";
1481 char saved_state[32] = "";
1482 char current_digest[65] = "";
1483 PetscBool found = PETSC_FALSE;
1484 PetscBool name_matches = PETSC_FALSE;
1485
1486 PetscFunctionBeginUser;
1488
1489#define PICURV_STATISTICS_REQUIRE(suffix, getter, target) \
1490 do { \
1491 PetscCall(PetscSNPrintf(option_name, sizeof(option_name), \
1492 "-checkpoint_statistics_window_%" PetscInt_FMT "_" suffix, window)); \
1493 PetscCall(getter(options, NULL, option_name, target, &found)); \
1494 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED, \
1495 "Statistics continuation requested, but '%s' records no %s for window " \
1496 "%" PetscInt_FMT ".", metadata_path, suffix, window); \
1497 } while (0)
1498
1499 PetscCall(PetscSNPrintf(option_name, sizeof(option_name),
1500 "-checkpoint_statistics_window_%" PetscInt_FMT "_name", window));
1501 PetscCall(PetscOptionsGetString(options, NULL, option_name, saved_name, sizeof(saved_name), &found));
1502 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
1503 "Statistics continuation requested, but '%s' records no name for window %" PetscInt_FMT ".",
1504 metadata_path, window);
1505 PetscCall(PetscStrcmp(saved_name, state->definition.name, &name_matches));
1506 PetscCheck(name_matches, PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
1507 "Statistics window %" PetscInt_FMT " is '%s' in the checkpoint but '%s' in this run. "
1508 "Window order and names must match to continue.",
1509 window, saved_name, state->definition.name);
1510
1511 PetscCall(PetscSNPrintf(option_name, sizeof(option_name),
1512 "-checkpoint_statistics_window_%" PetscInt_FMT "_hash", window));
1513 PetscCall(PetscOptionsGetString(options, NULL, option_name, saved_digest, sizeof(saved_digest), &found));
1514 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
1515 "Statistics continuation requested, but '%s' records no hash for window '%s'.",
1516 metadata_path, state->definition.name);
1517 PetscCall(PicurvWindowComputeHash(&state->definition, current_digest, NULL));
1518 if (strcmp(saved_digest, current_digest)) {
1519 const char *differing = "an unrecorded property";
1520
1521 /* The saved definition itself is not stored, so the per-group digests are
1522 * what make it possible to name the property that changed rather than
1523 * reporting only that two opaque hashes differ. */
1524 PetscCall(PetscSNPrintf(option_name, sizeof(option_name),
1525 "-checkpoint_statistics_window_%" PetscInt_FMT "_hash_groups", window));
1526 PetscCall(PetscOptionsGetString(options, NULL, option_name, saved_groups,
1527 sizeof(saved_groups), &found));
1528 if (found) {
1529 PetscInt group = -1;
1530
1531 PetscCall(PicurvWindowFirstHashDifference(&state->definition, saved_groups, &group));
1532 if (group >= 0) differing = PicurvWindowHashGroupName(group);
1533 }
1534 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
1535 "Statistics window '%s' was defined differently in the checkpoint: %s changed. "
1536 "Continuing would merge incompatible samples; rename the window to start a new one.",
1537 state->definition.name, differing);
1538 }
1539
1540 PICURV_STATISTICS_REQUIRE("sample_count", PetscOptionsGetInt, &state->sample_count);
1541 PICURV_STATISTICS_REQUIRE("total_weight", PetscOptionsGetReal, &state->total_weight);
1542 PICURV_STATISTICS_REQUIRE("represented_time", PetscOptionsGetReal, &state->represented_time);
1543 PICURV_STATISTICS_REQUIRE("last_accepted_time", PetscOptionsGetReal, &state->last_accepted_time);
1544 PICURV_STATISTICS_REQUIRE("effective_start", PetscOptionsGetReal, &state->effective_start);
1545 PICURV_STATISTICS_REQUIRE("effective_end", PetscOptionsGetReal, &state->effective_end);
1546 PICURV_STATISTICS_REQUIRE("activation_step", PetscOptionsGetInt, &state->activation_step);
1547 PICURV_STATISTICS_REQUIRE("last_event_step", PetscOptionsGetInt, &state->last_event_step);
1548 PICURV_STATISTICS_REQUIRE("next_time_target", PetscOptionsGetInt, &state->next_time_target);
1549 PICURV_STATISTICS_REQUIRE("restart_count", PetscOptionsGetInt, &state->restart_count);
1550#undef PICURV_STATISTICS_REQUIRE
1551
1552 PetscCall(PetscSNPrintf(option_name, sizeof(option_name),
1553 "-checkpoint_statistics_window_%" PetscInt_FMT "_state", window));
1554 PetscCall(PetscOptionsGetString(options, NULL, option_name, saved_state, sizeof(saved_state), &found));
1555 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
1556 "Statistics continuation requested, but '%s' records no lifecycle state for window '%s'.",
1557 metadata_path, state->definition.name);
1558 if (!strcmp(saved_state, "complete")) state->state = PICURV_WINDOW_COMPLETE;
1559 else if (!strcmp(saved_state, "active")) state->state = PICURV_WINDOW_ACTIVE;
1560 else state->state = PICURV_WINDOW_PENDING;
1561
1562 /* A window saved as complete may still be resumable: page 58 §10 permits moving
1563 * a bounded end forward, and the end time is deliberately outside the hash. */
1564 if (state->state == PICURV_WINDOW_COMPLETE && state->definition.bounded &&
1565 state->definition.end_time > state->effective_end) {
1566 /* Only across an unbroken span. Under right-rectangle weighting the first
1567 * sample after the former end carries the whole interval back to it, so
1568 * resuming across a gap would weight time the window never observed. One
1569 * step of slack is the closing state's own clipping, not a gap. */
1570 PetscCheck(checkpoint_time - state->effective_end <= PetscMax(step_size, 0.0),
1571 PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
1572 "Statistics window '%s' ended at t=%.17g and this checkpoint is at t=%.17g, "
1573 "so extending it to %.17g would weight %.17g of unobserved time. "
1574 "Start a new window instead.",
1575 state->definition.name, (double)state->effective_end, (double)checkpoint_time,
1576 (double)state->definition.end_time,
1577 (double)(checkpoint_time - state->effective_end));
1579 "Statistics window '%s' was complete at t=%.6g and is extended to t=%.6g.\n",
1580 state->definition.name, (double)state->effective_end,
1581 (double)state->definition.end_time);
1582 state->state = PICURV_WINDOW_ACTIVE;
1583 }
1584 PetscCheck(!state->definition.bounded || state->definition.end_time >= state->effective_end,
1585 PETSC_COMM_WORLD, PETSC_ERR_ARG_INCOMP,
1586 "Statistics window '%s' already represents time up to %.17g, past the requested end "
1587 "%.17g. A window may be extended forward but never shortened; rename it to start a new one.",
1588 state->definition.name, (double)state->effective_end,
1589 (double)state->definition.end_time);
1590 /* A post-processing read is analysis, not a continuation, so it must not look
1591 * like another restart segment. Only a solver resuming the window advances the
1592 * lineage; otherwise deriving a series of steps would inflate it once per step. */
1593 if (exec_mode == EXEC_MODE_SOLVER) state->restart_count += 1;
1595 PetscFunctionReturn(0);
1596}
1597
1598/**
1599 * @brief Implementation of \ref RestoreFieldStatisticsState().
1600 * @details Full API contract (arguments, ownership, side effects) is documented with
1601 * the header declaration in `include/io.h`.
1602 * @see RestoreFieldStatisticsState()
1603 */
1604PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
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 }
1634 source_path = (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) ? simCtx->pps->source_dir
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,
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}
1709
1710/**
1711 * @brief Implementation of \ref ReadSwarmField().
1712 * @see ReadSwarmField()
1713 */
1714PetscErrorCode ReadSwarmField(UserCtx *user, const char *field_name, const char *ext)
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}
1741
1742/**
1743 * @brief Implementation of \ref ReadSwarmIntField().
1744 * @see ReadSwarmIntField()
1745 */
1746PetscErrorCode ReadSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
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}
1810
1811/**
1812 * @brief Implementation of \ref ReadAllSwarmFields().
1813 * @see ReadAllSwarmFields()
1814 */
1815PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti)
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}
1866
1867/** @brief Implementation of \ref ReadCheckpointParticleCount(). */
1868PetscErrorCode ReadCheckpointParticleCount(UserCtx *user, PetscInt ti, PetscInt *particle_count)
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}
1895
1896
1897/**
1898 * @brief Implementation of \ref WriteFieldData().
1899 * @see WriteFieldData()
1900 */
1901PetscErrorCode WriteFieldData(UserCtx *user,
1902 const char *field_name,
1903 Vec field_vec,
1904 const char *ext)
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}
1947
1948/**
1949 * @brief Implementation of \ref WriteSimulationFields().
1950 * @details Full API contract (arguments, ownership, side effects) is documented with
1951 * the header declaration in `include/io.h`.
1952 * @see WriteSimulationFields()
1953 */
1954PetscErrorCode WriteSimulationFields(UserCtx *user, const char *checkpoint_directory)
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}
1987
1988/** @brief Write every window's accumulator payloads for one block into a bundle. */
1989static PetscErrorCode WriteStatisticsFields(UserCtx *user, const char *checkpoint_directory)
1990{
1991 SimCtx *simCtx = user->simCtx;
1992
1993 PetscFunctionBeginUser;
1995 PetscCheck(checkpoint_directory != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1996 "Checkpoint destination cannot be NULL.");
1997 if (!FieldStatisticsIsActive(simCtx) || !user->fieldStatisticsStorage) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1998
1999 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
2000 const PicurvWindowStorage *storage = &user->fieldStatisticsStorage[window];
2001 PetscInt payload_count = 0;
2002
2003 PetscCall(FormatStatisticsPath(checkpoint_directory, window, user->_this, NULL,
2004 simCtx->_io_context_buffer,
2005 sizeof(simCtx->_io_context_buffer)));
2006 simCtx->current_io_directory = simCtx->_io_context_buffer;
2007 PetscCall(PicurvWindowStoragePayloadCount(storage, &payload_count));
2008 for (PetscInt index = 0; index < payload_count; ++index) {
2010
2011 PetscCall(PicurvWindowStoragePayload(user, &simCtx->fieldStatisticsWindows[window].definition,
2012 storage, index, &payload));
2013 PetscCall(WriteFieldData(user, payload.name, payload.vec, "dat"));
2014 }
2016 "Wrote %d statistics payload(s) for window '%s' block %d.\n",
2017 (int)payload_count, simCtx->fieldStatisticsWindows[window].definition.name,
2018 (int)user->_this);
2019 }
2020 simCtx->current_io_directory = NULL;
2022 PetscFunctionReturn(0);
2023}
2024
2025/**
2026 * @brief Implementation of \ref WriteSwarmField().
2027 * @details Full API contract (arguments, ownership, side effects) is documented with
2028 * the header declaration in `include/io.h`.
2029 * @see WriteSwarmField()
2030 */
2031PetscErrorCode WriteSwarmField(UserCtx *user, const char *field_name, const char *ext)
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}
2083
2084/**
2085 * @brief Implementation of \ref WriteSwarmIntField().
2086 * @see WriteSwarmIntField()
2087 */
2088PetscErrorCode WriteSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
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}
2150
2151/**
2152 * @brief Implementation of \ref WriteAllSwarmFields().
2153 * @see WriteAllSwarmFields()
2154 */
2155PetscErrorCode WriteAllSwarmFields(UserCtx *user, const char *checkpoint_directory)
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}
2191
2192/** @brief Append one payload inventory entry to a checkpoint manifest. */
2193static PetscErrorCode WriteCheckpointPayloadEntry(FILE *manifest,
2194 const char *checkpoint_directory,
2195 PetscInt payload_index,
2196 const char *relative_path,
2197 const char *kind,
2198 const char *field_name,
2199 PetscInt block,
2200 const char *layout,
2201 PetscInt components,
2202 const char *logical_type,
2203 PetscInt global_size,
2204 const char *encoding)
2205{
2206 char payload_path[PETSC_MAX_PATH_LEN];
2207 struct stat payload_stat;
2208
2209 PetscFunctionBeginUser;
2211 PetscCheck(manifest != NULL && checkpoint_directory != NULL && relative_path != NULL,
2212 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Checkpoint payload metadata inputs are required.");
2213 PetscCall(PetscSNPrintf(payload_path, sizeof(payload_path), "%s/%s",
2214 checkpoint_directory, relative_path));
2215 PetscCheck(stat(payload_path, &payload_stat) == 0 && S_ISREG(payload_stat.st_mode),
2216 PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
2217 "Expected checkpoint payload was not written: %s", payload_path);
2218 PetscCheck(fprintf(manifest,
2219 "-checkpoint_payload_%" PetscInt_FMT "_path %s\n"
2220 "-checkpoint_payload_%" PetscInt_FMT "_kind %s\n"
2221 "-checkpoint_payload_%" PetscInt_FMT "_field %s\n"
2222 "-checkpoint_payload_%" PetscInt_FMT "_block %" PetscInt_FMT "\n"
2223 "-checkpoint_payload_%" PetscInt_FMT "_layout %s\n"
2224 "-checkpoint_payload_%" PetscInt_FMT "_components %" PetscInt_FMT "\n"
2225 "-checkpoint_payload_%" PetscInt_FMT "_logical_type %s\n"
2226 "-checkpoint_payload_%" PetscInt_FMT "_global_size %" PetscInt_FMT "\n"
2227 "-checkpoint_payload_%" PetscInt_FMT "_encoding %s\n"
2228 "-checkpoint_payload_%" PetscInt_FMT "_bytes %lld\n",
2229 payload_index, relative_path,
2230 payload_index, kind,
2231 payload_index, field_name,
2232 payload_index, block,
2233 payload_index, layout,
2234 payload_index, components,
2235 payload_index, logical_type,
2236 payload_index, global_size,
2237 payload_index, encoding,
2238 payload_index, (long long)payload_stat.st_size) > 0,
2239 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2240 "Unable to append payload metadata for '%s'.", relative_path);
2242 PetscFunctionReturn(0);
2243}
2244
2245/** @brief Write the complete manifest after every payload has closed successfully. */
2246static PetscErrorCode WriteCheckpointManifest(SimCtx *simCtx, UserCtx *user,
2247 const char *checkpoint_directory,
2248 const char *reason,
2249 const char *geometry_digest,
2250 PetscInt particle_count,
2251 char manifest_digest[65])
2252{
2253 char metadata_path[PETSC_MAX_PATH_LEN];
2254 PetscInt payload_count = 0;
2255 PetscInt payload_index = 0;
2256 FILE *manifest = NULL;
2257
2258 PetscFunctionBeginUser;
2260 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2261 for (PetscInt raw_id = 0; raw_id < FIELD_ID_COUNT; ++raw_id) {
2262 const FieldDescriptor *descriptor = NULL;
2263 PetscCall(FieldGetDescriptor((FieldId)raw_id, &descriptor));
2264 if (CheckpointFieldIsEnabled(simCtx, descriptor)) ++payload_count;
2265 }
2266 }
2267 if (ParticlesEnabled(simCtx)) {
2268 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
2269 const ParticleFieldDescriptor *descriptor = NULL;
2270 PetscCall(ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor));
2271 if (descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_CHECKPOINT) ++payload_count;
2272 }
2273 }
2274 if (FieldStatisticsIsActive(simCtx)) {
2275 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2276 if (!user[block].fieldStatisticsStorage) continue;
2277 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
2278 PetscInt storage_payloads = 0;
2279
2280 PetscCall(PicurvWindowStoragePayloadCount(&user[block].fieldStatisticsStorage[window],
2281 &storage_payloads));
2282 payload_count += storage_payloads;
2283 }
2284 }
2285 }
2286
2287 if (simCtx->rank == 0) {
2288 PetscCall(PetscSNPrintf(metadata_path, sizeof(metadata_path),
2289 "%s/checkpoint.meta", checkpoint_directory));
2290 manifest = fopen(metadata_path, "w");
2291 PetscCheck(manifest != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
2292 "Unable to create checkpoint metadata '%s'.", metadata_path);
2293 PetscCheck(fprintf(manifest,
2294 "-checkpoint_format %s\n"
2295 "-checkpoint_version %d\n"
2296 "-checkpoint_picurv_release %s\n"
2297 "-checkpoint_picurv_commit %s\n"
2298 "-checkpoint_picurv_dirty %s\n"
2299 "-checkpoint_petsc_index_bytes %d\n"
2300 "-checkpoint_step %" PetscInt_FMT "\n"
2301 "-checkpoint_time %.17g\n"
2302 "-checkpoint_dt %.17g\n"
2303 "-checkpoint_reason %s\n"
2304 "-checkpoint_geometry_sha256 %s\n"
2305 "-checkpoint_block_count %" PetscInt_FMT "\n"
2306 "-checkpoint_particles %s\n"
2307 "-checkpoint_particle_count %" PetscInt_FMT "\n"
2308 "-checkpoint_les %s\n"
2309 "-checkpoint_inflow_fluctuation %s\n"
2310 "-checkpoint_payload_count %" PetscInt_FMT "\n",
2313 (int)sizeof(PetscInt), simCtx->step, (double)simCtx->ti, (double)simCtx->dt,
2314 reason, geometry_digest, simCtx->block_number,
2315 ParticlesEnabled(simCtx) ? "true" : "false",
2316 particle_count,
2317 simCtx->les ? "true" : "false",
2318 simCtx->inflowFluctuations ? "true" : "false",
2319 payload_count) > 0,
2320 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2321 "Unable to write checkpoint metadata '%s'.", metadata_path);
2322
2323 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2324 PetscCheck(fprintf(manifest,
2325 "-checkpoint_block_%" PetscInt_FMT "_im %" PetscInt_FMT "\n"
2326 "-checkpoint_block_%" PetscInt_FMT "_jm %" PetscInt_FMT "\n"
2327 "-checkpoint_block_%" PetscInt_FMT "_km %" PetscInt_FMT "\n",
2328 block, user[block].IM, block, user[block].JM, block, user[block].KM) > 0,
2329 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2330 "Unable to write block metadata for block %" PetscInt_FMT ".", block);
2331 }
2332 PetscCheck(fprintf(manifest, "-checkpoint_periodic %d,%d,%d\n",
2333 (int)simCtx->i_periodic, (int)simCtx->j_periodic,
2334 (int)simCtx->k_periodic) > 0,
2335 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2336 "Unable to write checkpoint periodicity metadata.");
2337
2338 /* Driven-flow controller state. `initial_flux` measures its target once
2339 * from the starting field, so a restart must read the latched value back
2340 * rather than re-measure it from a field that has since drifted. */
2341 PetscCheck(fprintf(manifest,
2342 "-checkpoint_driven_flux_latched %s\n"
2343 "-checkpoint_driven_flux_target %.17g\n",
2344 simCtx->drivenFluxTargetLatched ? "true" : "false",
2345 (double)simCtx->targetVolumetricFlux) > 0,
2346 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2347 "Unable to write driven-flow controller metadata.");
2348
2349 /* Window scalars are recorded even when no window is configured, so a
2350 * restart can tell an absent window list from an unreadable bundle. */
2351 PetscCheck(fprintf(manifest, "-checkpoint_statistics_window_count %" PetscInt_FMT "\n",
2352 FieldStatisticsIsActive(simCtx) ? simCtx->fieldStatisticsWindowCount : 0) > 0,
2353 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2354 "Unable to write statistics window count.");
2355 if (FieldStatisticsIsActive(simCtx)) {
2356 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
2357 const PicurvWindow *state = &simCtx->fieldStatisticsWindows[window];
2358 char digest[65] = "";
2360 /* Group digests plus their separators, with headroom so a longer
2361 * digest would not silently truncate into a false match. */
2363 size_t used = 0;
2364
2365 PetscCall(PicurvWindowComputeHash(&state->definition, digest, groups));
2366 for (PetscInt group = 0; group < PICURV_WINDOW_HASH_GROUP_COUNT; ++group) {
2367 PetscCall(PetscStrlen(group_list, &used));
2368 PetscCall(PetscSNPrintf(group_list + used, sizeof(group_list) - used, "%s%s",
2369 group ? "," : "", groups[group]));
2370 }
2371 PetscCheck(fprintf(manifest,
2372 "-checkpoint_statistics_window_%" PetscInt_FMT "_name %s\n"
2373 "-checkpoint_statistics_window_%" PetscInt_FMT "_hash %s\n"
2374 "-checkpoint_statistics_window_%" PetscInt_FMT "_hash_groups %s\n"
2375 "-checkpoint_statistics_window_%" PetscInt_FMT "_state %s\n"
2376 "-checkpoint_statistics_window_%" PetscInt_FMT "_sample_count %" PetscInt_FMT "\n"
2377 "-checkpoint_statistics_window_%" PetscInt_FMT "_total_weight %.17g\n"
2378 "-checkpoint_statistics_window_%" PetscInt_FMT "_represented_time %.17g\n"
2379 "-checkpoint_statistics_window_%" PetscInt_FMT "_last_accepted_time %.17g\n"
2380 "-checkpoint_statistics_window_%" PetscInt_FMT "_effective_start %.17g\n"
2381 "-checkpoint_statistics_window_%" PetscInt_FMT "_effective_end %.17g\n"
2382 "-checkpoint_statistics_window_%" PetscInt_FMT "_activation_step %" PetscInt_FMT "\n"
2383 "-checkpoint_statistics_window_%" PetscInt_FMT "_last_event_step %" PetscInt_FMT "\n"
2384 "-checkpoint_statistics_window_%" PetscInt_FMT "_next_time_target %" PetscInt_FMT "\n"
2385 "-checkpoint_statistics_window_%" PetscInt_FMT "_restart_count %" PetscInt_FMT "\n",
2386 window, state->definition.name,
2387 window, digest,
2388 window, group_list,
2389 window, PicurvWindowStateName(state->state),
2390 window, state->sample_count,
2391 window, (double)state->total_weight,
2392 window, (double)state->represented_time,
2393 window, (double)state->last_accepted_time,
2394 window, (double)state->effective_start,
2395 window, (double)state->effective_end,
2396 window, state->activation_step,
2397 window, state->last_event_step,
2398 window, state->next_time_target,
2399 window, state->restart_count) > 0,
2400 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2401 "Unable to write metadata for statistics window '%s'.",
2402 state->definition.name);
2403 }
2404 }
2405
2406 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2407 for (PetscInt raw_id = 0; raw_id < FIELD_ID_COUNT; ++raw_id) {
2408 const FieldDescriptor *descriptor = NULL;
2409 FieldView view;
2410 PetscInt global_size = 0;
2411 char relative_path[PETSC_MAX_PATH_LEN];
2412
2413 PetscCall(FieldGetDescriptor((FieldId)raw_id, &descriptor));
2414 if (!CheckpointFieldIsEnabled(simCtx, descriptor)) continue;
2415 PetscCall(FieldGetView(&user[block], descriptor->id, &view));
2416 PetscCall(VecGetSize(view.global_vec, &global_size));
2417 PetscCall(PetscSNPrintf(relative_path, sizeof(relative_path),
2418 "%s/block_%04" PetscInt_FMT "/%s.dat",
2419 PICURV_EULERIAN_DIRECTORY, block, descriptor->canonical_name));
2420 PetscCall(WriteCheckpointPayloadEntry(manifest, checkpoint_directory,
2421 payload_index++, relative_path,
2422 "eulerian", descriptor->canonical_name,
2423 block, FieldLayoutName(descriptor->layout),
2424 descriptor->dof, "PetscScalar", global_size,
2425 "petsc_vec_binary_natural"));
2426 }
2427 }
2428 if (ParticlesEnabled(simCtx)) {
2429 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
2430 const ParticleFieldDescriptor *descriptor = NULL;
2431 char relative_path[PETSC_MAX_PATH_LEN];
2432 const char *encoding = "petsc_vec_binary_global";
2433
2434 PetscCall(ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor));
2435 if (!(descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_CHECKPOINT)) continue;
2436 if (descriptor->data_type == PETSC_INT || descriptor->data_type == PETSC_INT64) {
2437 encoding = "petsc_vec_binary_scalar_cast";
2438 }
2439 PetscCall(PetscSNPrintf(relative_path, sizeof(relative_path),
2440 "%s/%s.dat", PICURV_PARTICLE_DIRECTORY,
2441 descriptor->canonical_name));
2442 PetscCall(WriteCheckpointPayloadEntry(manifest, checkpoint_directory,
2443 payload_index++, relative_path,
2444 "particle", descriptor->canonical_name,
2445 -1, "DMSwarm", descriptor->components,
2446 PetscDataTypes[descriptor->data_type],
2447 particle_count * descriptor->components,
2448 encoding));
2449 }
2450 }
2451 if (FieldStatisticsIsActive(simCtx)) {
2452 for (PetscInt block = 0; block < simCtx->block_number; ++block) {
2453 if (!user[block].fieldStatisticsStorage) continue;
2454 for (PetscInt window = 0; window < simCtx->fieldStatisticsWindowCount; ++window) {
2455 const PicurvWindowDefinition *definition =
2456 &simCtx->fieldStatisticsWindows[window].definition;
2457 const PicurvWindowStorage *storage = &user[block].fieldStatisticsStorage[window];
2458 PetscInt storage_payloads = 0;
2459
2460 PetscCall(PicurvWindowStoragePayloadCount(storage, &storage_payloads));
2461 for (PetscInt index = 0; index < storage_payloads; ++index) {
2463 PetscInt global_size = 0;
2464 char relative_path[PETSC_MAX_PATH_LEN];
2465 char qualified_name[PETSC_MAX_PATH_LEN];
2466
2467 PetscCall(PicurvWindowStoragePayload(&user[block], definition, storage,
2468 index, &payload));
2469 PetscCall(VecGetSize(payload.vec, &global_size));
2470 PetscCall(FormatStatisticsPath(NULL, window, block, payload.name,
2471 relative_path, sizeof(relative_path)));
2472 /* The inventory field name is qualified by window so two
2473 * windows accumulating the same field stay distinguishable
2474 * to anything reading the manifest alone. */
2475 PetscCall(PetscSNPrintf(qualified_name, sizeof(qualified_name), "%s/%s",
2476 definition->name, payload.name));
2477 PetscCall(WriteCheckpointPayloadEntry(manifest, checkpoint_directory,
2478 payload_index++, relative_path,
2479 payload.role, qualified_name,
2480 block, payload.layout,
2481 payload.components, "PetscScalar",
2482 global_size,
2483 "petsc_vec_binary_natural"));
2484 }
2485 }
2486 }
2487 }
2488 PetscCheck(fflush(manifest) == 0 && fsync(fileno(manifest)) == 0,
2489 PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2490 "Unable to flush checkpoint metadata '%s'.", metadata_path);
2491 PetscCheck(fclose(manifest) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2492 "Unable to close checkpoint metadata '%s'.", metadata_path);
2493 PetscCall(PicurvSHA256File(metadata_path, manifest_digest));
2494 }
2495 PetscCallMPI(MPI_Bcast(manifest_digest, 65, MPI_CHAR, 0, PETSC_COMM_WORLD));
2497 PetscFunctionReturn(0);
2498}
2499
2500/** @brief Implementation of the transactional full-state checkpoint coordinator. */
2501PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
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}
2628
2629/**
2630 * @brief Emit the rank-zero startup summary from the effective simulation context.
2631 * @details Reports only configuration that applies to the selected run mode. In
2632 * particular, pseudo-CFL is a Dual Time Picard--Jameson RK control and
2633 * is deliberately omitted for explicit and Newton--Krylov momentum solves.
2634 */
2635PetscErrorCode DisplayBanner(SimCtx *simCtx) // bboxlist is only valid on rank 0
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",
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}
2984
2985/** @brief Implementation of \ref PicurvPhysicalTime(). */
2986PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
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}
3000
3001/**
3002 * @brief Implementation of \ref PicurvFieldReferenceScale().
3003 * @details The argument and return contract is documented in `include/io.h`.
3004 * @see PicurvFieldReferenceScale()
3005 */
3006PetscErrorCode PicurvFieldReferenceScale(SimCtx *simCtx, const char *field_name,
3007 PetscReal *scale, char *description,
3008 size_t description_length)
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}
3045
3046
3047/**
3048 * @brief Implementation of \ref ParsePostProcessingSettings().
3049 * @see ParsePostProcessingSettings()
3050 */
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}
3249
3250/**
3251 * @brief Implementation of \ref ParseScalingInformation().
3252 * @details Full API contract (arguments, ownership, side effects) is documented with
3253 * the header declaration in `include/io.h`.
3254 * @see ParseScalingInformation()
3255 */
3256PetscErrorCode ParseScalingInformation(SimCtx *simCtx)
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}
3293
3294/**
3295 * @brief Implementation of \ref ReadDataFileToArray().
3296 * @details Full API contract (arguments, ownership, side effects) is documented with
3297 * the header declaration in `include/io.h`.
3298 * @see ReadDataFileToArray()
3299 */
3300PetscInt ReadDataFileToArray(const char *filename,
3301 double **data_out,
3302 PetscInt *Nout,
3303 MPI_Comm comm)
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}
3434
Small dependency-free SHA-256 utility for persistent metadata identity.
PetscErrorCode PicurvSHA256File(const char *path, char digest_hex[65])
Compute the lowercase SHA-256 digest of a file.
Definition checksum.c:130
void PicurvSHA256Init(PicurvSHA256Context *context)
Initialize an incremental SHA-256 calculation.
Definition checksum.c:62
void PicurvSHA256Update(PicurvSHA256Context *context, const void *data, size_t length)
Add bytes to an incremental SHA-256 calculation.
Definition checksum.c:74
void PicurvSHA256FinalHex(PicurvSHA256Context *context, char digest_hex[65])
Finish a SHA-256 calculation and return a lowercase hexadecimal digest.
Definition checksum.c:98
Incremental SHA-256 state.
Definition checksum.h:14
Authoritative identities and storage metadata for persistent Eulerian fields.
FieldLayout layout
@ FIELD_DIMENSION_FIXED
The exponents are the field's dimension.
PetscErrorCode FieldDimensionReferenceScale(const ScalingCtx *scaling, FieldDimension dimension, PetscReal *scale)
Return the factor that turns a solver value of one dimension into physical units.
@ FIELD_CAPABILITY_CHECKPOINT
@ FIELD_AVAILABILITY_WALL_MODEL
@ FIELD_AVAILABILITY_PARTICLES
@ FIELD_AVAILABILITY_TURBULENCE
@ FIELD_AVAILABILITY_LES_DYNAMIC
@ FIELD_AVAILABILITY_ALWAYS
@ FIELD_AVAILABILITY_INFLOW_FLUCTUATION
unsigned int capabilities
unsigned int availability
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
PetscErrorCode FieldTryIdFromName(const char *field_name, FieldId *field_id, PetscBool *found)
Look a name up without treating an unknown name as an error.
#define FIELD_DIM_TIME
FieldDimension dimension
FieldDimensionKind kind
const char * canonical_name
const char * FieldLayoutName(FieldLayout layout)
Return a stable printable label for a field layout.
PetscErrorCode FieldDimensionLabel(FieldDimension dimension, char *label, size_t length)
Write a printable form of a dimension, such as L^2 U or dimensionless.
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_COORDINATES
@ FIELD_ID_INVALID
@ FIELD_ID_COUNT
Immutable metadata for one field identity.
Physical dimension as exponents of the reference length, velocity, and density.
Non-owning runtime objects resolved for one field and UserCtx.
PetscErrorCode ParsePostProcessingSettings(SimCtx *simCtx)
Implementation of ParsePostProcessingSettings().
Definition io.c:3051
PetscErrorCode ParseScalingInformation(SimCtx *simCtx)
Implementation of ParseScalingInformation().
Definition io.c:3256
PetscInt ReadDataFileToArray(const char *filename, double **data_out, PetscInt *Nout, MPI_Comm comm)
Implementation of ReadDataFileToArray().
Definition io.c:3300
PetscErrorCode ReadGridFile(UserCtx *user)
Implementation of ReadGridFile().
Definition io.c:636
static PetscErrorCode WriteCheckpointPayloadEntry(FILE *manifest, const char *checkpoint_directory, PetscInt payload_index, const char *relative_path, const char *kind, const char *field_name, PetscInt block, const char *layout, PetscInt components, const char *logical_type, PetscInt global_size, const char *encoding)
Append one payload inventory entry to a checkpoint manifest.
Definition io.c:2193
PetscErrorCode StringToBCHandlerType(const char *str, BCHandlerType *handler_out)
Implementation of StringToBCHandlerType().
Definition io.c:773
PetscErrorCode ReadSwarmField(UserCtx *user, const char *field_name, const char *ext)
Implementation of ReadSwarmField().
Definition io.c:1714
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
#define PICURV_CHECKPOINT_STEP_WIDTH
Definition io.c:28
PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
Implementation of GetBCParamReal().
Definition io.c:819
#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 PetscInt * g_IMs_from_file
Caches the IM dimensions for all blocks read from the grid file.
Definition io.c:37
PetscErrorCode WriteSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
Implementation of WriteSwarmIntField().
Definition io.c:2088
PetscErrorCode ReadCheckpointParticleCount(UserCtx *user, PetscInt ti, PetscInt *particle_count)
Implementation of ReadCheckpointParticleCount().
Definition io.c:1868
#define PICURV_STATISTICS_DIRECTORY
Definition io.c:27
PetscErrorCode ReadSimulationFields(UserCtx *user, PetscInt ti)
Implementation of ReadSimulationFields().
Definition io.c:1387
static PetscInt g_nblk_from_file
Stores the number of blocks read from the grid file.
Definition io.c:35
PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step)
Implementation of ShouldWriteDataOutput().
Definition io.c:521
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
#define PICURV_CHECKPOINT_FORMAT
Definition io.c:22
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 GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found)
Implementation of GetDrivenSeamFluxFlag().
Definition io.c:888
PetscErrorCode ParseAllBoundaryConditions(UserCtx *user, const char *bcs_input_filename)
Implementation of ParseAllBoundaryConditions().
Definition io.c:911
PetscErrorCode ValidateBCHandlerForBCType(BCType type, BCHandlerType handler)
Implementation of ValidateBCHandlerForBCType().
Definition io.c:793
void TrimWhitespace(char *str)
Implementation of TrimWhitespace().
Definition io.c:486
PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti)
Implementation of ReadAllSwarmFields().
Definition io.c:1815
PetscErrorCode WriteSimulationFields(UserCtx *user, const char *checkpoint_directory)
Implementation of WriteSimulationFields().
Definition io.c:1954
PetscBool CheckpointFieldIsEnabled(const SimCtx *simCtx, const FieldDescriptor *descriptor)
Implementation of CheckpointFieldIsEnabled().
Definition io.c:75
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 PetscErrorCode CreateCheckpointDirectoryCollective(const SimCtx *simCtx, const char *path)
Create one directory on rank zero and report failures collectively.
Definition io.c:303
static PetscBool g_file_has_been_read
A flag to ensure the grid file is read only once.
Definition io.c:43
PetscErrorCode ReadGridGenerationInputs(UserCtx *user)
Implementation of ReadGridGenerationInputs().
Definition io.c:537
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
PetscErrorCode ReadFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Implementation of ReadFieldData().
Definition io.c:1248
PetscErrorCode DeterminePeriodicity(SimCtx *simCtx)
Implementation of DeterminePeriodicity().
Definition io.c:1096
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 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 RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
Implementation of RestoreFieldStatisticsState().
Definition io.c:1604
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
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
PetscErrorCode StringToBCFace(const char *str, BCFace *face_out)
Implementation of StringToBCFace().
Definition io.c:736
PetscErrorCode GetBCParamString(BC_Param *params, const char *key, const char **value_out, PetscBool *found)
Implementation of GetBCParamString().
Definition io.c:859
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
PetscErrorCode WriteSwarmField(UserCtx *user, const char *field_name, const char *ext)
Implementation of WriteSwarmField().
Definition io.c:2031
PetscErrorCode ReadSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
Implementation of ReadSwarmIntField().
Definition io.c:1746
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
PetscErrorCode WriteFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Implementation of WriteFieldData().
Definition io.c:1901
PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists)
Implementation of VerifyPathExistence().
Definition io.c:1202
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
PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
Implementation of GetBCParamBool().
Definition io.c:836
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
PetscErrorCode DisplayBanner(SimCtx *simCtx)
Emit the rank-zero startup summary from the effective simulation context.
Definition io.c:2635
#define PICURV_CHECKPOINT_VERSION
Definition io.c:23
PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
Implementation of the transactional full-state checkpoint coordinator.
Definition io.c:2501
#define PICURV_EULERIAN_DIRECTORY
Definition io.c:25
#define PICURV_STATISTICS_REQUIRE(suffix, getter, target)
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Implementation of PicurvPhysicalTime().
Definition io.c:2986
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
Public interface for data input/output routines.
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
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
const char * ParticleBoundaryPolicyToString(ParticleBoundaryPolicy policy)
Returns the configuration token for a particle boundary policy.
Definition logging.c:850
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
#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_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
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_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
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
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Typed identities and metadata for persistent solver-particle fields.
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_POSITION
@ PARTICLE_FIELD_ID_COUNT
@ PARTICLE_FIELD_ID_INVALID
@ PARTICLE_FIELD_CAPABILITY_CHECKPOINT
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
PetscErrorCode ParticleFieldTryIdFromName(const char *field_name, ParticleFieldId *field_id, PetscBool *found)
Look a name up without treating an unknown name as an error.
Immutable metadata for one persistent particle field.
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
Per-window PETSc accumulator storage and pointwise application.
PetscInt components
Degrees of freedom the vector carries.
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.
const char * role
Inventory role: occupancy, mean, second_moment, co_moment.
char name[96]
File basename, no extension.
const char * layout
Catalog layout name for the inventory entry.
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.
Control ingress for the field-statistics pipeline.
PetscErrorCode ParsePostStatisticsEnsembles(SimCtx *simCtx)
Resolves the statistics ensembles a post-processing recipe defines.
PetscInt last_event_step
Guards against a step being offered twice.
PetscErrorCode PicurvWindowComputeHash(const PicurvWindowDefinition *definition, char digest_hex[65], char group_digest_hex[][17])
Computes the resolved identity hash of one window definition.
#define PICURV_WINDOW_HASH_GROUP_COUNT
Number of independently hashed property groups in a window definition.
#define PICURV_WINDOW_HASH_GROUP_LENGTH
Stored length of one truncated group digest, including the terminator.
PetscReal effective_start
Origin of the first represented interval.
const char * PicurvWindowHashGroupName(PetscInt group)
Returns the stable name of one hashed property group.
PetscInt sample_count
PetscReal last_accepted_time
Right edge of the last represented interval.
PicurvWindowState state
PetscInt restart_count
Restart segments this state descends from.
PetscReal effective_end
End of the last represented interval.
PetscReal end_time
Requested end; ignored when bounded is false.
PetscReal total_weight
#define PICURV_WINDOW_NAME_LENGTH
Maximum stored length of a window name, including the terminator.
@ PICURV_WINDOW_PENDING
Requested start not yet reached.
@ PICURV_WINDOW_COMPLETE
Bounded end reached; accepts nothing further.
@ PICURV_WINDOW_ACTIVE
Accepting due states.
const char * PicurvWindowStateName(PicurvWindowState state)
Returns a stable human-readable name for a window state.
PetscBool bounded
False for an open-ended window.
PicurvWindowDefinition definition
PetscInt next_time_target
k in effective_start + k*time_cadence.
PetscBool FieldStatisticsIsActive(const struct SimCtx *simCtx)
Reports whether this run has live field-statistics state.
PetscInt activation_step
Step at which the window became active.
PetscReal represented_time
Physical time the window covers.
PetscErrorCode PicurvWindowFirstHashDifference(const PicurvWindowDefinition *definition, const char *saved_group_digests, PetscInt *group)
Reports which hashed property group first differs from saved group digests.
Runtime state of one window.
The scientifically immutable definition of one window.
PetscBool inflowFluctuations
Some inlet adds synthetic fluctuations; their filter state is checkpointed.
Definition variables.h:1043
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
@ 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
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
char statistics_output_prefix[256]
basename for CSV output, e.g.
Definition variables.h:816
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
PetscReal yoshizawa_ci
Yoshizawa constant for the reported SGS kinetic energy.
Definition variables.h:677
UserCtx * user
Definition variables.h:768
PetscBool inletFaceDefined
Definition variables.h:1183
PetscBool profilingFinalSummary
Definition variables.h:1107
char particle_output_prefix[256]
Definition variables.h:811
PetscMPIInt rank
Definition variables.h:919
PetscInt dynamic_frequency
Recompute the dynamic coefficient every N steps.
Definition variables.h:665
PetscInt cgrid
Definition variables.h:1177
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
PetscInt block_number
Definition variables.h:1009
#define PICURV_BUILD_DIRTY
Definition variables.h:41
BCFace identifiedInletBCFace
Definition variables.h:1184
PetscReal targetVolumetricFlux
Definition variables.h:1024
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
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
PetscReal StartTime
Definition variables.h:932
PetscInt nTracePIDs
Number of entries in tracePIDs (at most PICURV_MAX_TRACED_PARTICLES).
Definition variables.h:1089
PetscBool runtimeMemoryLogEnabled
Enable the rank-reduced runtime memory log (log_dir/Runtime_Memory.csv).
Definition variables.h:1123
char output_prefix[256]
Definition variables.h:808
PetscBool dimensionalize
Whether derived output leaves non-dimensional form, from global_operations.dimensionalize.
Definition variables.h:828
char ** bcs_files
Definition variables.h:1015
struct BC_Param_s * next
Definition variables.h:375
PetscReal Min_X
Definition variables.h:1172
PetscReal min_pseudo_cfl
Definition variables.h:967
char * key
Definition variables.h:373
PetscInt KM
Definition variables.h:1171
PetscInt tiout
Definition variables.h:928
char field_statistics_output_prefix[PETSC_MAX_PATH_LEN]
Analysis prefix for CSV summaries; VTK continues to use output_prefix.
Definition variables.h:826
UserMG usermg
Definition variables.h:1082
#define MAX_FIELD_LIST_LENGTH
Definition variables.h:784
PetscBool inflowFluctuationsRestored
That state was read from the restart checkpoint.
Definition variables.h:1044
PetscReal walltimeGuardMinSeconds
Definition variables.h:1113
PetscReal L_ref
Definition variables.h:898
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
@ 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
#define MAX_PIPELINE_LENGTH
Definition variables.h:783
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 drivenFluxTargetLatched
Definition variables.h:1029
PetscInt _this
Definition variables.h:1175
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
char output_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:940
PetscBool solutionConvergenceEnabled
Definition variables.h:980
PetscReal dt
Definition variables.h:933
PetscReal ry
Definition variables.h:1176
@ LES_CLIP_CLAMP
Definition variables.h:653
PetscInt StepsToRun
Definition variables.h:927
char profilingTimestepMode[32]
Definition variables.h:1106
PetscInt k_periodic
Definition variables.h:1010
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
WallFunctionModel
Selects the wall model applied on WALL faces.
Definition variables.h:600
@ WALL_FUNCTION_LOG_LAW
Definition variables.h:602
PetscInt timeStep
Definition variables.h:800
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
PetscReal Max_Y
Definition variables.h:1172
PetscBool no_pseudo_cfl_backtrack
Definition variables.h:969
#define PICURV_GIT_COMMIT
Definition variables.h:38
char * value
Definition variables.h:374
PetscBool skipFinalCheckpoint
io.write_final_checkpoint false: no end-of-run bundle.
Definition variables.h:930
#define MAX_FILENAME_LENGTH
Definition variables.h:785
PetscInt StartStep
Definition variables.h:926
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
char * current_io_directory
Definition variables.h:944
char grid_file[PETSC_MAX_PATH_LEN]
Definition variables.h:1012
char statistics_pipeline[1024]
e.g.
Definition variables.h:815
InterpolationMethod interpolationMethod
Definition variables.h:1055
char field_statistics_formats[1024]
Comma-separated formats: vtk for derived fields, csv for the convergence history.
Definition variables.h:824
PetscReal max_pseudo_cfl
Definition variables.h:967
char output_fields_instantaneous[1024]
Definition variables.h:807
char particleRestartMode[16]
Definition variables.h:1056
char eulerianExt[8]
Definition variables.h:840
BoundingBox * bboxlist
Definition variables.h:1053
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
Vec lNu_t
Definition variables.h:1259
PetscReal rz
Definition variables.h:1176
char source_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:795
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
char particle_pipeline[1024]
Definition variables.h:809
BC_Param * params
Definition variables.h:429
char eulerianSource[PETSC_MAX_PATH_LEN]
Definition variables.h:938
PetscBool walltimeGuardEnabled
Definition variables.h:1109
PetscBool checkpointGeometryHashReady
Definition variables.h:946
PetscReal wall_roughness_height
Definition variables.h:1004
PetscInt walltimeGuardWarmupSteps
Definition variables.h:1111
ParticleInitializationType ParticleInitialization
Definition variables.h:1054
PetscScalar z
Definition variables.h:145
ScalingCtx scaling
Definition variables.h:1003
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 JM
Definition variables.h:1171
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
PetscInt da_procs[3]
Postprocessor MPI decomposition (i, j, k) from the recipe; PETSC_DECIDE where unset.
Definition variables.h:845
PetscInt mglevels
Definition variables.h:775
PetscReal Min_Z
Definition variables.h:1172
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
char process_pipeline[1024]
Definition variables.h:806
PetscInt particle_output_freq
Definition variables.h:812
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
char particle_fields[1024]
Definition variables.h:810
PetscReal pseudo_cfl_growth_factor
Definition variables.h:966
PetscBool outputParticles
Definition variables.h:803
char initialConditionDirectory[PETSC_MAX_PATH_LEN]
Definition variables.h:979
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
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
PetscReal Max_X
Definition variables.h:1172
PetscInt particleConsoleOutputFreq
Definition variables.h:931
PetscBool initialConditionStaged
Definition variables.h:977
PetscReal Min_Y
Definition variables.h:1172
PetscInt i_periodic
Definition variables.h:1010
PetscBool skipInitialCheckpoint
io.write_initial_checkpoint false: no initial/branch_start bundle.
Definition variables.h:929
char checkpointGeometrySHA256[65]
Definition variables.h:945
PetscInt step
Definition variables.h:924
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
PostProcessParams * pps
Definition variables.h:1131
PetscScalar y
Definition variables.h:145
@ IC_FIELD_UCAT
Definition variables.h:202
PetscMPIInt size
Definition variables.h:920
ExecutionMode
Defines the execution mode of the application.
Definition variables.h:887
@ EXEC_MODE_SOLVER
Definition variables.h:888
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
@ EXEC_MODE_RESTART_CHECK
Definition variables.h:890
PetscInt IM
Definition variables.h:1171
char _io_context_buffer[PETSC_MAX_PATH_LEN]
Definition variables.h:943
PetscInt field_statistics_source_step
Committed step supplying the state; negative means the step being processed.
Definition variables.h:830
Cmpnts periodic_translation[3]
Definition variables.h:1178
char particleExt[8]
Definition variables.h:841
PetscReal walltimeGuardEstimatorAlpha
Definition variables.h:1114
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
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
MGCtx * mgctx
Definition variables.h:778
@ 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
PetscReal P_ref
Definition variables.h:901
PetscReal rx
Definition variables.h:1176
InitialConditionField initialConditionField
Definition variables.h:978
ExecutionMode exec_mode
Definition variables.h:937
PetscInt startTime
Definition variables.h:798
PetscReal rho_ref
Definition variables.h:900
BoundingBox bbox
Definition variables.h:1173
PetscBool restartHistoryAvailable
Definition variables.h:947
PetscBool field_statistics_homogeneous[3]
Directions profiles merge over, in (i, j, k) order; none selected writes no profile.
Definition variables.h:832
PetscReal ti
Definition variables.h:925
PetscReal walltimeGuardMultiplier
Definition variables.h:1112
PetscReal Max_Z
Definition variables.h:1172
PetscReal U_ref
Definition variables.h:899
MomentumSolverType mom_solver_type
Definition variables.h:958
PetscInt immersed
Definition variables.h:950
char PostprocessingControlFile[PETSC_MAX_PATH_LEN]
Definition variables.h:1130
char restart_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:939
PetscReal pseudo_cfl
Definition variables.h:965
PetscInt LoggingFrequency
Definition variables.h:1087
#define PICURV_RELEASE_VERSION
Definition variables.h:32
PetscBool fieldStatisticsContinue
Definition variables.h:995
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ 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
PetscInt j_periodic
Definition variables.h:1010
BoundaryCondition * handler
Definition variables.h:430
A node in a linked list for storing key-value parameters from the bcs.dat file.
Definition variables.h:372
Holds the complete configuration for one of the six boundary faces.
Definition variables.h:424
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
Holds all configuration parameters for a post-processing run.
Definition variables.h:793
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157