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 Computes the unit normal vectors and areas of the three faces of a computational cell.
92 *
93 * Given the metric vectors (csi, eta, zet), this function calculates the geometric
94 * properties of the cell faces aligned with the i, j, and k directions.
95 *
96 * @param csi Covariant xi metric vector.
97 * @param eta Covariant eta metric vector.
98 * @param zet Covariant zeta metric vector.
99 * @param[out] ni Unit normal of the xi-normal face.
100 * @param[out] nj Unit normal of the eta-normal face.
101 * @param[out] nk Unit normal of the zeta-normal face.
102 * @param[out] Ai Area of the xi-normal face.
103 * @param[out] Aj Area of the eta-normal face.
104 * @param[out] Ak Area of the zeta-normal face.
105 * @return PetscErrorCode 0 on success.
106 */
107PetscErrorCode CalculateFaceNormalAndArea(Cmpnts csi, Cmpnts eta, Cmpnts zet, double ni[3], double nj[3], double nk[3], double *Ai, double *Aj, double *Ak);
108
109/**
110 * @brief Inverts the 3x3 covariant metric tensor to obtain the contravariant metric tensor.
111 *
112 * In curvilinear coordinates, the input matrix `g` contains the dot products of the
113 * covariant basis vectors (e.g., g_ij = e_i . e_j). Its inverse, `G`, is the
114 * contravariant metric tensor, which is essential for transforming vectors and tensors
115 * between coordinate systems.
116 *
117 * @param covariantTensor Input: A 3x3 matrix representing the covariant metric tensor.
118 * @param[out] contravariantTensor Inverse metric tensor written in place.
119 * @return PetscErrorCode 0 on success.
120 */
121PetscErrorCode InvertCovariantMetricTensor(double covariantTensor[3][3], double contravariantTensor[3][3]);
122
123/**
124 * @brief Computes characteristic length scales (dx, dy, dz) for a curvilinear cell.
125 *
126 * For a non-uniform, non-orthogonal cell, there is no single "dx". This function
127 * computes an effective length scale in each Cartesian direction based on the cell
128 * volume and the areas of its faces.
129 *
130 * @param ajc Cell Jacobian/volume metric at the cell center.
131 * @param csi Covariant xi metric vector.
132 * @param eta Covariant eta metric vector.
133 * @param zet Covariant zeta metric vector.
134 * @param[out] dx Effective physical length associated with xi variation.
135 * @param[out] dy Effective physical length associated with eta variation.
136 * @param[out] dz Effective physical length associated with zeta variation.
137 * @return PetscErrorCode 0 on success.
138 */
139PetscErrorCode ComputeCellCharacteristicLengthScale(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, double *dx, double *dy, double *dz);
140
141/**
142 * @brief Builds translated periodic images for cell centers and grid spacing.
143 *
144 * PETSc wraps field indices but does not translate coordinates. This routine
145 * applies the validated per-axis geometric translation to wrapped center
146 * coordinates and refreshes the associated local grid spacing.
147 *
148 * @param user The UserCtx containing grid and field data.
149 * @return PetscErrorCode 0 on success.
150 */
152
153/**
154 * @brief Builds translated periodic images for i-face centers (Centx).
155 *
156 * Every active periodic axis can affect the ghost images of Centx. This must
157 * be called after Centx is computed and before it is used for metric calculations.
158 *
159 * @param user The UserCtx containing grid and field data.
160 * @return PetscErrorCode 0 on success.
161 */
163
164/**
165 * @brief Builds translated periodic images for j-face centers (Centy).
166 *
167 * Every active periodic axis can affect the ghost images of Centy. This must
168 * be called after Centy is computed and before it is used for metric calculations.
169 *
170 * @param user The UserCtx containing grid and field data.
171 * @return PetscErrorCode 0 on success.
172 */
174
175/**
176 * @brief Builds translated periodic images for k-face centers (Centz).
177 *
178 * Every active periodic axis can affect the ghost images of Centz. This must
179 * be called after Centz is computed and before it is used for metric calculations.
180 *
181 * @param user The UserCtx containing grid and field data.
182 * @return PetscErrorCode 0 on success.
183 */
185
186/**
187 * @brief Computes the primary face metric components (Csi, Eta, Zet), including
188 * boundary extrapolation, and stores them in the corresponding global Vec
189 * members of the UserCtx structure (user->Csi, user->Eta, user->Zet).
190 *
191 * This is a self-contained routine that performs the following steps:
192 * 1. Obtains local ghosted nodal coordinates using DMGetCoordinatesLocal.
193 * 2. Calculates metrics for INTERIOR faces where finite difference stencils are valid.
194 * 3. EXTRAPOLATES metrics for faces on the physical domain boundaries by copying
195 * from the nearest computed interior face.
196 * 4. Assembles the global `user->Csi`, `user->Eta`, `user->Zet` Vecs.
197 * 5. Updates the local ghosted `user->lCsi`, `user->lEta`, `user->lZet` Vecs.
198 *
199 * @param[in,out] user Pointer to the UserCtx structure.
200 *
201 * @return PetscErrorCode 0 on success.
202 *
203 * @note
204 * - This function is a complete "compute and make ready" unit for Csi, Eta, and Zet.
205 * - It's recommended to call `VecZeroEntries` on user->Csi, Eta, Zet before this
206 * if they might contain old data.
207 */
208PetscErrorCode ComputeFaceMetrics(UserCtx *user);
209
210/**
211 * @brief Calculates the cell-centered inverse Jacobian determinant (1/J) for INTERIOR cells
212 * and stores it in `user->Aj`. This version includes boundary extrapolation.
213 *
214 * Nodal coordinates are obtained internally.
215 * Refer to previous Doxygen comments for details on physical locations and
216 * storage convention (`aj_arr[k_n][j_n][i_n]` for cell `C(i_n-1,j_n-1,k_n-1)`).
217 *
218 * @param[in,out] user Pointer to the UserCtx structure.
219 *
220 * @return PetscErrorCode 0 on success.
221 */
222PetscErrorCode ComputeCellCenteredJacobianInverse(UserCtx *user);
223
224/**
225 * @brief Verify and, when consistently inverted, repair the **right-handed** metric basis (`Csi`, `Eta`, `Zet`) and a
226 * **positive Jacobian** (`Aj`) over the whole domain.
227 *
228 * The metric-generation kernels are completely algebraic, so they will happily
229 * deliver a *left-handed* basis if the mesh file enumerates nodes in the
230 * opposite ζ-direction.
231 * This routine makes the orientation explicit and—if needed—repairs it
232 * **once per run**:
233 *
234 * | Step | Action |
235 * |------|--------|
236 * | 1 | Compute global `Aj_min`, `Aj_max`. |
237 * | 2 | **Mixed signs** (`Aj_min < 0 && Aj_max > 0`) &rarr; abort: the mesh is topologically inconsistent. |
238 * | 3 | **All negative** (`Aj_max < 0`) &rarr; flip <br>`Csi`, `Eta`, `Zet`, `Aj` & update local ghosts. |
239 * | 4 | Store `user->orientation = ±1` so BC / IC routines can apply sign-aware logic if they care about inlet direction. |
240 *
241 * @param[in,out] user Fully initialised #UserCtx that already contains
242 * `Csi`, `Eta`, `Zet`, `Aj`, their **local** ghosts, and
243 * valid distributed DMs.
244 *
245 * @return `0` on success or a PETSc error code on failure.
246 *
247 * @note Call **immediately after** `ComputeCellCenteredJacobianInverse()` and
248 * before any routine that differentiates or applies BCs.
249 *
250 * @note Author metadata intentionally omitted in API docs.
251 */
252PetscErrorCode CheckAndFixGridOrientation(UserCtx *user);
253
254/**
255 * @brief Computes the physical location of cell centers and the spacing between them.
256 *
257 * This function calculates two key geometric properties from the nodal coordinates:
258 * 1. `Cent`: A vector field storing the (x,y,z) coordinates of the center of each grid cell.
259 * 2. `GridSpace`: A vector field storing the physical distance between adjacent
260 * cell centers in the i, j, and k computational directions.
261 *
262 * It is a direct adaptation of the corresponding logic from the legacy `FormMetrics`.
263 *
264 * @param user The UserCtx for a specific grid level. The function populates `user->Cent` and `user->GridSpace`.
265 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
266 */
267PetscErrorCode ComputeCellCentersAndSpacing(UserCtx *user);
268
269/**
270 * @brief Computes metrics centered on constant-i faces (i-faces).
271 *
272 * This function calculates the metric terms (ICsi, IEta, IZet) and the inverse
273 * Jacobian (IAj) located at the center of each i-face. The stencils use
274 * i-face-centered coordinates (`Centx`) which must be computed first.
275 * The logic is a direct adaptation of the legacy FormMetrics function.
276 *
277 * @param user The UserCtx for a specific grid level. Populates user->ICsi, etc.
278 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
279 */
280PetscErrorCode ComputeIFaceMetrics(UserCtx *user);
281
282/**
283 * @brief Computes metrics centered on constant-j faces (j-faces).
284 *
285 * This function calculates the metric terms (`JCsi`, `JEta`, `JZet`) and the
286 * inverse Jacobian (`JAj`) located at the geometric center of each constant-j
287 * face. This is a critical step for staggered-grid finite difference schemes.
288 *
289 * The process is a direct and faithful refactoring of the corresponding logic
290 * from the legacy `FormMetrics` function:
291 * 1. It first calculates the physical (x,y,z) coordinates of the center of
292 * each i-face and stores them in the `user->Centy` vector.
293 * 2. It then uses a boundary-aware, second-order finite difference stencil on
294 * the `Centy` field to compute the derivatives (e.g., d(x)/d(csi)).
295 * - Central differences are used in the grid interior.
296 * - One-sided differences are used at the physical domain boundaries.
297 * 3. Finally, these derivatives are used to compute the final metric terms and
298 * the inverse Jacobian, which are stored in their respective `Vec` objects.
299 *
300 * @param user The UserCtx for a specific grid level. This function populates
301 * the `user->JCsi`, `user->JEta`, `user->JZet`, and `user->JAj` vectors.
302 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
303 */
304PetscErrorCode ComputeJFaceMetrics(UserCtx *user);
305
306/**
307 * @brief Computes metrics centered on constant-k faces (k-faces).
308 *
309 * This function calculates the metric terms (`KCsi`, `KEta`, `KZet`) and the
310 * inverse Jacobian (`KAj`) located at the geometric center of each constant-j
311 * face. This is a critical step for staggered-grid finite difference schemes.
312 *
313 * The process is a direct and faithful refactoring of the corresponding logic
314 * from the legacy `FormMetrics` function:
315 * 1. It first calculates the physical (x,y,z) coordinates of the center of
316 * each i-face and stores them in the `user->Centz` vector.
317 * 2. It then uses a boundary-aware, second-order finite difference stencil on
318 * the `Centz` field to compute the derivatives (e.g., d(x)/d(csi)).
319 * - Central differences are used in the grid interior.
320 * - One-sided differences are used at the physical domain boundaries.
321 * 3. Finally, these derivatives are used to compute the final metric terms and
322 * the inverse Jacobian, which are stored in their respective `Vec` objects.
323 *
324 * @param user The UserCtx for a specific grid level. This function populates
325 * the `user->KCsi`, `user->KEta`, `user->KZet`, and `user->KAj` vectors.
326 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
327 */
328PetscErrorCode ComputeKFaceMetrics(UserCtx *user);
329
330/**
331 * @brief Performs a diagnostic check on the divergence of the face area metric vectors.
332 *
333 * For a closed cell, the sum of the face area vectors should be zero (Gauss's
334 * divergence theorem). This function computes a measure of this divergence and
335 * reports the maximum value over the domain. A small value indicates a
336 * well-formed grid. This is a direct adaptation of the legacy function.
337 *
338 * @param user The UserCtx for a specific grid level (typically the finest).
339 * @return PetscErrorCode 0 on success, or a PETSc error code on failure.
340 */
341PetscErrorCode ComputeMetricsDivergence(UserCtx *user);
342
343/**
344 * @brief Computes the max-min values of the grid metrics.
345 *
346 * This function serves as a diagnostic tool to assess the quality of the grid
347 * metrics. It calculates the bounds of the face metrics (Csi, Eta, Zet).
348 *
349 * @param user The UserCtx, containing all necessary grid data.
350 * @return PetscErrorCode
351 */
352PetscErrorCode ComputeMetricNorms(UserCtx *user);
353
354/**
355 * @brief Orchestrates the calculation of all grid metrics.
356 *
357 * This function iterates through every UserCtx in the multigrid and multi-block
358 * hierarchy. For each context, it calls a series of modern, modular helper
359 * functions to compute the face metrics (Csi, Eta, Zet), the cell-centered
360 * inverse Jacobian (Aj), and to validate the grid's orientation.
361 *
362 * @param simCtx The master SimCtx, containing the configured UserCtx hierarchy.
363 * @return PetscErrorCode
364 */
365PetscErrorCode CalculateAllGridMetrics(SimCtx *simCtx);
366#endif /* METRIC_H */
PetscErrorCode CalculateAllGridMetrics(SimCtx *simCtx)
Orchestrates the calculation of all grid metrics.
Definition Metric.c:1940
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:105
PetscErrorCode InvertCovariantMetricTensor(double covariantTensor[3][3], double contravariantTensor[3][3])
Inverts the 3x3 covariant metric tensor to obtain the contravariant metric tensor.
Definition Metric.c:202
PetscErrorCode ComputeMetricNorms(UserCtx *user)
Computes the max-min values of the grid metrics.
Definition Metric.c:1808
PetscErrorCode ApplyPeriodicCorrectionsToCellCentersAndSpacing(UserCtx *user)
Builds translated periodic images for cell centers and grid spacing.
Definition Metric.c:391
PetscErrorCode CheckAndFixGridOrientation(UserCtx *user)
Verify and, when consistently inverted, repair the right-handed metric basis (Csi,...
Definition Metric.c:313
PetscErrorCode ComputeCellCentersAndSpacing(UserCtx *user)
Computes the physical location of cell centers and the spacing between them.
Definition Metric.c:993
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:26
PetscErrorCode ComputeJFaceMetrics(UserCtx *user)
Computes metrics centered on constant-j faces (j-faces).
Definition Metric.c:1307
PetscErrorCode ComputeMetricsDivergence(UserCtx *user)
Performs a diagnostic check on the divergence of the face area metric vectors.
Definition Metric.c:1716
PetscErrorCode ComputeFaceMetrics(UserCtx *user)
Computes the primary face metric components (Csi, Eta, Zet), including boundary extrapolation,...
Definition Metric.c:637
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:282
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:236
PetscErrorCode ApplyPeriodicCorrectionsToIFaceCenter(UserCtx *user)
Builds translated periodic images for i-face centers (Centx).
Definition Metric.c:590
PetscErrorCode ComputeCellCenteredJacobianInverse(UserCtx *user)
Calculates the cell-centered inverse Jacobian determinant (1/J) for INTERIOR cells and stores it in u...
Definition Metric.c:849
PetscErrorCode ComputeKFaceMetrics(UserCtx *user)
Computes metrics centered on constant-k faces (k-faces).
Definition Metric.c:1502
PetscErrorCode ApplyPeriodicCorrectionsToJFaceCenter(UserCtx *user)
Builds translated periodic images for j-face centers (Centy).
Definition Metric.c:606
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:76
PetscErrorCode ComputeIFaceMetrics(UserCtx *user)
Computes metrics centered on constant-i faces (i-faces).
Definition Metric.c:1096
PetscErrorCode ApplyPeriodicCorrectionsToKFaceCenter(UserCtx *user)
Builds translated periodic images for k-face centers (Centz).
Definition Metric.c:622
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:165
Public interface for data input/output routines.
Logging utilities and macros for PETSc-based applications.
Main header file for a complex fluid dynamics solver.
A 3D point or vector with PetscScalar components.
Definition variables.h:102
The master context for the entire simulation.
Definition variables.h:695
User-defined context containing data specific to a single computational grid level.
Definition variables.h:906