PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Macros | Functions
grid.c File Reference
#include "grid.h"
#include "statistics_window.h"
#include "logging.h"
Include dependency graph for grid.c:

Go to the source code of this file.

Macros

#define BBOX_TOLERANCE   1e-6
 
#define PICURV_FINE_NODE(c)   ((c) == 0 ? 0 : (refinements ? (((c) - 1) << refinements) + 1 : (c)))
 

Functions

static PetscErrorCode ParseAndSetGridInputs (UserCtx *user)
 Parse grid-generation options and store the resulting geometry settings in the context.
 
PetscErrorCode DefineAllGridDimensions (SimCtx *simCtx)
 Implementation of DefineAllGridDimensions().
 
PetscErrorCode CreateCompatibleBlockDM (DM source, PetscInt dof, DM *result)
 Implementation of CreateCompatibleBlockDM().
 
PetscErrorCode BalanceCoarsestOwnership (PetscInt coarse_nodes, PetscInt fine_cells, PetscInt refinements, PetscInt ranks, PetscInt *l)
 Implementation of BalanceCoarsestOwnership().
 
static PetscErrorCode InitializeSingleGridDM (UserCtx *user, UserCtx *coarse_user)
 Create and configure one PETSc DMDA for a multigrid level.
 
PetscErrorCode InitializeAllGridDMs (SimCtx *simCtx)
 Implementation of InitializeAllGridDMs().
 
static PetscErrorCode SetFinestLevelCoordinates (UserCtx *user)
 Attach the generated physical coordinates to the finest-level DMDA.
 
static PetscErrorCode GenerateAndSetCoordinates (UserCtx *user)
 Generate analytic grid coordinates and install them on the finest grid level.
 
static PetscErrorCode ReadAndSetCoordinates (UserCtx *user, FILE *fd)
 Load grid coordinates from the input file and install them on the finest level.
 
static PetscErrorCode RestrictCoordinates (UserCtx *coarse_user, UserCtx *fine_user)
 Restrict finest-grid coordinates onto each coarser multigrid level.
 
PetscErrorCode AssignAllGridCoordinates (SimCtx *simCtx)
 Implementation of AssignAllGridCoordinates().
 
static PetscReal CoordinateComponent (Cmpnts value, PetscInt component)
 Returns one Cartesian component from a coordinate/vector value.
 
PetscErrorCode ValidatePeriodicGeometry (UserCtx *user)
 Implementation of ValidatePeriodicGeometry().
 
static PetscReal ComputeStretchedCoord (PetscInt i, PetscInt N, PetscReal L, PetscReal r)
 Map a uniform logical coordinate to its configured stretched physical coordinate.
 
PetscErrorCode ComputeLocalBoundingBox (UserCtx *user, BoundingBox *localBBox)
 Implementation of ComputeLocalBoundingBox().
 
PetscErrorCode GatherAllBoundingBoxes (UserCtx *user, BoundingBox **allBBoxes)
 Implementation of GatherAllBoundingBoxes().
 
PetscErrorCode BroadcastAllBoundingBoxes (UserCtx *user, BoundingBox **bboxlist)
 Implementation of BroadcastAllBoundingBoxes().
 
PetscErrorCode CalculateInletProperties (UserCtx *user)
 Implementation of CalculateInletProperties().
 
PetscErrorCode CalculateOutletProperties (UserCtx *user)
 Implementation of CalculateOutletProperties().
 
PetscErrorCode CalculateFaceCenterAndArea (UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
 Implementation of CalculateFaceCenterAndArea().
 

Macro Definition Documentation

◆ BBOX_TOLERANCE

#define BBOX_TOLERANCE   1e-6

Definition at line 7 of file grid.c.

◆ PICURV_FINE_NODE

#define PICURV_FINE_NODE (   c)    ((c) == 0 ? 0 : (refinements ? (((c) - 1) << refinements) + 1 : (c)))

Function Documentation

◆ ParseAndSetGridInputs()

static PetscErrorCode ParseAndSetGridInputs ( UserCtx *  user)
static

Parse grid-generation options and store the resulting geometry settings in the context.

Definition at line 12 of file grid.c.

13{
14 PetscErrorCode ierr;
15 SimCtx *simCtx = user->simCtx; // Get the global context via the back-pointer
16
17 PetscFunctionBeginUser;
18
20 if (simCtx->generate_grid) {
21 LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "Rank %d: Block %" PetscInt_FMT " is programmatically generated.\n", simCtx->rank, user->_this);
22 ierr = ReadGridGenerationInputs(user); CHKERRQ(ierr);
23 } else {
24 LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "Rank %d: Block %" PetscInt_FMT " is file-based.\n", simCtx->rank, user->_this);
25 ierr = ReadGridFile(user); CHKERRQ(ierr);
26 }
27
29
30 PetscFunctionReturn(0);
31}
PetscErrorCode ReadGridFile(UserCtx *user)
Sets grid dimensions from a file for a SINGLE block using a one-time read cache.
Definition io.c:636
PetscErrorCode ReadGridGenerationInputs(UserCtx *user)
Parses command-line options for a programmatically generated grid for a SINGLE block.
Definition io.c:537
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscMPIInt rank
Definition variables.h:919
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscInt _this
Definition variables.h:1175
PetscBool generate_grid
Definition variables.h:1011
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DefineAllGridDimensions()

PetscErrorCode DefineAllGridDimensions ( SimCtx *  simCtx)

Implementation of DefineAllGridDimensions().

Orchestrates the parsing and setting of grid dimensions for all blocks.

See also
DefineAllGridDimensions()

Definition at line 38 of file grid.c.

39{
40 PetscErrorCode ierr;
41 PetscInt nblk = simCtx->block_number;
42 UserCtx *finest_users;
43
44 PetscFunctionBeginUser;
45
47
48 if (simCtx->usermg.mglevels == 0) {
49 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "MG levels not set. Cannot get finest_users.");
50 }
51 // Get the UserCtx array for the finest grid level
52 finest_users = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
53
54 LOG_ALLOW(GLOBAL, LOG_INFO, "Defining grid dimensions for %" PetscInt_FMT " blocks...\n", nblk);
55
56 // Loop over each block to configure its grid dimensions and geometry.
57 for (PetscInt bi = 0; bi < nblk; bi++) {
58 LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "Rank %d: --- Configuring Geometry for Block %" PetscInt_FMT " ---\n", simCtx->rank, bi);
59
60 // Before calling any helpers, set the block index in the context.
61 // This makes the UserCtx self-aware of which block it represents.
62 LOG_ALLOW(GLOBAL,LOG_DEBUG,"finest_users->_this = %" PetscInt_FMT ", bi = %" PetscInt_FMT "\n",finest_users[bi]._this,bi);
63 //finest_user[bi]._this = bi;
64
65 // Call the helper function for this specific block. It can now derive
66 // all necessary information from the UserCtx pointer it receives.
67 ierr = ParseAndSetGridInputs(&finest_users[bi]); CHKERRQ(ierr);
68 }
69
71
72 PetscFunctionReturn(0);
73}
static PetscErrorCode ParseAndSetGridInputs(UserCtx *user)
Parse grid-generation options and store the resulting geometry settings in the context.
Definition grid.c:12
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
UserCtx * user
Definition variables.h:768
PetscInt block_number
Definition variables.h:1009
UserMG usermg
Definition variables.h:1082
PetscInt mglevels
Definition variables.h:775
MGCtx * mgctx
Definition variables.h:778
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CreateCompatibleBlockDM()

PetscErrorCode CreateCompatibleBlockDM ( DM  source,
PetscInt  dof,
DM *  result 
)

Implementation of CreateCompatibleBlockDM().

Creates a DMDA sharing a block's decomposition at a different degree of freedom.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CreateCompatibleBlockDM()

Definition at line 81 of file grid.c.

82{
83 PetscErrorCode ierr;
84 PetscInt dim = 0, M = 0, N = 0, P = 0, m = 0, n = 0, p = 0, source_dof = 0, stencil_width = 0;
85 DMBoundaryType bx = DM_BOUNDARY_NONE, by = DM_BOUNDARY_NONE, bz = DM_BOUNDARY_NONE;
86 DMDAStencilType stencil_type = DMDA_STENCIL_BOX;
87 const PetscInt *lx = NULL, *ly = NULL, *lz = NULL;
88
89 PetscFunctionBeginUser;
91 PetscCheck(source != NULL && result != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
92 "Source DM and output pointer are required.");
93 PetscCheck(dof > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
94 "A compatible DM needs a positive degree of freedom, got %" PetscInt_FMT ".", dof);
95
96 ierr = DMDAGetInfo(source, &dim, &M, &N, &P, &m, &n, &p, &source_dof, &stencil_width,
97 &bx, &by, &bz, &stencil_type); CHKERRQ(ierr);
98 ierr = DMDAGetOwnershipRanges(source, &lx, &ly, &lz); CHKERRQ(ierr);
99 {
100 char object[96];
101 ierr = PetscSNPrintf(object, sizeof(object), "A %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT
102 " grid field of %" PetscInt_FMT " components", M, N, P, dof); CHKERRQ(ierr);
103 ierr = PicurvCheckPetscIntRange(PetscObjectComm((PetscObject)source), (PetscInt64)M * N * P * dof, object); CHKERRQ(ierr);
104 }
105 ierr = DMDACreate3d(PetscObjectComm((PetscObject)source), bx, by, bz, stencil_type,
106 M, N, P, m, n, p, dof, stencil_width, lx, ly, lz, result); CHKERRQ(ierr);
107 ierr = DMSetUp(*result); CHKERRQ(ierr);
109 "Created a dof-%d DM mirroring the block decomposition (%dx%dx%d ranks).\n",
110 (int)dof, (int)m, (int)n, (int)p);
112 PetscFunctionReturn(0);
113}
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object)
Refuse a PETSc object whose global size this build's PetscInt cannot index.
Definition setup.c:102
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BalanceCoarsestOwnership()

PetscErrorCode BalanceCoarsestOwnership ( PetscInt  coarse_nodes,
PetscInt  fine_cells,
PetscInt  refinements,
PetscInt  ranks,
PetscInt *  l 
)

Implementation of BalanceCoarsestOwnership().

Split one axis of the coarsest level so the finest level's owned cells balance.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
BalanceCoarsestOwnership()

Definition at line 121 of file grid.c.

