PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Metric.h
Go to the documentation of this file.
1#ifndef METRIC_H
2#define METRIC_H
3
4// Include necessary headers
5#include <petsc.h>
6#include "variables.h" // Common type definitions
7#include "logging.h" // Logging macros and definitions
8#include <stdlib.h>
9#include "io.h"
10#include "setup.h" // For SetDMDAProcLayout
11
12/**
13 * @brief Maps a logical point inside one hexahedral cell to physical space.
14 *
15 * Uses trilinear interpolation of the eight cell vertices. Logical coordinates
16 * are measured from the cell's lower logical corner and normally lie in [0, 1].
17 *
18 * @param user Grid context used for cell indexing.
19 * @param X Ghosted node-coordinate array for the block.
20 * @param i Cell index in the xi direction.
21 * @param j Cell index in the eta direction.
22 * @param k Cell index in the zeta direction.
23 * @param xi Local xi coordinate within the cell.
24 * @param eta Local eta coordinate within the cell.
25 * @param zta Local zeta coordinate within the cell.
26 * @param[out] Xp Physical Cartesian position evaluated at the logical point.
27 * @return PetscErrorCode 0 on success.
28 */
29PetscErrorCode MetricLogicalToPhysical(UserCtx *user, const Cmpnts ***X,
30 PetscInt i,PetscInt j,PetscInt k,
31 PetscReal xi,PetscReal eta,PetscReal zta,
32 Cmpnts *Xp);
33
34/**
35 * @brief Collects the eight node coordinates of one logical hexahedral cell.
36 *
37 * Vertex ordering matches the trilinear metric kernels in this module.
38 *
39 * @param user Grid context used for cell indexing.
40 * @param X Ghosted node-coordinate array for the block.
41 * @param i Cell index in the xi direction.
42 * @param j Cell index in the eta direction.
43 * @param k Cell index in the zeta direction.
44 * @param[out] V Eight physical vertex coordinates in metric-kernel order.
45 * @return PetscErrorCode 0 on success.
46 */
47PetscErrorCode MetricGetCellVertices(UserCtx *user,const Cmpnts ***X,
48 PetscInt i,PetscInt j,PetscInt k,
49 Cmpnts V[8]);
50
51/**
52 * @brief Evaluates the trilinear mapping Jacobian and its determinant in one cell.
53 *
54 * The returned matrix is \f$\partial(x,y,z)/\partial(\xi,\eta,\zeta)\f$;
55 * callers use its determinant to reject degenerate or inverted cells.
56 *
57 * @param user Grid context used for cell indexing.
58 * @param X Ghosted node-coordinate array for the block.
59 * @param i Cell index in the xi direction.
60 * @param j Cell index in the eta direction.
61 * @param k Cell index in the zeta direction.
62 * @param xi Local xi coordinate within the cell.
63 * @param eta Local eta coordinate within the cell.
64 * @param zta Local zeta coordinate within the cell.
65 * @param[out] J Mapping Jacobian in row-major Cartesian/logical form.
66 * @param[out] detJ Determinant of J.
67 * @return PetscErrorCode 0 on success.
68 */
69PetscErrorCode MetricJacobian(UserCtx *user,const Cmpnts ***X,
70 PetscInt i,PetscInt j,PetscInt k,
71 PetscReal xi,PetscReal eta,PetscReal zta,
72 PetscReal J[3][3],PetscReal *detJ);
73
74/**
75 * @brief Converts a Cartesian velocity vector to contravariant logical components.
76 *
77 * Uses the inverse of the physical-to-logical Jacobian; `detJ` must describe
78 * the same mapping as `J` and must be nonzero.
79 *
80 * @param J Mapping Jacobian at the evaluation point.
81 * @param detJ Determinant of J.
82 * @param u Cartesian velocity components.
83 * @param[out] uc Contravariant xi/eta/zeta velocity components.
84 * @return PetscErrorCode 0 on success.
85 */
86PetscErrorCode MetricVelocityContravariant(const PetscReal J[3][3],
87 PetscReal detJ,
88 const PetscReal u[3],PetscReal uc[3]);
89
90/**
91 * @brief @p velocity less its component along the face metric @p metric, which leaves it tangent
92 * to the face. A face of zero area has no normal, and @p velocity is returned unchanged.
93 * Shared by the boundary handlers and the wall model, which both need the wall-parallel
94 * part of a velocity on a curvilinear face.
95 * @param velocity Velocity to project.
96 * @param metric The face's area vector (any length, any orientation).
97 * @return The tangential part of @p velocity.
98 */
99static inline Cmpnts RemoveFaceNormalComponent(Cmpnts velocity, Cmpnts metric)
100{
101 const PetscReal area_sq = metric.x * metric.x + metric.y * metric.y + metric.z * metric.z;
102 const PetscReal normal = (area_sq > 0.0)
103 ? (velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z) / area_sq : 0.0;
104 Cmpnts tangential;
105
106 tangential.x = velocity.x - normal * metric.x;
107 tangential.y = velocity.y - normal * metric.y;
108 tangential.z = velocity.z - normal * metric.z;
109 return tangential;
110}
111
112/**
113 * @brief Computes the unit normal vectors and areas of the three faces of a computational cell.
114 *
115 * Given the metric vectors (csi, eta, zet), this function calculates the geometric
116 * properties of the cell faces aligned with the i, j, and k directions.
117 *
118 * @param csi Covariant xi metric vector.
119 * @param eta Covariant eta metric vector.
120 * @param zet Covariant zeta metric vector.
121 * @param[out] ni Unit normal of the xi-normal face.
122 * @param[out] nj Unit normal of the eta-normal face.
123 * @param[out] nk Unit normal of the zeta-normal face.
124 * @param[out] Ai Area of the xi-normal face.
125 * @param[out] Aj Area of the eta-normal face.
126 * @param[out] Ak Area of the zeta-normal face.
127 * @deprecated Unreachable from any executable: its only caller is
128 * @ref ComputeCellCharacteristicLengthScale, which has none. Kept for now with
129 * its unit tests; do not add new callers - use @ref ComputeCellDirectionalExtents or
130 * @ref ComputeCellEdgeVectors, which do not depend on the cell's orientation.
131 * @return PetscErrorCode 0 on success.
132 */
133PetscErrorCode CalculateFaceNormalAndArea(Cmpnts csi, Cmpnts eta, Cmpnts zet, double ni[3], double nj[3], double nk[3], double *Ai, double *Aj, double *Ak);
134
135/**
136 * @brief Inverts the 3x3 matrix of face-area vectors to obtain the covariant directions.
137 *
138 * The caller fills the rows with `csi`, `eta` and `zet` - the face-area vectors, which
139 * are the contravariant basis scaled by the cell Jacobian. The inverse's columns are the
140 * covariant (tangent) directions `dx/dxi`, `dx/deta`, `dx/dzeta` divided by that
141 * Jacobian, which is what `CalculateFaceNormalAndArea()` normalizes.
142 *
143 * Degeneracy is judged relative to the rows' own magnitude, because the determinant of
144 * area vectors scales as the square of the cell volume: an absolute floor would reject a
145 * well-formed cell purely for being small.
146 *
147 * @param covariantTensor Input: rows are the three face-area vectors.
148 * @param[out] contravariantTensor Inverse written in place.
149 * @deprecated Unreachable from any executable: its only caller is
150 * @ref CalculateFaceNormalAndArea, which is reached only from the deprecated
151 * @ref ComputeCellCharacteristicLengthScale. Kept for now with its unit tests;
152 * do not add new callers - use @ref ComputeCellDirectionalExtents or
153 * @ref ComputeCellEdgeVectors, which do not depend on the cell's orientation.
154 * @return PetscErrorCode 0 on success; `PETSC_ERR_MAT_LU_ZRPVT` when the rows are
155 * coplanar or one of them vanishes.
156 */
157PetscErrorCode InvertCovariantMetricTensor(double covariantTensor[3][3], double contravariantTensor[3][3]);
158
159/**
160 * @brief Computes characteristic length scales (dx, dy, dz) for a curvilinear cell.
161 *
162 * For a non-uniform, non-orthogonal cell, there is no single "dx". This function
163 * computes an effective length scale in each Cartesian direction based on the cell
164 * volume and the areas of its faces: the three outputs are the Cartesian components of
165 * the cell diagonal, so they change when an otherwise identical cell is rotated. Use
166 * @ref ComputeCellDirectionalExtents for a measure of the cell itself.
167 *
168 * @param ajc Cell Jacobian/volume metric at the cell center.
169 * @param csi Covariant xi metric vector.
170 * @param eta Covariant eta metric vector.
171 * @param zet Covariant zeta metric vector.
172 * @param[out] dx Effective physical length associated with xi variation.
173 * @param[out] dy Effective physical length associated with eta variation.
174 * @param[out] dz Effective physical length associated with zeta variation.
175 * @deprecated No production caller. Its outputs are Cartesian projections of the cell
176 * diagonal, so they change when an identical cell is rotated; the LES filter
177 * widths and the Clark term stopped using it for that reason. Kept for now
178 * with its unit tests; do not add new callers - use @ref ComputeCellDirectionalExtents or
179 * @ref ComputeCellEdgeVectors, which do not depend on the cell's orientation.
180 * @return PetscErrorCode 0 on success.
181 */
182PetscErrorCode ComputeCellCharacteristicLengthScale(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, double *dx, double *dy, double *dz);
183
184/**
185 * @brief Computes a cell's extent along each of its own grid directions.
186 *
187 * Each extent is the cell volume divided by the area of the face pair it crosses, which
188 * is the distance between those two faces. Unlike
189 * @ref ComputeCellCharacteristicLengthScale, whose outputs are the Cartesian components
190 * of the cell diagonal and so change when the same cell is rotated, these depend on the
191 * cell alone: a filter width built from them is the same for a cell in a straight
192 * section and for an identical cell turned by a bend.
193 *
194 * @param ajc Inverse cell volume at the cell center.
195 * @param csi Face-area vector of the xi faces.
196 * @param eta Face-area vector of the eta faces.
197 * @param zet Face-area vector of the zeta faces.
198 * @param[out] l_xi Extent across the xi faces.
199 * @param[out] l_eta Extent across the eta faces.
200 * @param[out] l_zeta Extent across the zeta faces.
201 * @return PetscErrorCode 0 on success; `PETSC_ERR_ARG_OUTOFRANGE` for a non-positive
202 * Jacobian or a face of zero area.
203 */
204PetscErrorCode ComputeCellDirectionalExtents(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet,
205 double *l_xi, double *l_eta, double *l_zeta);
206
207/**
208 * @brief Computes a cell's edge vectors along its three grid directions.
209 *
210 * Each is the covariant basis vector `dx/dxi_k` over one index step: the physical
211 * displacement from one cell to the next along that grid line, with both its direction
212 * and its length. Projecting a velocity gradient onto it gives the change in velocity
213 * across the cell in that direction, which is what a direction-resolved subgrid model
214 * needs and what does not depend on how the grid is oriented.
215 *
216 * @param ajc Inverse cell volume at the cell center.
217 * @param csi Face-area vector of the xi faces.
218 * @param eta Face-area vector of the eta faces.
219 * @param zet Face-area vector of the zeta faces.
220 * @param[out] edges Edge vectors along xi, eta and zeta, in that order.
221 * @return PetscErrorCode 0 on success; `PETSC_ERR_ARG_OUTOFRANGE` for a non-positive Jacobian.
222 */
223PetscErrorCode ComputeCellEdgeVectors(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet,
224 Cmpnts edges[3]);
225
226/**
227 * @brief Builds translated periodic images for the dummy cell centers of periodic axes.
228 *
229 * PETSc wraps field indices but does not translate coordinates. This routine sets the dummy
230 * slot before the first cell of each periodic axis to the last cell's center minus the
231 * validated seam translation, and the slot after the last cell to the first cell's center
232 * plus it, axis by axis with a ghost refresh in between, so edge and corner dummies carry the
233 * translation of every periodic axis they cross. Grid spacing is not modified.
234 *
235 * @param user The UserCtx containing grid and field data.
236 * @return PetscErrorCode 0 on success.
237 */
239
240/**
241 * @brief Builds translated periodic images for i-face centers (Centx).
242 *
243 * Every active periodic axis can affect the ghost images of Centx. This must
244 * be called after Centx is computed and before it is used for metric calculations.
245 *
246 * @param user The UserCtx containing grid and field data.
247 * @return PetscErrorCode 0 on success.
248 */
250
251/**
252 * @brief Builds translated periodic images for j-face centers (Centy).
253 *
254 * Every active periodic axis can affect the ghost images of Centy. This must
255 * be called after Centy is computed and before it is used for metric calculations.
256 *
257 * @param user The UserCtx containing grid and field data.
258 * @return PetscErrorCode 0 on success.
259 */
261
262/**
263 * @brief Builds translated periodic images for k-face centers (Centz).
264 *
265 * Every active periodic axis can affect the ghost images of Centz. This must
266 * be called after Centz is computed and before it is used for metric calculations.
267 *
268 * @param user The UserCtx containing grid and field data.
269 * @return PetscErrorCode 0 on success.
270 */
272
273/**
274 * @brief Computes the primary face metric components (Csi, Eta, Zet), including
275 * boundary extrapolation, and stores them in the corresponding global Vec
276 * members of the UserCtx structure (user->Csi, user->Eta, user->Zet).
277 *
278 * This is a self-contained routine that performs the following steps:
279 * 1. Obtains local ghosted nodal coordinates using DMGetCoordinatesLocal.
280 * 2. Calculates metrics for INTERIOR faces where finite difference stencils are valid.
281 * 3. EXTRAPOLATES metrics for faces on the physical domain boundaries by copying
282 * from the nearest computed interior face.
283 * 4. Assembles the global `user->Csi`, `user->Eta`, `user->Zet` Vecs.
284 * 5. Updates the local ghosted `user->lCsi`, `user->lEta`, `user->lZet` Vecs.
285 *
286 * @param[in,out] user Pointer to the UserCtx structure.
287 *
288 * @return PetscErrorCode 0 on success.
289 *
290 * @note
291 * - This function is a complete "compute and make ready" unit for Csi, Eta, and Zet.
292 * - It's recommended to call `VecZeroEntries` on user->Csi, Eta, Zet before this
293 * if they might contain old data.
294 */
295PetscErrorCode ComputeFaceMetrics(UserCtx *user);
296
297/**
298 * @brief Calculates the cell-centered inverse Jacobian determinant (1/J) for INTERIOR cells
299 * and stores it in `user->Aj`. This version includes boundary extrapolation.
300 *
301 * Nodal coordinates are obtained internally.
302 * Refer to previous Doxygen comments for details on physical locations and
303 * storage convention (`aj_arr[k_n][j_n][i_n]` for cell `C(i_n-1,j_n-1,k_n-1)`).
304 *
305 * @param[in,out] user Pointer to the UserCtx structure.
306 *
307 * @return PetscErrorCode 0 on success.
308 */
309PetscErrorCode ComputeCellCenteredJacobianInverse(UserCtx *user);
310
311/**
312 * @brief Verify and, when consistently inverted, repair the **right-handed** metric basis (`Csi`, `Eta`, `Zet`) and a
313 * **positive Jacobian** (`Aj`) over the whole domain.
314 *
315 * The metric-generation kernels are completely algebraic, so they will happily
316 * deliver a *left-handed* basis if the mesh file enumerates nodes in the
317 * opposite ζ-direction.
318 * This routine makes the orientation explicit and—if needed—repairs it
319 * **once per run**:
320 *
321 * | Step | Action |
322 * |------|--------|
323 * | 1 | Compute global `Aj_min`, `Aj_max`. |
324 * | 2 | **Mixed signs** (`Aj_min < 0 && Aj_max > 0`) &rarr; abort: the mesh is topologically inconsistent. |
325 * | 3 | **All negative** (`Aj_max < 0`) &rarr; abort: the grid is left-handed. Negating the metric vectors is not a valid repair (a mirrored duct solved that way was wrong by a factor of forty), so the grid must be renumbered along one logical axis instead. |
326 * | 4 | Store `user->GridOrientation = +1`, the only orientation the solver accepts. |
327 *
328 * @param[in,out] user Fully initialised #UserCtx that already contains
329 * `Csi`, `Eta`, `Zet`, `Aj`, their **local** ghosts, and
330 * valid distributed DMs.
331 *
332 * @return `0` on success or a PETSc error code on failure.
333 *
334 * @note Call **immediately after** `ComputeCellCenteredJacobianInverse()` and
335 * before any routine that differentiates or applies BCs.
336 *
337 * @note Author metadata intentionally omitted in API docs.
338 */
339PetscErrorCode CheckAndFixGridOrientation(UserCtx *user);
340
341/**
342 * @brief Computes the physical location of each cell's center from the nodal coordinates.
343 *
344 * @param user The UserCtx for a specific grid level. The function populates `user->Cent`.
345 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
346 */
347PetscErrorCode ComputeCellCenters(UserCtx *user);
348
349/**
350 * @brief Arc-length position of every owned cell centre along its three grid lines.
351 * @details For each grid line through an interior cell, the line's length is the sum of
352 * the cell edge lengths along it (ComputeCellEdgeVectors()), and a cell's fraction
353 * is the length before it plus half its own, over that total: 0 at the line's
354 * negative face and 1 at its positive face, proportional to distance along the
355 * line, so it is the same on uniform and stretched grids. Lines that cross ranks
356 * are summed with a scan along the line. Collective on `PETSC_COMM_WORLD`; needs the
357 * face metrics and the Jacobian with their local ghosts.
358 * @param[in] user Block and level whose grid lines are measured.
359 * @param[out] fraction Global vector on `user->fda`: the xi, eta, zeta fractions in
360 * `.x`, `.y`, `.z` at interior cells; other entries are untouched.
361 * @param[out] length Global vector on `user->fda`: the lengths of the same three lines,
362 * in solver units.
363 * @return Zero on success.
364 */
365PetscErrorCode ComputeGridLineFractions(UserCtx *user, Vec fraction, Vec length);
366
367/**
368 * @brief Computes metrics centered on constant-i faces (i-faces).
369 *
370 * This function calculates the metric terms (ICsi, IEta, IZet) and the inverse
371 * Jacobian (IAj) located at the center of each i-face. The stencils use
372 * i-face-centered coordinates (`Centx`) which must be computed first.
373 * The logic is a direct adaptation of the legacy FormMetrics function.
374 *
375 * @param user The UserCtx for a specific grid level. Populates user->ICsi, etc.
376 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
377 */
378PetscErrorCode ComputeIFaceMetrics(UserCtx *user);
379
380/**
381 * @brief Computes metrics centered on constant-j faces (j-faces).
382 *
383 * This function calculates the metric terms (`JCsi`, `JEta`, `JZet`) and the
384 * inverse Jacobian (`JAj`) located at the geometric center of each constant-j
385 * face. This is a critical step for staggered-grid finite difference schemes.
386 *
387 * The process is a direct and faithful refactoring of the corresponding logic
388 * from the legacy `FormMetrics` function:
389 * 1. It first calculates the physical (x,y,z) coordinates of the center of
390 * each i-face and stores them in the `user->Centy` vector.
391 * 2. It then uses a boundary-aware, second-order finite difference stencil on
392 * the `Centy` field to compute the derivatives (e.g., d(x)/d(csi)).
393 * - Central differences are used in the grid interior.
394 * - One-sided differences are used at the physical domain boundaries.
395 * 3. Finally, these derivatives are used to compute the final metric terms and
396 * the inverse Jacobian, which are stored in their respective `Vec` objects.
397 *
398 * @param user The UserCtx for a specific grid level. This function populates
399 * the `user->JCsi`, `user->JEta`, `user->JZet`, and `user->JAj` vectors.
400 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
401 */
402PetscErrorCode ComputeJFaceMetrics(UserCtx *user);
403
404/**
405 * @brief Computes metrics centered on constant-k faces (k-faces).
406 *
407 * This function calculates the metric terms (`KCsi`, `KEta`, `KZet`) and the
408 * inverse Jacobian (`KAj`) located at the geometric center of each constant-j
409 * face. This is a critical step for staggered-grid finite difference schemes.
410 *
411 * The process is a direct and faithful refactoring of the corresponding logic
412 * from the legacy `FormMetrics` function:
413 * 1. It first calculates the physical (x,y,z) coordinates of the center of
414 * each i-face and stores them in the `user->Centz` vector.
415 * 2. It then uses a boundary-aware, second-order finite difference stencil on
416 * the `Centz` field to compute the derivatives (e.g., d(x)/d(csi)).
417 * - Central differences are used in the grid interior.
418 * - One-sided differences are used at the physical domain boundaries.
419 * 3. Finally, these derivatives are used to compute the final metric terms and
420 * the inverse Jacobian, which are stored in their respective `Vec` objects.
421 *
422 * @param user The UserCtx for a specific grid level. This function populates
423 * the `user->KCsi`, `user->KEta`, `user->KZet`, and `user->KAj` vectors.
424 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
425 */
426PetscErrorCode ComputeKFaceMetrics(UserCtx *user);
427
428/**
429 * @brief Performs a diagnostic check on the divergence of the face area metric vectors.
430 *
431 * For a closed cell, the sum of the face area vectors should be zero (Gauss's
432 * divergence theorem). This function computes a measure of this divergence and
433 * reports the maximum value over the domain. A small value indicates a
434 * well-formed grid. This is a direct adaptation of the legacy function.
435 *
436 * @param user The UserCtx for a specific grid level (typically the finest).
437 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
438 */
439PetscErrorCode ComputeMetricsDivergence(UserCtx *user);
440
441/**
442 * @brief Computes the max-min values of the grid metrics.
443 *
444 * This function serves as a diagnostic tool to assess the quality of the grid
445 * metrics. It calculates the bounds of the face metrics (Csi, Eta, Zet).
446 *
447 * @param user The UserCtx, containing all necessary grid data.
448 * @return PetscErrorCode
449 */
450PetscErrorCode ComputeMetricNorms(UserCtx *user);
451
452/**
453 * @brief Orchestrates the calculation of all grid metrics.
454 *
455 * This function iterates through every UserCtx in the multigrid and multi-block
456 * hierarchy. For each context, it calls a series of modern, modular helper
457 * functions to compute the face metrics (Csi, Eta, Zet), the cell-centered
458 * inverse Jacobian (Aj), and to validate the grid's orientation.
459 *
460 * @param simCtx The master SimCtx, containing the configured UserCtx hierarchy.
461 * @return PetscErrorCode
462 */
463PetscErrorCode CalculateAllGridMetrics(SimCtx *simCtx);
464
465/**
466 * @brief Builds one face plane: the unit outward normal of (v2 - v1) x (v4 - v1) and the vertex mean.
467 *
468 * The single definition of a cell face plane: the per-cell planes of MetricBuildCellFacePlanes() and
469 * the precomputed per-face planes both use it, so their distances are bit-identical. The normal points
470 * away from `cell_centroid`. A degenerate face (normal magnitude below 1e-12) is reported
471 * through `degenerate` and left unnormalised.
472 *
473 * @param[in] v1 First face vertex; the normal's origin.
474 * @param[in] v2 Second face vertex; the normal's first edge is v2 - v1.
475 * @param[in] v3 Third face vertex; it enters only the centroid.
476 * @param[in] v4 Fourth face vertex; the normal's second edge is v4 - v1.
477 * @param[in] cell_centroid Centroid of the cell the face belongs to, which fixes the outward side.
478 * @param[out] plane The face plane.
479 * @param[out] degenerate Whether the normal magnitude is below 1e-12.
480 * @return PETSC_TRUE when the orientation is ambiguous (the face plane contains the centroid offset).
481 */
482PetscBool MetricFacePlane(const Cmpnts v1, const Cmpnts v2, const Cmpnts v3, const Cmpnts v4,
483 const Cmpnts cell_centroid, FacePlane *plane, PetscBool *degenerate);
484
485/**
486 * @brief Builds the six face planes of a hexahedron, as the particle search tests them.
487 *
488 * Face vertex orders and orientation are those CalculateDistancesToCellFaces() has always
489 * used; degenerate faces set their bit in `degenerate`. `size` is set to 0. This per-cell form
490 * serves callers holding only a Cell; MetricComputeFacePlanes() precomputes the shared per-face form.
491 *
492 * @param[in] cell The cell, vertices in RetrieveCurrentCell() order.
493 * @param[out] planes The cell's face planes.
494 */
495void MetricBuildCellFacePlanes(const Cell *cell, CellFacePlanes *planes);
496
497/**
498 * @brief Builds the block's particle face planes once, as catalogued per-face fields.
499 *
500 * Each face carries one plane, shared by the two cells on either side: a unit normal pointing
501 * toward +i, +j or +k and the mean of its four vertices, built by MetricFacePlane() in the vertex
502 * order of the minus face (LEFT, BOTTOM, BACK) of the cell above it and oriented by that cell
503 * (by the cell below where only it is local). Grid-cell faces come from the node coordinates and
504 * are stored in the I/J/K-face layouts (`PlaneNormal*`, `PlaneCentroid*`: the face whose lower
505 * corner is node (i,j,k) sits at [k+1][j+1][i] for I, [k+1][j][i+1] for J, [k][j+1][i+1] for K);
506 * dual-cell faces come from lCent and sit at their lower-corner cell centre (`DualPlaneNormal*`,
507 * `DualPlaneCentroid*`). `SearchCellSize` holds each cell's GetCellCharacteristicSize() at its
508 * shifted cell-centred index. A face with no plane (degenerate, or beyond the ghosted region) has a
509 * zero normal. Owned values are the global fields; the locals are their ghost update through
510 * UpdateLocalGhosts() and the fields' catalogued sync classes. Collective. Built by
511 * CalculateAllGridMetrics() on the finest level of a particle run, after the coordinates and lCent
512 * are final; a no-op once built. Coordinates are fixed thereafter (there are no moving grids); a
513 * grid that changes must MetricDestroyFacePlanes() and rebuild.
514 *
515 * @param[in,out] user Block whose planes are built; MetricDestroyFacePlanes() frees them.
516 * @return PetscErrorCode 0 on success, or a PETSc error.
517 */
518PetscErrorCode MetricComputeFacePlanes(UserCtx *user);
519
520/**
521 * @brief Frees the face-plane fields MetricComputeFacePlanes() built, if any.
522 * @param[in,out] user Block whose planes are freed; their Vecs are reset to NULL.
523 * @return PetscErrorCode 0 on success, or a PETSc error.
524 */
525PetscErrorCode MetricDestroyFacePlanes(UserCtx *user);
526
527/** @brief Read-only flat arrays of one family of face planes (grid cells or dual cells). */
528typedef struct FacePlaneArrays {
529 PetscBool dual; ///< Dual-cell planes (from lCent) rather than grid-cell planes.
530 const Cmpnts *normal[3]; ///< Unit normals toward +i, +j, +k; zero where there is no plane.
531 const Cmpnts *centroid[3]; ///< Face vertex means.
532 const PetscReal *size; ///< Grid-cell sizes; NULL for dual cells.
534
535/**
536 * @brief Opens a family's face-plane arrays for reading; MetricComputeFacePlanes() must have run.
537 * @param[in] user Block whose planes are read.
538 * @param[in] dual PETSC_TRUE for the dual-cell planes, PETSC_FALSE for the grid-cell planes.
539 * @param[out] arrays The open arrays; close with MetricRestoreFacePlaneArrays().
540 * @return PetscErrorCode 0 on success, or PETSC_ERR_ARG_WRONGSTATE if the planes are not built.
541 */
542PetscErrorCode MetricGetFacePlaneArrays(UserCtx *user, PetscBool dual, FacePlaneArrays *arrays);
543
544/**
545 * @brief Closes arrays opened by MetricGetFacePlaneArrays().
546 * @param[in] user Block whose planes were read.
547 * @param[in,out] arrays The arrays to close.
548 * @return PetscErrorCode 0 on success, or a PETSc error.
549 */
550PetscErrorCode MetricRestoreFacePlaneArrays(UserCtx *user, FacePlaneArrays *arrays);
551
552/**
553 * @brief Assembles one cell's six outward face planes from the shared per-face planes.
554 *
555 * A cell's plus faces use the stored normals and its minus faces their exact negation; a face
556 * whose stored normal is zero sets its `degenerate` bit. For a grid cell `(i, j, k)` is its origin
557 * node; for a dual cell, the lower-corner cell centre.
558 *
559 * @param[in] arrays Open plane arrays.
560 * @param[in] info The block's DMDA local info, for its ghosted extents.
561 * @param[in] i Cell origin i index.
562 * @param[in] j Cell origin j index.
563 * @param[in] k Cell origin k index.
564 * @param[out] planes The cell's planes, with `size` from `SearchCellSize` (0 for dual cells).
565 */
566void MetricGatherCellFacePlanes(const FacePlaneArrays *arrays, const DMDALocalInfo *info,
567 PetscInt i, PetscInt j, PetscInt k, CellFacePlanes *planes);
568
569/**
570 * @brief Index of point (i, j, k) in a block's ghosted local arrays (coordinates, lCent, planes).
571 * @param[in] info The block's DMDA local info, for its ghosted extents.
572 * @param[in] i Global i index, within the ghosted range.
573 * @param[in] j Global j index, within the ghosted range.
574 * @param[in] k Global k index, within the ghosted range.
575 * @return The flat index, x fastest.
576 */
577static inline PetscInt MetricCellFacePlanesIndex(const DMDALocalInfo *info, PetscInt i, PetscInt j, PetscInt k)
578{
579 const PetscInt di = i - info->gxs, dj = j - info->gys, dk = k - info->gzs;
580 return (dk * info->gym + dj) * info->gxm + di;
581}
582#endif /* METRIC_H */
PetscErrorCode ComputeCellEdgeVectors(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, Cmpnts edges[3])
Computes a cell's edge vectors along its three grid directions.
Definition Metric.c:749
PetscErrorCode MetricRestoreFacePlaneArrays(UserCtx *user, FacePlaneArrays *arrays)
Closes arrays opened by MetricGetFacePlaneArrays().
Definition Metric.c:401
PetscErrorCode CalculateAllGridMetrics(SimCtx *simCtx)
Orchestrates the calculation of all grid metrics.
Definition Metric.c:2267
static Cmpnts RemoveFaceNormalComponent(Cmpnts velocity, Cmpnts metric)
velocity less its component along the face metric metric, which leaves it tangent to the face.
Definition Metric.h:99
PetscErrorCode MetricJacobian(UserCtx *user, const Cmpnts ***X, PetscInt i, PetscInt j, PetscInt k, PetscReal xi, PetscReal eta, PetscReal zta, PetscReal J[3][3], PetscReal *detJ)
Evaluates the trilinear mapping Jacobian and its determinant in one cell.
Definition Metric.c:502
PetscErrorCode ComputeCellCenters(UserCtx *user)
Computes the physical location of each cell's center from the nodal coordinates.
Definition Metric.c:1291
PetscBool MetricFacePlane(const Cmpnts v1, const Cmpnts v2, const Cmpnts v3, const Cmpnts v4, const Cmpnts cell_centroid, FacePlane *plane, PetscBool *degenerate)
Builds one face plane: the unit outward normal of (v2 - v1) x (v4 - v1) and the vertex mean.
Definition Metric.c:47
PetscErrorCode InvertCovariantMetricTensor(double covariantTensor[3][3], double contravariantTensor[3][3])
Inverts the 3x3 matrix of face-area vectors to obtain the covariant directions.
Definition Metric.c:595
PetscErrorCode ComputeMetricNorms(UserCtx *user)
Computes the max-min values of the grid metrics.
Definition Metric.c:2137
PetscErrorCode CheckAndFixGridOrientation(UserCtx *user)
Verify and, when consistently inverted, repair the right-handed metric basis (Csi,...
Definition Metric.c:778
PetscErrorCode MetricGetCellVertices(UserCtx *user, const Cmpnts ***X, PetscInt i, PetscInt j, PetscInt k, Cmpnts V[8])
Collects the eight node coordinates of one logical hexahedral cell.
Definition Metric.c:24
void MetricGatherCellFacePlanes(const FacePlaneArrays *arrays, const DMDALocalInfo *info, PetscInt i, PetscInt j, PetscInt k, CellFacePlanes *planes)
Assembles one cell's six outward face planes from the shared per-face planes.
Definition Metric.c:421
PetscErrorCode ComputeJFaceMetrics(UserCtx *user)
Computes metrics centered on constant-j faces (j-faces).
Definition Metric.c:1646
PetscErrorCode MetricDestroyFacePlanes(UserCtx *user)
Frees the face-plane fields MetricComputeFacePlanes() built, if any.
Definition Metric.c:355
PetscErrorCode ComputeMetricsDivergence(UserCtx *user)
Performs a diagnostic check on the divergence of the face area metric vectors.
Definition Metric.c:2047
PetscErrorCode MetricComputeFacePlanes(UserCtx *user)
Builds the block's particle face planes once, as catalogued per-face fields.
Definition Metric.c:208
PetscErrorCode MetricGetFacePlaneArrays(UserCtx *user, PetscBool dual, FacePlaneArrays *arrays)
Opens a family's face-plane arrays for reading; MetricComputeFacePlanes() must have run.
Definition Metric.c:376
const Cmpnts * normal[3]
Unit normals toward +i, +j, +k; zero where there is no plane.
Definition Metric.h:530
const Cmpnts * centroid[3]
Face vertex means.
Definition Metric.h:531
PetscErrorCode ComputeGridLineFractions(UserCtx *user, Vec fraction, Vec length)
Arc-length position of every owned cell centre along its three grid lines.
Definition Metric.c:1362
PetscErrorCode ComputeFaceMetrics(UserCtx *user)
Computes the primary face metric components (Csi, Eta, Zet), including boundary extrapolation,...
Definition Metric.c:937
static PetscInt MetricCellFacePlanesIndex(const DMDALocalInfo *info, PetscInt i, PetscInt j, PetscInt k)
Index of point (i, j, k) in a block's ghosted local arrays (coordinates, lCent, planes).
Definition Metric.h:577
PetscErrorCode ComputeCellCharacteristicLengthScale(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, double *dx, double *dy, double *dz)
Computes characteristic length scales (dx, dy, dz) for a curvilinear cell.
Definition Metric.c:688
PetscErrorCode CalculateFaceNormalAndArea(Cmpnts csi, Cmpnts eta, Cmpnts zet, double ni[3], double nj[3], double nk[3], double *Ai, double *Aj, double *Ak)
Computes the unit normal vectors and areas of the three faces of a computational cell.
Definition Metric.c:644
PetscErrorCode ApplyPeriodicCorrectionsToIFaceCenter(UserCtx *user)
Builds translated periodic images for i-face centers (Centx).
Definition Metric.c:890
void MetricBuildCellFacePlanes(const Cell *cell, CellFacePlanes *planes)
Builds the six face planes of a hexahedron, as the particle search tests them.
Definition Metric.c:108
const PetscReal * size
Grid-cell sizes; NULL for dual cells.
Definition Metric.h:532
PetscErrorCode ComputeCellCenteredJacobianInverse(UserCtx *user)
Calculates the cell-centered inverse Jacobian determinant (1/J) for INTERIOR cells and stores it in u...
Definition Metric.c:1147
PetscErrorCode ComputeKFaceMetrics(UserCtx *user)
Computes metrics centered on constant-k faces (k-faces).
Definition Metric.c:1837
PetscErrorCode ApplyPeriodicCorrectionsToJFaceCenter(UserCtx *user)
Builds translated periodic images for j-face centers (Centy).
Definition Metric.c:906
PetscBool dual
Dual-cell planes (from lCent) rather than grid-cell planes.
Definition Metric.h:529
PetscErrorCode ComputeCellDirectionalExtents(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, double *l_xi, double *l_eta, double *l_zeta)
Computes a cell's extent along each of its own grid directions.
Definition Metric.c:717
PetscErrorCode MetricLogicalToPhysical(UserCtx *user, const Cmpnts ***X, PetscInt i, PetscInt j, PetscInt k, PetscReal xi, PetscReal eta, PetscReal zta, Cmpnts *Xp)
Maps a logical point inside one hexahedral cell to physical space.
Definition Metric.c:475
PetscErrorCode ComputeIFaceMetrics(UserCtx *user)
Computes metrics centered on constant-i faces (i-faces).
Definition Metric.c:1439
PetscErrorCode ApplyPeriodicCorrectionsToCellCenters(UserCtx *user)
Builds translated periodic images for the dummy cell centers of periodic axes.
Definition Metric.c:831
PetscErrorCode ApplyPeriodicCorrectionsToKFaceCenter(UserCtx *user)
Builds translated periodic images for k-face centers (Centz).
Definition Metric.c:922
PetscErrorCode MetricVelocityContravariant(const PetscReal J[3][3], PetscReal detJ, const PetscReal u[3], PetscReal uc[3])
Converts a Cartesian velocity vector to contravariant logical components.
Definition Metric.c:560
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Definition Metric.h:528
Public interface for data input/output routines.
Logging utilities and macros for PETSc-based applications.
Main header file for a complex fluid dynamics solver.
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
PetscScalar y
Definition variables.h:145
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
The six face planes of one hexahedron, indexed by Face, and its characteristic size.
Definition variables.h:229
A 3D point or vector with PetscScalar components.
Definition variables.h:144
One cell face as the particle search tests against it: a plane through the vertex mean.
Definition variables.h:223
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