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> <int32|int64> <arch> <dir>`,
30 * the third field being the width of PetscInt.
31 * The second line is also kept in the binary behind a `PICURV_PETSC_BUILD:`
32 * marker, so the conductor can read it from a binary that cannot start.
33 * @param[in] argc Native executable argument count.
34 * @param[in] argv Native executable argument vector.
35 * @param[in] executable_name Name printed when argv[0] is absent; otherwise the basename of
36 * argv[0] is printed, so `simulator64` names itself as the conductor staged it.
37 * @return Nonzero when a version flag was handled and execution should stop.
38 */
39int PicurvHandleVersionArgument(int argc, char **argv, const char *executable_name);
40
41/**
42 * @brief Refuse to start when the loaded libpetsc's PetscInt width differs from this build's.
43 * @details The 32- and 64-bit-index PETSc builds share the library name libpetsc.so.MAJOR.MINOR,
44 * so another build's library first on LD_LIBRARY_PATH (a PETSc module, say) is loaded
45 * without complaint and corrupts every size it is handed. The library reports its own
46 * width through PetscDataTypeGetSize(PETSC_INT), whose signature does not depend on it,
47 * so this is safe to call before PetscInitialize().
48 * @param[in] argc Native executable argument count.
49 * @param[in] argv Native executable argument vector; the message names argv[0]'s basename.
50 * @param[in] executable_name Name used in the message when argv[0] is absent.
51 * @return 0 when the widths agree; nonzero, after a message on stderr, when they do not.
52 */
53int PicurvCheckLinkedPetscIndexWidth(int argc, char **argv, const char *executable_name);
54
55/**
56 * @brief Refuse a PETSc object whose global size this build's PetscInt cannot index.
57 * @details A vector's or matrix's global size, and every index into it, is a PetscInt. Past
58 * PETSC_MAX_INT a 32-bit-index build overflows silently, corrupting sizes, ownership
59 * ranges and checkpoint headers, so every object PICurv sizes passes through here
60 * before it is created: particle fields at setup, each grid DM where grid.c creates
61 * it, and so every solver's vectors and matrices built on those DMs.
62 * @param[in] comm Communicator on which the refusal is raised (collective when it is).
63 * @param[in] entries Global entries the object needs, computed in 64 bits.
64 * @param[in] object What the object is, for the message (e.g. "a 3-component grid DM").
65 * @return 0, or PETSC_ERR_ARG_OUTOFRANGE naming the remedy (a 64-bit-index PETSc build).
66 */
67PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object);
68
69
70/* Macro to automatically select the correct allocation function */
71#define Allocate3DArray(array, nz, ny, nx) \
72 _Generic((array), \
73 PetscReal ****: Allocate3DArrayScalar, \
74 Cmpnts ****: Allocate3DArrayVector \
75 )(array, nz, ny, nx)
76
77/* Macro for deallocation */
78#define Deallocate3DArray(array, nz, ny) \
79 _Generic((array), \
80 PetscReal ***: Deallocate3DArrayScalar, \
81 Cmpnts ***: Deallocate3DArrayVector \
82 )(array, nz, ny)
83
84
85/**
86 * @brief Allocates and populates the master SimulationContext object.
87 *
88 * This function serves as the single, authoritative entry point for all
89 * simulation configuration. It merges the setup logic from both the legacy
90 * FSI/IBM solver and the modern particle solver into a unified, robust
91 * process.
92 *
93 * The function follows a strict sequence:
94 * 1. **Allocate Context & Set Defaults:** It first allocates the `SimulationContext`
95 * and populates every field with a sane, hardcoded default value. This
96 * ensures the simulation starts from a known, predictable state.
97 * 2. **Configure Logging System:** It configures the custom logging framework. It
98 * parses the `-func_config_file` option to load a list of function names
99 * allowed to produce log output. This configuration (the file path and the
100 * list of function names) is stored within the `SimulationContext` for
101 * later reference and cleanup.
102 * 3. **Parse All Options:** It performs a comprehensive pass of `PetscOptionsGet...`
103 * calls for every possible command-line flag, overriding the default
104 * values set in step 1.
105 * 4. **Log Summary:** After all options are parsed, it uses the now-active
106 * logging system to print a summary of the key simulation parameters.
107 *
108 * @param[in] argc Argument count passed from `main`.
109 * @param[in] argv Argument vector passed from `main`.
110 * @param[out] p_simCtx On success, this will point to the newly created and
111 * fully configured `SimulationContext` pointer. The caller
112 * is responsible for eventually destroying this object by
113 * calling `FinalizeSimulation()`.
114 *
115 * @return PetscErrorCode Returns 0 on success, or a non-zero PETSc error code on failure.
116 */
117PetscErrorCode CreateSimulationContext(int argc, char **argv, SimCtx **p_simCtx);
118
119/**
120 * @brief Parse a positive floating-point seconds value from runtime metadata.
121 *
122 * This helper is used for shell-exported walltime metadata such as
123 * `PICURV_JOB_START_EPOCH` and `PICURV_WALLTIME_LIMIT_SECONDS`.
124 *
125 * @param[in] text String to parse.
126 * @param[out] seconds_out Parsed positive seconds value when successful.
127 * @return PetscBool `PETSC_TRUE` when parsing succeeds, else `PETSC_FALSE`.
128 */
129PetscBool RuntimeWalltimeGuardParsePositiveSeconds(const char *text, PetscReal *seconds_out);
130
131/**
132 * @brief Verifies and prepares the complete I/O environment for a simulation run.
133 *
134 * This function performs a comprehensive series of checks and setup actions to
135 * ensure a valid and clean environment. It is parallel-safe; all filesystem
136 * operations and checks are performed by Rank 0, with collective error handling.
137 *
138 * The function's responsibilities include:
139 * 1. **Checking Mandatory Inputs:** Verifies existence of grid and BCs files.
140 * 2. **Checking Optional Inputs:** Warns if optional config files (whitelist, profile) are missing.
141 * 3. **Validating Run Mode Paths:** Ensures `restart_dir` or post-processing source directories exist when needed.
142 * 4. **Preparing Log Directory:** Creates the log directory and cleans it of previous logs.
143 * 5. **Preparing Output Directories:** Creates the main output directory and its required subdirectories.
144 *
145 * @param[in] simCtx The fully configured SimulationContext object.
146 *
147 * @return PetscErrorCode Returns 0 on success, or a non-zero error code if a
148 * mandatory file/directory is missing or a critical operation fails.
149 */
150PetscErrorCode SetupSimulationEnvironment(SimCtx *simCtx);
151
152/**
153 * @brief The main orchestrator for setting up all grid-related components.
154 *
155 * This function is the high-level driver for creating the entire computational
156 * domain, including the multigrid hierarchy, PETSc DMDA and Vec objects, and
157 * calculating all necessary grid metrics.
158 *
159 * @param simCtx The fully configured SimulationContext.
160 * @return PetscErrorCode
161 */
162PetscErrorCode SetupGridAndSolvers(SimCtx *simCtx);
163
164/**
165 @brief Creates and initializes all PETSc Vec objects for all fields.
166 *
167 * This function iterates through every UserCtx in the multigrid and multi-block
168 * hierarchy. For each context, it creates the comprehensive set of global and
169 * local PETSc Vecs required by the flow solver (e.g., Ucont, P, Nvert, metrics,
170 * turbulence fields, etc.). Each vector is initialized to zero.
171 *
172 * @param simCtx The master SimCtx, containing the configured UserCtx hierarchy.
173 * @return PetscErrorCode
174 */
175PetscErrorCode CreateAndInitializeAllVectors(SimCtx *simCtx);
176
177/**
178 * @brief Updates the local vector (including ghost points) from its corresponding global vector.
179 *
180 * This function resolves the correct global vector, local vector, and DM from the
181 * authoritative field catalog and performs the standard PETSc
182 * DMGlobalToLocalBegin/End sequence.
183 * For registered single-face-family and component-staggered fields, it then
184 * repairs the adjacent periodic ghost in each normal direction so central
185 * differences see the correct neighboring face. Cell-centered fields and
186 * tangential face directions retain PETSc's native periodic wraparound.
187 * Includes optional debugging output (max norms before/after).
188 *
189 * @param user The UserCtx structure containing the vectors and DMs.
190 * @param field_id Typed identity of the catalogued field to update.
191 *
192 * @return PetscErrorCode 0 on success, non-zero on failure.
193 *
194 * @note This function assumes the global vector associated with field_id has already
195 * been populated with the desired data (including any boundary conditions and
196 * periodic duplicate planes). It scatters that current global state into the
197 * local vector; it does not repair stale global periodic duplicate planes.
198 * @note Wider QUICK-style normal ghost layers require a separate dedicated
199 * exchange; this function repairs the adjacent layer used by central stencils.
200 */
201PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id);
202
203/**
204 * @brief Applies a catalogued field's periodic normal-face ghost repair to a local vector.
205 * @details The step UpdateLocalGhosts() runs after its scatter: for single-face-family and
206 * component-staggered fields, each active periodic face's adjacent normal ghost is
207 * rewritten from the deeper PETSc ghost; other fields are left unchanged. The result
208 * depends only on the local vector's scattered entries, so it may be reapplied after
209 * any partial rescatter of them.
210 * @param user Block context owning the field's boundary metadata.
211 * @param view Field view from FieldGetView(); its DM lays out local_vec.
212 * @param local_vec Local vector to repair: the field's own, or a scratch copy of it.
213 * @return PetscErrorCode 0 on success.
214 */
215PetscErrorCode RepairPeriodicFieldGhosts(UserCtx *user, const FieldView *view, Vec local_vec);
216
217/**
218 * @brief (Orchestrator) Sets up all boundary conditions for the simulation.
219 *
220 * @param simCtx Simulation context controlling the operation.
221 * @return PetscErrorCode 0 on success.
222 */
223PetscErrorCode SetupBoundaryConditions(SimCtx *simCtx);
224
225/**
226 * @brief Allocates any runtime storage required by solution-convergence logging.
227 *
228 * This helper is setup-owned because it allocates mode-specific buffers once
229 * the finest-level Eulerian vectors already exist. It does not compute or log
230 * any metrics; it only prepares storage for later use by
231 * `LOG_SOLUTION_CONVERGENCE()`.
232 *
233 * Allocation depends on the active solution-convergence mode:
234 * - steady/transient: no extra storage beyond counters
235 * - periodic_deterministic: one phase-aligned `Ucat` / `P` reference slot per
236 * configured period step and per block
237 * - statistical_steady: rolling scalar histories sized for two adjacent
238 * windows of `mean_speed` and `mean_ke`
239 *
240 * The helper also resets the recorded-sample counter so warmup behavior starts
241 * from a clean state each time solver setup is rebuilt.
242 *
243 * @param[in,out] simCtx Master simulation context owning the runtime storage.
244 * @return PetscErrorCode 0 on success.
245 */
246PetscErrorCode InitializeSolutionConvergenceState(SimCtx *simCtx);
247
248/**
249 * @brief Frees any runtime storage allocated for solution-convergence logging.
250 *
251 * This helper is the cleanup counterpart to
252 * `InitializeSolutionConvergenceState()`. It releases periodic reference
253 * buffers and statistical-history arrays, then resets the associated pointers
254 * and counters. It is safe to call during teardown even if a given mode never
255 * allocated optional storage.
256 *
257 * @param[in,out] simCtx Master simulation context owning the runtime storage.
258 * @return PetscErrorCode 0 on success.
259 */
260PetscErrorCode DestroySolutionConvergenceState(SimCtx *simCtx);
261
262/**
263 * @brief Allocates a 3D array of PetscReal values using PetscCalloc.
264 *
265 * This function dynamically allocates memory for a 3D array of PetscReal values
266 * with dimensions nz (layers) x ny (rows) x nx (columns). It uses PetscCalloc1
267 * to ensure the memory is zero-initialized.
268 *
269 * The allocation is done in three steps:
270 * 1. Allocate an array of nz pointers (one for each layer).
271 * 2. Allocate a contiguous block for nz*ny row pointers and assign each layer’s row pointers.
272 * 3. Allocate a contiguous block for all nz*ny*nx PetscReal values.
273 *
274 * This setup allows the array to be accessed as array[k][j][i], and the memory
275 * for the data is contiguous, which improves cache efficiency.
276 *
277 * @param[out] array Pointer to the 3D array to be allocated.
278 * @param[in] nz Number of layers (z-direction).
279 * @param[in] ny Number of rows (y-direction).
280 * @param[in] nx Number of columns (x-direction).
281 *
282 * @return PetscErrorCode 0 on success, nonzero on failure.
283 */
284 PetscErrorCode Allocate3DArrayScalar(PetscReal ****array, PetscInt nz, PetscInt ny, PetscInt nx);
285
286/**
287 * @brief Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.
288 *
289 * This function frees the memory allocated for a 3D array of PetscReal values.
290 * It assumes the memory was allocated using Allocate3DArrayScalar, which allocated
291 * three separate memory blocks: one for the contiguous data, one for the row pointers,
292 * and one for the layer pointers.
293 *
294 * @param[in] array Pointer to the 3D array to be deallocated.
295 * @param[in] nz Number of layers (z-direction).
296 * @param[in] ny Number of rows (y-direction).
297 *
298 * @return PetscErrorCode 0 on success, nonzero on failure.
299 */
300PetscErrorCode Deallocate3DArrayScalar(PetscReal ***array, PetscInt nz, PetscInt ny);
301
302/**
303 * @brief Allocates a contiguous 3D array of `Cmpnts` values.
304 *
305 * The memory layout mirrors `Allocate3DArrayScalar`: layer pointers, row pointers,
306 * and contiguous payload are allocated such that indexing as `array[k][j][i]` is valid
307 * while keeping payload data contiguous.
308 *
309 * @param[out] array Pointer to the 3D vector array to allocate.
310 * @param[in] nz Number of layers in the z-direction.
311 * @param[in] ny Number of rows in the y-direction.
312 * @param[in] nx Number of columns in the x-direction.
313 * @return PetscErrorCode 0 on success, nonzero on failure.
314 */
315 PetscErrorCode Allocate3DArrayVector(Cmpnts ****array, PetscInt nz, PetscInt ny, PetscInt nx);
316
317/**
318 * @brief Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.
319 *
320 * This function frees the memory allocated for a 3D array of Cmpnts structures.
321 * It assumes the memory was allocated using Allocate3DArrayVector, which created three
322 * separate memory blocks: one for the contiguous vector data, one for the row pointers,
323 * and one for the layer pointers.
324 *
325 * @param[in] array Pointer to the 3D array to be deallocated.
326 * @param[in] nz Number of layers in the z-direction.
327 * @param[in] ny Number of rows in the y-direction.
328 *
329 * @return PetscErrorCode 0 on success, nonzero on failure.
330 */
331PetscErrorCode Deallocate3DArrayVector(Cmpnts ***array, PetscInt nz, PetscInt ny);
332
333/**
334 * @brief Determines the global starting index and number of CELLS owned by the
335 * current processor in a specified dimension. Ownership is defined by the
336 * rank owning the cell's origin node (min i,j,k corner).
337 *
338 * @param[in] info_nodes Pointer to the DMDALocalInfo struct obtained from the NODE-based DMDA
339 * (e.g., user->da or user->fda, assuming they have consistent nodal partitioning
340 * for defining cell origins).
341 * @param[in] dim The dimension to compute the range for (0 for x/i, 1 for y/j, 2 for z/k).
342 * @param[out] xs_cell_global_out Pointer to store the starting global cell index owned by this process.
343 * @param[out] xm_cell_local_out Pointer to store the number of owned cells in this dimension.
344 *
345 * @return PetscErrorCode 0 on success.
346 */
347PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes,
348 PetscInt dim,
349 PetscInt *xs_cell_global_out,
350 PetscInt *xm_cell_local_out);
351
352/**
353 * @brief Which grid axes are periodic.
354 * @details From the run's flags, which the loader derives from the boundary files and which
355 * selected DM_BOUNDARY_PERIODIC when the DMDAs were built. The loader refuses a case
356 * whose opposite faces or whose blocks disagree on periodicity, so the flags hold for
357 * every face, block and multigrid level.
358 * @param[in] simCtx Simulation context.
359 * @param[out] periodic Whether the i, j and k axes are periodic.
360 */
361static inline void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
362{
363 periodic[0] = (PetscBool)(simCtx->i_periodic != 0);
364 periodic[1] = (PetscBool)(simCtx->j_periodic != 0);
365 periodic[2] = (PetscBool)(simCtx->k_periodic != 0);
366}
367
368/**
369 * @brief Index bounds of the interior cells this rank owns in the solver's cell-centred
370 * layout: the owned range with the dummy layer at index 0 and at index m-1 removed.
371 * @details `lo[a] <= c < hi[a]` along each axis. A periodic axis is treated like a walled
372 * one: its seam face at index 0 is not included, and callers that set it extend
373 * the range themselves.
374 * @param[in] info Local info of the block's da (or fda; they share the decomposition).
375 * @param[out] lo First owned interior index along i, j, k.
376 * @param[out] hi One past the last owned interior index along i, j, k.
377 */
378static inline void GetOwnedInteriorCellBounds(const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
379{
380 const PetscInt m[3] = {info->mx, info->my, info->mz};
381 const PetscInt start[3] = {info->xs, info->ys, info->zs};
382 const PetscInt end[3] = {info->xs + info->xm, info->ys + info->ym, info->zs + info->zm};
383
384 for (PetscInt a = 0; a < 3; a++) {
385 lo[a] = (start[a] == 0) ? 1 : start[a];
386 hi[a] = (end[a] == m[a]) ? m[a] - 1 : end[a];
387 }
388}
389
390/**
391 * @brief Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.
392 *
393 * This function retrieves the neighbor information from the primary DMDA (user->da)
394 * and stores the face neighbors (xm, xp, ym, yp, zm, zp) in the user->neighbors structure.
395 * It assumes a standard PETSc ordering for the neighbors array returned by DMDAGetNeighbors.
396 * Logs warnings if the assumed indices seem incorrect (e.g., center rank mismatch).
397 *
398 * @param[in,out] user Pointer to the UserCtx structure where neighbor info will be stored.
399 *
400 * @return PetscErrorCode 0 on success, non-zero on failure.
401 */
402PetscErrorCode ComputeAndStoreNeighborRanks(UserCtx *user);
403
404/**
405 * @brief Sets the processor layout for a given DMDA based on PETSc options.
406 *
407 * Reads the desired number of processors in x, y, and z directions using
408 * PETSc options (e.g., -dm_processors_x, -dm_processors_y, -dm_processors_z).
409 * If an option is not provided for a direction, PETSC_DECIDE is used for that direction.
410 * Applies the layout using DMDASetNumProcs.
411 *
412 * Also stores the retrieved/decided values in user->procs_x/y/z if user context is provided.
413 *
414 * @param dm The DMDA object to configure the layout for.
415 * @param user Pointer to the UserCtx structure (optional, used to store layout values).
416 *
417 * @return PetscErrorCode 0 on success, non-zero on failure.
418 */
419PetscErrorCode SetDMDAProcLayout(DM dm, UserCtx *user);
420
421/**
422 * @brief Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchange.
423 *
424 * This function orchestrates the following steps:
425 * 1. Compute and store the neighbor ranks in the user context.
426 * 2. Gather all local bounding boxes to rank 0.
427 * 3. Broadcast the complete bounding box list to all ranks.
428 *
429 * The final result is that each rank has access to its immediate neighbors and the bounding box information of all ranks.
430 *
431 * @param[in,out] simCtx Pointer to initialized simulation context that owns all block UserCtx objects.
432 *
433 * @return PetscErrorCode Returns 0 on success or non-zero PETSc error code.
434 */
435PetscErrorCode SetupDomainRankInfo(SimCtx *simCtx);
436
437/**
438 * @brief Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant
439 * velocity (Ucont) defined on cell faces.
440 *
441 * This function performs the transformation from a contravariant velocity representation
442 * (which is natural on a curvilinear grid) to a Cartesian (x,y,z) representation.
443 * For each interior computational cell owned by the rank, it performs the following:
444 *
445 * 1. It averages the contravariant velocity components (U¹, U², U³) from the
446 * surrounding faces to get an estimate of the contravariant velocity at the cell center.
447 * 2. It averages the metric vectors (Csi, Eta, Zet) from the surrounding faces
448 * to get an estimate of the metric tensor at the cell center. This tensor forms
449 * the transformation matrix.
450 * 3. It solves the linear system `[MetricTensor] * [ucat] = [ucont]` for the
451 * Cartesian velocity vector `ucat = (u,v,w)` using Cramer's rule.
452 * 4. The computed Cartesian velocity is stored only at independent owned cells in
453 * the global `user->Ucat` vector.
454 *
455 * The function operates on local, ghosted versions of the input vectors (`user->lUcont`,
456 * `user->lCsi`, etc.) to ensure stencils are valid across processor boundaries.
457 *
458 * @param[in,out] user Pointer to the UserCtx structure. The function reads from
459 * `user->lUcont`, `user->lCsi`, `user->lEta`, `user->lZet`, `user->lNvert`
460 * and writes to the global `user->Ucat` vector.
461 *
462 * @return PetscErrorCode 0 on success.
463 *
464 * @note
465 * - This function should be called AFTER `user->lUcont` and all local metric vectors
466 * (`user->lCsi`, etc.) have been populated with up-to-date ghost values via `UpdateLocalGhosts`.
467 * - It only computes `Ucat` for interior cells (not on physical boundaries) and for
468 * cells not marked as solid/blanked by `user->lNvert`.
469 * - The function performs no communication, does not synchronize periodic duplicate
470 * planes, and does not refresh `user->lUcat`.
471 * - Before stencil consumption, the caller must synchronize periodic cell values with
472 * `SynchronizePeriodicCellFields(user, 1, {FIELD_ID_UCAT})` and then call
473 * `UpdateLocalGhosts(user, FIELD_ID_UCAT)`. The latter remains necessary for the fully
474 * nonperiodic case because periodic synchronization is then a no-op.
475 */
476PetscErrorCode Contra2Cart(UserCtx *user);
477
478/**
479 * @brief Cartesian velocity at a point of one cell from the cell's face fluxes.
480 *
481 * Each contravariant flux (U^1, U^2, U^3) and each face-area vector row (Csi, Eta, Zet) is
482 * interpolated linearly between the cell's two faces of that family, at the fraction
483 * `w.x`, `w.y`, `w.z` of the way from the minimum face, and `S_i . u = U^i` is solved by
484 * Cramer's rule. With `w = (1/2, 1/2, 1/2)` this is the cell-centre value Contra2Cart()
485 * stores. The flux through each face family varies linearly along that family's own axis,
486 * so on a cell whose face-area vectors do not vary along their own axis (any rectilinear
487 * cell) the velocity's divergence is the cell's discrete flux divergence, and zero when the
488 * fluxes are divergence-free. It is inline and has no profiling hook: it runs once per cell or
489 * particle, inside Contra2Cart()'s loop on the solver's hot path.
490 *
491 * @param[in] lucont Ghosted local `Ucont` array.
492 * @param[in] lcsi Ghosted local `Csi` array.
493 * @param[in] leta Ghosted local `Eta` array.
494 * @param[in] lzet Ghosted local `Zet` array.
495 * @param[in] i Cell index in cell-centred array numbering (physical cell `i - 1`).
496 * @param[in] j As `i`, for the j direction.
497 * @param[in] k As `i`, for the k direction.
498 * @param[in] w Position in the cell, each component in [0, 1] from the minimum face.
499 * @param[out] ucat Cartesian velocity at that position.
500 *
501 * @return PetscErrorCode 0 on success; `PETSC_ERR_FLOP_COUNT` when the face-area vectors are degenerate.
502 */
503static inline PetscErrorCode ContravariantToCartesianInCell(Cmpnts ***lucont, Cmpnts ***lcsi, Cmpnts ***leta, Cmpnts ***lzet,
504 PetscInt i, PetscInt j, PetscInt k, Cmpnts w, Cmpnts *ucat)
505{
506 PetscFunctionBeginUser;
507 // Transformation matrix [mat]: the face-area vectors at the point, each family
508 // interpolated between the cell's two faces of that family.
509 PetscReal mat[3][3];
510
511 mat[0][0] = (1.0 - w.x) * lcsi[k][j][i-1].x + w.x * lcsi[k][j][i].x;
512 mat[0][1] = (1.0 - w.x) * lcsi[k][j][i-1].y + w.x * lcsi[k][j][i].y;
513 mat[0][2] = (1.0 - w.x) * lcsi[k][j][i-1].z + w.x * lcsi[k][j][i].z;
514
515 mat[1][0] = (1.0 - w.y) * leta[k][j-1][i].x + w.y * leta[k][j][i].x;
516 mat[1][1] = (1.0 - w.y) * leta[k][j-1][i].y + w.y * leta[k][j][i].y;
517 mat[1][2] = (1.0 - w.y) * leta[k][j-1][i].z + w.y * leta[k][j][i].z;
518
519 mat[2][0] = (1.0 - w.z) * lzet[k-1][j][i].x + w.z * lzet[k][j][i].x;
520 mat[2][1] = (1.0 - w.z) * lzet[k-1][j][i].y + w.z * lzet[k][j][i].y;
521 mat[2][2] = (1.0 - w.z) * lzet[k-1][j][i].z + w.z * lzet[k][j][i].z;
522
523 // Contravariant velocity vector `q` at the point, interpolated the same way.
524 PetscReal q[3];
525 q[0] = (1.0 - w.x) * lucont[k][j][i-1].x + w.x * lucont[k][j][i].x; // U¹
526 q[1] = (1.0 - w.y) * lucont[k][j-1][i].y + w.y * lucont[k][j][i].y; // U²
527 q[2] = (1.0 - w.z) * lucont[k-1][j][i].z + w.z * lucont[k][j][i].z; // U³
528
529 // Solve the 3x3 system `mat * ucat = q` using Cramer's rule.
530 PetscReal det = mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) -
531 mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) +
532 mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]);
533
534 if (PetscAbsReal(det) < 1.0e-18) {
535 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FLOP_COUNT, "Transformation matrix determinant is near zero at cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") \n", i, j, k);
536 }
537
538 PetscReal det_inv = 1.0 / det;
539
540 PetscReal det0 = q[0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) -
541 q[1] * (mat[0][1] * mat[2][2] - mat[0][2] * mat[2][1]) +
542 q[2] * (mat[0][1] * mat[1][2] - mat[0][2] * mat[1][1]);
543
544 PetscReal det1 = -q[0] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) +
545 q[1] * (mat[0][0] * mat[2][2] - mat[0][2] * mat[2][0]) -
546 q[2] * (mat[0][0] * mat[1][2] - mat[0][2] * mat[1][0]);
547
548 PetscReal det2 = q[0] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]) -
549 q[1] * (mat[0][0] * mat[2][1] - mat[0][1] * mat[2][0]) +
550 q[2] * (mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]);
551
552 ucat->x = det0 * det_inv;
553 ucat->y = det1 * det_inv;
554 ucat->z = det2 * det_inv;
555 PetscFunctionReturn(0);
556}
557
558/**
559 * @brief Convert the ghosted Cartesian velocity field to contravariant face fluxes.
560 * @ingroup InitialConditions
561 *
562 * Interpolates `user->lUcat` to each logical face and dots it with the
563 * corresponding face-area metric vector. Writes independent entries of
564 * `user->Ucont`. Periodic and physical endpoint values in `user->lUcat` must be
565 * finalized and its MPI ghosts current before entry. The resulting `Ucont` is not
566 * synchronized; callers must use the staggered-field workflow before stencil use.
567 *
568 * @param[in,out] user UserCtx for the block; Ucont is written in place.
569 * @return PetscErrorCode 0 on success.
570 */
571PetscErrorCode Cart2Contra(UserCtx *user);
572
573/**
574 * @brief Creates and distributes a map of the domain's cell decomposition to all ranks.
575 * @ingroup DomainInfo
576 *
577 * This function is a critical part of the simulation setup. It determines the global
578 * cell ownership for each MPI rank and makes this information available to all
579 * other ranks. This "decomposition map" is essential for the robust "Walk and Handoff"
580 * particle migration strategy, allowing any rank to quickly identify the owner of a
581 * target cell.
582 *
583 * The process involves:
584 * 1. Each rank gets its own node ownership information from the DMDA.
585 * 2. It converts this node information into cell ownership ranges using the
586 * `GetOwnedCellRange` helper function.
587 * 3. It participates in an `MPI_Allgather` collective operation to build a complete
588 * array (`user->RankCellInfoMap`) containing the ownership information for every rank.
589 *
590 * This function should be called once during initialization after the primary DMDA
591 * (user->da) has been set up.
592 *
593 * @param[in,out] user Pointer to the UserCtx structure. The function will allocate and
594 * populate `user->RankCellInfoMap` and set `user->num_ranks`.
595 *
596 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
597 * Errors can occur if input pointers are NULL or if MPI communication fails.
598 */
599PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user);
600
601/**
602 * @brief Performs a binary search for a key in a sorted array of PetscInt64.
603 *
604 * This is a standard binary search algorithm implemented as a PETSc-style helper function.
605 * It efficiently determines if a given `key` exists within a `sorted` array.
606 *
607 * @param[in] n The number of elements in the array.
608 * @param[in] arr A pointer to the sorted array of PetscInt64 values to be searched.
609 * @param[in] key The PetscInt64 value to search for.
610 * @param[out] found A pointer to a PetscBool that will be set to PETSC_TRUE if the key
611 * is found, and PETSC_FALSE otherwise.
612 *
613 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
614 *
615 * @note The input array `arr` **must** be sorted in ascending order for the algorithm
616 * to work correctly.
617 */
618PetscErrorCode BinarySearchInt64(PetscInt n, const PetscInt64 arr[], PetscInt64 key, PetscBool *found);
619
620
621/**
622 * @brief Computes the discrete divergence of the contravariant velocity field.
623 *
624 * This diagnostic/kernel routine evaluates continuity residuals on the local block
625 * and writes the resulting divergence field into the configured output vector(s).
626 *
627 * @param[in,out] user Block-level context containing velocity and metric fields.
628 * @return PetscErrorCode 0 on success.
629 */
630PetscErrorCode ComputeDivergence(UserCtx *user);
631
632/**
633 * @brief Transforms scalar derivatives from computational space to physical space
634 *
635 * using the chain rule.
636 * Formula: dPhi/dx = J * ( dPhi/dCsi * dCsi/dx + dPhi/dEta * dEta/dx + ... )
637 *
638 * @param jacobian Local mapping Jacobian determinant.
639 * @param csi_metrics Physical gradient of the xi coordinate.
640 * @param eta_metrics Physical gradient of the eta coordinate.
641 * @param zet_metrics Physical gradient of the zeta coordinate.
642 * @param dPhi_dcsi Scalar derivative in the xi direction.
643 * @param dPhi_deta Scalar derivative in the eta direction.
644 * @param dPhi_dzet Scalar derivative in the zeta direction.
645 * @param[out] gradPhi Physical Cartesian scalar gradient.
646 */
647 void TransformScalarDerivativesToPhysical(PetscReal jacobian,
648 Cmpnts csi_metrics,
649 Cmpnts eta_metrics,
650 Cmpnts zet_metrics,
651 PetscReal dPhi_dcsi,
652 PetscReal dPhi_deta,
653 PetscReal dPhi_dzet,
654 Cmpnts *gradPhi);
655
656/**
657 * @brief Computes the gradient of a cell-centered SCALAR field at a specific grid point.
658 *
659 * @param user Block metric context.
660 * @param i Cell index in the xi direction.
661 * @param j Cell index in the eta direction.
662 * @param k Cell index in the zeta direction.
663 * @param field_data Ghosted scalar values indexed as [k][j][i].
664 * @param[out] grad Physical Cartesian gradient at the requested cell.
665 * @return PetscErrorCode 0 on success.
666 */
667PetscErrorCode ComputeScalarFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k,
668 PetscReal ***field_data, Cmpnts *grad);
669
670/**
671 * @brief Computes the derivatives of a cell-centered vector field at a specific grid point.
672 *
673 * This function orchestrates the calculation of spatial derivatives. It first computes
674 * the derivatives in computational space (d/dcsi, d/deta, d/dzet) using a central
675 * difference scheme and then transforms them into physical space (d/dx, d/dy, d/dz).
676 *
677 * @param user Block metric context.
678 * @param i Cell index in the xi direction.
679 * @param j Cell index in the eta direction.
680 * @param k Cell index in the zeta direction.
681 * @param field_data Ghosted Cartesian vector values indexed as [k][j][i].
682 * @param[out] dudx Gradient of the x velocity component.
683 * @param[out] dvdx Gradient of the y velocity component.
684 * @param[out] dwdx Gradient of the z velocity component.
685 * @return PetscErrorCode 0 on success.
686 */
687PetscErrorCode ComputeVectorFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, Cmpnts ***field_data,
688 Cmpnts *dudx, Cmpnts *dvdx, Cmpnts *dwdx);
689
690/**
691 * @brief Installs the shipped defaults for every LES closure parameter.
692 *
693 * One definition of the defaults, shared by the control-file ingress and by test
694 * fixtures, so the two cannot drift apart. It lives with the rest of the context
695 * construction because defaults are ingress, not closure behaviour, and because the
696 * postprocessor builds a simulation context without linking the LES module.
697 *
698 * Local averaging and clamped limiting are the defaults because they are the only
699 * settings valid on arbitrary geometry; cases with homogeneous directions or an
700 * interest in backscatter opt into the alternatives.
701 *
702 * @param[out] config Configuration block to populate.
703 * @return PetscErrorCode 0 on success, or `PETSC_ERR_ARG_NULL` for a null argument.
704 */
705PetscErrorCode LESConfigSetDefaults(LESConfig *config);
706
707/**
708 * @brief Destroys all PETSc Vec objects within a single UserCtx structure.
709 *
710 * This helper function systematically destroys the Vec objects stored in a UserCtx.
711 * The vectors are organized into functional groups for clarity:
712 * - Primary flow fields (Ucont, Ucat, P, Nvert)
713 * - Solver work vectors (Phi)
714 * - Time-stepping vectors (Ucont_o, Ucont_rm1, etc.)
715 * - Grid metrics (cell-centered, face-centered, coordinates)
716 * - Turbulence vectors (Nu_t, CS, lFriction_Velocity)
717 * - Particle vectors (ParticleCount, Psi)
718 * - Boundary condition vectors (Ubcs, Uch)
719 * - Post-processing vectors (P_nodal, Qcrit)
720 * - And more...
721 *
722 * All destroys are protected with NULL checks to handle conditional allocations safely.
723 *
724 * @param[in,out] user Pointer to the UserCtx containing the vectors to destroy.
725 *
726 * @return PetscErrorCode 0 on success.
727 */
728PetscErrorCode DestroyUserVectors(UserCtx *user);
729
730/**
731 * @brief Destroys all resources allocated within a single UserCtx structure.
732 *
733 * This function cleans up all memory and PETSc objects associated with a single
734 * UserCtx (grid level). It calls the helper functions and destroys remaining objects
735 * in the proper dependency order:
736 * 1. Boundary conditions (handlers and their data)
737 * 2. All PETSc vectors (via DestroyUserVectors)
738 * 3. Matrix and solver objects (A, MR, MP, ksp, nullsp)
739 * 4. Application ordering (AO)
740 * 5. Distributed mesh objects (DMs) - most derived first
741 * 6. Raw PetscMalloc'd arrays (RankCellInfoMap)
742 *
743 * This function should be called for each UserCtx in the multigrid hierarchy.
744 *
745 * @param[in,out] user Pointer to the UserCtx to be destroyed.
746 *
747 * @return PetscErrorCode 0 on success.
748 */
749PetscErrorCode DestroyUserContext(UserCtx *user);
750
751/**
752 * @brief Main cleanup function for the entire simulation context.
753 *
754 * This function is responsible for destroying ALL memory and PETSc objects allocated
755 * during the simulation, including:
756 * - All UserCtx structures in the multigrid hierarchy (via DestroyUserContext)
757 * - The multigrid management structures (UserMG, MGCtx array)
758 * - All SimCtx-level objects (logviewer, dm_swarm, bboxlist, string arrays, etc.)
759 * - The SimCtx allocation itself.
760 *
761 * This function should be called ONCE at the end of the simulation, after all
762 * computation is complete, but BEFORE PetscFinalize().
763 *
764 * Call order in main:
765 * 1. [Simulation runs]
766 * 2. ProfilingFinalize(simCtx);
767 * 3. FinalizeSimulation(simCtx); <- This function
768 * 4. PetscFinalize();
769 *
770 * @param[in,out] simCtx Pointer to the master SimulationContext to be destroyed.
771 * The pointer is invalid after this call returns.
772 *
773 * @return PetscErrorCode 0 on success.
774 */
775PetscErrorCode FinalizeSimulation(SimCtx *simCtx);
776
777
778 #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.
Non-owning runtime objects resolved for one field and UserCtx.
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:3842
int PicurvCheckLinkedPetscIndexWidth(int argc, char **argv, const char *executable_name)
Refuse to start when the loaded libpetsc's PetscInt width differs from this build's.
Definition setup.c:79
PetscErrorCode DestroyUserContext(UserCtx *user)
Destroys all resources allocated within a single UserCtx structure.
Definition setup.c:4046
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:3021
static void GetOwnedInteriorCellBounds(const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned rang...
Definition setup.h:378
PetscErrorCode SetupDomainRankInfo(SimCtx *simCtx)
Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchang...
Definition setup.c:3242
PetscErrorCode Deallocate3DArrayVector(Cmpnts ***array, PetscInt nz, PetscInt ny)
Deallocates a 3D array of Cmpnts structures allocated by Allocate3DArrayVector.
Definition setup.c:2954
PetscErrorCode SetupGridAndSolvers(SimCtx *simCtx)
The main orchestrator for setting up all grid-related components.
Definition setup.c:2066
static PetscErrorCode ContravariantToCartesianInCell(Cmpnts ***lucont, Cmpnts ***lcsi, Cmpnts ***leta, Cmpnts ***lzet, PetscInt i, PetscInt j, PetscInt k, Cmpnts w, Cmpnts *ucat)
Cartesian velocity at a point of one cell from the cell's face fluxes.
Definition setup.h:503
PetscErrorCode SetupSimulationEnvironment(SimCtx *simCtx)
Verifies and prepares the complete I/O environment for a simulation run.
Definition setup.c:1728
PetscErrorCode CreateAndInitializeAllVectors(SimCtx *simCtx)
Creates and initializes all PETSc Vec objects for all fields.
Definition setup.c:2099
PetscErrorCode ComputeAndStoreNeighborRanks(UserCtx *user)
Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.
Definition setup.c:3116
PetscErrorCode Contra2Cart(UserCtx *user)
Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on...
Definition setup.c:3313
PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object)
Refuse a PETSc object whose global size this build's PetscInt cannot index.
Definition setup.c:102
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:3753
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:119
PetscErrorCode DestroySolutionConvergenceState(SimCtx *simCtx)
Frees any runtime storage allocated for solution-convergence logging.
Definition setup.c:230
PetscErrorCode Allocate3DArrayScalar(PetscReal ****array, PetscInt nz, PetscInt ny, PetscInt nx)
Allocates a 3D array of PetscReal values using PetscCalloc.
Definition setup.c:2819
PetscErrorCode CreateSimulationContext(int argc, char **argv, SimCtx **p_simCtx)
Allocates and populates the master SimulationContext object.
Definition setup.c:453
PetscErrorCode InitializeSolutionConvergenceState(SimCtx *simCtx)
Allocates any runtime storage required by solution-convergence logging.
Definition setup.c:176
PetscErrorCode SetDMDAProcLayout(DM dm, UserCtx *user)
Sets the processor layout for a given DMDA based on PETSc options.
Definition setup.c:3166
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:3799
PetscErrorCode ComputeDivergence(UserCtx *user)
Computes the discrete divergence of the contravariant velocity field.
Definition setup.c:3599
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
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:3532
PetscErrorCode Cart2Contra(UserCtx *user)
Convert the ghosted Cartesian velocity field to contravariant face fluxes.
Definition setup.c:3396
PetscErrorCode DestroyUserVectors(UserCtx *user)
Destroys all PETSc Vec objects within a single UserCtx structure.
Definition setup.c:3894
PetscErrorCode Allocate3DArrayVector(Cmpnts ****array, PetscInt nz, PetscInt ny, PetscInt nx)
Allocates a contiguous 3D array of Cmpnts values.
Definition setup.c:2902
PetscErrorCode SetupBoundaryConditions(SimCtx *simCtx)
(Orchestrator) Sets up all boundary conditions for the simulation.
Definition setup.c:2755
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
PetscErrorCode LESConfigSetDefaults(LESConfig *config)
Installs the shipped defaults for every LES closure parameter.
Definition setup.c:288
PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user)
Creates and distributes a map of the domain's cell decomposition to all ranks.
Definition setup.c:3467
PetscErrorCode FinalizeSimulation(SimCtx *simCtx)
Main cleanup function for the entire simulation context.
Definition setup.c:4137
PetscErrorCode RepairPeriodicFieldGhosts(UserCtx *user, const FieldView *view, Vec local_vec)
Applies a catalogued field's periodic normal-face ghost repair to a local vector.
Definition setup.c:2556
PetscErrorCode Deallocate3DArrayScalar(PetscReal ***array, PetscInt nz, PetscInt ny)
Deallocates a 3D array of PetscReal values allocated by Allocate3DArrayScalar.
Definition setup.c:2856
PetscBool RuntimeWalltimeGuardParsePositiveSeconds(const char *text, PetscReal *seconds_out)
Parse a positive floating-point seconds value from runtime metadata.
Definition setup.c:144
Main header file for a complex fluid dynamics solver.
PetscInt k_periodic
Definition variables.h:1010
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
PetscInt i_periodic
Definition variables.h:1010
PetscScalar y
Definition variables.h:145
PetscInt j_periodic
Definition variables.h:1010
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Every user-selectable parameter of the LES closure.
Definition variables.h:664
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
Header file for particle location functions using the walking search algorithm.