123{
124 const PetscInt width = coarse_nodes / ranks, extras = coarse_nodes % ranks, cols = extras + 1;
125 PetscInt *worst = NULL; // [r * cols + e]: least largest share over ranks 0..r using e spare points
126 PetscInt *wide = NULL; // [r * cols + e]: how many spare points rank r takes on that optimum
127
128 PetscFunctionBeginUser;
130 PetscCall(PetscMalloc2(ranks * cols, &worst, ranks * cols, &wide));
131 #define PICURV_FINE_NODE(c) ((c) == 0 ? 0 : (refinements ? (((c) - 1) << refinements) + 1 : (c)))
132 for (PetscInt r = 0; r < ranks; ++r) {
133 for (PetscInt e = 0; e < cols; ++e) {
134 worst[r * cols + e] = PETSC_MAX_INT;
135 for (PetscInt w = 0; w <= e; ++w) {
136 const PetscInt before = e - w;
137 if (r == 0 ? before != 0 : worst[(r - 1) * cols + before] == PETSC_MAX_INT) continue;
138 const PetscInt start = PICURV_FINE_NODE(r * width + before);
139 const PetscInt end = (r == ranks - 1) ? fine_cells : PICURV_FINE_NODE((r + 1) * width + e);
140 const PetscInt share = PetscMax(end - start, r ? worst[(r - 1) * cols + before] : 0);
141 if (share < worst[r * cols + e]) { worst[r * cols + e] = share; wide[r * cols + e] = w; }
142 }
143 }
144 }
145 #undef PICURV_FINE_NODE
146 for (PetscInt r = ranks - 1, e = extras; r >= 0; --r) {
147 l[r] = width + wide[r * cols + e];
148 e -= wide[r * cols + e];
149 }
150 PetscCall(PetscFree2(worst, wide));
152 PetscFunctionReturn(0);
153}
#define PICURV_FINE_NODE(c)
Here is the caller graph for this function:

◆ InitializeSingleGridDM()

static PetscErrorCode InitializeSingleGridDM ( UserCtx *  user,
UserCtx *  coarse_user 
)
static

Create and configure one PETSc DMDA for a multigrid level.

Definition at line 158 of file grid.c.

