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