PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
setup.h
Go to the documentation of this file.
1#ifndef SETUP_H
2#define SETUP_H
3
4#include <petscpf.h>
5#include <petscdmswarm.h>
6#include <stdlib.h>
7#include <time.h>
8#include <math.h>
9#include <petsctime.h>
10#include <petscsys.h>
11#include <petscdmcomposite.h>
12#include <petscsystypes.h>
13
14// Include additional headers
15#include "variables.h" // Shared type definitions
16#include "field_catalog.h" // Typed identities for persistent Eulerian fields
17#include "ParticleSwarm.h" // Particle swarm functions
18#include "walkingsearch.h" // Particle location functions
19#include "grid.h" // Grid functions
20#include "logging.h" // Logging macros
21#include "io.h" // Data Input and Output functions
22#include "interpolation.h" // Interpolation routines
23#include "ParticleMotion.h" // Functions related to motion of particles
24#include "Boundaries.h" // Functions related to Boundary conditions
25
26/**
27 * @brief Print the shared native build identity when a version flag is present.
28 * @details Prints two lines: `<name> <release>+g<commit>[.dirty]`, then the PETSc this
29 * binary was compiled against, `petsc <version> <debug|optimized> <arch> <dir>`.
30 * The second line is also kept in the binary behind a `PICURV_PETSC_BUILD:`
31 * marker, so the conductor can read it from a binary that cannot start.
32 * @param[in] argc Native executable argument count.
33 * @param[in] argv Native executable argument vector.
34 * @param[in] executable_name User-facing executable name printed with the identity.
35 * @return Nonzero when a version flag was handled and execution should stop.
36 */
37int PicurvHandleVersionArgument(int argc, char **argv, const char *executable_name);
38
39
40/* Macro to automatically select the correct allocation function */
41#define Allocate3DArray(array, nz, ny, nx) \
42 _Generic((array), \
43 PetscReal ****: Allocate3DArrayScalar, \
44 Cmpnts ****: Allocate3DArrayVector \
45 )(array, nz, ny, nx)
46
47/* Macro for deallocation */
48#define Deallocate3DArray(array, nz, ny) \
49 _Generic((array), \
50 PetscReal ***: Deallocate3DArrayScalar, \
51 Cmpnts ***: Deallocate3DArrayVector \
52 )(array, nz, ny)
53
54
55/**
56 * @brief Allocates and populates the master SimulationContext object.
57 *
58 * This function serves as the single, authoritative entry point for all
59 * simulation configuration. It merges the setup logic from both the legacy
60 * FSI/IBM solver and the modern particle solver into a unified, robust
61 * process.
62 *
63 * The function follows a strict sequence:
64 * 1. **Allocate Context & Set Defaults:** It first allocates the `SimulationContext`
65 * and populates every field with a sane, hardcoded default value. This
66 * ensures the simulation starts from a known, predictable state.
67 * 2. **Configure Logging System:** It configures the custom logging framework. It
68 * parses the `-func_config_file` option to load a list of function names
69 * allowed to produce log output. This configuration (the file path and the
70 * list of function names) is stored within the `SimulationContext` for
71 * later reference and cleanup.
72 * 3. **Parse All Options:** It performs a comprehensive pass of `PetscOptionsGet...`
73 * calls for every possible command-line flag, overriding the default
74 * values set in step 1.
75 * 4. **Log Summary:** After all options are parsed, it uses the now-active
76 * logging system to print a summary of the key simulation parameters.
77 *
78 * @param[in] argc Argument count passed from `main`.
79 * @param[in] argv Argument vector passed from `main`.
80 * @param[out] p_simCtx On success, this will point to the newly created and
81 * fully configured `SimulationContext` pointer. The caller
82 * is responsible for eventually destroying this object by
83 * calling `FinalizeSimulation()`.
84 *
85 * @return PetscErrorCode Returns 0 on success, or a non-zero PETSc error code on failure.
86 */
87PetscErrorCode CreateSimulationContext(int argc, char **argv, SimCtx **p_simCtx);
88
89/**
90 * @brief Parse a positive floating-point seconds value from runtime metadata.
91 *
92 * This helper is used for shell-exported walltime metadata such as
93 * `PICURV_JOB_START_EPOCH` and `PICURV_WALLTIME_LIMIT_SECONDS`.
94 *
95 * @param[in] text String to parse.
96 * @param[out] seconds_out Parsed positive seconds value when successful.
97 * @return PetscBool `PETSC_TRUE` when parsing succeeds, else `PETSC_FALSE`.
98 */
99PetscBool RuntimeWalltimeGuardParsePositiveSeconds(const char *text, PetscReal *seconds_out);
100
101/**
102 * @brief Verifies and prepares the complete I/O environment for a simulation run.
103 *
104 * This function performs a comprehensive series of checks and setup actions to
105 * ensure a valid and clean environment. It is parallel-safe; all filesystem
106 * operations and checks are performed by Rank 0, with collective error handling.
107 *
108 * The function's responsibilities include:
109 * 1. **Checking Mandatory Inputs:** Verifies existence of grid and BCs files.
110 * 2. **Checking Optional Inputs:** Warns if optional config files (whitelist, profile) are missing.
111 * 3. **Validating Run Mode Paths:** Ensures `restart_dir` or post-processing source directories exist when needed.
112 * 4. **Preparing Log Directory:** Creates the log directory and cleans it of previous logs.
113 * 5. **Preparing Output Directories:** Creates the main output directory and its required subdirectories.
114 *
115 * @param[in] simCtx The fully configured SimulationContext object.
116 *
117 * @return PetscErrorCode Returns 0 on success, or a non-zero error code if a
118 * mandatory file/directory is missing or a critical operation fails.
119 */
120PetscErrorCode SetupSimulationEnvironment(SimCtx *simCtx);
121
122/**
123 * @brief The main orchestrator for setting up all grid-related components.
124 *
125 * This function is the high-level driver for creating the entire computational
126 * domain, including the multigrid hierarchy, PETSc DMDA and Vec objects, and
127 * calculating all necessary grid metrics.
128 *
129 * @param simCtx The fully configured SimulationContext.
130 * @return PetscErrorCode
131 */
132PetscErrorCode SetupGridAndSolvers(SimCtx *simCtx);
133
134/**
135 @brief Creates and initializes all PETSc Vec objects for all fields.
136 *
137 * This function iterates through every UserCtx in the multigrid and multi-block
138 * hierarchy. For each context, it creates the comprehensive set of global and
139 * local PETSc Vecs required by the flow solver (e.g., Ucont, P, Nvert, metrics,
140 * turbulence fields, etc.). Each vector is initialized to zero.
141 *
142 * @param simCtx The master SimCtx, containing the configured UserCtx hierarchy.
143 * @return PetscErrorCode
144 */
145PetscErrorCode CreateAndInitializeAllVectors(SimCtx *simCtx);
146
147/**
148 * @brief Updates the local vector (including ghost points) from its corresponding global vector.
149 *
150 * This function resolves the correct global vector, local vector, and DM from the
151 * authoritative field catalog and performs the standard PETSc
152 * DMGlobalToLocalBegin/End sequence.
153 * For registered single-face-family and component-staggered fields, it then
154 * repairs the adjacent periodic ghost in each normal direction so central
155 * differences see the correct neighboring face. Cell-centered fields and
156 * tangential face directions retain PETSc's native periodic wraparound.
157 * Includes optional debugging output (max norms before/after).
158 *
159 * @param user The UserCtx structure containing the vectors and DMs.
160 * @param field_id Typed identity of the catalogued field to update.
161 *
162 * @return PetscErrorCode 0 on success, non-zero on failure.
163 *
164 * @note This function assumes the global vector associated with field_id has already
165 * been populated with the desired data (including any boundary conditions and
166 * periodic duplicate planes). It scatters that current global state into the
167 * local vector; it does not repair stale global periodic duplicate planes.
168 * @note Wider QUICK-style normal ghost layers require a separate dedicated
169 * exchange; this function repairs the adjacent layer used by central stencils.
170 */
171PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id);
172
173/**
174 * @brief (Orchestrator) Sets up all boundary conditions for the simulation.
175 *
176 * @param simCtx Simulation context controlling the operation.
177 * @return PetscErrorCode 0 on success.
178 */
179PetscErrorCode SetupBoundaryConditions(SimCtx *simCtx);
180
181/**
182 * @brief Allocates any runtime storage required by solution-convergence logging.
183 *
184 * This helper is setup-owned because it allocates mode-specific buffers once
185 * the finest-level Eulerian vectors already exist. It does not compute or log
186 * any metrics; it only prepares storage for later use by
187 * `LOG_SOLUTION_CONVERGENCE()`.
188 *
189 * Allocation depends on the active solution-convergence mode:
190 * - steady/transient: no extra storage beyond counters
191 * - periodic_deterministic: one phase-aligned `Ucat` / `P` reference slot per
192 * configured period step and per block
193 * - statistical_steady: rolling scalar histories sized for two adjacent
194 * windows of `mean_speed` and `mean_ke`
195 *
196 * The helper also resets the recorded-sample counter so warmup behavior starts
197 * from a clean state each time solver setup is rebuilt.
198 *
199 * @param[in,out] simCtx Master simulation context owning the runtime storage.
200 * @return PetscErrorCode 0 on success.
201 */
202PetscErrorCode InitializeSolutionConvergenceState(SimCtx *simCtx);
203
204/**
205 * @brief Frees any runtime storage allocated for solution-convergence logging.
206 *
207 * This helper is the cleanup counterpart to
208 * `InitializeSolutionConvergenceState()`. It releases periodic reference
209 * buffers and statistical-history arrays, then resets the associated pointers
210 * and counters. It is safe to call during teardown even if a given mode never
211 * allocated optional storage.
212 *
213 * @param[in,out] simCtx Master simulation context owning the runtime storage.
214 * @return PetscErrorCode 0 on success.
215 */
216PetscErrorCode DestroySolutionConvergenceState(SimCtx *simCtx);
217
218/**
219 * @brief Allocates a 3D array of PetscReal values using PetscCalloc.
220 *
221 * This function dynamically allocates memory for a 3D array of PetscReal values
222 * with dimensions nz (layers) x ny (rows) x nx (columns). It uses PetscCalloc1
223 * to ensure the memory is zero-initialized.
224 *
225 * The allocation is done in three steps:
226 * 1. Allocate an array of nz pointers (one for each layer).
227 * 2. Allocate a contiguous block for nz*ny row pointers and assign each layer’s row pointers.
228 * 3. Allocate a contiguous block for all nz*ny*nx PetscReal values.
229 *
230 * This setup allows the array to be accessed as array[k][j][i], and the memory
231 * for the data is contiguous, which improves cache efficiency.
232 *
233 * @param[out] array Pointer to the 3D array to be allocated.
234 * @param[in] nz Number of layers (z-direction).
235 * @param[in] ny Number of rows (y-direction).
236 * @param[in] nx Number of columns (x-direction).
237 *
238 * @return PetscErrorCode 0 on success, nonzero on failure.
239 */
240 PetscErrorCode Allocate3DArrayScalar(PetscReal ****array, PetscInt nz, PetscInt ny, PetscInt nx);
241
242/**
243 * @brief Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.
244 *
245 * This function frees the memory allocated for a 3D array of PetscReal values.
246 * It assumes the memory was allocated using Allocate3DArrayScalar, which allocated
247 * three separate memory blocks: one for the contiguous data, one for the row pointers,
248 * and one for the layer pointers.
249 *
250 * @param[in] array Pointer to the 3D array to be deallocated.
251 * @param[in] nz Number of layers (z-direction).
252 * @param[in] ny Number of rows (y-direction).
253 *
254 * @return PetscErrorCode 0 on success, nonzero on failure.
255 */
256PetscErrorCode Deallocate3DArrayScalar(PetscReal ***array, PetscInt nz, PetscInt ny);
257
258/**
259 * @brief Allocates a contiguous 3D array of `Cmpnts` values.
260 *
261 * The memory layout mirrors `Allocate3DArrayScalar`: layer pointers, row pointers,
262 * and contiguous payload are allocated such that indexing as `array[k][j][i]` is valid
263 * while keeping payload data contiguous.
264 *
265 * @param[out] array Pointer to the 3D vector array to allocate.
266 * @param[in] nz Number of layers in the z-direction.
267 * @param[in] ny Number of rows in the y-direction.
268 * @param[in] nx Number of columns in the x-direction.
269 * @return PetscErrorCode 0 on success, nonzero on failure.
270 */
271 PetscErrorCode Allocate3DArrayVector(Cmpnts ****array, PetscInt nz, PetscInt ny, PetscInt nx);
272
273/**
274 * @brief Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.
275 *
276 * This function frees the memory allocated for a 3D array of Cmpnts structures.
277 * It assumes the memory was allocated using Allocate3DArrayVector, which created three
278 * separate memory blocks: one for the contiguous vector data, one for the row pointers,
279 * and one for the layer pointers.
280 *
281 * @param[in] array Pointer to the 3D array to be deallocated.
282 * @param[in] nz Number of layers in the z-direction.
283 * @param[in] ny Number of rows in the y-direction.
284 *
285 * @return PetscErrorCode 0 on success, nonzero on failure.
286 */
287PetscErrorCode Deallocate3DArrayVector(Cmpnts ***array, PetscInt nz, PetscInt ny);
288
289/**
290 * @brief Determines the global starting index and number of CELLS owned by the
291 * current processor in a specified dimension. Ownership is defined by the
292 * rank owning the cell's origin node (min i,j,k corner).
293 *
294 * @param[in] info_nodes Pointer to the DMDALocalInfo struct obtained from the NODE-based DMDA
295 * (e.g., user->da or user->fda, assuming they have consistent nodal partitioning
296 * for defining cell origins).
297 * @param[in] dim The dimension to compute the range for (0 for x/i, 1 for y/j, 2 for z/k).
298 * @param[out] xs_cell_global_out Pointer to store the starting global cell index owned by this process.
299 * @param[out] xm_cell_local_out Pointer to store the number of owned cells in this dimension.
300 *
301 * @return PetscErrorCode 0 on success.
302 */
303PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes,
304 PetscInt dim,
305 PetscInt *xs_cell_global_out,
306 PetscInt *xm_cell_local_out);
307
308/**
309 * @brief Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.
310 *
311 * This function retrieves the neighbor information from the primary DMDA (user->da)
312 * and stores the face neighbors (xm, xp, ym, yp, zm, zp) in the user->neighbors structure.
313 * It assumes a standard PETSc ordering for the neighbors array returned by DMDAGetNeighbors.
314 * Logs warnings if the assumed indices seem incorrect (e.g., center rank mismatch).
315 *
316 * @param[in,out] user Pointer to the UserCtx structure where neighbor info will be stored.
317 *
318 * @return PetscErrorCode 0 on success, non-zero on failure.
319 */
320PetscErrorCode ComputeAndStoreNeighborRanks(UserCtx *user);
321
322/**
323 * @brief Sets the processor layout for a given DMDA based on PETSc options.
324 *
325 * Reads the desired number of processors in x, y, and z directions using
326 * PETSc options (e.g., -dm_processors_x, -dm_processors_y, -dm_processors_z).
327 * If an option is not provided for a direction, PETSC_DECIDE is used for that direction.
328 * Applies the layout using DMDASetNumProcs.
329 *
330 * Also stores the retrieved/decided values in user->procs_x/y/z if user context is provided.
331 *
332 * @param dm The DMDA object to configure the layout for.
333 * @param user Pointer to the UserCtx structure (optional, used to store layout values).
334 *
335 * @return PetscErrorCode 0 on success, non-zero on failure.
336 */
337PetscErrorCode SetDMDAProcLayout(DM dm, UserCtx *user);
338
339/**
340 * @brief Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchange.
341 *
342 * This function orchestrates the following steps:
343 * 1. Compute and store the neighbor ranks in the user context.
344 * 2. Gather all local bounding boxes to rank 0.
345 * 3. Broadcast the complete bounding box list to all ranks.
346 *
347 * The final result is that each rank has access to its immediate neighbors and the bounding box information of all ranks.
348 *
349 * @param[in,out] simCtx Pointer to initialized simulation context that owns all block UserCtx objects.
350 *
351 * @return PetscErrorCode Returns 0 on success or non-zero PETSc error code.
352 */
353PetscErrorCode SetupDomainRankInfo(SimCtx *simCtx);
354
355/**
356 * @brief Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant
357 * velocity (Ucont) defined on cell faces.
358 *
359 * This function performs the transformation from a contravariant velocity representation
360 * (which is natural on a curvilinear grid) to a Cartesian (x,y,z) representation.
361 * For each interior computational cell owned by the rank, it performs the following:
362 *
363 * 1. It averages the contravariant velocity components (U¹, U², U³) from the
364 * surrounding faces to get an estimate of the contravariant velocity at the cell center.
365 * 2. It averages the metric vectors (Csi, Eta, Zet) from the surrounding faces
366 * to get an estimate of the metric tensor at the cell center. This tensor forms
367 * the transformation matrix.
368 * 3. It solves the linear system `[MetricTensor] * [ucat] = [ucont]` for the
369 * Cartesian velocity vector `ucat = (u,v,w)` using Cramer's rule.
370 * 4. The computed Cartesian velocity is stored only at independent owned cells in
371 * the global `user->Ucat` vector.
372 *
373 * The function operates on local, ghosted versions of the input vectors (`user->lUcont`,
374 * `user->lCsi`, etc.) to ensure stencils are valid across processor boundaries.
375 *
376 * @param[in,out] user Pointer to the UserCtx structure. The function reads from
377 * `user->lUcont`, `user->lCsi`, `user->lEta`, `user->lZet`, `user->lNvert`
378 * and writes to the global `user->Ucat` vector.
379 *
380 * @return PetscErrorCode 0 on success.
381 *
382 * @note
383 * - This function should be called AFTER `user->lUcont` and all local metric vectors
384 * (`user->lCsi`, etc.) have been populated with up-to-date ghost values via `UpdateLocalGhosts`.
385 * - It only computes `Ucat` for interior cells (not on physical boundaries) and for
386 * cells not marked as solid/blanked by `user->lNvert`.
387 * - The function performs no communication, does not synchronize periodic duplicate
388 * planes, and does not refresh `user->lUcat`.
389 * - Before stencil consumption, the caller must synchronize periodic cell values with
390 * `SynchronizePeriodicCellFields(user, 1, {FIELD_ID_UCAT})` and then call
391 * `UpdateLocalGhosts(user, FIELD_ID_UCAT)`. The latter remains necessary for the fully
392 * nonperiodic case because periodic synchronization is then a no-op.
393 */
394PetscErrorCode Contra2Cart(UserCtx *user);
395
396/**
397 * @brief Convert the ghosted Cartesian velocity field to contravariant face fluxes.
398 * @ingroup InitialConditions
399 *
400 * Interpolates `user->lUcat` to each logical face and dots it with the
401 * corresponding face-area metric vector. Writes independent entries of
402 * `user->Ucont`. Periodic and physical endpoint values in `user->lUcat` must be
403 * finalized and its MPI ghosts current before entry. The resulting `Ucont` is not
404 * synchronized; callers must use the staggered-field workflow before stencil use.
405 *
406 * @param[in,out] user UserCtx for the block; Ucont is written in place.
407 * @return PetscErrorCode 0 on success.
408 */
409PetscErrorCode Cart2Contra(UserCtx *user);
410
411/**
412 * @brief Populate contravariant fluxes from one uniform Cartesian velocity.
413 *
414 * @param[in,out] user UserCtx for the block; Ucont is written in place.
415 * @param[in] u Physical x-velocity component.
416 * @param[in] v Physical y-velocity component.
417 * @param[in] w Physical z-velocity component.
418 * @return PetscErrorCode 0 on success.
419 */
420PetscErrorCode UniformCart2Contra(UserCtx *user, PetscReal u, PetscReal v, PetscReal w);
421
422
423/**
424 * @brief Creates and distributes a map of the domain's cell decomposition to all ranks.
425 * @ingroup DomainInfo
426 *
427 * This function is a critical part of the simulation setup. It determines the global
428 * cell ownership for each MPI rank and makes this information available to all
429 * other ranks. This "decomposition map" is essential for the robust "Walk and Handoff"
430 * particle migration strategy, allowing any rank to quickly identify the owner of a
431 * target cell.
432 *
433 * The process involves:
434 * 1. Each rank gets its own node ownership information from the DMDA.
435 * 2. It converts this node information into cell ownership ranges using the
436 * `GetOwnedCellRange` helper function.
437 * 3. It participates in an `MPI_Allgather` collective operation to build a complete
438 * array (`user->RankCellInfoMap`) containing the ownership information for every rank.
439 *
440 * This function should be called once during initialization after the primary DMDA
441 * (user->da) has been set up.
442 *
443 * @param[in,out] user Pointer to the UserCtx structure. The function will allocate and
444 * populate `user->RankCellInfoMap` and set `user->num_ranks`.
445 *
446 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
447 * Errors can occur if input pointers are NULL or if MPI communication fails.
448 */
449PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user);
450
451/**
452 * @brief Performs a binary search for a key in a sorted array of PetscInt64.
453 *
454 * This is a standard binary search algorithm implemented as a PETSc-style helper function.
455 * It efficiently determines if a given `key` exists within a `sorted` array.
456 *
457 * @param[in] n The number of elements in the array.
458 * @param[in] arr A pointer to the sorted array of PetscInt64 values to be searched.
459 * @param[in] key The PetscInt64 value to search for.
460 * @param[out] found A pointer to a PetscBool that will be set to PETSC_TRUE if the key
461 * is found, and PETSC_FALSE otherwise.
462 *
463 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
464 *
465 * @note The input array `arr` **must** be sorted in ascending order for the algorithm
466 * to work correctly.
467 */
468PetscErrorCode BinarySearchInt64(PetscInt n, const PetscInt64 arr[], PetscInt64 key, PetscBool *found);
469
470
471/**
472 * @brief Computes the discrete divergence of the contravariant velocity field.
473 *
474 * This diagnostic/kernel routine evaluates continuity residuals on the local block
475 * and writes the resulting divergence field into the configured output vector(s).
476 *
477 * @param[in,out] user Block-level context containing velocity and metric fields.
478 * @return PetscErrorCode 0 on success.
479 */
480PetscErrorCode ComputeDivergence(UserCtx *user);
481
482/**
483 * @brief Initializes random number generators for assigning particle properties.
484 *
485 * This function creates and configures separate PETSc random number generators for the x, y, and z coordinates.
486 *
487 * @param[in,out] user Pointer to the UserCtx structure containing simulation context.
488 * @param[out] randx Pointer to store the RNG for the x-coordinate.
489 * @param[out] randy Pointer to store the RNG for the y-coordinate.
490 * @param[out] randz Pointer to store the RNG for the z-coordinate.
491 *
492 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
493 */
494PetscErrorCode InitializeRandomGenerators(UserCtx *user, PetscRandom *randx, PetscRandom *randy, PetscRandom *randz);
495
496/**
497 * @brief Initializes random number generators for logical space operations [0.0, 1.0).
498 *
499 * This function creates and configures three separate PETSc random number generators,
500 * one for each logical dimension (i, j, k or xi, eta, zeta equivalent).
501 * Each RNG is configured to produce uniformly distributed real numbers in the interval [0.0, 1.0).
502 * These are typically used for selecting owned cells or generating intra-cell logical coordinates.
503 *
504 * @param[in] base_seed Base particle seed (`SimCtx::particleRandomSeed`); each stream adds a fixed offset and the rank.
505 * @param[out] rand_logic_i Pointer to store the RNG for the i-logical dimension.
506 * @param[out] rand_logic_j Pointer to store the RNG for the j-logical dimension.
507 * @param[out] rand_logic_k Pointer to store the RNG for the k-logical dimension.
508 *
509 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
510 */
511PetscErrorCode InitializeLogicalSpaceRNGs(PetscInt base_seed, PetscRandom *rand_logic_i, PetscRandom *rand_logic_j, PetscRandom *rand_logic_k);
512
513/**
514 * @brief Initializes a single master RNG for time-stepping physics (Brownian motion).
515 * Configures it for Uniform [0, 1) which is required for Box-Muller transformation.
516 * Seeded from `particleRandomSeed`, the rank, and `StartStep`, so identical inputs on
517 * the same rank count reproduce, and a restart draws a fresh sequence.
518 *
519 * @param[in,out] simCtx Pointer to the Simulation Context.
520 * @return PetscErrorCode
521 */
522PetscErrorCode InitializeBrownianRNG(SimCtx *simCtx);
523
524/**
525 * @brief Transforms scalar derivatives from computational space to physical space
526 *
527 * using the chain rule.
528 * Formula: dPhi/dx = J * ( dPhi/dCsi * dCsi/dx + dPhi/dEta * dEta/dx + ... )
529 *
530 * @param jacobian Local mapping Jacobian determinant.
531 * @param csi_metrics Physical gradient of the xi coordinate.
532 * @param eta_metrics Physical gradient of the eta coordinate.
533 * @param zet_metrics Physical gradient of the zeta coordinate.
534 * @param dPhi_dcsi Scalar derivative in the xi direction.
535 * @param dPhi_deta Scalar derivative in the eta direction.
536 * @param dPhi_dzet Scalar derivative in the zeta direction.
537 * @param[out] gradPhi Physical Cartesian scalar gradient.
538 */
539 void TransformScalarDerivativesToPhysical(PetscReal jacobian,
540 Cmpnts csi_metrics,
541 Cmpnts eta_metrics,
542 Cmpnts zet_metrics,
543 PetscReal dPhi_dcsi,
544 PetscReal dPhi_deta,
545 PetscReal dPhi_dzet,
546 Cmpnts *gradPhi);
547
548/**
549 * @brief Computes the gradient of a cell-centered SCALAR field at a specific grid point.
550 *
551 * @param user Block metric context.
552 * @param i Cell index in the xi direction.
553 * @param j Cell index in the eta direction.
554 * @param k Cell index in the zeta direction.
555 * @param field_data Ghosted scalar values indexed as [k][j][i].
556 * @param[out] grad Physical Cartesian gradient at the requested cell.
557 * @return PetscErrorCode 0 on success.
558 */
559PetscErrorCode ComputeScalarFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k,
560 PetscReal ***field_data, Cmpnts *grad);
561
562/**
563 * @brief Computes the derivatives of a cell-centered vector field at a specific grid point.
564 *
565 * This function orchestrates the calculation of spatial derivatives. It first computes
566 * the derivatives in computational space (d/dcsi, d/deta, d/dzet) using a central
567 * difference scheme and then transforms them into physical space (d/dx, d/dy, d/dz).
568 *
569 * @param user Block metric context.
570 * @param i Cell index in the xi direction.
571 * @param j Cell index in the eta direction.
572 * @param k Cell index in the zeta direction.
573 * @param field_data Ghosted Cartesian vector values indexed as [k][j][i].
574 * @param[out] dudx Gradient of the x velocity component.
575 * @param[out] dvdx Gradient of the y velocity component.
576 * @param[out] dwdx Gradient of the z velocity component.
577 * @return PetscErrorCode 0 on success.
578 */
579PetscErrorCode ComputeVectorFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, Cmpnts ***field_data,
580 Cmpnts *dudx, Cmpnts *dvdx, Cmpnts *dwdx);
581
582/**
583 * @brief Installs the shipped defaults for every LES closure parameter.
584 *
585 * One definition of the defaults, shared by the control-file ingress and by test
586 * fixtures, so the two cannot drift apart. It lives with the rest of the context
587 * construction because defaults are ingress, not closure behaviour, and because the
588 * postprocessor builds a simulation context without linking the LES module.
589 *
590 * Local averaging and clamped limiting are the defaults because they are the only
591 * settings valid on arbitrary geometry; cases with homogeneous directions or an
592 * interest in backscatter opt into the alternatives.
593 *
594 * @param[out] config Configuration block to populate.
595 * @return PetscErrorCode 0 on success, or `PETSC_ERR_ARG_NULL` for a null argument.
596 */
597PetscErrorCode LESConfigSetDefaults(LESConfig *config);
598
599/**
600 * @brief Destroys all PETSc Vec objects within a single UserCtx structure.
601 *
602 * This helper function systematically destroys the Vec objects stored in a UserCtx.
603 * The vectors are organized into functional groups for clarity:
604 * - Primary flow fields (Ucont, Ucat, P, Nvert)
605 * - Solver work vectors (Phi)
606 * - Time-stepping vectors (Ucont_o, Ucont_rm1, etc.)
607 * - Grid metrics (cell-centered, face-centered, coordinates)
608 * - Turbulence vectors (Nu_t, CS, lFriction_Velocity)
609 * - Particle vectors (ParticleCount, Psi)
610 * - Boundary condition vectors (Ubcs, Uch)
611 * - Post-processing vectors (P_nodal, Qcrit)
612 * - And more...
613 *
614 * All destroys are protected with NULL checks to handle conditional allocations safely.
615 *
616 * @param[in,out] user Pointer to the UserCtx containing the vectors to destroy.
617 *
618 * @return PetscErrorCode 0 on success.
619 */
620PetscErrorCode DestroyUserVectors(UserCtx *user);
621
622/**
623 * @brief Destroys all resources allocated within a single UserCtx structure.
624 *
625 * This function cleans up all memory and PETSc objects associated with a single
626 * UserCtx (grid level). It calls the helper functions and destroys remaining objects
627 * in the proper dependency order:
628 * 1. Boundary conditions (handlers and their data)
629 * 2. All PETSc vectors (via DestroyUserVectors)
630 * 3. Matrix and solver objects (A, MR, MP, ksp, nullsp)
631 * 4. Application ordering (AO)
632 * 5. Distributed mesh objects (DMs) - most derived first
633 * 6. Raw PetscMalloc'd arrays (RankCellInfoMap)
634 *
635 * This function should be called for each UserCtx in the multigrid hierarchy.
636 *
637 * @param[in,out] user Pointer to the UserCtx to be destroyed.
638 *
639 * @return PetscErrorCode 0 on success.
640 */
641PetscErrorCode DestroyUserContext(UserCtx *user);
642
643/**
644 * @brief Main cleanup function for the entire simulation context.
645 *
646 * This function is responsible for destroying ALL memory and PETSc objects allocated
647 * during the simulation, including:
648 * - All UserCtx structures in the multigrid hierarchy (via DestroyUserContext)
649 * - The multigrid management structures (UserMG, MGCtx array)
650 * - All SimCtx-level objects (logviewer, dm_swarm, bboxlist, string arrays, etc.)
651 * - The SimCtx allocation itself.
652 *
653 * This function should be called ONCE at the end of the simulation, after all
654 * computation is complete, but BEFORE PetscFinalize().
655 *
656 * Call order in main:
657 * 1. [Simulation runs]
658 * 2. ProfilingFinalize(simCtx);
659 * 3. FinalizeSimulation(simCtx); <- This function
660 * 4. PetscFinalize();
661 *
662 * @param[in,out] simCtx Pointer to the master SimulationContext to be destroyed.
663 * The pointer is invalid after this call returns.
664 *
665 * @return PetscErrorCode 0 on success.
666 */
667PetscErrorCode FinalizeSimulation(SimCtx *simCtx);
668
669
670 #endif // SETUP_H
Header file for Particle Motion and migration related functions.
Header file for Particle Swarm management functions.
Authoritative identities and storage metadata for persistent Eulerian fields.
FieldId
Compile-time identity for a catalogued Eulerian field.
Public interface for grid, solver, and metric setup routines.
Public interface for data input/output routines.
Logging utilities and macros for PETSc-based applications.
PetscErrorCode ComputeVectorFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, Cmpnts ***field_data, Cmpnts *dudx, Cmpnts *dvdx, Cmpnts *dwdx)
Computes the derivatives of a cell-centered vector field at a specific grid point.
Definition setup.c:4074
PetscErrorCode DestroyUserContext(UserCtx *user)
Destroys all resources allocated within a single UserCtx structure.
Definition setup.c:4278
PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
Determines the global starting index and number of CELLS owned by the current processor in a specifie...
Definition setup.c:2936
PetscErrorCode SetupDomainRankInfo(SimCtx *simCtx)
Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchang...
Definition setup.c:3227
PetscErrorCode UniformCart2Contra(UserCtx *user, PetscReal u, PetscReal v, PetscReal w)
Populate contravariant fluxes from one uniform Cartesian velocity.
Definition setup.c:3504
PetscErrorCode InitializeRandomGenerators(UserCtx *user, PetscRandom *randx, PetscRandom *randy, PetscRandom *randz)
Initializes random number generators for assigning particle properties.
Definition setup.c:3851
PetscErrorCode Deallocate3DArrayVector(Cmpnts ***array, PetscInt nz, PetscInt ny)
Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.
Definition setup.c:2870
PetscErrorCode SetupGridAndSolvers(SimCtx *simCtx)
The main orchestrator for setting up all grid-related components.
Definition setup.c:2001
PetscErrorCode InitializeBrownianRNG(SimCtx *simCtx)
Initializes a single master RNG for time-stepping physics (Brownian motion).
Definition setup.c:3940
PetscErrorCode SetupSimulationEnvironment(SimCtx *simCtx)
Verifies and prepares the complete I/O environment for a simulation run.
Definition setup.c:1685
PetscErrorCode CreateAndInitializeAllVectors(SimCtx *simCtx)
Creates and initializes all PETSc Vec objects for all fields.
Definition setup.c:2036
PetscErrorCode ComputeAndStoreNeighborRanks(UserCtx *user)
Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.
Definition setup.c:3033
PetscErrorCode Contra2Cart(UserCtx *user)
Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on...
Definition setup.c:3300
void TransformScalarDerivativesToPhysical(PetscReal jacobian, Cmpnts csi_metrics, Cmpnts eta_metrics, Cmpnts zet_metrics, PetscReal dPhi_dcsi, PetscReal dPhi_deta, PetscReal dPhi_dzet, Cmpnts *gradPhi)
Transforms scalar derivatives from computational space to physical space.
Definition setup.c:3983
int PicurvHandleVersionArgument(int argc, char **argv, const char *executable_name)
Print the shared native build identity when a version flag is present.
Definition setup.c:47
PetscErrorCode InitializeLogicalSpaceRNGs(PetscInt base_seed, PetscRandom *rand_logic_i, PetscRandom *rand_logic_j, PetscRandom *rand_logic_k)
Initializes random number generators for logical space operations [0.0, 1.0).
Definition setup.c:3895
PetscErrorCode DestroySolutionConvergenceState(SimCtx *simCtx)
Frees any runtime storage allocated for solution-convergence logging.
Definition setup.c:148
PetscErrorCode Allocate3DArrayScalar(PetscReal ****array, PetscInt nz, PetscInt ny, PetscInt nx)
Allocates a 3D array of PetscReal values using PetscCalloc.
Definition setup.c:2742
PetscErrorCode CreateSimulationContext(int argc, char **argv, SimCtx **p_simCtx)
Allocates and populates the master SimulationContext object.
Definition setup.c:371
PetscErrorCode InitializeSolutionConvergenceState(SimCtx *simCtx)
Allocates any runtime storage required by solution-convergence logging.
Definition setup.c:96
PetscErrorCode SetDMDAProcLayout(DM dm, UserCtx *user)
Sets the processor layout for a given DMDA based on PETSc options.
Definition setup.c:3149
PetscErrorCode ComputeScalarFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscReal ***field_data, Cmpnts *grad)
Computes the gradient of a cell-centered SCALAR field at a specific grid point.
Definition setup.c:4031
PetscErrorCode ComputeDivergence(UserCtx *user)
Computes the discrete divergence of the contravariant velocity field.
Definition setup.c:3685
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2489
PetscErrorCode BinarySearchInt64(PetscInt n, const PetscInt64 arr[], PetscInt64 key, PetscBool *found)
Performs a binary search for a key in a sorted array of PetscInt64.
Definition setup.c:3616
PetscErrorCode Cart2Contra(UserCtx *user)
Convert the ghosted Cartesian velocity field to contravariant face fluxes.
Definition setup.c:3435
PetscErrorCode DestroyUserVectors(UserCtx *user)
Destroys all PETSc Vec objects within a single UserCtx structure.
Definition setup.c:4128
PetscErrorCode Allocate3DArrayVector(Cmpnts ****array, PetscInt nz, PetscInt ny, PetscInt nx)
Allocates a contiguous 3D array of Cmpnts values.
Definition setup.c:2820
PetscErrorCode SetupBoundaryConditions(SimCtx *simCtx)
(Orchestrator) Sets up all boundary conditions for the simulation.
Definition setup.c:2678
PetscErrorCode LESConfigSetDefaults(LESConfig *config)
Installs the shipped defaults for every LES closure parameter.
Definition setup.c:206
PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user)
Creates and distributes a map of the domain's cell decomposition to all ranks.
Definition setup.c:3551
PetscErrorCode FinalizeSimulation(SimCtx *simCtx)
Main cleanup function for the entire simulation context.
Definition setup.c:4368
PetscErrorCode Deallocate3DArrayScalar(PetscReal ***array, PetscInt nz, PetscInt ny)
Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.
Definition setup.c:2777
PetscBool RuntimeWalltimeGuardParsePositiveSeconds(const char *text, PetscReal *seconds_out)
Parse a positive floating-point seconds value from runtime metadata.
Definition setup.c:67
Main header file for a complex fluid dynamics solver.
A 3D point or vector with PetscScalar components.
Definition variables.h:121
Every user-selectable parameter of the LES closure.
Definition variables.h:629
The master context for the entire simulation.
Definition variables.h:859
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1074
Header file for particle location functions using the walking search algorithm.