159{
160 PetscErrorCode ierr;
161 SimCtx *simCtx = user->simCtx;
162
163 DMBoundaryType xperiod = (simCtx->i_periodic) ? DM_BOUNDARY_PERIODIC : DM_BOUNDARY_NONE;
164 DMBoundaryType yperiod = (simCtx->j_periodic) ? DM_BOUNDARY_PERIODIC : DM_BOUNDARY_NONE;
165 DMBoundaryType zperiod = (simCtx->k_periodic) ? DM_BOUNDARY_PERIODIC : DM_BOUNDARY_NONE;
166 PetscInt stencil_width = (simCtx->i_periodic || simCtx->j_periodic || simCtx->k_periodic) ? 3:2; // Stencil width is 2 in the legacy code
167
168 PetscInt *lx = NULL, *ly = NULL, *lz = NULL;
169 PetscInt m, n, p;
170
171 PetscFunctionBeginUser;
172
174
175 if (coarse_user) {
176 // --- This is a FINE grid; it must be aligned with the COARSE grid ---
177 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: [Aligning DM] for block %" PetscInt_FMT " level %" PetscInt_FMT " (size %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT ") with level %" PetscInt_FMT "\n", simCtx->rank, user->_this, user->thislevel, user->IM, user->JM, user->KM, coarse_user->thislevel);
178
179 DMDAGetInfo(coarse_user->da, NULL, NULL, NULL, NULL, &m, &n, &p, NULL, NULL, NULL, NULL, NULL, NULL);
180 LOG_ALLOW_SYNC(LOCAL, LOG_TRACE, "Rank %d: Coarse grid processor decomposition is %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT "\n", simCtx->rank, m, n, p);
181
182 // This is the core logic from MGDACreate to ensure processor alignment.
183 PetscInt *lx_contrib, *ly_contrib, *lz_contrib;
184 ierr = PetscMalloc3(m, &lx_contrib, n, &ly_contrib, p, &lz_contrib); CHKERRQ(ierr);
185 ierr = PetscMemzero(lx_contrib, m * sizeof(PetscInt)); CHKERRQ(ierr);
186 ierr = PetscMemzero(ly_contrib, n * sizeof(PetscInt)); CHKERRQ(ierr);
187 ierr = PetscMemzero(lz_contrib, p * sizeof(PetscInt)); CHKERRQ(ierr);
188
189 DMDALocalInfo info;
190 info = coarse_user->info;
191 PetscInt xs = info.xs, xe = info.xs + info.xm, mx = info.mx;
192 PetscInt ys = info.ys, ye = info.ys + info.ym, my = info.my;
193 PetscInt zs = info.zs, ze = info.zs + info.zm, mz = info.mz;
194
195 PetscMPIInt rank;
196 rank = simCtx->rank;
197 PetscInt proc_i = rank % m;
198 PetscInt proc_j = (rank / m) % n;
199 PetscInt proc_k = rank / (m * n);
200
201 // --- X-Direction Logic (Identical to MGDACreate) ---
202 if (user->isc) lx_contrib[proc_i] = (xe - xs);
203 else {
204 if (m == 1) lx_contrib[0] = user->IM + 1;
205 else if (xs == 0) lx_contrib[0] = 2 * xe - 1;
206 else if (xe == mx) lx_contrib[proc_i] = user->IM + 1 - (2 * xs - 1);
207 else lx_contrib[proc_i] = (xe - xs) * 2;
208 }
209
210 // --- Y-Direction Logic (Identical to MGDACreate) ---
211 if (user->jsc) ly_contrib[proc_j] = (ye - ys);
212 else {
213 if (n == 1) ly_contrib[0] = user->JM + 1;
214 else if (ys == 0) ly_contrib[0] = 2 * ye - 1;
215 else if (ye == my) ly_contrib[proc_j] = user->JM + 1 - (2 * ys - 1);
216 else ly_contrib[proc_j] = (ye - ys) * 2;
217 }
218
219 // --- Z-Direction Logic (Identical to MGDACreate) ---
220 if (user->ksc) lz_contrib[proc_k] = (ze - zs);
221 else {
222 if (p == 1) lz_contrib[0] = user->KM + 1;
223 else if (zs == 0) lz_contrib[0] = 2 * ze - 1;
224 else if (ze == mz) lz_contrib[proc_k] = user->KM + 1 - (2 * zs - 1);
225 else lz_contrib[proc_k] = (ze - zs) * 2;
226 }
227 LOG_ALLOW_SYNC(LOCAL, LOG_VERBOSE, "Rank %d: Calculated this rank's node contribution to fine grid: lx=%" PetscInt_FMT ", ly=%" PetscInt_FMT ", lz=%" PetscInt_FMT "\n", simCtx->rank, lx_contrib[proc_i], ly_contrib[proc_j], lz_contrib[proc_k]);
228
229 // Allocate the final distribution arrays and Allreduce to get the global distribution
230 ierr = PetscMalloc3(m, &lx, n, &ly, p, &lz); CHKERRQ(ierr);
231 ierr = MPI_Allreduce(lx_contrib, lx, m, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
232 ierr = MPI_Allreduce(ly_contrib, ly, n, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
233 ierr = MPI_Allreduce(lz_contrib, lz, p, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
234
235 ierr = PetscFree3(lx_contrib, ly_contrib, lz_contrib); CHKERRQ(ierr);
236
237 } else {
238 // --- CASE 2: This is the COARSEST grid; use default or user-specified decomposition ---
239 if(simCtx->exec_mode == EXEC_MODE_SOLVER){
240
241 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Creating coarsest DM for block %" PetscInt_FMT " level %" PetscInt_FMT " (size %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT ")\n", simCtx->rank, user->_this, user->thislevel, user->IM, user->JM, user->KM);
242 m = simCtx->da_procs_x;
243 n = simCtx->da_procs_y;
244 p = simCtx->da_procs_z;
245
246 } else if(simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR){
247 /* The postprocessor's own decomposition from its recipe; PETSc decides where unset. */
248 m = simCtx->pps->da_procs[0];
249 n = simCtx->pps->da_procs[1];
250 p = simCtx->pps->da_procs[2];
251 }
252 // With a full layout, choose the coarsest split so the finest level balances;
253 // otherwise lx, ly, lz stay NULL and PETSc splits the coarsest level evenly.
254 if (m > 0 && n > 0 && p > 0) {
255 const UserCtx *finest = &simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user[user->_this];
256 const PetscInt refinements = simCtx->usermg.mglevels - 1;
257 ierr = PetscMalloc3(m, &lx, n, &ly, p, &lz); CHKERRQ(ierr);
258 ierr = BalanceCoarsestOwnership(user->IM + 1, finest->IM - 1, user->isc ? 0 : refinements, m, lx); CHKERRQ(ierr);
259 ierr = BalanceCoarsestOwnership(user->JM + 1, finest->JM - 1, user->jsc ? 0 : refinements, n, ly); CHKERRQ(ierr);
260 ierr = BalanceCoarsestOwnership(user->KM + 1, finest->KM - 1, user->ksc ? 0 : refinements, p, lz); CHKERRQ(ierr);
261 }
262 }
263
264 // --- Create the DMDA for the current UserCtx ---
265 /* The coordinate DM PETSc derives from this one carries 3 components per node; a wider
266 field is checked where CreateCompatibleBlockDM() creates it. */
267 {
268 char object[96];
269 ierr = PetscSNPrintf(object, sizeof(object), "The %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT
270 " grid's 3-component fields", user->IM + 1, user->JM + 1, user->KM + 1); CHKERRQ(ierr);
271 ierr = PicurvCheckPetscIntRange(PETSC_COMM_WORLD, (PetscInt64)(user->IM + 1) * (user->JM + 1) * (user->KM + 1) * 3,
272 object); CHKERRQ(ierr);
273 }
274 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Calling DMDACreate3d...\n", simCtx->rank);
275 ierr = DMDACreate3d(PETSC_COMM_WORLD, xperiod, yperiod, zperiod, DMDA_STENCIL_BOX,
276 user->IM + 1, user->JM + 1, user->KM + 1,
277 m, n, p,
278 1, stencil_width, lx, ly, lz, &user->da); CHKERRQ(ierr);
279
280 if (lx) {
281 ierr = PetscFree3(lx, ly, lz); CHKERRQ(ierr);
282 }
283
284 // --- Standard DM setup applicable to all levels ---
285 ierr = DMSetUp(user->da); CHKERRQ(ierr);
286 ierr = DMGetCoordinateDM(user->da, &user->fda); CHKERRQ(ierr);
287 /* The symmetric-tensor DM exists only to carry statistics products, and only the
288 * finest level accumulates them. Configuration is resolved before grid setup, so
289 * a run without statistics never builds it. */
290 if (FieldStatisticsNeedsWorkspace(simCtx) && user->thislevel == simCtx->mglevels - 1) {
291 ierr = CreateCompatibleBlockDM(user->da, 6, &user->fda6); CHKERRQ(ierr);
292 }
293 ierr = DMDASetUniformCoordinates(user->da, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0); CHKERRQ(ierr);
294 ierr = DMGetCoordinates(user->da, &user->Coor); CHKERRQ(ierr);
295 ierr = DMGetCoordinatesLocal(user->da, &user->lCoor); CHKERRQ(ierr);
296 ierr = DMDAGetLocalInfo(user->da, &user->info); CHKERRQ(ierr);
297 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: DM creation for block %" PetscInt_FMT " level %" PetscInt_FMT " complete.\n", simCtx->rank, user->_this, user->thislevel);
298
300
301 PetscFunctionReturn(0);
302}
PetscErrorCode BalanceCoarsestOwnership(PetscInt coarse_nodes, PetscInt fine_cells, PetscInt refinements, PetscInt ranks, PetscInt *l)
Implementation of BalanceCoarsestOwnership().
Definition grid.c:121
PetscErrorCode CreateCompatibleBlockDM(DM source, PetscInt dof, DM *result)
Implementation of CreateCompatibleBlockDM().
Definition grid.c:81
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
PetscBool FieldStatisticsNeedsWorkspace(const struct SimCtx *simCtx)
Reports whether this process derives field statistics of any kind.
PetscInt isc
Definition variables.h:1175
PetscInt da_procs_z
Definition variables.h:1013
PetscInt ksc
Definition variables.h:1175
PetscInt KM
Definition variables.h:1171
PetscInt da_procs_y
Definition variables.h:1013
PetscInt k_periodic
Definition variables.h:1010
PetscInt jsc
Definition variables.h:1175
PetscInt thislevel
Definition variables.h:1269
PetscInt JM
Definition variables.h:1171
PetscInt da_procs[3]
Postprocessor MPI decomposition (i, j, k) from the recipe; PETSC_DECIDE where unset.
Definition variables.h:845
PetscInt mglevels
Definition variables.h:961
Vec lCoor
Definition variables.h:1243
PetscInt da_procs_x
Definition variables.h:1013
PetscInt i_periodic
Definition variables.h:1010
DMDALocalInfo info
Definition variables.h:1169
PostProcessParams * pps
Definition variables.h:1131
@ EXEC_MODE_SOLVER
Definition variables.h:888
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
PetscInt IM
Definition variables.h:1171
ExecutionMode exec_mode
Definition variables.h:937
PetscInt j_periodic
Definition variables.h:1010
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeAllGridDMs()

PetscErrorCode InitializeAllGridDMs ( SimCtx *  simCtx)

Implementation of InitializeAllGridDMs().

Orchestrates the creation of DMDA objects for every block and multigrid level.

See also
InitializeAllGridDMs()

Definition at line 309 of file grid.c.

310{
311 PetscErrorCode ierr;
312 UserMG *usermg = &simCtx->usermg;
313 MGCtx *mgctx = usermg->mgctx;
314 PetscInt nblk = simCtx->block_number;
315
316 PetscFunctionBeginUser;
317
319
320 LOG_ALLOW(GLOBAL,LOG_INFO, "Pre-scanning BCs to identify domain periodicity.\n");
321 ierr = DeterminePeriodicity(simCtx); CHKERRQ(ierr);
322
323 LOG_ALLOW(GLOBAL, LOG_INFO, "Creating DMDA objects for all levels and blocks...\n");
324
325 // --- Part 1: Calculate Coarse Grid Dimensions & VALIDATE ---
326 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Calculating and validating coarse grid dimensions...\n");
327 for (PetscInt level = usermg->mglevels - 2; level >= 0; level--) {
328 for (PetscInt bi = 0; bi < nblk; bi++) {
329 UserCtx *user_coarse = &mgctx[level].user[bi];
330 UserCtx *user_fine = &mgctx[level + 1].user[bi];
331
332 user_coarse->IM = user_fine->isc ? user_fine->IM : (user_fine->IM + 1) / 2;
333 user_coarse->JM = user_fine->jsc ? user_fine->JM : (user_fine->JM + 1) / 2;
334 user_coarse->KM = user_fine->ksc ? user_fine->KM : (user_fine->KM + 1) / 2;
335
336 LOG_ALLOW_SYNC(LOCAL, LOG_TRACE, "Rank %d: Block %" PetscInt_FMT ", Level %" PetscInt_FMT " dims calculated: %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT "\n",
337 simCtx->rank, bi, level, user_coarse->IM, user_coarse->JM, user_coarse->KM);
338
339 // Validation check from legacy MGDACreate to ensure coarsening is possible
340 PetscInt check_i = user_coarse->IM * (2 - user_coarse->isc) - (user_fine->IM + 1 - user_coarse->isc);
341 PetscInt check_j = user_coarse->JM * (2 - user_coarse->jsc) - (user_fine->JM + 1 - user_coarse->jsc);
342 PetscInt check_k = user_coarse->KM * (2 - user_coarse->ksc) - (user_fine->KM + 1 - user_coarse->ksc);
343
344 if (check_i + check_j + check_k != 0) {
345 // SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
346 // "Grid at level %d, block %d cannot be coarsened from %dx%dx%d to %dx%dx%d with the given semi-coarsening flags. Check grid dimensions.",
347 // level, bi, user_fine->IM, user_fine->JM, user_fine->KM, user_coarse->IM, user_coarse->JM, user_coarse->KM);
348 LOG(GLOBAL,LOG_WARNING,"WARNING: Grid at level %" PetscInt_FMT ", block %" PetscInt_FMT " can't be consistently coarsened further.\n", level, bi);
349 }
350 }
351 }
352
353 // --- Part 2: Create DMs from Coarse to Fine for each Block ---
354 for (PetscInt bi = 0; bi < nblk; bi++) {
355 LOG_ALLOW(GLOBAL, LOG_DEBUG, "--- Creating DMs for Block %" PetscInt_FMT " ---\n", bi);
356
357 // Create the coarsest level DM first (passing NULL for the coarse_user)
358 ierr = InitializeSingleGridDM(&mgctx[0].user[bi], NULL); CHKERRQ(ierr);
359
360 // Create finer level DMs, passing the next-coarser context for alignment
361 for (PetscInt level = 1; level < usermg->mglevels; level++) {
362 ierr = InitializeSingleGridDM(&mgctx[level].user[bi], &mgctx[level-1].user[bi]); CHKERRQ(ierr);
363 }
364 }
365
366 // --- Optional: View the finest DM for debugging verification ---
367 if (get_log_level() >= LOG_DEBUG) {
368 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Viewing Finest DMDA (Level %" PetscInt_FMT ", Block 0) ---\n", usermg->mglevels - 1);
369 ierr = DMView(mgctx[usermg->mglevels - 1].user[0].da, PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
370 }
371
372 LOG_ALLOW(GLOBAL, LOG_INFO, "DMDA object creation complete.\n");
373
375
376 PetscFunctionReturn(0);
377}
static PetscErrorCode InitializeSingleGridDM(UserCtx *user, UserCtx *coarse_user)
Create and configure one PETSc DMDA for a multigrid level.
Definition grid.c:158
PetscErrorCode DeterminePeriodicity(SimCtx *simCtx)
Scans all block-specific boundary condition files to determine a globally consistent periodicity for ...
Definition io.c:1096
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Context for Multigrid operations.
Definition variables.h:767
User-level context for managing the entire multigrid hierarchy.
Definition variables.h:774
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetFinestLevelCoordinates()

static PetscErrorCode SetFinestLevelCoordinates ( UserCtx *  user)
static

Attach the generated physical coordinates to the finest-level DMDA.

Definition at line 585 of file grid.c.

586{
587 PetscErrorCode ierr;
588 SimCtx *simCtx = user->simCtx;
589
590 PetscFunctionBeginUser;
591
593
594 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Setting finest level coordinates for block %" PetscInt_FMT "...\n", simCtx->rank, user->_this);
595
596 if (simCtx->generate_grid) {
597 ierr = GenerateAndSetCoordinates(user); CHKERRQ(ierr);
598 } else {
599
600 FILE *grid_file_handle = NULL;
601 // Only Rank 0 opens the file.
602 if (simCtx->rank == 0) {
603 grid_file_handle = fopen(simCtx->grid_file, "r");
604 if (!grid_file_handle) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Cannot open file: %s", simCtx->grid_file);
605
606 // Now, on Rank 0, we skip the entire header section once.
607 // This is the logic from your modern code's AssignGridCoordinates.
608 PetscInt headerLines = simCtx->block_number + 2; // 1 for nblk, plus one for each block's dims
609 char dummy_buffer[2048];
610 for (PetscInt s = 0; s < headerLines; ++s) {
611 if (!fgets(dummy_buffer, sizeof(dummy_buffer), grid_file_handle)) {
612 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Unexpected EOF while skipping grid header");
613 }
614 }
615 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank 0: Skipped %" PetscInt_FMT " header lines, now at coordinate data.\n", headerLines);
616 }
617
618 // We now call the coordinate reader, passing the file handle.
619 // It's responsible for reading its block's data and broadcasting.
620 ierr = ReadAndSetCoordinates(user, grid_file_handle); CHKERRQ(ierr);
621
622 // Only Rank 0, which opened the file, should close it.
623 if (simCtx->rank == 0) {
624 fclose(grid_file_handle);
625 }
626 }
627
628 // Populate local ghost coordinates from the owned global coordinates.
629 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Scattering coordinates to update ghost nodes for block %" PetscInt_FMT "...\n", simCtx->rank, user->_this);
630 ierr = UpdateLocalGhosts(user, FIELD_ID_COORDINATES); CHKERRQ(ierr);
631
633
634 PetscFunctionReturn(0);
635}
@ FIELD_ID_COORDINATES
static PetscErrorCode GenerateAndSetCoordinates(UserCtx *user)
Generate analytic grid coordinates and install them on the finest grid level.
Definition grid.c:653
static PetscErrorCode ReadAndSetCoordinates(UserCtx *user, FILE *fd)
Load grid coordinates from the input file and install them on the finest level.
Definition grid.c:720
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
char grid_file[PETSC_MAX_PATH_LEN]
Definition variables.h:1012
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GenerateAndSetCoordinates()

static PetscErrorCode GenerateAndSetCoordinates ( UserCtx *  user)
static

Generate analytic grid coordinates and install them on the finest grid level.

DEBUG: This verifies the presence of a last "unphysical" layer of coordinates.

Definition at line 653 of file grid.c.

654{
655 PetscErrorCode ierr;
656 DMDALocalInfo info;
657 Cmpnts ***coor;
658 Vec gCoor;
659
660 PetscFunctionBeginUser;
661
663
664 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Generating coordinates for block %" PetscInt_FMT "...\n", user->simCtx->rank, user->_this);
665
666 info = user->info;
667 gCoor = user->Coor;
668
669 PetscInt xs = info.xs, xe = info.xs + info.xm;
670 PetscInt ys = info.ys, ye = info.ys + info.ym;
671 PetscInt zs = info.zs, ze = info.zs + info.zm;
672
673 LOG_ALLOW_SYNC(LOCAL, LOG_TRACE, "Rank %d: Local Info for block %" PetscInt_FMT " - X range - [%" PetscInt_FMT ",%" PetscInt_FMT "], Y range - [%" PetscInt_FMT ",%" PetscInt_FMT "], Z range - [%" PetscInt_FMT ",%" PetscInt_FMT "]\n",
674 user->simCtx->rank, user->_this, xs, xe, ys, ye, zs, ze);
675
676 LOG_ALLOW_SYNC(LOCAL, LOG_TRACE, "Rank %d: Local Info for block %" PetscInt_FMT " - X domain - [%.4f,%.4f], Y range - [%.4f,%.4f], Z range - [%.4f,%.4f]\n",
677 user->simCtx->rank, user->_this, user->Min_X,user->Max_X,user->Min_Y,user->Max_Y,user->Min_Z,user->Max_Z);
678
679 ierr = VecSet(gCoor, 0.0); CHKERRQ(ierr);
680 ierr = DMDAVecGetArray(user->fda, gCoor, &coor); CHKERRQ(ierr);
681
682 PetscReal Lx = user->Max_X - user->Min_X;
683 PetscReal Ly = user->Max_Y - user->Min_Y;
684 PetscReal Lz = user->Max_Z - user->Min_Z;
685
686 // Loop over the nodes owned by this process.
687 for (PetscInt k = zs; k < ze; k++) {
688 for (PetscInt j = ys; j < ye; j++) {
689 for (PetscInt i = xs; i < xe; i++) {
690 if(k < user->KM && j < user->JM && i < user->IM){
691 coor[k][j][i].x = user->Min_X + ComputeStretchedCoord(i, user->IM, Lx, user->rx);
692 coor[k][j][i].y = user->Min_Y + ComputeStretchedCoord(j, user->JM, Ly, user->ry);
693 coor[k][j][i].z = user->Min_Z + ComputeStretchedCoord(k, user->KM, Lz, user->rz);
694 }
695 }
696 }
697 }
698
699 /// DEBUG: This verifies the presence of a last "unphysical" layer of coordinates.
700 /*
701 PetscInt KM = user->KM;
702 for (PetscInt j = ys; j < ye; j++){
703 for(PetscInt i = xs; i < xe; i++){
704 LOG_ALLOW(GLOBAL,LOG_DEBUG,"coor[%d][%d][%d].(x,y,z) = %le,%le,%le",KM,j,i,coor[KM][j][i].x,coor[KM][j][i].y,coor[KM][j][i].z);
705 }
706 }
707 */
708
709
710
711 ierr = DMDAVecRestoreArray(user->fda, gCoor, &coor); CHKERRQ(ierr);
712
714
715 PetscFunctionReturn(0);
716}
static PetscReal ComputeStretchedCoord(PetscInt i, PetscInt N, PetscReal L, PetscReal r)
Map a uniform logical coordinate to its configured stretched physical coordinate.
Definition grid.c:639
PetscReal Min_X
Definition variables.h:1172
PetscReal ry
Definition variables.h:1176
PetscReal Max_Y
Definition variables.h:1172
PetscScalar x
Definition variables.h:145
PetscReal rz
Definition variables.h:1176
PetscScalar z
Definition variables.h:145
PetscReal Min_Z
Definition variables.h:1172
PetscReal Max_X
Definition variables.h:1172
PetscReal Min_Y
Definition variables.h:1172
PetscScalar y
Definition variables.h:145
PetscReal rx
Definition variables.h:1176
PetscReal Max_Z
Definition variables.h:1172
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadAndSetCoordinates()

static PetscErrorCode ReadAndSetCoordinates ( UserCtx *  user,
FILE *  fd 
)
static

Load grid coordinates from the input file and install them on the finest level.

Definition at line 720 of file grid.c.

721{
722 PetscErrorCode ierr;
723 SimCtx *simCtx = user->simCtx;
724 PetscMPIInt rank = simCtx->rank;
725 PetscInt block_index = user->_this;
726 PetscInt IM = user->IM, JM = user->JM, KM = user->KM;
727 DMDALocalInfo info;
728 Cmpnts ***coor;
729 Vec gCoor;
730 PetscReal *gc = NULL; // Global coordinate buffer, allocated on all ranks
731
732 PetscFunctionBeginUser;
733
735
736 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d: Reading interleaved coordinates from file for block %" PetscInt_FMT "...\n",
737 simCtx->rank, block_index);
738
739 // 1. Allocate the buffer on ALL ranks to receive the broadcast data.
740 // PetscInt n_nodes = (IM + 1) * (JM + 1) * (KM + 1);
741 PetscInt n_nodes = (IM) * (JM) * (KM);
742 ierr = PetscMalloc1(3 * n_nodes, &gc); CHKERRQ(ierr);
743
744 // 2. Only Rank 0 opens the file and reads the data.
745 if (rank == 0) {
746 if (!fd) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Recieved a NULL file handle.\n");
747
748 // Read the coordinate data for the CURRENT block.
749 for (PetscInt k = 0; k < KM; k++) {
750 for (PetscInt j = 0; j < JM; j++) {
751 for (PetscInt i = 0; i < IM; i++) {
752 PetscInt base_index = 3 * ((k * (JM) + j) * (IM) + i);
753 if (fscanf(fd, "%le %le %le\n", &gc[base_index], &gc[base_index + 1], &gc[base_index + 2]) != 3) {
754 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading coordinates for node (i,j,k)=(%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") in block %" PetscInt_FMT "", i, j, k, block_index);
755 }
756 }
757 }
758 }
759
760 }
761
762 // 3. Broadcast the coordinate block for the current block to all other processes.
763 ierr = MPI_Bcast(gc, 3 * n_nodes, MPIU_REAL, 0, PETSC_COMM_WORLD); CHKERRQ(ierr);
764
765 // 4. Each rank populates its owned portion of the global coordinate vector.
766 info = user->info;
767 gCoor = user->Coor;
768 ierr = VecSet(gCoor, 0.0); CHKERRQ(ierr);
769 ierr = DMDAVecGetArray(user->fda, gCoor, &coor); CHKERRQ(ierr);
770
771 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
772 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
773 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
774 if(k< KM && j < JM && i < IM){
775 PetscInt base_idx = 3 * ((k * (JM) + j) * (IM) + i);
776 coor[k][j][i].x = gc[base_idx];
777 coor[k][j][i].y = gc[base_idx + 1];
778 coor[k][j][i].z = gc[base_idx + 2];
779 }
780 }
781 }
782 }
783
784 // 5. Clean up and restore.
785 ierr = DMDAVecRestoreArray(user->fda, gCoor, &coor); CHKERRQ(ierr);
786 ierr = PetscFree(gc); CHKERRQ(ierr);
787
789
790 PetscFunctionReturn(0);
791}
Here is the caller graph for this function:

◆ RestrictCoordinates()

static PetscErrorCode RestrictCoordinates ( UserCtx *  coarse_user,
UserCtx *  fine_user 
)
static

Restrict finest-grid coordinates onto each coarser multigrid level.

Definition at line 796 of file grid.c.

797{
798 PetscErrorCode ierr;
799 Vec c_gCoor, f_lCoor;
800 Cmpnts ***c_coor;
801 const Cmpnts ***f_coor; // Use const for read-only access
802 DMDALocalInfo c_info;
803 PetscInt ih, jh, kh; // Fine-grid indices corresponding to coarse-grid i,j,k
804
805 PetscFunctionBeginUser;
806
808
809 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Restricting coords from level %" PetscInt_FMT " to level %" PetscInt_FMT " for block %" PetscInt_FMT "\n",
810 fine_user->simCtx->rank, fine_user->thislevel, coarse_user->thislevel, coarse_user->_this);
811
812 c_info = coarse_user->info;
813
814 c_gCoor = coarse_user->Coor;
815 f_lCoor = fine_user->lCoor;
816
817 ierr = VecSet(c_gCoor, 0.0); CHKERRQ(ierr);
818 ierr = DMDAVecGetArray(coarse_user->fda, c_gCoor, &c_coor); CHKERRQ(ierr);
819 ierr = DMDAVecGetArrayRead(fine_user->fda, f_lCoor, &f_coor); CHKERRQ(ierr);
820
821 // Get the local owned range of the coarse grid.
822 PetscInt xs = c_info.xs, xe = c_info.xs + c_info.xm;
823 PetscInt ys = c_info.ys, ye = c_info.ys + c_info.ym;
824 PetscInt zs = c_info.zs, ze = c_info.zs + c_info.zm;
825
826 // Get the global dimensions of the coarse grid.
827 PetscInt mx = c_info.mx, my = c_info.my, mz = c_info.mz;
828
829 // If this process owns the maximum boundary node, contract the loop by one
830 // to prevent the index doubling `2*i` from going out of bounds.
831 // This is also ensuring we do not manipulate the unphysical layer of coors present in the finest level.
832 if (xe == mx) xe--;
833 if (ye == my) ye--;
834 if (ze == mz) ze--;
835
836 for (PetscInt k = zs; k < ze; k++) {
837 for (PetscInt j = ys; j < ye; j++) {
838 for (PetscInt i = xs; i < xe; i++) {
839 // Determine the corresponding parent node index on the FINE grid,
840 // respecting the semi-coarsening flags of the FINE grid's UserCtx.
841 ih = coarse_user->isc ? i : 2 * i;
842 jh = coarse_user->jsc ? j : 2 * j;
843 kh = coarse_user->ksc ? k : 2 * k;
844
845 // LOG_ALLOW(GLOBAL,LOG_DEBUG," [kh][ih][jh] = %d,%d,%d - k,j,i = %d,%d,%d.\n",kh,jh,ih,k,j,i);
846
847 c_coor[k][j][i] = f_coor[kh][jh][ih];
848 }
849 }
850 }
851
852 ierr = DMDAVecRestoreArray(coarse_user->fda, c_gCoor, &c_coor); CHKERRQ(ierr);
853 ierr = DMDAVecRestoreArrayRead(fine_user->fda, f_lCoor, &f_coor); CHKERRQ(ierr);
854
855 // Populate the coarse-grid local ghost coordinates from the restricted global coordinates.
856 ierr = UpdateLocalGhosts(coarse_user, FIELD_ID_COORDINATES); CHKERRQ(ierr);
857
859
860 PetscFunctionReturn(0);
861}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AssignAllGridCoordinates()

