PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
Loading...
Searching...
No Matches
io.h
Go to the documentation of this file.
1#ifndef IO_H
2#define IO_H
3
4#include "variables.h" // Essential for SimCtx and UserCtx definitions
5#include "logging.h" // For logging macros.
6#include "Boundaries.h"
7/**
8 * @file io.h
9 * @brief Public interface for data input/output routines.
10 *
11 * This header declares functions responsible for parsing grid geometry
12 * information, either from command-line options for programmatically
13 * generated grids or by reading the header of a grid definition file.
14 */
15
16/**
17 * @brief Parses command-line options for a programmatically generated grid for a SINGLE block.
18 *
19 * This function reads all per-block array options related to grid geometry,
20 * such as dimensions (-im), domain bounds (-xMins), and stretching ratios (-rxs).
21 * It then populates the fields of the provided `UserCtx` struct using its
22 * internal block index `user->_this`.
23 *
24 * @param user Pointer to the `UserCtx` for a specific block. The function will
25 * populate the geometric fields (`IM`, `Min_X`, `rx`, etc.) within this struct.
26 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
27 */
28PetscErrorCode ReadGridGenerationInputs(UserCtx *user);
29
30/**
31 * @brief Parses grid resolution arrays (`-im`, `-jm`, `-km`) once and applies them to all finest-grid blocks.
32 *
33 * This helper centralizes one-time resolution ingestion for analytical grid setup.
34 * It fills `IM/JM/KM` in each element of the finest-level `UserCtx` array.
35 *
36 * @param finest_users Pointer to the finest-level `UserCtx` array (length `nblk`).
37 * @param nblk Number of blocks in the finest-level array.
38 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
39 */
40PetscErrorCode PopulateFinestUserGridResolutionFromOptions(UserCtx *finest_users, PetscInt nblk);
41
42/**
43 * @brief Sets grid dimensions from a file for a SINGLE block using a one-time read cache.
44 *
45 * This function uses a static-variable pattern to ensure the grid file header
46 * is read only once, collectively, by all processes on the first call.
47 * Subsequent calls simply retrieve the pre-loaded and broadcasted data for
48 * the specified block.
49 *
50 * @param user Pointer to the `UserCtx` for a specific block. This function will
51 * populate the `IM`, `JM`, and `KM` fields.
52 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
53 */
54PetscErrorCode ReadGridFile(UserCtx *user);
55
56/**
57 * @brief A parallel-safe helper to verify the existence of a generic file or directory path.
58 *
59 * This function centralizes the logic for checking arbitrary paths. Only Rank 0 performs the
60 * filesystem check, and the result is broadcast to all other processes. This ensures
61 * collective and synchronized decision-making across all ranks. It is intended for
62 * configuration files, source directories, etc., where the path is known completely.
63 *
64 * @param[in] path The full path to the file or directory to check.
65 * @param[in] is_dir PETSC_TRUE if checking for a directory, PETSC_FALSE for a file.
66 * @param[in] is_optional PETSC_TRUE if the path is optional (results in a warning),
67 * PETSC_FALSE if mandatory (results in an error).
68 * @param[in] description A user-friendly description of the path for logging (e.g., "Grid file").
69 * @param[out] exists The result of the check (identical on all ranks).
70 *
71 * @return PetscErrorCode
72 */
73PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists);
74
75/**
76 * @brief Returns whether full field/restart output should be written for the
77 *
78 * completed timestep.
79 *
80 * @param simCtx Simulation context controlling the operation.
81 * @param completed_step Completed step index used by the decision helper.
82 * @return PetscBool indicating the result of `ShouldWriteDataOutput()`.
83 */
84PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step);
85
86/**
87 * @brief Write and atomically publish one complete checkpoint bundle.
88 * @param[in,out] simCtx Simulation context owning all enabled checkpoint state.
89 * @param[in] reason Stable lifecycle reason such as `initial`, `cadence`, `final`, or `signal`.
90 * @return Zero on success or a PETSc/MPI/filesystem error.
91 */
92PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason);
93
94/**
95 * @brief Reads binary field data for velocity, pressure, and other required vectors.
96 *
97 * Validates one committed checkpoint bundle and reads every enabled Eulerian
98 * checkpoint field through the field catalog.
99 *
100 * @param[in,out] user Pointer to the UserCtx structure containing the simulation context.
101 * @param[in] ti Checkpoint step resolved below the configured source root.
102 *
103 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
104 */
105PetscErrorCode ReadSimulationFields(UserCtx *user, PetscInt ti);
106
107/**
108 * @brief Restores field-statistics window state and accumulators from a checkpoint.
109 *
110 * Resumes every configured window from the bundle at @p ti when continuation was
111 * requested, per @ref p58_checkpoint_sec. Window scalars come from the bundle
112 * manifest and accumulator payloads
113 * through the same natural-ordering vector reader Eulerian fields use, so a restart
114 * on a different MPI rank count restores identical state.
115 *
116 * Does nothing when statistics are disabled, no window is configured, or
117 * continuation was not requested. Anything else is fatal rather than silently
118 * zeroed: a window count mismatch, a renamed window, a changed definition hash, a
119 * requested end earlier than the represented span, or missing state.
120 *
121 * @param[in,out] simCtx Simulation context carrying the windows and accumulators.
122 * @param[in] ti Step whose committed bundle supplies the state.
123 * @return Zero on success, or a PETSc error when continuation cannot be honored.
124 */
125PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti);
126
127
128/**
129 * @brief Reads data for a specific field from a file into the provided vector.
130 *
131 * This function uses the field name to construct the file path and reads the data
132 * from the corresponding file into the provided PETSc vector.
133 *
134 * @param[in] user Pointer to the UserCtx structure containing simulation context.
135 * @param[in] field_name Name of the field (e.g., "ufield", "vfield", "pfield").
136 * @param[out] field_vec PETSc vector to store the field data.
137 * @param[in] ext File extension (e.g., "dat").
138 *
139 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
140 */
141PetscErrorCode ReadFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext);
142
143
144/**
145 * @brief Writes data from a specific PETSc vector to a file.
146 *
147 * This function uses the field name to construct the file path and writes the data
148 * from the provided PETSc vector to the corresponding file.
149 *
150 * @param[in] user Pointer to the UserCtx structure containing simulation context.
151 * @param[in] field_name Name of the field (e.g., "ufield", "vfield", "pfield").
152 * @param[in] field_vec PETSc vector containing the field data to write.
153 * @param[in] ext File extension (e.g., "dat").
154 *
155 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
156 */
157PetscErrorCode WriteFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext);
158
159
160/**
161 * @brief Writes simulation fields to files.
162 *
163 * This function writes contravariant velocity, Cartesian velocity, pressure, and node state
164 * fields to their respective binary files. It also conditionally writes LES and RANS
165 * model fields when those models are enabled.
166 *
167 * @param[in] user Pointer to the UserCtx structure containing simulation context.
168 * @param[in] checkpoint_directory Root of the in-progress checkpoint bundle.
169 *
170 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
171 */
172PetscErrorCode WriteSimulationFields(UserCtx *user, const char *checkpoint_directory);
173
174/**
175 * @brief Writes data from a specific field in a PETSc Swarm to a file.
176 *
177 * This function retrieves the Swarm from the UserCtx (i.e., `user->swarm`) and
178 * creates a global PETSc vector from the specified Swarm field. It then calls
179 * the existing WriteFieldData() function to handle the actual I/O operation.
180 * After writing the data, the function destroys the temporary global vector
181 * to avoid memory leaks.
182 *
183 * @param[in] user Pointer to the UserCtx structure containing simulation context
184 * and the PetscSwarm (as `user->swarm`).
185 * @param[in] field_name Name of the Swarm field to be written (e.g., "my_field").
186 * @param[in] ext File extension (e.g., "dat", "bin").
187 *
188 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
189 *
190 * @note Compatible with PETSc 3.14.4.
191 */
192PetscErrorCode WriteSwarmField(UserCtx *user, const char *field_name, const char *ext);
193
194/**
195 * @brief Writes integer data from a specific PETSc Swarm field to a file.
196 *
197 * This function is designed for swarm fields that store integer data (e.g.,
198 * DMSwarm_CellID), which cannot be converted to a standard PETSc Vec of
199 * PetscScalars. It accesses the raw data pointer for the field on each rank
200 * using DMSwarmGetField(), writes the local data to a rank-specific binary file,
201 * and then restores the field access.
202 *
203 * @param[in] user Pointer to the UserCtx structure containing the PetscSwarm.
204 * @param[in] field_name Name of the integer Swarm field to be written.
205 * @param[in] ext File extension (e.g., "dat", "bin").
206 *
207 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
208 */
209PetscErrorCode WriteSwarmIntField(UserCtx *user, const char *field_name, const char *ext);
210
211/**
212 * @brief Writes a predefined set of PETSc Swarm fields to files.
213 *
214 * This function iterates through checkpoint-capable particle catalog entries
215 * and delegates each payload to the existing generic swarm writer.
216 *
217 * This function will only execute if particles are enabled in the simulation
218 * (i.e., `user->simCtx->np > 0` and `user->swarm` is not NULL).
219 *
220 * @param[in] user Pointer to the UserCtx structure containing the simulation context
221 * and the PetscSwarm.
222 * @param[in] checkpoint_directory Root of the in-progress checkpoint bundle.
223 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
224 */
225PetscErrorCode WriteAllSwarmFields(UserCtx *user, const char *checkpoint_directory);
226
227/**
228 * @brief Reads a simple ASCII data file containing one numeric value per line.
229 *
230 * This helper performs rank-0 file I/O, broadcasts the parsed result to the rest
231 * of the communicator, and returns a replicated array on every rank.
232 *
233 * @param filename Path to the input data file.
234 * @param data_out Output pointer to the allocated scalar array.
235 * @param Nout Output pointer storing the number of values read.
236 * @param comm MPI communicator used for the coordinated read/broadcast sequence.
237 * @return Integer value produced by `ReadDataFileToArray()`.
238 */
239PetscInt ReadDataFileToArray(const char *filename,
240 double **data_out,
241 PetscInt *Nout,
242 MPI_Comm comm);
243
244/**
245 * @brief Creates a VTK file from prepared metadata and field payloads.
246 *
247 * This helper dispatches to the structured-grid or polydata writer based on the
248 * metadata contents and emits the assembled VTK file on the requested communicator.
249 *
250 * @param filename Path to the output VTK file.
251 * @param meta VTK metadata describing the output geometry and field payloads.
252 * @param comm MPI communicator used by the write operation.
253 * @return Integer value produced by `CreateVTKFileFromMetadata()`.
254 */
255PetscInt CreateVTKFileFromMetadata(const char *filename,
256 const VTKMetaData *meta,
257 MPI_Comm comm);
258
259/**
260 * @brief Gathers the contents of a distributed PETSc Vec into a single array on rank 0.
261 *
262 * @param[in] inVec The input (possibly distributed) Vec.
263 * @param[out] N The global size of the vector.
264 * @param[out] arrayOut On rank 0, points to the newly allocated array holding all data.
265 * On other ranks, it is set to NULL.
266 *
267 * @return PetscErrorCode Return 0 on success, nonzero on failure.
268 */
269PetscErrorCode VecToArrayOnRank0(Vec inVec, PetscInt *N, double **arrayOut);
270
271/**
272 * @brief Gathers any DMSwarm field from all ranks to a single, contiguous array on rank 0.
273 *
274 * This is a generic, type-aware version of SwarmFieldToArrayOnRank0.
275 * It is a COLLECTIVE operation.
276 *
277 * @param[in] swarm The DMSwarm to gather from.
278 * @param[in] field_name The name of the field to gather.
279 * @param[out] n_total_particles Total number of particles in the global swarm on every rank.
280 * @param[out] n_components Number of components for the field on every rank.
281 * @param[out] field_type_out PETSc storage type for the field on all ranks.
282 * @param[out] gathered_array On rank 0, a newly allocated array containing the full, gathered data; NULL elsewhere.
283 * The caller is responsible for freeing this memory and for casting it to the correct type.
284 * @return PetscErrorCode
285 */
286PetscErrorCode SwarmFieldToArrayOnRank0(DM swarm, const char *field_name,
287 PetscInt *n_total_particles, PetscInt *n_components,
288 PetscDataType *field_type_out, void **gathered_array);
289
290/**
291 * @brief Reads data from a file into a specified field of a PETSc DMSwarm.
292 *
293 * This function is the counterpart to WriteSwarmField(). It creates a global PETSc vector
294 * that references the specified DMSwarm field, uses ReadFieldData() to read the data from
295 * a file, and then destroys the global vector reference.
296 *
297 * @param[in] user Pointer to the UserCtx structure (containing `user->swarm`).
298 * @param[in] field_name Name of the DMSwarm field to read into (must be previously declared/allocated).
299 * @param[in] ext File extension (e.g., "dat" or "bin").
300 *
301 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
302 *
303 * @note Compatible with PETSc 3.14.x.
304 */
305PetscErrorCode ReadSwarmField(UserCtx *user, const char *field_name, const char *ext);
306
307/**
308 * @brief Reads integer swarm data by using ReadFieldData and casting the result.
309 *
310 * This function is the counterpart to WriteSwarmIntField. It reads a file
311 * containing floating-point data (that was originally integer) into a temporary
312 * Vec and then casts it back to the integer swarm field. It works by:
313 * 1. Creating a temporary parallel Vec.
314 * 2. Calling the standard ReadFieldData() to populate this Vec.
315 * 3. Accessing the local data of both the Vec and the swarm field.
316 * 4. Populating the swarm's integer field by casting each PetscScalar back to a PetscInt.
317 * 5. Destroying the temporary Vec.
318 *
319 * @param[in] user Pointer to the UserCtx structure.
320 * @param[in] field_name Name of the integer Swarm field to be read.
321 * @param[in] ext File extension.
322 *
323 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
324 */
325PetscErrorCode ReadSwarmIntField(UserCtx *user, const char *field_name, const char *ext);
326
327/**
328 * @brief Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.
329 *
330 * This function is analogous to ReadSimulationFields() but targets a DMSwarm.
331 * Each Swarm field is read from a separate file using ReadSwarmField().
332 *
333 * @param[in,out] user Pointer to the UserCtx structure containing the DMSwarm (user->swarm).
334 * @param[in] ti Time index for constructing the file name.
335 *
336 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
337 */
338PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti);
339
340/**
341 * @brief Read the particle count from a validated committed checkpoint.
342 *
343 * @param[in,out] user Simulation context and active grid used for validation.
344 * @param[in] ti Checkpoint step resolved below the configured source root.
345 * @param[out] particle_count Number of particles recorded by the bundle.
346 * @return Zero on success or a checkpoint-validation error.
347 */
348PetscErrorCode ReadCheckpointParticleCount(UserCtx *user, PetscInt ti, PetscInt *particle_count);
349
350/**
351 * @brief Reads coordinate data (for particles) from file into a PETSc Vec, then gathers it to rank 0.
352 *
353 * This function uses \c ReadFieldData to fill a PETSc Vec with coordinate data,
354 * then leverages \c VecToArrayOnRank0 to gather that data into a contiguous array
355 * (valid on rank 0 only).
356 *
357 * @param[in] timeIndex The time index used to construct file names.
358 * @param[in] user Pointer to the user context.
359 * @param[out] coordsArray On rank 0, will point to a newly allocated array holding the coordinates.
360 * @param[out] Ncoords On rank 0, the length of \p coordsArray. On other ranks, 0.
361 *
362 * @return PetscErrorCode Returns 0 on success, or non-zero on failures.
363 */
364PetscErrorCode ReadPositionsFromFile(PetscInt timeIndex,
365 UserCtx *user,
366 double **coordsArray,
367 PetscInt *Ncoords);
368
369
370/**
371 * @brief Reads a named field from file into a PETSc Vec, then gathers it to rank 0.
372 *
373 * This function wraps \c ReadFieldData and \c VecToArrayOnRank0 into a single step.
374 * The gathered data is stored in \p scalarArray on rank 0, with its length in \p Nscalars.
375 *
376 * @param[in] timeIndex The time index used to construct file names.
377 * @param[in] fieldName Name of the field to be read (e.g., "velocity").
378 * @param[in] user Pointer to the user context.
379 * @param[out] scalarArray On rank 0, a newly allocated array holding the field data.
380 * @param[out] Nscalars On rank 0, length of \p scalarArray. On other ranks, 0.
381 *
382 * @return PetscErrorCode Returns 0 on success, or non-zero on failures.
383 */
384PetscErrorCode ReadFieldDataToRank0(PetscInt timeIndex,
385 const char *fieldName,
386 UserCtx *user,
387 double **scalarArray,
388 PetscInt *Nscalars);
389
390/**
391 * @brief Displays a structured banner summarizing the simulation configuration.
392 *
393 * This function prints effective key simulation parameters to standard output
394 * on MPI rank 0. It retrieves global domain bounds and block metadata from
395 * `simCtx`, and suppresses settings that do not apply to the selected mode.
396 * For example, `Initial Pseudo-CFL (Courant)` appears only for the Dual Time
397 * Picard--Jameson RK momentum solver; it is not a Newton--Krylov control.
398 * The report also identifies active logging, profiling, runtime-memory, and
399 * solution-convergence modes so the startup log records the effective
400 * observability contract.
401 *
402 * @param[in] simCtx Pointer to the master simulation context.
403 *
404 * @return PetscErrorCode Returns `0` on success.
405 */
406PetscErrorCode DisplayBanner(SimCtx *simCtx);
407
408
409// --- Conversion and Validation Utilities ---
410// These are now public and can be used by other parts of the application.
411
412/**
413 * @brief Converts a face-token string (e.g., "-Xi", "+Eta") to the internal `BCFace` enum.
414 *
415 * @param[in] str Input token from configuration.
416 * @param[out] face_out Parsed enum value on success.
417 * @return PetscErrorCode 0 on success, non-zero for invalid tokens or null pointers.
418 */
419PetscErrorCode StringToBCFace(const char* str, BCFace* face_out);
420
421/**
422 * @brief Converts a mathematical BC type string (e.g., "PERIODIC", "WALL") to `BCType`.
423 *
424 * @param[in] str Input token from configuration.
425 * @param[out] type_out Parsed enum value on success.
426 * @return PetscErrorCode 0 on success, non-zero for invalid tokens or null pointers.
427 */
428PetscErrorCode StringToBCType(const char* str, BCType* type_out);
429
430/**
431 * @brief Converts a BC handler token (implementation strategy) to `BCHandlerType`.
432 *
433 * @param[in] str Input handler token from configuration.
434 * @param[out] handler_out Parsed enum value on success.
435 * @return PetscErrorCode 0 on success, non-zero for invalid tokens or null pointers.
436 */
437PetscErrorCode StringToBCHandlerType(const char* str, BCHandlerType* handler_out);
438
439/**
440 * @brief Validates that a selected handler is compatible with a mathematical BC type.
441 *
442 * @param[in] type Mathematical BC type (e.g., WALL, PERIODIC).
443 * @param[in] handler Selected handler implementation enum.
444 * @return PetscErrorCode 0 if compatible, non-zero if the combination is invalid.
445 */
446PetscErrorCode ValidateBCHandlerForBCType(BCType type, BCHandlerType handler);
447
448// --- Memory Management ---
449
450/**
451 * @brief Frees an entire linked list of boundary-condition parameters.
452 *
453 * @param[in,out] head Head pointer of the `BC_Param` list to destroy.
454 */
455void FreeBC_ParamList(BC_Param *head);
456
457/**
458 * @brief Searches a BC_Param linked list for a key and returns its value as a double.
459 * @param params The head of the BC_Param linked list.
460 * @param key The key to search for (case-insensitive).
461 * @param[out] value_out The found value, converted to a PetscReal.
462 * @param[out] found Set to PETSC_TRUE if the key was found, PETSC_FALSE otherwise.
463 * @return 0 on success.
464 */
465PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found);
466
467/**
468 * @brief Searches a BC_Param linked list for a key and returns its value as a bool.
469 * @param params The head of the BC_Param linked list.
470 * @param key The key to search for (case-insensitive).
471 * @param[out] value_out The found value, converted to a PetscBool.
472 * @param[out] found Set to PETSC_TRUE if the key was found, PETSC_FALSE otherwise.
473 * @return 0 on success.
474 */
475PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found);
476
477/**
478 * @brief Read the driven-flow seam-flux flag, accepting its deprecated `apply_trim` spelling.
479 * @param[in] params Parameter list for the face.
480 * @param[out] value_out Resolved flag value.
481 * @param[out] found Whether either spelling was present.
482 * @return PetscErrorCode 0 on success.
483 */
484PetscErrorCode GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found);
485
486/**
487 * @brief Parses the boundary conditions file to configure the type, handler, and
488 * any associated parameters for all 6 global faces of the domain.
489 *
490 * This function performs the following steps:
491 * 1. On MPI rank 0, it reads the specified configuration file line-by-line.
492 * 2. It parses each line for `<Face> <Type> <Handler> [param=value]...` format.
493 * 3. It validates the parsed strings and stores the configuration, including a
494 * linked list of parameters, in a temporary array.
495 * 4. It then serializes this configuration and broadcasts it to all other MPI ranks.
496 * 5. All ranks (including rank 0) then deserialize the broadcasted data to populate
497 * their local `user->boundary_faces` array identically.
498 * 6. It also sets the particle inlet lookup fields in `UserCtx`.
499 *
500 * @param[in,out] user The main UserCtx struct where the final configuration
501 * for all ranks will be stored.
502 * @param[in] bcs_input_filename The path to the boundary conditions configuration file.
503 * @return PetscErrorCode 0 on success, error code on failure.
504 */
505PetscErrorCode ParseAllBoundaryConditions(UserCtx *user, const char *bcs_input_filename);
506
507/**
508 * @brief Scans all block-specific boundary condition files to determine a globally
509 * consistent periodicity for each dimension, reusing the core type parser.
510 *
511 * This is a lightweight pre-parser intended to be called before DMDA creation.
512 * It ensures that the periodicity setting is consistent across all blocks, which is a
513 * physical requirement for the domain.
514 *
515 * 1. It collectively verifies that the mandatory BCS file for each block exists.
516 * 2. On MPI rank 0, it then iterates through the files.
517 * 3. For each line, it attempts to convert the type string to a BCType enum using the
518 * standard `StringToBCType` helper.
519 * 4. If the conversion is successful AND the type is PERIODIC, it flags the corresponding face.
520 * 5. If the conversion fails (e.g., for "WALL", "INLET", etc.), the error is cleared
521 * and the line is simply ignored, as it's not relevant to periodicity.
522 * 6. It validates consistency (e.g., -Xi and +Xi match) and ensures all block files
523 * specify the same global periodicity.
524 * 7. It broadcasts the final three flags (as integers 0 or 1) to all MPI ranks.
525 * 8. All ranks update the i_periodic, j_periodic, and k_periodic fields in their SimCtx.
526 *
527 * @param[in,out] simCtx The master SimCtx struct, containing the bcs_files list and
528 * where the final periodicity flags will be stored.
529 * @return PetscErrorCode 0 on success, error code on failure.
530 */
531PetscErrorCode DeterminePeriodicity(SimCtx *simCtx);
532
533/**
534 * @brief Removes leading and trailing ASCII whitespace from a mutable string.
535 * @param[in,out] str NUL-terminated string compacted in place.
536 */
537void TrimWhitespace(char *str);
538
539/**
540 * @brief Initializes post-processing settings from a config file and command-line overrides.
541 *
542 * This function establishes the configuration for a post-processing run by:
543 * 1. Setting hardcoded default values in the PostProcessParams struct.
544 * 2. Reading a configuration file to override the defaults.
545 * 3. Parsing command-line options (-startTime, -endTime, etc.) which can override
546 * both the defaults and the file settings.
547 *
548 * @param simCtx The pointer to the simulation context that contains the postprocessing file and struct.
549 * @return PetscErrorCode
550 */
551PetscErrorCode ParsePostProcessingSettings(SimCtx *simCtx);
552
553/**
554 * @brief Parses physical scaling parameters from command-line options.
555 *
556 * This function reads the reference length, velocity, and density from the
557 * PETSc options database (provided via -scaling_L_ref, etc.). It populates
558 * the simCtx->scaling struct and calculates the derived reference pressure.
559 * It sets default values of 1.0 for a fully non-dimensional case if the
560 * options are not provided.
561 *
562 * @param[in,out] simCtx The simulation context whose 'scaling' member will be populated.
563 * @return PetscErrorCode
564 */
565PetscErrorCode ParseScalingInformation(SimCtx *simCtx);
566
567#endif // IO_H
PetscErrorCode ParsePostProcessingSettings(SimCtx *simCtx)
Initializes post-processing settings from a config file and command-line overrides.
Definition io.c:3076
PetscErrorCode ParseScalingInformation(SimCtx *simCtx)
Parses physical scaling parameters from command-line options.
Definition io.c:3242
PetscInt ReadDataFileToArray(const char *filename, double **data_out, PetscInt *Nout, MPI_Comm comm)
Reads a simple ASCII data file containing one numeric value per line.
Definition io.c:3286
PetscErrorCode ReadGridFile(UserCtx *user)
Sets grid dimensions from a file for a SINGLE block using a one-time read cache.
Definition io.c:581
PetscErrorCode StringToBCHandlerType(const char *str, BCHandlerType *handler_out)
Converts a BC handler token (implementation strategy) to BCHandlerType.
Definition io.c:709
PetscErrorCode ReadSwarmField(UserCtx *user, const char *field_name, const char *ext)
Reads data from a file into a specified field of a PETSc DMSwarm.
Definition io.c:1767
PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a double.
Definition io.c:752
PetscErrorCode SwarmFieldToArrayOnRank0(DM swarm, const char *field_name, PetscInt *n_total_particles, PetscInt *n_components, PetscDataType *field_type_out, void **gathered_array)
Gathers any DMSwarm field from all ranks to a single, contiguous array on rank 0.
Definition io.c:2686
PetscErrorCode WriteAllSwarmFields(UserCtx *user, const char *checkpoint_directory)
Writes a predefined set of PETSc Swarm fields to files.
Definition io.c:2196
PetscErrorCode WriteSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
Writes integer data from a specific PETSc Swarm field to a file.
Definition io.c:2131
PetscErrorCode ReadCheckpointParticleCount(UserCtx *user, PetscInt ti, PetscInt *particle_count)
Read the particle count from a validated committed checkpoint.
Definition io.c:1914
PetscErrorCode ReadSimulationFields(UserCtx *user, PetscInt ti)
Reads binary field data for velocity, pressure, and other required vectors.
Definition io.c:1463
PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step)
Returns whether full field/restart output should be written for the.
Definition io.c:432
PetscErrorCode GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found)
Read the driven-flow seam-flux flag, accepting its deprecated apply_trim spelling.
Definition io.c:814
PetscErrorCode ParseAllBoundaryConditions(UserCtx *user, const char *bcs_input_filename)
Parses the boundary conditions file to configure the type, handler, and any associated parameters for...
Definition io.c:837
PetscErrorCode ValidateBCHandlerForBCType(BCType type, BCHandlerType handler)
Validates that a selected handler is compatible with a mathematical BC type.
Definition io.c:727
void TrimWhitespace(char *str)
Removes leading and trailing ASCII whitespace from a mutable string.
Definition io.c:399
PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti)
Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.
Definition io.c:1864
PetscErrorCode WriteSimulationFields(UserCtx *user, const char *checkpoint_directory)
Writes simulation fields to files.
Definition io.c:2002
PetscErrorCode ReadGridGenerationInputs(UserCtx *user)
Parses command-line options for a programmatically generated grid for a SINGLE block.
Definition io.c:447
PetscErrorCode ReadFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Reads data for a specific field from a file into the provided vector.
Definition io.c:1174
PetscErrorCode PopulateFinestUserGridResolutionFromOptions(UserCtx *finest_users, PetscInt nblk)
Parses grid resolution arrays (-im, -jm, -km) once and applies them to all finest-grid blocks.
Definition io.c:532
PetscErrorCode DeterminePeriodicity(SimCtx *simCtx)
Scans all block-specific boundary condition files to determine a globally consistent periodicity for ...
Definition io.c:1024
PetscErrorCode ReadFieldDataToRank0(PetscInt timeIndex, const char *fieldName, UserCtx *user, double **scalarArray, PetscInt *Nscalars)
Reads a named field from file into a PETSc Vec, then gathers it to rank 0.
Definition io.c:3456
PetscErrorCode VecToArrayOnRank0(Vec inVec, PetscInt *N, double **arrayOut)
Gathers the contents of a distributed PETSc Vec into a single array on rank 0.
Definition io.c:2650
PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
Restores field-statistics window state and accumulators from a checkpoint.
Definition io.c:1667
PetscErrorCode StringToBCFace(const char *str, BCFace *face_out)
Converts a face-token string (e.g., "-Xi", "+Eta") to the internal BCFace enum.
Definition io.c:679
PetscErrorCode ReadPositionsFromFile(PetscInt timeIndex, UserCtx *user, double **coordsArray, PetscInt *Ncoords)
Reads coordinate data (for particles) from file into a PETSc Vec, then gathers it to rank 0.
Definition io.c:3418
PetscErrorCode WriteSwarmField(UserCtx *user, const char *field_name, const char *ext)
Writes data from a specific field in a PETSc Swarm to a file.
Definition io.c:2076
PetscErrorCode ReadSwarmIntField(UserCtx *user, const char *field_name, const char *ext)
Reads integer swarm data by using ReadFieldData and casting the result.
Definition io.c:1797
PetscErrorCode WriteFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Writes data from a specific PETSc vector to a file.
Definition io.c:1947
PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists)
A parallel-safe helper to verify the existence of a generic file or directory path.
Definition io.c:1128
PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a bool.
Definition io.c:773
void FreeBC_ParamList(BC_Param *head)
Frees an entire linked list of boundary-condition parameters.
Definition io.c:664
PetscInt CreateVTKFileFromMetadata(const char *filename, const VTKMetaData *meta, MPI_Comm comm)
Creates a VTK file from prepared metadata and field payloads.
Definition vtk_io.c:149
PetscErrorCode StringToBCType(const char *str, BCType *type_out)
Converts a mathematical BC type string (e.g., "PERIODIC", "WALL") to BCType.
Definition io.c:694
PetscErrorCode DisplayBanner(SimCtx *simCtx)
Displays a structured banner summarizing the simulation configuration.
Definition io.c:2776
PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
Write and atomically publish one complete checkpoint bundle.
Definition io.c:2530
Logging utilities and macros for PETSc-based applications.
Main header file for a complex fluid dynamics solver.
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:283
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:303
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:261
A node in a linked list for storing key-value parameters from the bcs.dat file.
Definition variables.h:336
The master context for the entire simulation.
Definition variables.h:695
User-defined context containing data specific to a single computational grid level.
Definition variables.h:906