PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
grid.h
Go to the documentation of this file.
1// in include/grid.h
2
3#ifndef GRID_H
4#define GRID_H
5
6#include "variables.h" // Essential for SimulationContext and UserCtx definitions
7#include "logging.h" // Logging macros and definitions
8#include "io.h"
9#include "setup.h" // For SetDMDAProcLayout
10/**
11 * @file grid.h
12 * @brief Public interface for grid, solver, and metric setup routines.
13 */
14
15/**
16 * @brief Orchestrates the parsing and setting of grid dimensions for all blocks.
17 *
18 * This function serves as the high-level entry point for defining the geometric
19 * properties of each grid block in the simulation. It iterates through every
20 * block defined by `simCtx->block_number`.
21 *
22 * For each block, it performs two key actions:
23 * 1. It explicitly sets the block's index (`_this`) in the corresponding `UserCtx`
24 * struct for the finest multigrid level. This makes the context "self-aware".
25 * 2. It calls a helper function (`ParseAndSetGridInputs`) to handle the detailed
26 * work of parsing options or files to populate the rest of the geometric
27 * properties for that specific block (e.g., `IM`, `Min_X`, `rx`).
28 *
29 * @param simCtx The master SimCtx, which contains the number of blocks and the
30 * UserCtx hierarchy to be configured.
31 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
32 */
33PetscErrorCode DefineAllGridDimensions(SimCtx *simCtx);
34
35/**
36 * @brief Orchestrates the creation of DMDA objects for every block and multigrid level.
37 *
38 * This function systematically builds the entire DMDA hierarchy. It first
39 * calculates the dimensions (IM, JM, KM) for all coarse grids based on the
40 * finest grid's dimensions and the semi-coarsening flags. It then iterates
41 * from the coarsest to the finest level, calling a powerful helper function
42 * (`InitializeSingleGridDM`) to create the DMs for each block, ensuring that
43 * finer grids are properly aligned with their coarser parents for multigrid efficiency.
44 *
45 * @param simCtx The master SimCtx, containing the configured UserCtx hierarchy.
46 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
47 */
48PetscErrorCode InitializeAllGridDMs(SimCtx *simCtx);
49
50/**
51 * @brief Orchestrates the assignment of physical coordinates to all DMDA objects.
52 *
53 * This function manages the entire process of populating the coordinate vectors
54 * for every DMDA across all multigrid levels and blocks. It follows a two-part
55 * strategy that is essential for multigrid methods:
56 *
57 * 1. **Populate Finest Level:** It first loops through each block and calls a
58 * helper (`SetFinestLevelCoordinates`) to set the physical coordinates for
59 * the highest-resolution grid (the finest multigrid level).
60 * 2. **Restrict to Coarser Levels:** It then iterates downwards from the finest
61 * level, calling a helper (`RestrictCoordinates`) to copy the coordinate
62 * values from the fine grid nodes to their corresponding parent nodes on the
63 * coarser grids. This ensures all levels represent the exact same geometry.
64 *
65 * @param simCtx The master SimCtx, containing the configured UserCtx hierarchy.
66 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
67 */
68PetscErrorCode AssignAllGridCoordinates(SimCtx *simCtx);
69
70/**
71 * @brief Validates that configured geometric periodic seams match by translation.
72 *
73 * Each active periodic direction is checked independently using the physical nodal
74 * coordinates. On success, the constant seam translation is stored in the UserCtx.
75 *
76 * @param user Grid/block context with assigned coordinates and boundary configuration.
77 * @return PetscErrorCode 0 on success, or a user-input error for unsupported geometry.
78 */
79PetscErrorCode ValidatePeriodicGeometry(UserCtx *user);
80
81
82/**
83 * @brief Computes the local bounding box of the grid on the current process.
84 *
85 * This function calculates the minimum and maximum coordinates of the local grid points owned
86 * by the current MPI process and stores the computed bounding box in the provided structure.
87 *
88 * @param[in] user Pointer to the user-defined context containing grid information.
89 * @param[out] localBBox Pointer to the BoundingBox structure to store the computed bounding box.
90 *
91 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
92 */
93PetscErrorCode ComputeLocalBoundingBox(UserCtx *user, BoundingBox *localBBox);
94
95/**
96 * @brief Gathers local bounding boxes from all MPI processes to rank 0.
97 *
98 * This function computes the local bounding box on each process, then collects all local
99 * bounding boxes on the root process (rank 0) using MPI. The result is stored in an array
100 * of BoundingBox structures on rank 0.
101 *
102 * @param[in] user Pointer to the user-defined context containing grid information.
103 * @param[out] allBBoxes Pointer to a pointer where the array of gathered bounding boxes
104 * will be stored on rank 0. The caller on rank 0 must free this array.
105 *
106 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
107 */
108PetscErrorCode GatherAllBoundingBoxes(UserCtx *user, BoundingBox **allBBoxes);
109
110/**
111 * @brief Broadcasts the bounding box information collected on rank 0 to all other ranks.
112 *
113 * This function assumes that `GatherAllBoundingBoxes()` was previously called, so `bboxlist`
114 * is allocated and populated on rank 0. All other ranks will allocate memory for `bboxlist`,
115 * and this function will use MPI_Bcast to distribute the bounding box data to them.
116 *
117 * @param[in] user Pointer to the UserCtx structure. (Currently unused in this function, but kept for consistency.)
118 * @param[in,out] bboxlist Pointer to the array of BoundingBoxes. On rank 0, this should point to
119 * a valid array of size 'size' (where size is the number of MPI ranks).
120 * On non-root ranks, this function will allocate memory for `bboxlist`.
121 *
122 * @return PetscErrorCode Returns 0 on success, non-zero on MPI or PETSc-related errors.
123 */
124PetscErrorCode BroadcastAllBoundingBoxes(UserCtx *user, BoundingBox **bboxlist);
125
126/**
127 * @brief Calculates the center and area of the primary INLET face.
128 *
129 * This function identifies the primary INLET face from the boundary face
130 * configurations, computes its geometric center and total area using a
131 * generic utility function, and stores these results in the simulation context.
132 *
133 * @param user Pointer to the UserCtx containing boundary face information.
134 * @return PetscErrorCode
135 */
136PetscErrorCode CalculateInletProperties(UserCtx *user);
137
138/**
139 * @brief Calculates the center and area of the primary OUTLET face.
140 *
141 * This function identifies the primary OUTLET face from the boundary face
142 * configurations, computes its geometric center and total area using a
143 * generic utility function, and stores these results in the simulation context.
144 * @param user Pointer to the UserCtx containing boundary face information.
145 * @return PetscErrorCode
146 */
147PetscErrorCode CalculateOutletProperties(UserCtx *user);
148
149/**
150 * @brief Calculates the geometric center and total area of a specified boundary face.
151 *
152 * This function computes two key properties of a boundary face in the computational domain:
153 * 1. **Geometric Center**: The average (x,y,z) position of all physical nodes on the face
154 * 2. **Total Area**: The sum of face area vector magnitudes from all non-solid cells adjacent to the face
155 *
156 * @section architecture Indexing Architecture
157 *
158 * The solver uses different indexing conventions for different field types:
159 *
160 * **Node-Centered Fields (Coordinates):**
161 * - Direct indexing: Node n stored at coor[n]
162 * - For mx=26: Physical nodes [0-24], Dummy at [25]
163 * - For mz=98: Physical nodes [0-96], Dummy at [97]
164 *
165 * **Face-Centered Fields (Metrics: csi, eta, zet):**
166 * - Direct indexing: Face n stored at csi/eta/zet[n]
167 * - For mx=26: Physical faces [0-24], Dummy at [25]
168 * - For mz=98: Physical faces [0-96], Dummy at [97]
169 * - Face at index k bounds cells k-1 and k
170 *
171 * **Cell-Centered Fields (nvert):**
172 * - Shifted indexing: Physical cell c stored at nvert[c+1]
173 * - For mx=26 (25 cells): Cell 0→nvert[1], Cell 23→nvert[24]
174 * - For mz=98 (96 cells): Cell 0→nvert[1], Cell 95→nvert[96]
175 * - nvert[0] and nvert[mx-1] are ghost values
176 *
177 * @section face_geometry Face-to-Index Mapping
178 *
179 * Example for a domain with mx=26, my=26, mz=98:
180 *
181 * | Face ID | Node Index | Face Metric | Adjacent Cell (shifted) | Physical Extent |
182 * |---------------|------------|------------------|-------------------------|-----------------|
183 * | BC_FACE_NEG_X | i=0 | csi[k][j][0] | nvert[k][j][1] (Cell 0) | j∈[0,24], k∈[0,96] |
184 * | BC_FACE_POS_X | i=24 | csi[k][j][24] | nvert[k][j][24] (Cell 23)| j∈[0,24], k∈[0,96] |
185 * | BC_FACE_NEG_Y | j=0 | eta[k][0][i] | nvert[k][1][i] (Cell 0) | i∈[0,24], k∈[0,96] |
186 * | BC_FACE_POS_Y | j=24 | eta[k][24][i] | nvert[k][24][i] (Cell 23)| i∈[0,24], k∈[0,96] |
187 * | BC_FACE_NEG_Z | k=0 | zet[0][j][i] | nvert[1][j][i] (Cell 0) | i∈[0,24], j∈[0,24] |
188 * | BC_FACE_POS_Z | k=96 | zet[96][j][i] | nvert[96][j][i] (Cell 95)| i∈[0,24], j∈[0,24] |
189 *
190 * @section algorithm Algorithm
191 *
192 * The function performs two separate computations with different loop bounds:
193 *
194 * **1. Center Calculation (uses ALL physical nodes):**
195 * - Loop over all physical nodes on the face (excluding dummy indices)
196 * - Accumulate coordinate sums: Σx, Σy, Σz
197 * - Count number of nodes
198 * - Average: center = (Σx/n, Σy/n, Σz/n)
199 *
200 * **2. Area Calculation (uses INTERIOR cells only):**
201 * - Loop over interior cell range to avoid accessing ghost values in nvert
202 * - For each face adjacent to a fluid cell (nvert < 0.1):
203 * - Compute area magnitude: |csi/eta/zet| = √(x² + y² + z²)
204 * - Accumulate to total area
205 *
206 * @section loop_bounds Loop Bound Details
207 *
208 * **Why different bounds for center vs. area?**
209 *
210 * For BC_FACE_NEG_X at i=0 with my=26, mz=98:
211 *
212 * *Center calculation (coordinates):*
213 * - j ∈ [ys, j_max): Includes j=[0,24] (25 nodes), excludes dummy at j=25
214 * - k ∈ [zs, k_max): Includes k=[0,96] (97 nodes), excludes dummy at k=97
215 * - Total: 25 × 97 = 2,425 nodes
216 *
217 * *Area calculation (nvert checks):*
218 * - j ∈ [lys, lye): j=[1,24] (24 values), excludes boundaries
219 * - k ∈ [lzs, lze): k=[1,96] (96 values), excludes boundaries
220 * - Why restricted?
221 * - At j=0: nvert[k][0][1] is ghost (no cell at j=-1)
222 * - At j=25: nvert[k][25][1] is ghost (no cell at j=24, index 25 is dummy)
223 * - At k=0: nvert[0][j][1] is ghost (no cell at k=-1)
224 * - At k=97: nvert[97][j][1] is ghost (no cell at k=96, index 97 is dummy)
225 * - Total: 24 × 96 = 2,304 interior cells adjacent to face
226 *
227 * @section area_formulas Area Calculation Formulas
228 *
229 * Face area contributions are computed from metric tensor magnitudes:
230 * - **i-faces (±Xi)**: Area = |csi| = √(csi_x² + csi_y² + csi_z²)
231 * - **j-faces (±Eta)**: Area = |eta| = √(eta_x² + eta_y² + eta_z²)
232 * - **k-faces (±Zeta)**: Area = |zet| = √(zet_x² + zet_y² + zet_z²)
233 *
234 * @param[in] user Pointer to UserCtx containing grid info, DMs, and field vectors
235 * @param[in] face_id Enum identifying which boundary face to analyze (BC_FACE_NEG_X, etc.)
236 * @param[out] face_center Pointer to Cmpnts structure to store computed geometric center (x,y,z)
237 * @param[out] face_area Pointer to PetscReal to store computed total face area
238 *
239 * @return PetscErrorCode Returns 0 on success, non-zero PETSc error code on failure
240 *
241 * @note This function uses MPI_Allreduce, so it must be called collectively by all ranks
242 * @note Only ranks that own the specified boundary face contribute to the calculation
243 * @note Center calculation includes ALL physical nodes on the face
244 * @note Area calculation ONLY includes faces adjacent to fluid cells (nvert < 0.1)
245 * @note Dummy/unused indices (e.g., k=97, j=25 for standard test case) are excluded
246 *
247 * @warning Assumes grid and field arrays have been properly initialized
248 * @warning Incorrect face_id values will result in zero contribution from all ranks
249 *
250 * @see CanRankServiceFace() for determining rank ownership of boundary faces
251 * @see BCFace enum for valid face_id values
252 * @see LOG_FIELD_ANATOMY() for debugging field indexing
253 *
254 * @par Example Usage:
255 * @code
256 * Cmpnts inlet_center;
257 * PetscReal inlet_area;
258 * ierr = CalculateFaceCenterAndArea(user, BC_FACE_NEG_Z, &inlet_center, &inlet_area);
259 * PetscPrintf(PETSC_COMM_WORLD, "Inlet center: (%.4f, %.4f, %.4f), Area: %.6f\n",
260 * inlet_center.x, inlet_center.y, inlet_center.z, inlet_area);
261 * @endcode
262 */
263PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id,
264 Cmpnts *face_center, PetscReal *face_area);
265
266/**
267 * @brief Creates a DMDA sharing a block's decomposition at a different degree of freedom.
268 *
269 * Fields whose component count is neither one nor three still have to live on the
270 * same index space as the block, so a pointwise loop can read `da` and write them at
271 * the same `(i,j,k)`. Copying the source DM's sizes, boundary types, stencil, and —
272 * critically — its explicit per-rank ownership ranges makes the decomposition
273 * identical rather than merely similar. Letting PETSc re-decide the split would be
274 * free to disagree, and the loop would misalign silently.
275 *
276 * @param[in] source Existing block DMDA whose decomposition is mirrored.
277 * @param[in] dof Degrees of freedom the new DM carries; must be positive.
278 * @param[out] result Created DM; the caller owns it and must destroy it.
279 * @return Zero on success, or a PETSc error for a null argument or non-positive dof.
280 */
281PetscErrorCode CreateCompatibleBlockDM(DM source, PetscInt dof, DM *result);
282
283/**
284 * @brief Split one axis of the coarsest level so the finest level's owned cells balance.
285 * @details The finer levels inherit their ownership by refinement (InitializeSingleGridDM):
286 * each refinement maps a coarse rank boundary at node c to 2c - 1, so a boundary
287 * at coarsest node c lands at finest node 2^R (c - 1) + 1. Refining PETSc's default
288 * coarsest split compounds its remainder, e.g. 128 cells on 4 ranks at 3 levels own
289 * 33/36/32/27 cells. A rank owns the cells whose lower-corner node it owns, and the
290 * last node is padding. Every rank keeps at least PETSc's floor width, so every
291 * stencil-width check on the default split still holds, and the spare points go where
292 * they minimise the largest finest-level share, by dynamic programming over (rank,
293 * spare points used so far): O(ranks x spare^2) once per axis at setup. A rank may take
294 * several: unrefined, 128 cells on 4 ranks split 32/32/32/34 nodes, 32 cells each.
295 * The share counted is the particles' (GetOwnedCellRange); cell-centred Eulerian storage
296 * puts cell c at node c + 1, so it differs by one cell at each end and is not balanced
297 * with it (GitHub #21).
298 * @param[in] coarse_nodes Coarsest-level DA points on the axis.
299 * @param[in] fine_cells Finest-level physical cells on the axis.
300 * @param[in] refinements Refinements of the axis between the coarsest and finest levels.
301 * @param[in] ranks Ranks on the axis.
302 * @param[out] l Coarsest-level DA points owned by each rank on the axis.
303 * @return PetscErrorCode 0 on success, or a PETSc allocation error.
304 */
305PetscErrorCode BalanceCoarsestOwnership(PetscInt coarse_nodes, PetscInt fine_cells, PetscInt refinements,
306 PetscInt ranks, PetscInt *l);
307
308#endif // GRID_H
PetscErrorCode DefineAllGridDimensions(SimCtx *simCtx)
Orchestrates the parsing and setting of grid dimensions for all blocks.
Definition grid.c:38
PetscErrorCode CalculateOutletProperties(UserCtx *user)
Calculates the center and area of the primary OUTLET face.
Definition grid.c:1170
PetscErrorCode BroadcastAllBoundingBoxes(UserCtx *user, BoundingBox **bboxlist)
Broadcasts the bounding box information collected on rank 0 to all other ranks.
Definition grid.c:1071
PetscErrorCode ValidatePeriodicGeometry(UserCtx *user)
Validates that configured geometric periodic seams match by translation.
Definition grid.c:450
PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
Calculates the geometric center and total area of a specified boundary face.
Definition grid.c:1211
PetscErrorCode BalanceCoarsestOwnership(PetscInt coarse_nodes, PetscInt fine_cells, PetscInt refinements, PetscInt ranks, PetscInt *l)
Split one axis of the coarsest level so the finest level's owned cells balance.
Definition grid.c:121
PetscErrorCode InitializeAllGridDMs(SimCtx *simCtx)
Orchestrates the creation of DMDA objects for every block and multigrid level.
Definition grid.c:309
PetscErrorCode AssignAllGridCoordinates(SimCtx *simCtx)
Orchestrates the assignment of physical coordinates to all DMDA objects.
Definition grid.c:389
PetscErrorCode CreateCompatibleBlockDM(DM source, PetscInt dof, DM *result)
Creates a DMDA sharing a block's decomposition at a different degree of freedom.
Definition grid.c:81
PetscErrorCode ComputeLocalBoundingBox(UserCtx *user, BoundingBox *localBBox)
Computes the local bounding box of the grid on the current process.
Definition grid.c:869
PetscErrorCode CalculateInletProperties(UserCtx *user)
Calculates the center and area of the primary INLET face.
Definition grid.c:1119
PetscErrorCode GatherAllBoundingBoxes(UserCtx *user, BoundingBox **allBBoxes)
Gathers local bounding boxes from all MPI processes to rank 0.
Definition grid.c:1011
Public interface for data input/output routines.
Logging utilities and macros for PETSc-based applications.
Main header file for a complex fluid dynamics solver.
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
A 3D point or vector with PetscScalar components.
Definition variables.h:144
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