PetscErrorCode AssignAllGridCoordinates ( SimCtx *  simCtx)

Implementation of AssignAllGridCoordinates().

Orchestrates the assignment of physical coordinates to all DMDA objects.

See also
AssignAllGridCoordinates()

Definition at line 389 of file grid.c.

390{
391 PetscErrorCode ierr;
392 UserMG *usermg = &simCtx->usermg;
393 PetscInt nblk = simCtx->block_number;
394
395 PetscFunctionBeginUser;
396
398
399 LOG_ALLOW(GLOBAL, LOG_INFO, "Assigning physical coordinates to all grid DMs...\n");
400
401 // --- Part 1: Populate the Finest Grid Level ---
402 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Setting coordinates for the finest grid level (%" PetscInt_FMT ")...\n", usermg->mglevels - 1);
403 for (PetscInt bi = 0; bi < nblk; bi++) {
404 UserCtx *fine_user = &usermg->mgctx[usermg->mglevels - 1].user[bi];
405 ierr = SetFinestLevelCoordinates(fine_user); CHKERRQ(ierr);
406 LOG_ALLOW(GLOBAL,LOG_TRACE,"The Finest level coordinates for block %" PetscInt_FMT " have been set.\n",bi);
407 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true){
408 ierr = LOG_FIELD_MIN_MAX(fine_user, FIELD_ID_COORDINATES);
409 }
410 }
411 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Finest level coordinates have been set for all blocks.\n");
412
413 // --- Part 2: Restrict Coordinates to Coarser Levels ---
414 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Restricting coordinates to coarser grid levels...\n");
415 for (PetscInt level = usermg->mglevels - 2; level >= 0; level--) {
416 for (PetscInt bi = 0; bi < nblk; bi++) {
417 UserCtx *coarse_user = &usermg->mgctx[level].user[bi];
418 UserCtx *fine_user = &usermg->mgctx[level + 1].user[bi];
419 ierr = RestrictCoordinates(coarse_user, fine_user); CHKERRQ(ierr);
420
421 LOG_ALLOW(GLOBAL,LOG_TRACE,"Coordinates restricted to block %" PetscInt_FMT " level %" PetscInt_FMT ".\n",bi,level);
422 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true) {
423 ierr = LOG_FIELD_MIN_MAX(coarse_user, FIELD_ID_COORDINATES);
424 }
425 }
426 }
427
428 LOG_ALLOW(GLOBAL, LOG_INFO, "Physical coordinates assigned to all grid levels and blocks.\n");
429
431
432 PetscFunctionReturn(0);
433}
static PetscErrorCode RestrictCoordinates(UserCtx *coarse_user, UserCtx *fine_user)
Restrict finest-grid coordinates onto each coarser multigrid level.
Definition grid.c:796
static PetscErrorCode SetFinestLevelCoordinates(UserCtx *user)
Attach the generated physical coordinates to the finest-level DMDA.
Definition grid.c:585
PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
Computes and logs the local and global min/max values of a 3-component vector field.
Definition logging.c:2501
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CoordinateComponent()

