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