static PetscReal CoordinateComponent ( Cmpnts  value,
PetscInt  component 
)
inlinestatic

Returns one Cartesian component from a coordinate/vector value.

Definition at line 438 of file grid.c.

439{
440 if (component == 0) return value.x;
441 if (component == 1) return value.y;
442 return value.z;
443}
Here is the caller graph for this function:

◆ ValidatePeriodicGeometry()

PetscErrorCode ValidatePeriodicGeometry ( UserCtx *  user)

Implementation of ValidatePeriodicGeometry().

Validates that configured geometric periodic seams match by translation.

Full API contract is documented with the header declaration in include/grid.h.

Definition at line 450 of file grid.c.

451{
452 const BCFace neg_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
453 const BCFace pos_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
454 const char axis_names[3] = {'X', 'Y', 'Z'};
455 const Cmpnts ***coor = NULL;
456 Vec lcoor = NULL;
457 DMDALocalInfo info;
458
459 PetscFunctionBeginUser;
461 info = user->info;
462 lcoor = user->lCoor;
463 PetscCheck(lcoor != NULL, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
464 "Cannot validate periodic geometry before local coordinates are assigned.");
465 for (PetscInt axis = 0; axis < 3; axis++) {
466 const PetscBool neg_periodic =
467 user->boundary_faces[neg_faces[axis]].mathematical_type == PERIODIC;
468 const PetscBool pos_periodic =
469 user->boundary_faces[pos_faces[axis]].mathematical_type == PERIODIC;
470 PetscReal local_min[3] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MAX_REAL};
471 PetscReal local_max[3] = {-PETSC_MAX_REAL, -PETSC_MAX_REAL, -PETSC_MAX_REAL};
472 PetscReal global_min[3], global_max[3];
473 PetscInt local_count = 0, global_count = 0;
474
475 user->periodic_translation_valid[axis] = PETSC_FALSE;
476 user->periodic_translation[axis] = (Cmpnts){0.0, 0.0, 0.0};
477 if (!neg_periodic && !pos_periodic) continue;
478
479 PetscCheck(neg_periodic && pos_periodic, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
480 "Periodic geometry in the %c direction requires paired negative and positive faces.",
481 axis_names[axis]);
482 const PetscInt axis_size = axis == 0 ? info.mx : (axis == 1 ? info.my : info.mz);
483 PetscCheck(axis_size >= 5, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
484 "%c-periodic geometry on block %" PetscInt_FMT " level %" PetscInt_FMT " requires at least four physical "
485 "nodes in that direction; found %" PetscInt_FMT ".",
486 axis_names[axis], user->_this, user->thislevel, axis_size - 1);
487
488 PetscCall(DMDAVecGetArrayRead(user->fda, lcoor, &coor));
489 if (axis == 0 && info.xs == 0) {
490 for (PetscInt k = PetscMax(info.zs, 0); k < PetscMin(info.zs + info.zm, info.mz - 1); k++) {
491 for (PetscInt j = PetscMax(info.ys, 0); j < PetscMin(info.ys + info.ym, info.my - 1); j++) {
492 const Cmpnts delta = {
493 coor[k][j][-2].x - coor[k][j][0].x,
494 coor[k][j][-2].y - coor[k][j][0].y,
495 coor[k][j][-2].z - coor[k][j][0].z
496 };
497 for (PetscInt c = 0; c < 3; c++) {
498 local_min[c] = PetscMin(local_min[c], CoordinateComponent(delta, c));
499 local_max[c] = PetscMax(local_max[c], CoordinateComponent(delta, c));
500 }
501 local_count++;
502 }
503 }
504 } else if (axis == 1 && info.ys == 0) {
505 for (PetscInt k = PetscMax(info.zs, 0); k < PetscMin(info.zs + info.zm, info.mz - 1); k++) {
506 for (PetscInt i = PetscMax(info.xs, 0); i < PetscMin(info.xs + info.xm, info.mx - 1); i++) {
507 const Cmpnts delta = {
508 coor[k][-2][i].x - coor[k][0][i].x,
509 coor[k][-2][i].y - coor[k][0][i].y,
510 coor[k][-2][i].z - coor[k][0][i].z
511 };
512 for (PetscInt c = 0; c < 3; c++) {
513 local_min[c] = PetscMin(local_min[c], CoordinateComponent(delta, c));
514 local_max[c] = PetscMax(local_max[c], CoordinateComponent(delta, c));
515 }
516 local_count++;
517 }
518 }
519 } else if (axis == 2 && info.zs == 0) {
520 for (PetscInt j = PetscMax(info.ys, 0); j < PetscMin(info.ys + info.ym, info.my - 1); j++) {
521 for (PetscInt i = PetscMax(info.xs, 0); i < PetscMin(info.xs + info.xm, info.mx - 1); i++) {
522 const Cmpnts delta = {
523 coor[-2][j][i].x - coor[0][j][i].x,
524 coor[-2][j][i].y - coor[0][j][i].y,
525 coor[-2][j][i].z - coor[0][j][i].z
526 };
527 for (PetscInt c = 0; c < 3; c++) {
528 local_min[c] = PetscMin(local_min[c], CoordinateComponent(delta, c));
529 local_max[c] = PetscMax(local_max[c], CoordinateComponent(delta, c));
530 }
531 local_count++;
532 }
533 }
534 }
535 PetscCall(DMDAVecRestoreArrayRead(user->fda, lcoor, &coor));
536
537 PetscCallMPI(MPI_Allreduce(local_min, global_min, 3, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD));
538 PetscCallMPI(MPI_Allreduce(local_max, global_max, 3, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
539 PetscCallMPI(MPI_Allreduce(&local_count, &global_count, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
540 PetscCheck(global_count > 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
541 "No physical seam nodes were available to validate %c-periodic geometry.",
542 axis_names[axis]);
543
544 PetscReal translation[3];
545 PetscReal scale = 1.0;
546 PetscReal max_mismatch = 0.0;
547 for (PetscInt c = 0; c < 3; c++) {
548 translation[c] = 0.5 * (global_min[c] + global_max[c]);
549 scale = PetscMax(scale, PetscAbsReal(translation[c]));
550 max_mismatch = PetscMax(max_mismatch, global_max[c] - global_min[c]);
551 }
552 const PetscReal tolerance = 1.0e-9 * scale + 100.0 * PETSC_MACHINE_EPSILON;
553 const PetscReal magnitude = PetscSqrtReal(
554 PetscSqr(translation[0]) + PetscSqr(translation[1]) + PetscSqr(translation[2]));
555
556 PetscCheck(max_mismatch <= tolerance, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
557 "Unsupported %c-periodic geometry on block %" PetscInt_FMT " level %" PetscInt_FMT ": opposite physical "
558 "surfaces are not related by one constant translation. Maximum component "
559 "mismatch is %.12e (tolerance %.12e).",
560 axis_names[axis], user->_this, user->thislevel,
561 (double)max_mismatch, (double)tolerance);
562 PetscCheck(magnitude > tolerance, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
563 "Unsupported %c-periodic geometry on block %" PetscInt_FMT " level %" PetscInt_FMT ": seam translation "
564 "magnitude %.12e is zero or too small.",
565 axis_names[axis], user->_this, user->thislevel, (double)magnitude);
566
567 user->periodic_translation[axis] =
568 (Cmpnts){translation[0], translation[1], translation[2]};
569 user->periodic_translation_valid[axis] = PETSC_TRUE;
571 "Validated %c-periodic geometry for block %" PetscInt_FMT " level %" PetscInt_FMT " with translation "
572 "(%.12e, %.12e, %.12e).\n",
573 axis_names[axis], user->_this, user->thislevel,
574 (double)translation[0], (double)translation[1], (double)translation[2]);
575 }
576
578 PetscFunctionReturn(0);
579}
static PetscReal CoordinateComponent(Cmpnts value, PetscInt component)
Returns one Cartesian component from a coordinate/vector value.
Definition grid.c:438
@ PERIODIC
Definition variables.h:325
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
Cmpnts periodic_translation[3]
Definition variables.h:1178
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
BCType mathematical_type
Definition variables.h:426
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeStretchedCoord()

static PetscReal ComputeStretchedCoord ( PetscInt  i,
PetscInt  N,
PetscReal  L,
PetscReal  r 
)
inlinestatic

Map a uniform logical coordinate to its configured stretched physical coordinate.

Definition at line 639 of file grid.c.

640{
641 if (N <=1) return 0.0;
642 PetscReal fraction = (PetscReal)i / ((PetscReal)N - 1.0);
643 if (PetscAbsReal(r - 1.0) < 1.0e-9) { // Use a tolerance for float comparison
644 return L * fraction;
645 } else {
646 return L * (PetscPowReal(r, fraction) - 1.0) / (r - 1.0);
647 }
648}
Here is the caller graph for this function:

◆ ComputeLocalBoundingBox()

PetscErrorCode ComputeLocalBoundingBox ( UserCtx *  user,
BoundingBox *  localBBox 
)

Implementation of ComputeLocalBoundingBox().

Computes the local bounding box of the grid on the current process.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
ComputeLocalBoundingBox()

Definition at line 869 of file grid.c.

870{
871 PetscErrorCode ierr;
872 PetscInt i, j, k;
873 PetscMPIInt rank;
874 PetscInt xs, ys, zs, xe, ye, ze;
875 DMDALocalInfo info;
876 Vec coordinates;
877 Cmpnts ***coordArray;
878 Cmpnts minCoords, maxCoords;
879
880 PetscFunctionBeginUser;
881
883
884 // Start of function execution
885 LOG_ALLOW(GLOBAL, LOG_INFO, "Entering the function.\n");
886
887 // Validate input Pointers
888 if (!user) {
889 LOG_ALLOW(LOCAL, LOG_ERROR, "Input 'user' Pointer is NULL.\n");
891 return PETSC_ERR_ARG_NULL;
892 }
893 if (!localBBox) {
894 LOG_ALLOW(LOCAL, LOG_ERROR, "Output 'localBBox' Pointer is NULL.\n");
896 return PETSC_ERR_ARG_NULL;
897 }
898
899 // Get MPI rank
900 rank = PetscGlobalRank;
901
902 // Get the local coordinates vector from the DMDA
903 coordinates = user->lCoor;
904
905 if (!coordinates) {
906 LOG_ALLOW(LOCAL, LOG_ERROR, "Coordinates vector is NULL.\n");
908 return PETSC_ERR_ARG_NULL;
909 }
910
911 // Access the coordinate array for reading
912 ierr = DMDAVecGetArrayRead(user->fda, coordinates, &coordArray);
913 if (ierr) {
914 LOG_ALLOW(LOCAL, LOG_ERROR, "Error accessing coordinate array.\n");
916 return ierr;
917 }
918
919 // Get the local grid information (indices and sizes)
920 info = user->info;
921 if (ierr) {
922 LOG_ALLOW(LOCAL, LOG_ERROR, "Error getting DMDA local info.\n");
924 return ierr;
925 }
926
927
928 xs = info.gxs; xe = xs + info.gxm;
929 ys = info.gys; ye = ys + info.gym;
930 zs = info.gzs; ze = zs + info.gzm;
931
932 /*
933 xs = info.xs; xe = xs + info.xm;
934 ys = info.ys; ye = ys + info.ym;
935 zs = info.zs; ze = zs + info.zm;
936 */
937
938 // Initialize min and max coordinates with extreme values
939 minCoords.x = minCoords.y = minCoords.z = PETSC_MAX_REAL;
940 maxCoords.x = maxCoords.y = maxCoords.z = PETSC_MIN_REAL;
941
942 LOG_ALLOW(LOCAL, LOG_TRACE, "[Rank %d] Grid indices (Including Ghosts): xs=%" PetscInt_FMT ", xe=%" PetscInt_FMT ", ys=%" PetscInt_FMT ", ye=%" PetscInt_FMT ", zs=%" PetscInt_FMT ", ze=%" PetscInt_FMT ".\n",rank, xs, xe, ys, ye, zs, ze);
943
944 // Iterate over the local grid to find min and max coordinates
945 for (k = zs; k < ze; k++) {
946 for (j = ys; j < ye; j++) {
947 for (i = xs; i < xe; i++) {
948 // Only consider nodes within the physical domain.
949 if(i < user->IM && j < user->JM && k < user->KM){
950 Cmpnts coord = coordArray[k][j][i];
951
952 // Update min and max coordinates
953 if (coord.x < minCoords.x) minCoords.x = coord.x;
954 if (coord.y < minCoords.y) minCoords.y = coord.y;
955 if (coord.z < minCoords.z) minCoords.z = coord.z;
956
957 if (coord.x > maxCoords.x) maxCoords.x = coord.x;
958 if (coord.y > maxCoords.y) maxCoords.y = coord.y;
959 if (coord.z > maxCoords.z) maxCoords.z = coord.z;
960 }
961 }
962 }
963 }
964
965
966 // Add tolerance to bboxes.
967 minCoords.x = minCoords.x - BBOX_TOLERANCE;
968 minCoords.y = minCoords.y - BBOX_TOLERANCE;
969 minCoords.z = minCoords.z - BBOX_TOLERANCE;
970
971 maxCoords.x = maxCoords.x + BBOX_TOLERANCE;
972 maxCoords.y = maxCoords.y + BBOX_TOLERANCE;
973 maxCoords.z = maxCoords.z + BBOX_TOLERANCE;
974
975 LOG_ALLOW(LOCAL,LOG_DEBUG," Tolerance added to the limits: %.8e .\n",(PetscReal)BBOX_TOLERANCE);
976
977 // Log the computed min and max coordinates
978 LOG_ALLOW(LOCAL, LOG_INFO,"[Rank %d] Bounding Box Ranges = X[%.6f, %.6f], Y[%.6f,%.6f], Z[%.6f, %.6f].\n",rank,minCoords.x, maxCoords.x,minCoords.y, maxCoords.y, minCoords.z, maxCoords.z);
979
980
981
982 // Restore the coordinate array
983 ierr = DMDAVecRestoreArrayRead(user->fda, coordinates, &coordArray);
984 if (ierr) {
985 LOG_ALLOW(LOCAL, LOG_ERROR, "Error restoring coordinate array.\n");
987 return ierr;
988 }
989
990 // Set the local bounding box
991 localBBox->min_coords = minCoords;
992 localBBox->max_coords = maxCoords;
993
994 // Update the bounding box inside the UserCtx for consistency
995 user->bbox = *localBBox;
996
997 LOG_ALLOW(GLOBAL, LOG_INFO, "Exiting the function successfully.\n");
998
1000
1001 PetscFunctionReturn(0);
1002}
#define BBOX_TOLERANCE
Definition grid.c:7
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
BoundingBox bbox
Definition variables.h:1173
Here is the caller graph for this function:

◆ GatherAllBoundingBoxes()

PetscErrorCode GatherAllBoundingBoxes ( UserCtx *  user,
BoundingBox **  allBBoxes 
)

Implementation of GatherAllBoundingBoxes().

Gathers local bounding boxes from all MPI processes to rank 0.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
GatherAllBoundingBoxes()

Definition at line 1011 of file grid.c.

1012{
1013 PetscErrorCode ierr;
1014 PetscMPIInt rank, size;
1015 BoundingBox *bboxArray = NULL;
1016 BoundingBox localBBox;
1017
1018 PetscFunctionBeginUser;
1019
1021
1022 /* Validate */
1023 if (!user || !allBBoxes) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1024 "GatherAllBoundingBoxes: NULL pointer");
1025
1026 rank = PetscGlobalRank;
1027 size = PetscGlobalSize;
1028
1029 /* Compute local bbox */
1030 ierr = ComputeLocalBoundingBox(user, &localBBox); CHKERRQ(ierr);
1031
1032 /* Ensure everyone is synchronized before the gather */
1033 MPI_Barrier(PETSC_COMM_WORLD);
1035 "Rank %d: about to MPI_Gather(localBBox)\n", rank);
1036
1037 /* Allocate on root */
1038 if (rank == 0) {
1039 bboxArray = (BoundingBox*)malloc(size * sizeof(BoundingBox));
1040 if (!bboxArray) SETERRABORT(PETSC_COMM_WORLD, PETSC_ERR_MEM,
1041 "GatherAllBoundingBoxes: malloc failed");
1042 }
1043
1044 /* Collective: every rank must call */
1045 ierr = MPI_Gather(&localBBox, sizeof(BoundingBox), MPI_BYTE,
1046 bboxArray, sizeof(BoundingBox), MPI_BYTE,
1047 0, PETSC_COMM_WORLD);
1048 CHKERRMPI(ierr);
1049
1050 MPI_Barrier(PETSC_COMM_WORLD);
1052 "Rank %d: completed MPI_Gather(localBBox)\n", rank);
1053
1054 /* Return result */
1055 if (rank == 0) {
1056 *allBBoxes = bboxArray;
1057 } else {
1058 *allBBoxes = NULL;
1059 }
1060
1062
1063 PetscFunctionReturn(0);
1064}
PetscErrorCode ComputeLocalBoundingBox(UserCtx *user, BoundingBox *localBBox)
Implementation of ComputeLocalBoundingBox().
Definition grid.c:869
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BroadcastAllBoundingBoxes()

PetscErrorCode BroadcastAllBoundingBoxes ( UserCtx *  user,
BoundingBox **  bboxlist 
)

Implementation of BroadcastAllBoundingBoxes().

Broadcasts the bounding box information collected on rank 0 to all other ranks.

See also
BroadcastAllBoundingBoxes()

Definition at line 1071 of file grid.c.

1072{
1073 PetscErrorCode ierr;
1074 (void)user;
1075 PetscMPIInt rank, size;
1076
1077 PetscFunctionBeginUser;
1078
1080
1081 if (!bboxlist) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1082 "BroadcastAllBoundingBoxes: NULL pointer");
1083
1084 rank = user->simCtx->rank;
1085 size = user->simCtx->size;
1086
1087 /* Non-root ranks must allocate before the Bcast */
1088 if (rank != 0) {
1089 *bboxlist = (BoundingBox*)malloc(size * sizeof(BoundingBox));
1090 if (!*bboxlist) SETERRABORT(PETSC_COMM_WORLD, PETSC_ERR_MEM,
1091 "BroadcastAllBoundingBoxes: malloc failed");
1092 }
1093
1094 MPI_Barrier(PETSC_COMM_WORLD);
1096 "Rank %d: about to MPI_Bcast(%d boxes)\n", rank, size);
1097
1098 /* Collective: every rank must call */
1099 ierr = MPI_Bcast(*bboxlist, size * sizeof(BoundingBox), MPI_BYTE,
1100 0, PETSC_COMM_WORLD);
1101 CHKERRMPI(ierr);
1102
1103 MPI_Barrier(PETSC_COMM_WORLD);
1105 "Rank %d: completed MPI_Bcast(%d boxes)\n", rank, size);
1106
1107
1109
1110 PetscFunctionReturn(0);
1111}
PetscMPIInt size
Definition variables.h:920
Here is the caller graph for this function:

◆ CalculateInletProperties()

PetscErrorCode CalculateInletProperties ( UserCtx *  user)

Implementation of CalculateInletProperties().

Calculates the center and area of the primary INLET face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CalculateInletProperties()

Definition at line 1119 of file grid.c.

1120{
1121 PetscErrorCode ierr;
1122 BCFace inlet_face_id = -1;
1123 PetscBool inlet_found = PETSC_FALSE;
1124
1125 PetscFunctionBeginUser;
1127
1128 // 1. Identify the primary inlet face from the configuration
1129 for (int i = 0; i < 6; i++) {
1130 if (user->boundary_faces[i].mathematical_type == INLET) {
1131 inlet_face_id = user->boundary_faces[i].face_id;
1132 inlet_found = PETSC_TRUE;
1133 break; // Use the first inlet found
1134 }
1135 }
1136
1137 if (!inlet_found) {
1138 LOG_ALLOW(GLOBAL, LOG_INFO, "No INLET face found. Skipping inlet center calculation.\n");
1140 PetscFunctionReturn(0);
1141 }
1142
1143 Cmpnts inlet_center;
1144 PetscReal inlet_area;
1145
1146 // 2. Call the generic utility to compute the center and area of any face.
1147 ierr = CalculateFaceCenterAndArea(user,inlet_face_id,&inlet_center,&inlet_area); CHKERRQ(ierr);
1148
1149 // 3. Store results in the SimCtx
1150 user->simCtx->CMx_c = inlet_center.x;
1151 user->simCtx->CMy_c = inlet_center.y;
1152 user->simCtx->CMz_c = inlet_center.z;
1153 user->simCtx->AreaInSum = inlet_area;
1154
1156 "Rank[%d] Inlet Center: (%.6f, %.6f, %.6f), Area: %.6f\n",
1157 user->simCtx->rank, inlet_center.x, inlet_center.y, inlet_center.z, inlet_area);
1158
1160 PetscFunctionReturn(0);
1161
1162}
PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
Implementation of CalculateFaceCenterAndArea().
Definition grid.c:1211
@ INLET
Definition variables.h:323
PetscReal CMy_c
Definition variables.h:1001
PetscReal CMz_c
Definition variables.h:1001
PetscReal AreaInSum
Definition variables.h:1036
PetscReal CMx_c
Definition variables.h:1001
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CalculateOutletProperties()

PetscErrorCode CalculateOutletProperties ( UserCtx *  user)

Implementation of CalculateOutletProperties().

Calculates the center and area of the primary OUTLET face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CalculateOutletProperties()

Definition at line 1170 of file grid.c.

1171{
1172 PetscErrorCode ierr;
1173 BCFace outlet_face_id = -1;
1174 PetscBool outlet_found = PETSC_FALSE;
1175 PetscFunctionBeginUser;
1177 // 1. Identify the primary outlet face from the configuration
1178 for (int i = 0; i < 6; i++) {
1179 if (user->boundary_faces[i].mathematical_type == OUTLET) {
1180 outlet_face_id = user->boundary_faces[i].face_id;
1181 outlet_found = PETSC_TRUE;
1182 break; // Use the first outlet found
1183 }
1184 }
1185 if (!outlet_found) {
1186 LOG_ALLOW(GLOBAL, LOG_INFO, "No OUTLET face found. Skipping outlet center calculation.\n");
1188 PetscFunctionReturn(0);
1189 }
1190 PetscReal outlet_area;
1191 Cmpnts outlet_center;
1192 // 2. Call the generic utility to compute the center and area of any face
1193 ierr = CalculateFaceCenterAndArea(user,outlet_face_id,&outlet_center,&outlet_area); CHKERRQ(ierr);
1194 // 3. Store results in the SimCtx
1195 user->simCtx->AreaOutSum = outlet_area;
1196
1198 "Outlet Center: (%.6f, %.6f, %.6f), Area: %.6f\n",
1199 outlet_center.x, outlet_center.y, outlet_center.z, outlet_area);
1200
1202 PetscFunctionReturn(0);
1203}
@ OUTLET
Definition variables.h:322
PetscReal AreaOutSum
Definition variables.h:1036
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CalculateFaceCenterAndArea()

PetscErrorCode CalculateFaceCenterAndArea ( UserCtx *  user,
BCFace  face_id,
Cmpnts *  face_center,
PetscReal *  face_area 
)

Implementation of CalculateFaceCenterAndArea().

Calculates the geometric center and total area of a specified boundary face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CalculateFaceCenterAndArea()

< Local sum of (x,y,z) coordinates

< Local sum of face area magnitudes

< Local count of nodes

< Global sum of coordinates

< Global sum of areas

< Global count of nodes

< i-range: [xs, xe)

< j-range: [ys, ye)

< k-range: [zs, ze)

< Physical domain size in i (exclude dummy)

< Physical domain size in j (exclude dummy)

< Physical domain size in k (exclude dummy)

< Start at 1 if on -Xi boundary

< End at mx-1 if on +Xi boundary

< Start at 1 if on -Eta boundary

< End at my-1 if on +Eta boundary

< Start at 1 if on -Zeta boundary

< End at mz-1 if on +Zeta boundary

< Exclude dummy at i=mx-1 (e.g., i=25)

< Exclude dummy at j=my-1 (e.g., j=25)

< Exclude dummy at k=mz-1 (e.g., k=97)

< Local ghosted coordinate vector

< Nodal coordinates [k][j][i]

< Face metric tensors [k][j][i]

< Cell blanking field [k][j][i] (shifted +1)

Definition at line 1211 of file grid.c.

1213{
1214 PetscErrorCode ierr;
1215 DMDALocalInfo info;
1216
1217 // ========================================================================
1218 // Local accumulators for this rank's contribution
1219 // ========================================================================
1220 PetscReal local_sum[3] = {0.0, 0.0, 0.0}; ///< Local sum of (x,y,z) coordinates
1221 PetscReal localAreaSum = 0.0; ///< Local sum of face area magnitudes
1222 PetscCount local_n_points = 0; ///< Local count of nodes
1223
1224 // ========================================================================
1225 // Global accumulators after MPI reduction
1226 // ========================================================================
1227 PetscReal global_sum[3] = {0.0, 0.0, 0.0}; ///< Global sum of coordinates
1228 PetscReal globalAreaSum = 0.0; ///< Global sum of areas
1229 PetscCount global_n_points = 0; ///< Global count of nodes
1230
1231 // ========================================================================
1232 // Grid information and array pointers
1233 // ========================================================================
1234 info = user->info;
1235
1236 // Rank's owned range in global indices
1237 PetscInt xs = info.xs, xe = info.xs + info.xm; ///< i-range: [xs, xe)
1238 PetscInt ys = info.ys, ye = info.ys + info.ym; ///< j-range: [ys, ye)
1239 PetscInt zs = info.zs, ze = info.zs + info.zm; ///< k-range: [zs, ze)
1240
1241 // Global domain dimensions (total allocated, includes dummy at end)
1242 PetscInt mx = info.mx, my = info.my, mz = info.mz;
1243 PetscInt IM = user->IM; ///< Physical domain size in i (exclude dummy)
1244 PetscInt JM = user->JM; ///< Physical domain size in j (exclude dummy)
1245 PetscInt KM = user->KM; ///< Physical domain size in k (exclude dummy)
1246
1247 // ========================================================================
1248 // Interior loop bounds (adjusted to avoid ghost/boundary cells)
1249 // These are used for nvert checks where we need valid cell indices
1250 // ========================================================================
1251 PetscInt lxs = xs; if(xs == 0) lxs = xs + 1; ///< Start at 1 if on -Xi boundary
1252 PetscInt lxe = xe; if(xe == mx) lxe = xe - 1; ///< End at mx-1 if on +Xi boundary
1253 PetscInt lys = ys; if(ys == 0) lys = ys + 1; ///< Start at 1 if on -Eta boundary
1254 PetscInt lye = ye; if(ye == my) lye = ye - 1; ///< End at my-1 if on +Eta boundary
1255 PetscInt lzs = zs; if(zs == 0) lzs = zs + 1; ///< Start at 1 if on -Zeta boundary
1256 PetscInt lze = ze; if(ze == mz) lze = ze - 1; ///< End at mz-1 if on +Zeta boundary
1257
1258 // ========================================================================
1259 // Physical node bounds (exclude dummy indices at mx-1, my-1, mz-1)
1260 // These are used for coordinate loops where we want ALL physical nodes
1261 // ========================================================================
1262 PetscInt i_max = (xe == mx) ? mx - 1 : xe; ///< Exclude dummy at i=mx-1 (e.g., i=25)
1263 PetscInt j_max = (ye == my) ? my - 1 : ye; ///< Exclude dummy at j=my-1 (e.g., j=25)
1264 PetscInt k_max = (ze == mz) ? mz - 1 : ze; ///< Exclude dummy at k=mz-1 (e.g., k=97)
1265
1266 // ========================================================================
1267 // Array pointers for field access
1268 // ========================================================================
1269 Vec lCoor; ///< Local ghosted coordinate vector
1270 Cmpnts ***coor; ///< Nodal coordinates [k][j][i]
1271 Cmpnts ***csi, ***eta, ***zet; ///< Face metric tensors [k][j][i]
1272 PetscReal ***nvert; ///< Cell blanking field [k][j][i] (shifted +1)
1273
1274 PetscFunctionBeginUser;
1276
1277 // ========================================================================
1278 // Step 1: Check if this rank owns the specified boundary face
1279 // ========================================================================
1280 PetscBool owns_face = PETSC_FALSE;
1281 ierr = CanRankServiceFace(&info,IM,JM,KM,face_id,&owns_face); CHKERRQ(ierr);
1282 if(owns_face){
1283 // ========================================================================
1284 // Step 2: Get read-only array access for all required fields
1285 // ========================================================================
1286 lCoor = user->lCoor;
1287 ierr = DMDAVecGetArrayRead(user->fda, lCoor, &coor); CHKERRQ(ierr);
1288 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, &nvert); CHKERRQ(ierr);
1289 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
1290 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
1291 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
1292
1293 // ========================================================================
1294 // Step 3: Loop over the specified face and accumulate center and area
1295 // ========================================================================
1296 switch (face_id) {
1297
1298 // ====================================================================
1299 // BC_FACE_NEG_X: Face at i=0 (bottom boundary in i-direction)
1300 // ====================================================================
1301 case BC_FACE_NEG_X:
1302 if (xs == 0) {
1303 PetscInt i = 0; // Face is at node index i=0
1304
1305 // ---- Part 1: Center calculation (ALL physical nodes) ----
1306 // Loop over ALL physical nodes on this face
1307 // For my=26, mz=98: j∈[0,24], k∈[0,96] → 25×97 = 2,425 nodes
1308 for (PetscInt k = zs; k < k_max; k++) {
1309 for (PetscInt j = ys; j < j_max; j++) {
1310 // Accumulate coordinates at node [k][j][0]
1311 local_sum[0] += coor[k][j][i].x;
1312 local_sum[1] += coor[k][j][i].y;
1313 local_sum[2] += coor[k][j][i].z;
1314 local_n_points++;
1315 }
1316 }
1317
1318 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1319 // Loop over interior range where nvert checks are valid
1320 // For my=26, mz=98: j∈[1,24], k∈[1,96] → 24×96 = 2,304 cells
1321 for (PetscInt k = lzs; k < lze; k++) {
1322 for (PetscInt j = lys; j < lye; j++) {
1323 // Check if adjacent cell is fluid
1324 // nvert[k][j][i+1] = nvert[k][j][1] checks Cell 0
1325 // (Physical Cell 0 in j-k plane, stored at shifted index [1])
1326 if (nvert[k][j][i+1] < 0.1) {
1327 // Cell is fluid - add face area contribution
1328 // Face area = magnitude of csi metric at [k][j][0]
1329 localAreaSum += sqrt(csi[k][j][i].x * csi[k][j][i].x +
1330 csi[k][j][i].y * csi[k][j][i].y +
1331 csi[k][j][i].z * csi[k][j][i].z);
1332 }
1333 }
1334 }
1335 }
1336 break;
1337
1338 // ====================================================================
1339 // BC_FACE_POS_X: Face at i=IM-1 (top boundary in i-direction)
1340 // ====================================================================
1341 case BC_FACE_POS_X:
1342 if (xe == mx) {
1343 PetscInt i = mx - 2; // Last physical node (e.g., i=24 for mx=26)
1344
1345 // ---- Part 1: Center calculation (ALL physical nodes) ----
1346 for (PetscInt k = zs; k < k_max; k++) {
1347 for (PetscInt j = ys; j < j_max; j++) {
1348 local_sum[0] += coor[k][j][i].x;
1349 local_sum[1] += coor[k][j][i].y;
1350 local_sum[2] += coor[k][j][i].z;
1351 local_n_points++;
1352 }
1353 }
1354
1355 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1356 for (PetscInt k = lzs; k < lze; k++) {
1357 for (PetscInt j = lys; j < lye; j++) {
1358 // Check if adjacent cell is fluid
1359 // nvert[k][j][i] = nvert[k][j][24] checks last cell (Cell 23)
1360 // (Physical Cell 23, stored at shifted index [24])
1361 if (nvert[k][j][i] < 0.1) {
1362 // Face area = magnitude of csi metric at [k][j][24]
1363 localAreaSum += sqrt(csi[k][j][i].x * csi[k][j][i].x +
1364 csi[k][j][i].y * csi[k][j][i].y +
1365 csi[k][j][i].z * csi[k][j][i].z);
1366 }
1367 }
1368 }
1369 }
1370 break;
1371
1372 // ====================================================================
1373 // BC_FACE_NEG_Y: Face at j=0 (bottom boundary in j-direction)
1374 // ====================================================================
1375 case BC_FACE_NEG_Y:
1376 if (ys == 0) {
1377 PetscInt j = 0; // Face is at node index j=0
1378
1379 // ---- Part 1: Center calculation (ALL physical nodes) ----
1380 // For mx=26, mz=98: i∈[0,24], k∈[0,96] → 25×97 = 2,425 nodes
1381 for (PetscInt k = zs; k < k_max; k++) {
1382 for (PetscInt i = xs; i < i_max; i++) {
1383 local_sum[0] += coor[k][j][i].x;
1384 local_sum[1] += coor[k][j][i].y;
1385 local_sum[2] += coor[k][j][i].z;
1386 local_n_points++;
1387 }
1388 }
1389
1390 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1391 // For mx=26, mz=98: i∈[1,24], k∈[1,96] → 24×96 = 2,304 cells
1392 for (PetscInt k = lzs; k < lze; k++) {
1393 for (PetscInt i = lxs; i < lxe; i++) {
1394 // nvert[k][j+1][i] = nvert[k][1][i] checks Cell 0
1395 if (nvert[k][j+1][i] < 0.1) {
1396 // Face area = magnitude of eta metric at [k][0][i]
1397 localAreaSum += sqrt(eta[k][j][i].x * eta[k][j][i].x +
1398 eta[k][j][i].y * eta[k][j][i].y +
1399 eta[k][j][i].z * eta[k][j][i].z);
1400 }
1401 }
1402 }
1403 }
1404 break;
1405
1406 // ====================================================================
1407 // BC_FACE_POS_Y: Face at j=JM-1 (top boundary in j-direction)
1408 // ====================================================================
1409 case BC_FACE_POS_Y:
1410 if (ye == my) {
1411 PetscInt j = my - 2; // Last physical node (e.g., j=24 for my=26)
1412
1413 // ---- Part 1: Center calculation (ALL physical nodes) ----
1414 for (PetscInt k = zs; k < k_max; k++) {
1415 for (PetscInt i = xs; i < i_max; i++) {
1416 local_sum[0] += coor[k][j][i].x;
1417 local_sum[1] += coor[k][j][i].y;
1418 local_sum[2] += coor[k][j][i].z;
1419 local_n_points++;
1420 }
1421 }
1422
1423 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1424 for (PetscInt k = lzs; k < lze; k++) {
1425 for (PetscInt i = lxs; i < lxe; i++) {
1426 // nvert[k][j][i] = nvert[k][24][i] checks last cell (Cell 23)
1427 if (nvert[k][j][i] < 0.1) {
1428 // Face area = magnitude of eta metric at [k][24][i]
1429 localAreaSum += sqrt(eta[k][j][i].x * eta[k][j][i].x +
1430 eta[k][j][i].y * eta[k][j][i].y +
1431 eta[k][j][i].z * eta[k][j][i].z);
1432 }
1433 }
1434 }
1435 }
1436 break;
1437
1438 // ====================================================================
1439 // BC_FACE_NEG_Z: Face at k=0 (inlet, bottom boundary in k-direction)
1440 // ====================================================================
1441 case BC_FACE_NEG_Z:
1442 if (zs == 0) {
1443 PetscInt k = 0; // Face is at node index k=0
1444
1445 // ---- Part 1: Center calculation (ALL physical nodes) ----
1446 // For mx=26, my=26: i∈[0,24], j∈[0,24] → 25×25 = 625 nodes
1447 for (PetscInt j = ys; j < j_max; j++) {
1448 for (PetscInt i = xs; i < i_max; i++) {
1449 local_sum[0] += coor[k][j][i].x;
1450 local_sum[1] += coor[k][j][i].y;
1451 local_sum[2] += coor[k][j][i].z;
1452 local_n_points++;
1453 }
1454 }
1455
1456 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1457 // For mx=26, my=26: i∈[1,24], j∈[1,24] → 24×24 = 576 cells
1458 for (PetscInt j = lys; j < lye; j++) {
1459 for (PetscInt i = lxs; i < lxe; i++) {
1460 // nvert[k+1][j][i] = nvert[1][j][i] checks Cell 0
1461 // (Physical Cell 0 in i-j plane, stored at shifted index [1])
1462 if (nvert[k+1][j][i] < 0.1) {
1463 // Face area = magnitude of zet metric at [0][j][i]
1464 localAreaSum += sqrt(zet[k][j][i].x * zet[k][j][i].x +
1465 zet[k][j][i].y * zet[k][j][i].y +
1466 zet[k][j][i].z * zet[k][j][i].z);
1467 }
1468 }
1469 }
1470 }
1471 break;
1472
1473 // ====================================================================
1474 // BC_FACE_POS_Z: Face at k=KM-1 (outlet, top boundary in k-direction)
1475 // ====================================================================
1476 case BC_FACE_POS_Z:
1477 if (ze == mz) {
1478 PetscInt k = mz - 2; // Last physical node (e.g., k=96 for mz=98)
1479
1480 // ---- Part 1: Center calculation (ALL physical nodes) ----
1481 // For mx=26, my=26: i∈[0,24], j∈[0,24] → 25×25 = 625 nodes
1482 for (PetscInt j = ys; j < j_max; j++) {
1483 for (PetscInt i = xs; i < i_max; i++) {
1484 local_sum[0] += coor[k][j][i].x;
1485 local_sum[1] += coor[k][j][i].y;
1486 local_sum[2] += coor[k][j][i].z;
1487 local_n_points++;
1488 }
1489 }
1490
1491 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1492 // For mx=26, my=26: i∈[1,24], j∈[1,24] → 24×24 = 576 cells
1493 for (PetscInt j = lys; j < lye; j++) {
1494 for (PetscInt i = lxs; i < lxe; i++) {
1495 // nvert[k][j][i] = nvert[96][j][i] checks last cell (Cell 95)
1496 // (Physical Cell 95, stored at shifted index [96])
1497 if (nvert[k][j][i] < 0.1) {
1498 // Face area = magnitude of zet metric at [96][j][i]
1499 localAreaSum += sqrt(zet[k][j][i].x * zet[k][j][i].x +
1500 zet[k][j][i].y * zet[k][j][i].y +
1501 zet[k][j][i].z * zet[k][j][i].z);
1502 }
1503 }
1504 }
1505 }
1506 break;
1507
1508 default:
1509 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1510 "Unknown face_id %d in CalculateFaceCenterAndArea", face_id);
1511 }
1512
1513 // ========================================================================
1514 // Step 4: Restore array access (release pointers)
1515 // ========================================================================
1516 ierr = DMDAVecRestoreArrayRead(user->fda, lCoor, &coor); CHKERRQ(ierr);
1517 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, &nvert); CHKERRQ(ierr);
1518 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
1519 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
1520 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
1521 }
1522 // ========================================================================
1523 // Step 5: Perform MPI reductions to get global sums
1524 // ========================================================================
1525 // Sum coordinate contributions from all ranks
1526 ierr = MPI_Allreduce(local_sum, global_sum, 3, MPI_DOUBLE, MPI_SUM,
1527 PETSC_COMM_WORLD); CHKERRQ(ierr);
1528
1529 // Sum node counts from all ranks
1530 ierr = MPI_Allreduce(&local_n_points, &global_n_points, 1, MPI_COUNT, MPI_SUM,
1531 PETSC_COMM_WORLD); CHKERRQ(ierr);
1532
1533 // Sum area contributions from all ranks
1534 ierr = MPI_Allreduce(&localAreaSum, &globalAreaSum, 1, MPI_DOUBLE, MPI_SUM,
1535 PETSC_COMM_WORLD); CHKERRQ(ierr);
1536
1537 // ========================================================================
1538 // Step 6: Calculate geometric center by averaging coordinates
1539 // ========================================================================
1540 if (global_n_points > 0) {
1541 face_center->x = global_sum[0] / global_n_points;
1542 face_center->y = global_sum[1] / global_n_points;
1543 face_center->z = global_sum[2] / global_n_points;
1545 "Calculated center for Face %s: (x=%.4f, y=%.4f, z=%.4f) from %lld nodes\n",
1546 BCFaceToString(face_id),
1547 face_center->x, face_center->y, face_center->z,
1548 (long long)global_n_points);
1549 } else {
1550 // No nodes found - this should not happen for a valid face
1552 "WARNING: Face %s identified but no grid points found. Center not calculated.\n",
1553 BCFaceToString(face_id));
1554 face_center->x = face_center->y = face_center->z = 0.0;
1555 }
1556
1557 // ========================================================================
1558 // Step 7: Return computed total area
1559 // ========================================================================
1560 *face_area = globalAreaSum;
1562 "Calculated area for Face %s: Area=%.6f\n",
1563 BCFaceToString(face_id), *face_area);
1564
1566 PetscFunctionReturn(0);
1567}
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Determines if the current MPI rank owns any part of a specified global face.
Definition Boundaries.c:22
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
Vec lNvert
Definition variables.h:1197
Here is the call graph for this function:
Here is the caller graph for this function: