PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
poisson.c
Go to the documentation of this file.
1/**
2 * @file poisson.c
3 * @brief Pressure-Poisson projection: operator, right-hand side, multigrid solve,
4 * pressure update, and velocity correction.
5 *
6 * Grid layout. Cell-centred quantities live at DMDA indices 1..m-2 on each axis; indices 0
7 * and m-1 are dummy layers that carry no unknown. On a periodic axis the interior wraps
8 * from m-2 to 1. The contravariant flux `Ucont[k][j][i].x` sits on the face between cells
9 * i and i+1, and likewise for the other two components.
10 *
11 * Face gradient. The flux of grad(Phi) through the face between cell c and c + e_n is
12 *
13 * sum_b g_nb D_b(Phi), g_nb = (F_b . F_n) * aj_n,
14 *
15 * where F_b are the contravariant base vectors stored on the n-faces, aj_n is the inverse
16 * Jacobian there, D_n is the difference across the face, and D_b (b != n) is the transverse
17 * difference chosen by PoissonOperator_TransverseDifference(). The operator assembles the
18 * divergence of this flux, and the projection subtracts it from `Ucont`, so the two are
19 * consistent by construction.
20 */
21#include "poisson.h"
22#include "logging.h"
23#include "setup.h"
24
25
26/** Offsets of the 19 stencil points, in the column order used to insert each row. */
27static const PetscInt POISSON_STENCIL_OFFSETS[19][3] = {
28 { 0, 0, 0}, /* centre */
29 { 1, 0, 0}, {-1, 0, 0}, { 0, 1, 0}, { 0, -1, 0}, /* faces */
30 { 0, 0, 1}, { 0, 0, -1},
31 { 1, 1, 0}, { 1, -1, 0}, {-1, 1, 0}, {-1, -1, 0}, /* edges */
32 { 0, 1, 1}, { 0, 1, -1}, { 0, -1, 1}, { 0, -1, -1},
33 { 1, 0, 1}, { 1, 0, -1}, {-1, 0, 1}, {-1, 0, -1},
34};
35
36
37/** @brief Field IDs of the face metric vectors, indexed as PoissonFaceMetrics. */
44
45/** @brief Everything needed to evaluate the gradient flux through one face. */
46typedef struct {
47 PetscReal dot[3]; /**< F_b . F_n on the face, b = 0..2. */
48 PetscReal aj; /**< Inverse Jacobian on the face. */
49 PoissonTransverseDifference diff[3]; /**< Transverse differences; diff[n] is unused. */
51
52/**
53 * @brief Value of a cell-centred array at cell @p c displaced by @p d.
54 *
55 * @param[in] field Ghosted cell-centred array, indexed [k][j][i].
56 * @param[in] c Cell (i, j, k).
57 * @param[in] d Displacement (di, dj, dk).
58 * @return The value at `c + d`.
59 */
60static PICURV_ALWAYS_INLINE PetscReal PoissonOperator_At(const PetscReal ***field, const PetscInt c[3],
61 const PetscInt d[3])
62{
63 return field[c[2] + d[2]][c[1] + d[1]][c[0] + d[0]];
64}
65
66/**
67 * @brief The rows and weight of the transverse difference along axis @p t at the face between
68 * cell @p c and `c + e_n`, for operator assembly; PoissonOperator_TransverseKind() chooses.
69 *
70 * @param[in] nvert Ghosted solid field.
71 * @param[in] c Cell on the low side of the face.
72 * @param[in] n Face orientation (0, 1, 2 for i, j, k).
73 * @param[in] t Transverse axis, not @p n.
74 * @param[in] m Grid sizes (mx, my, mz).
75 * @param[in] periodic Whether each axis is periodic.
76 * @return The rows and weight of the difference.
77 */
79 const PetscReal ***nvert, const PetscInt c[3], PetscInt n, PetscInt t,
80 const PetscInt m[3], const PetscBool periodic[3])
81{
82 PoissonTransverseDifference diff = {0, 0, 0.0};
83
84 switch (PoissonOperator_TransverseKind(nvert, c, n, t, m, periodic)) {
85 case POISSON_TRANSVERSE_LOWER: diff.lo = -1; diff.hi = 0; diff.weight = 0.5; break;
86 case POISSON_TRANSVERSE_UPPER: diff.lo = 0; diff.hi = 1; diff.weight = 0.5; break;
87 case POISSON_TRANSVERSE_CENTRAL: diff.lo = -1; diff.hi = 1; diff.weight = 0.25; break;
88 case POISSON_TRANSVERSE_NONE: break;
89 }
90 return diff;
91}
92
93/**
94 * @brief Gathers the metric coefficients and transverse differences of the gradient flux
95 * through the face between cell @p c and `c + e_n`.
96 *
97 * @param[in] metrics Face metric arrays from PoissonOperator_GetFaceMetrics().
98 * @param[in] nvert Ghosted solid field.
99 * @param[in] c Cell on the low side of the face.
100 * @param[in] n Face orientation (0, 1, 2 for i, j, k).
101 * @param[in] m Grid sizes (mx, my, mz).
102 * @param[in] periodic Whether each axis is periodic.
103 * @return The face's metric products, inverse Jacobian and transverse differences.
104 */
106 const PoissonFaceMetrics *metrics, const PetscReal ***nvert, const PetscInt c[3],
107 PetscInt n, const PetscInt m[3], const PetscBool periodic[3])
108{
110 const Cmpnts normal = metrics->metric[n][n][c[2]][c[1]][c[0]];
111
112 face.aj = metrics->aj[n][c[2]][c[1]][c[0]];
113 for (PetscInt b = 0; b < 3; b++) {
114 const Cmpnts base = metrics->metric[n][b][c[2]][c[1]][c[0]];
115 face.dot[b] = base.x * normal.x + base.y * normal.y + base.z * normal.z;
116 if (b == n) {
117 face.diff[b].lo = 0; face.diff[b].hi = 0; face.diff[b].weight = 0.0;
118 } else {
119 face.diff[b] = PoissonOperator_TransverseDifference(nvert, c, n, b, m, periodic);
120 }
121 }
122 return face;
123}
124
125/**
126 * @brief Maps the 19 stencil offsets to their slots; corners of the 3x3x3 block are -1.
127 */
128static PetscInt PoissonOperator_StencilSlot(const PetscInt d[3])
129{
130 for (PetscInt s = 0; s < 19; s++) {
131 if (POISSON_STENCIL_OFFSETS[s][0] == d[0] && POISSON_STENCIL_OFFSETS[s][1] == d[1] &&
132 POISSON_STENCIL_OFFSETS[s][2] == d[2]) return s;
133 }
134 return -1;
135}
136
137
138
139
140
141/**
142 * @brief Implementation of \ref PoissonOperator_GetFaceMetrics().
143 * @details Full API contract (arguments, ownership, side effects) is documented with
144 * the header declaration in `include/poisson.h`.
145 * @see PoissonOperator_GetFaceMetrics()
146 */
148{
149 FieldView view;
150
151 PetscFunctionBeginUser;
153 for (PetscInt n = 0; n < 3; n++) {
154 for (PetscInt b = 0; b < 3; b++) {
155 PetscCall(FieldGetView(user, POISSON_FACE_METRIC_FIELDS[n][b], &view));
156 PetscCall(DMDAVecGetArrayRead(view.dm, view.local_vec, (void *)&metrics->metric[n][b]));
157 }
158 PetscCall(FieldGetView(user, POISSON_FACE_AJ_FIELDS[n], &view));
159 PetscCall(DMDAVecGetArrayRead(view.dm, view.local_vec, (void *)&metrics->aj[n]));
160 }
162 PetscFunctionReturn(0);
163}
164
165/**
166 * @brief Implementation of \ref PoissonOperator_RestoreFaceMetrics().
167 * @details Full API contract (arguments, ownership, side effects) is documented with
168 * the header declaration in `include/poisson.h`.
169 * @see PoissonOperator_RestoreFaceMetrics()
170 */
172{
173 FieldView view;
174
175 PetscFunctionBeginUser;
177 for (PetscInt n = 0; n < 3; n++) {
178 for (PetscInt b = 0; b < 3; b++) {
179 PetscCall(FieldGetView(user, POISSON_FACE_METRIC_FIELDS[n][b], &view));
180 PetscCall(DMDAVecRestoreArrayRead(view.dm, view.local_vec, (void *)&metrics->metric[n][b]));
181 }
182 PetscCall(FieldGetView(user, POISSON_FACE_AJ_FIELDS[n], &view));
183 PetscCall(DMDAVecRestoreArrayRead(view.dm, view.local_vec, (void *)&metrics->aj[n]));
184 }
186 PetscFunctionReturn(0);
187}
188
189/**
190 * @brief Index of the neighbour at offset @p d (-1, 0, +1) from @p v on an axis of @p m
191 * points, wrapping between the interior layers 1 and m-2 when periodic.
192 */
193static inline PetscInt PoissonOperator_NeighborIndex(PetscInt v, PetscInt d, PetscInt m, PetscBool periodic)
194{
195 if (periodic && d == 1 && v == m - 2) return 1;
196 if (periodic && d == -1 && v == 1) return m - 2;
197 return v + d;
198}
199
200/**
201 * @brief Adds the signed gradient flux through one face to a row's stencil coefficients.
202 *
203 * @param[in] face Face gradient from PoissonOperator_FaceGradientStencil().
204 * @param[in] own Offset of the face's lower cell from the row cell.
205 * @param[in] n Normal axis of the face.
206 * @param[in] sign +1 for the row's upper face on the axis, -1 for its lower face.
207 * @param[in,out] coefficients The row's 19 coefficients.
208 */
209static void PoissonOperator_AddFaceFlux(const PoissonFaceGradient *face, const PetscInt own[3],
210 PetscInt n, PetscReal sign, PetscScalar coefficients[19])
211{
212 for (PetscInt b = 0; b < 3; b++) {
213 const PetscReal g = face->dot[b] * face->aj;
214 PetscInt lower[3] = {own[0], own[1], own[2]};
215 PetscInt upper[3] = {own[0], own[1], own[2]};
216
217 upper[n] += 1;
218 if (b == n) {
219 coefficients[PoissonOperator_StencilSlot(lower)] += sign * (-g);
220 coefficients[PoissonOperator_StencilSlot(upper)] += sign * g;
221 continue;
222 }
223
224 const PoissonTransverseDifference diff = face->diff[b];
225 if (diff.weight == 0.0) continue;
226 const PetscReal term = g * diff.weight;
227 PetscInt hi_lower[3] = {lower[0], lower[1], lower[2]}, hi_upper[3] = {upper[0], upper[1], upper[2]};
228 PetscInt lo_lower[3] = {lower[0], lower[1], lower[2]}, lo_upper[3] = {upper[0], upper[1], upper[2]};
229 hi_lower[b] += diff.hi; hi_upper[b] += diff.hi;
230 lo_lower[b] += diff.lo; lo_upper[b] += diff.lo;
231 coefficients[PoissonOperator_StencilSlot(hi_lower)] += sign * term;
232 coefficients[PoissonOperator_StencilSlot(hi_upper)] += sign * term;
233 coefficients[PoissonOperator_StencilSlot(lo_lower)] += sign * (-term);
234 coefficients[PoissonOperator_StencilSlot(lo_upper)] += sign * (-term);
235 }
236}
237
238/**
239 * @brief Implementation of \ref AssemblePoissonOperator().
240 * @details Full API contract (arguments, ownership, side effects) is documented with
241 * the header declaration in `include/poisson.h`.
242 * @see AssemblePoissonOperator()
243 */
244PetscErrorCode AssemblePoissonOperator(UserCtx *user)
245{
246 const DMDALocalInfo info = user->info;
247 const PetscInt m[3] = {info.mx, info.my, info.mz};
248 PetscBool periodic[3];
249 PoissonFaceMetrics metrics;
250 const PetscReal ***nvert, ***aj;
251 AO ao;
252
253 PetscFunctionBeginUser;
255
256 if (!user->A) {
257 PetscInt local_rows;
258 PetscCall(VecGetLocalSize(user->Phi, &local_rows));
259 PetscCall(MatCreateAIJ(PETSC_COMM_WORLD, local_rows, local_rows, m[0] * m[1] * m[2], m[0] * m[1] * m[2],
260 19, NULL, 19, NULL, &user->A));
261 }
262 PetscCall(MatZeroEntries(user->A));
263
264 GetPeriodicAxes(user->simCtx, periodic);
265 PetscCall(DMDAGetAO(user->da, &ao));
266 PetscCall(PoissonOperator_GetFaceMetrics(user, &metrics));
267 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
268 PetscCall(DMDAVecGetArrayRead(user->da, user->lAj, (void *)&aj));
269
270 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
271 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
272 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
273 const PetscInt c[3] = {i, j, k};
274 PetscInt row = i + j * m[0] + k * m[0] * m[1];
275 PetscInt columns[19];
276 PetscScalar coefficients[19] = {0.0};
277
278 PetscCall(AOApplicationToPetsc(ao, 1, &row));
279 if (i == 0 || i == m[0] - 1 || j == 0 || j == m[1] - 1 || k == 0 || k == m[2] - 1) {
280 const PetscScalar one = 1.0;
281 PetscCall(MatSetValues(user->A, 1, &row, 1, &row, &one, INSERT_VALUES));
282 continue;
283 }
284
285 for (PetscInt s = 0; s < 19; s++) {
286 const PetscInt *d = POISSON_STENCIL_OFFSETS[s];
287 columns[s] = PoissonOperator_NeighborIndex(i, d[0], m[0], periodic[0]) +
288 PoissonOperator_NeighborIndex(j, d[1], m[1], periodic[1]) * m[0] +
289 PoissonOperator_NeighborIndex(k, d[2], m[2], periodic[2]) * m[0] * m[1];
290 }
291 PetscCall(AOApplicationToPetsc(ao, 19, columns));
292
293 if (nvert[k][j][i] > POISSON_SOLID_THRESHOLD) {
294 /* Solid rows keep the fluid row's structure with zero couplings, so a
295 solid field that changes during a run reassembles in place. */
296 coefficients[0] = 1.0;
297 PetscCall(MatSetValues(user->A, 1, &row, 19, columns, coefficients, INSERT_VALUES));
298 continue;
299 }
300
301 /* Faces in the order east, west, north, south, top, bottom. Non-periodic
302 boundary faces carry no flux (homogeneous Neumann). */
303 for (PetscInt n = 0; n < 3; n++) {
304 const PetscInt first = periodic[n] ? 0 : 1;
305 const PetscInt last = periodic[n] ? m[n] - 1 : m[n] - 2;
306 for (PetscInt side = 0; side < 2; side++) {
307 PetscInt across[3] = {0, 0, 0}, own[3] = {0, 0, 0}, face_cell[3] = {i, j, k};
308 const PetscBool upper = (PetscBool)(side == 0);
309
310 across[n] = upper ? 1 : -1;
311 if (PoissonOperator_At(nvert, c, across) >= POISSON_SOLID_THRESHOLD) continue;
312 if (c[n] == (upper ? last : first)) continue;
313 if (!upper) { own[n] = -1; face_cell[n] -= 1; }
314
315 const PoissonFaceGradient face =
316 PoissonOperator_FaceGradientStencil(&metrics, nvert, face_cell, n, m, periodic);
317 PoissonOperator_AddFaceFlux(&face, own, n, upper ? 1.0 : -1.0, coefficients);
318 }
319 }
320
321 for (PetscInt s = 0; s < 19; s++) coefficients[s] *= -aj[k][j][i];
322 PetscCall(MatSetValues(user->A, 1, &row, 19, columns, coefficients, INSERT_VALUES));
323 }
324 }
325 }
326
327 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lAj, (void *)&aj));
328 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
329 PetscCall(PoissonOperator_RestoreFaceMetrics(user, &metrics));
330 PetscCall(MatAssemblyBegin(user->A, MAT_FINAL_ASSEMBLY));
331 PetscCall(MatAssemblyEnd(user->A, MAT_FINAL_ASSEMBLY));
332
333 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Poisson operator assembled on level %" PetscInt_FMT ".\n", user->thislevel);
335 PetscFunctionReturn(0);
336}
337
338/**
339 * @brief Implementation of \ref ComputePoissonRHS().
340 * @details Full API contract (arguments, ownership, side effects) is documented with
341 * the header declaration in `include/poisson.h`.
342 * @see ComputePoissonRHS()
343 */
344PetscErrorCode ComputePoissonRHS(UserCtx *user, Vec B)
345{
346 SimCtx *simCtx = user->simCtx;
347 const DMDALocalInfo info = user->info;
348 const PetscInt mx = info.mx, my = info.my, mz = info.mz;
349 const PetscReal dt = simCtx->dt;
350 const Cmpnts ***ucont;
351 const PetscReal ***nvert, ***aj;
352 PetscReal ***rhs;
353 PetscReal local_sum = 0.0, global_sum = 0.0;
354
355 PetscFunctionBeginUser;
357 PetscCall(DMDAVecGetArray(user->da, B, &rhs));
358 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcont, (void *)&ucont));
359 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
360 PetscCall(DMDAVecGetArrayRead(user->da, user->lAj, (void *)&aj));
361
362 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
363 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
364 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
365 if (i == 0 || i == mx - 1 || j == 0 || j == my - 1 || k == 0 || k == mz - 1 ||
366 nvert[k][j][i] > POISSON_SOLID_THRESHOLD) {
367 rhs[k][j][i] = 0.0;
368 } else {
369 rhs[k][j][i] = -(ucont[k][j][i].x - ucont[k][j][i-1].x +
370 ucont[k][j][i].y - ucont[k][j-1][i].y +
371 ucont[k][j][i].z - ucont[k-1][j][i].z) / dt * aj[k][j][i] * COEF_TIME_ACCURACY;
372 }
373 }
374 }
375 }
376
377 /* The integral of the right-hand side is the net volume flux into the domain carried
378 by the uncorrected velocity. With Neumann pressure boundaries it must vanish for
379 the equation to have a solution. */
380 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
381 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
382 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
383 local_sum += rhs[k][j][i] / aj[k][j][i] * dt / COEF_TIME_ACCURACY;
384 }
385 }
386 }
387 PetscCallMPI(MPI_Allreduce(&local_sum, &global_sum, 1, MPIU_REAL, MPI_SUM, PetscObjectComm((PetscObject)B)));
388 simCtx->poissonSourceImbalance = global_sum;
389 LOG_ALLOW(GLOBAL, LOG_INFO, "Poisson source imbalance: %le\n", (double)global_sum);
390
391 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lAj, (void *)&aj));
392 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
393 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcont, (void *)&ucont));
394 PetscCall(DMDAVecRestoreArray(user->da, B, &rhs));
396 PetscFunctionReturn(0);
397}
398
399/**
400 * @brief Implementation of \ref UpdatePressure().
401 * @details Full API contract (arguments, ownership, side effects) is documented with
402 * the header declaration in `include/poisson.h`.
403 * @see UpdatePressure()
404 */
405PetscErrorCode UpdatePressure(UserCtx *user)
406{
407 const FieldId periodic_fields[] = {FIELD_ID_P, FIELD_ID_PHI};
408
409 PetscFunctionBeginUser;
411 PetscCall(VecAXPY(user->P, 1.0, user->Phi));
412 PetscCall(SynchronizePeriodicCellFields(user, 2, periodic_fields));
413 PetscCall(UpdateLocalGhosts(user, FIELD_ID_P));
414 PetscCall(UpdateLocalGhosts(user, FIELD_ID_PHI));
416 PetscFunctionReturn(0);
417}
418
419/**
420 * @brief Implementation of \ref ProjectVelocity().
421 * @details Full API contract (arguments, ownership, side effects) is documented with
422 * the header declaration in `include/poisson.h`.
423 * @see ProjectVelocity()
424 */
425PetscErrorCode ProjectVelocity(UserCtx *user)
426{
427 SimCtx *simCtx = user->simCtx;
428 const DMDALocalInfo info = user->info;
429 const PetscInt m[3] = {info.mx, info.my, info.mz};
430 const PetscInt start[3] = {info.xs, info.ys, info.zs};
431 const PetscReal scale = simCtx->dt / COEF_TIME_ACCURACY;
432 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
433 PetscBool periodic[3];
434 PetscInt interior_start[3], interior_end[3];
435 PoissonFaceMetrics metrics;
436 const PetscReal ***nvert, ***phi;
437 Cmpnts ***ucont;
438
439 PetscFunctionBeginUser;
441 GetPeriodicAxes(user->simCtx, periodic);
442 GetOwnedInteriorCellBounds(&info, interior_start, interior_end);
443
444 PetscCall(PoissonOperator_GetFaceMetrics(user, &metrics));
445 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
446 PetscCall(DMDAVecGetArrayRead(user->da, user->lPhi, (void *)&phi));
447 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
448
449 /* One pass per face orientation. Faces between two interior cells are corrected on
450 every axis; a periodic axis also corrects its seam face at index 0. */
451 for (PetscInt n = 0; n < 3; n++) {
452 PetscInt lo[3], hi[3];
453 for (PetscInt a = 0; a < 3; a++) { lo[a] = interior_start[a]; hi[a] = interior_end[a]; }
454 if (periodic[n] && start[n] == 0) lo[n] = 0;
455 hi[n] = PetscMin(hi[n], periodic[n] ? m[n] - 1 : m[n] - 2);
456
457 for (PetscInt k = lo[2]; k < hi[2]; k++) {
458 for (PetscInt j = lo[1]; j < hi[1]; j++) {
459 for (PetscInt i = lo[0]; i < hi[0]; i++) {
460 const PetscInt c[3] = {i, j, k};
461 PetscInt across[3] = {0, 0, 0};
462
463 across[n] = 1;
464 if (nvert[k][j][i] > POISSON_SOLID_THRESHOLD ||
465 PoissonOperator_At(nvert, c, across) > POISSON_SOLID_THRESHOLD) continue;
466
467 const PetscReal flux = PoissonOperator_FaceGradientFlux(&metrics, nvert, phi, c, n, m, periodic);
468 const PetscReal correction = flux * scale;
469 if (n == 0) ucont[k][j][i].x -= correction;
470 else if (n == 1) ucont[k][j][i].y -= correction;
471 else ucont[k][j][i].z -= correction;
472 }
473 }
474 }
475 }
476
477 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
478 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lPhi, (void *)&phi));
479 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
480 PetscCall(PoissonOperator_RestoreFaceMetrics(user, &metrics));
481
482 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, staggered_fields));
483 PetscCall(Contra2Cart(user));
484 PetscCall(FinalizePostProjectionCellFields(user));
486 PetscFunctionReturn(0);
487}
488
489/**
490 * @brief Removes the null space of the Neumann pressure problem from a level vector.
491 *
492 * PETSc first removes the global constant. This callback then subtracts the mean over
493 * the interior fluid cells and zeroes the dummy layers and solid cells, which carry no
494 * unknown.
495 */
496static PetscErrorCode PoissonMultigrid_RemoveNullSpace(MatNullSpace nullsp, Vec X, void *ctx)
497{
498 UserCtx *user = (UserCtx *)ctx;
499 const DMDALocalInfo info = user->info;
500 const PetscInt mx = info.mx, my = info.my, mz = info.mz;
501 const PetscInt xs = info.xs, xe = info.xs + info.xm;
502 const PetscInt ys = info.ys, ye = info.ys + info.ym;
503 const PetscInt zs = info.zs, ze = info.zs + info.zm;
504 PetscInt lo[3], hi[3];
505 GetOwnedInteriorCellBounds(&info, lo, hi);
506 const PetscInt lxs = lo[0], lxe = hi[0], lys = lo[1], lye = hi[1], lzs = lo[2], lze = hi[2];
507 const PetscReal ***nvert;
508 PetscReal ***x;
509 PetscReal local[2] = {0.0, 0.0}, global[2];
510 MPI_Comm comm = PetscObjectComm((PetscObject)X);
511
512 PetscFunctionBeginUser;
514 (void)nullsp;
515 PetscCall(DMDAVecGetArray(user->da, X, &x));
516 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
517
518 for (PetscInt k = lzs; k < lze; k++) {
519 for (PetscInt j = lys; j < lye; j++) {
520 for (PetscInt i = lxs; i < lxe; i++) {
521 if (nvert[k][j][i] < POISSON_SOLID_THRESHOLD) {
522 local[0] += x[k][j][i];
523 local[1] += 1.0;
524 }
525 }
526 }
527 }
528 PetscCallMPI(MPI_Allreduce(&local[0], &global[0], 1, MPIU_REAL, MPI_SUM, comm));
529 PetscCallMPI(MPI_Allreduce(&local[1], &global[1], 1, MPIU_REAL, MPI_SUM, comm));
530 const PetscReal shift = global[0] / (-1.0 * global[1]);
531 for (PetscInt k = lzs; k < lze; k++) {
532 for (PetscInt j = lys; j < lye; j++) {
533 for (PetscInt i = lxs; i < lxe; i++) {
534 if (nvert[k][j][i] < POISSON_SOLID_THRESHOLD) x[k][j][i] += shift;
535 }
536 }
537 }
538
539 for (PetscInt k = zs; k < ze; k++) {
540 for (PetscInt j = ys; j < ye; j++) {
541 for (PetscInt i = xs; i < xe; i++) {
542 if (i == 0 || i == mx - 1 || j == 0 || j == my - 1 || k == 0 || k == mz - 1 ||
543 nvert[k][j][i] > POISSON_SOLID_THRESHOLD) x[k][j][i] = 0.0;
544 }
545 }
546 }
547
548 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
549 PetscCall(DMDAVecRestoreArray(user->da, X, &x));
551 PetscFunctionReturn(0);
552}
553
554/**
555 * @brief Coarse cell and interpolation direction along one axis for fine index @p f.
556 *
557 * Each fine cell takes 3/4 of its parent coarse cell and 1/4 of the coarse neighbour on
558 * the side it lies towards. The first and last interior cells and semi-coarsened axes use
559 * the parent only, as does a neighbour that is solid on the coarse grid.
560 */
561static void PoissonMultigrid_InterpolationParent(PetscInt f, PetscInt m, PetscInt semi,
562 PetscInt *coarse, PetscInt *direction)
563{
564 if (semi) {
565 *coarse = f;
566 *direction = 0;
567 return;
568 }
569 *coarse = (f + 1) / 2;
570 *direction = (f - 2 * (*coarse)) == 0 ? 1 : -1;
571 if (f == 1 || f == m - 2) *direction = 0;
572}
573
574/**
575 * @brief Prolongs a coarse-level correction to the next finer level (MatShell multiply).
576 * @details The shell context is the fine-level UserCtx.
577 */
578static PetscErrorCode PoissonMultigrid_Interpolate(Mat P, Vec X, Vec F)
579{
580 UserCtx *user, *coarse;
581 DMDALocalInfo info;
582 Vec lX;
583 const PetscReal ***x, ***nvert, ***nvert_c;
584 PetscReal ***f;
585
586 PetscFunctionBeginUser;
588 PetscCall(MatShellGetContext(P, &user));
589 coarse = user->user_c;
590 info = user->info;
591 const PetscInt mx = info.mx, my = info.my, mz = info.mz;
592 const PetscInt xs = info.xs, xe = info.xs + info.xm;
593 const PetscInt ys = info.ys, ye = info.ys + info.ym;
594 const PetscInt zs = info.zs, ze = info.zs + info.zm;
595 PetscInt lo[3], hi[3];
596 GetOwnedInteriorCellBounds(&info, lo, hi);
597 const PetscInt lxs = lo[0], lxe = hi[0], lys = lo[1], lye = hi[1], lzs = lo[2], lze = hi[2];
598
599 PetscCall(DMGetLocalVector(coarse->da, &lX));
600 PetscCall(DMGlobalToLocalBegin(coarse->da, X, INSERT_VALUES, lX));
601 PetscCall(DMGlobalToLocalEnd(coarse->da, X, INSERT_VALUES, lX));
602 PetscCall(DMDAVecGetArrayRead(coarse->da, lX, (void *)&x));
603 PetscCall(DMDAVecGetArrayRead(coarse->da, coarse->lNvert, (void *)&nvert_c));
604 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
605 PetscCall(DMDAVecGetArray(user->da, F, &f));
606
607 for (PetscInt k = lzs; k < lze; k++) {
608 for (PetscInt j = lys; j < lye; j++) {
609 for (PetscInt i = lxs; i < lxe; i++) {
610 PetscInt ic, jc, kc, ia, ja, ka;
611
612 PoissonMultigrid_InterpolationParent(i, mx, user->isc, &ic, &ia);
613 PoissonMultigrid_InterpolationParent(j, my, user->jsc, &jc, &ja);
614 PoissonMultigrid_InterpolationParent(k, mz, user->ksc, &kc, &ka);
615 if (ka == -1 && nvert_c[kc-1][jc][ic] > POISSON_SOLID_THRESHOLD) ka = 0;
616 else if (ka == 1 && nvert_c[kc+1][jc][ic] > POISSON_SOLID_THRESHOLD) ka = 0;
617 if (ja == -1 && nvert_c[kc][jc-1][ic] > POISSON_SOLID_THRESHOLD) ja = 0;
618 else if (ja == 1 && nvert_c[kc][jc+1][ic] > POISSON_SOLID_THRESHOLD) ja = 0;
619 if (ia == -1 && nvert_c[kc][jc][ic-1] > POISSON_SOLID_THRESHOLD) ia = 0;
620 else if (ia == 1 && nvert_c[kc][jc][ic+1] > POISSON_SOLID_THRESHOLD) ia = 0;
621
622 f[k][j][i] = (x[kc ][jc ][ic ] * 9 +
623 x[kc ][jc+ja][ic ] * 3 +
624 x[kc ][jc ][ic+ia] * 3 +
625 x[kc ][jc+ja][ic+ia]) * 3./64. +
626 (x[kc+ka][jc ][ic ] * 9 +
627 x[kc+ka][jc+ja][ic ] * 3 +
628 x[kc+ka][jc ][ic+ia] * 3 +
629 x[kc+ka][jc+ja][ic+ia]) / 64.;
630 }
631 }
632 }
633 for (PetscInt k = zs; k < ze; k++) {
634 for (PetscInt j = ys; j < ye; j++) {
635 for (PetscInt i = xs; i < xe; i++) {
636 if (i == 0 || i == mx - 1 || j == 0 || j == my - 1 || k == 0 || k == mz - 1 ||
637 nvert[k][j][i] > POISSON_SOLID_THRESHOLD) f[k][j][i] = 0.0;
638 }
639 }
640 }
641
642 PetscCall(DMDAVecRestoreArray(user->da, F, &f));
643 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
644 PetscCall(DMDAVecRestoreArrayRead(coarse->da, coarse->lNvert, (void *)&nvert_c));
645 PetscCall(DMDAVecRestoreArrayRead(coarse->da, lX, (void *)&x));
646 PetscCall(DMRestoreLocalVector(coarse->da, &lX));
648 PetscFunctionReturn(0);
649}
650
651/**
652 * @brief Restricts a fine-level residual to the next coarser level (MatShell multiply).
653 *
654 * Each coarse cell averages the eight fine cells it covers, weighting each by its fluid
655 * fraction; coarse dummy and solid cells receive zero. The shell context is the
656 * coarse-level UserCtx.
657 */
658static PetscErrorCode PoissonMultigrid_Restrict(Mat R, Vec X, Vec F)
659{
660 UserCtx *user, *fine;
661 DMDALocalInfo info;
662 Vec lX;
663 const PetscReal ***x, ***nvert, ***nvert_f;
664 PetscReal ***f;
665
666 PetscFunctionBeginUser;
668 PetscCall(MatShellGetContext(R, &user));
669 fine = user->user_f;
670 info = user->info;
671 const PetscInt mx = info.mx, my = info.my, mz = info.mz;
672 const PetscInt ia = user->isc ? 0 : 1, ja = user->jsc ? 0 : 1, ka = user->ksc ? 0 : 1;
673
674 PetscCall(DMGetLocalVector(fine->da, &lX));
675 PetscCall(DMGlobalToLocalBegin(fine->da, X, INSERT_VALUES, lX));
676 PetscCall(DMGlobalToLocalEnd(fine->da, X, INSERT_VALUES, lX));
677 PetscCall(DMDAVecGetArrayRead(fine->da, lX, (void *)&x));
678 PetscCall(DMDAVecGetArrayRead(fine->da, fine->lNvert, (void *)&nvert_f));
679 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
680 PetscCall(DMDAVecGetArray(user->da, F, &f));
681
682 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
683 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
684 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
685 if (i == 0 || i == mx - 1 || j == 0 || j == my - 1 || k == 0 || k == mz - 1 ||
686 nvert[k][j][i] > POISSON_SOLID_THRESHOLD) {
687 f[k][j][i] = 0.0;
688 continue;
689 }
690 const PetscInt ih = user->isc ? i : 2 * i;
691 const PetscInt jh = user->jsc ? j : 2 * j;
692 const PetscInt kh = user->ksc ? k : 2 * k;
693 f[k][j][i] = 0.125 *
694 (x[kh ][jh ][ih ] * PetscMax(0., 1 - nvert_f[kh ][jh ][ih ]) +
695 x[kh ][jh ][ih-ia] * PetscMax(0., 1 - nvert_f[kh ][jh ][ih-ia]) +
696 x[kh ][jh-ja][ih ] * PetscMax(0., 1 - nvert_f[kh ][jh-ja][ih ]) +
697 x[kh-ka][jh ][ih ] * PetscMax(0., 1 - nvert_f[kh-ka][jh ][ih ]) +
698 x[kh ][jh-ja][ih-ia] * PetscMax(0., 1 - nvert_f[kh ][jh-ja][ih-ia]) +
699 x[kh-ka][jh-ja][ih ] * PetscMax(0., 1 - nvert_f[kh-ka][jh-ja][ih ]) +
700 x[kh-ka][jh ][ih-ia] * PetscMax(0., 1 - nvert_f[kh-ka][jh ][ih-ia]) +
701 x[kh-ka][jh-ja][ih-ia] * PetscMax(0., 1 - nvert_f[kh-ka][jh-ja][ih-ia]));
702 }
703 }
704 }
705
706 PetscCall(DMDAVecRestoreArray(user->da, F, &f));
707 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
708 PetscCall(DMDAVecRestoreArrayRead(fine->da, fine->lNvert, (void *)&nvert_f));
709 PetscCall(DMDAVecRestoreArrayRead(fine->da, lX, (void *)&x));
710 PetscCall(DMRestoreLocalVector(fine->da, &lX));
712 PetscFunctionReturn(0);
713}
714
715/**
716 * @brief Gives each block factor of a block-Jacobi level solver a small diagonal shift, so
717 * the factorization of a nearly singular Neumann block does not fail on a zero
718 * pivot. Does nothing for any other preconditioner.
719 */
720static PetscErrorCode PoissonMultigrid_ShiftBlockFactors(KSP level_ksp)
721{
722 PC level_pc;
723 PCType level_pc_type;
724 PetscBool is_bjacobi = PETSC_FALSE;
725 KSP *block_ksp;
726 PetscInt nblocks;
727
728 PetscFunctionBeginUser;
730 PetscCall(KSPGetPC(level_ksp, &level_pc));
731 PetscCall(PCGetType(level_pc, &level_pc_type));
732 if (level_pc_type) PetscCall(PetscStrcmp(level_pc_type, PCBJACOBI, &is_bjacobi));
733 if (!is_bjacobi) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
734
735 PetscCall(KSPSetUp(level_ksp));
736 PetscCall(PCBJacobiGetSubKSP(level_pc, &nblocks, NULL, &block_ksp));
737 for (PetscInt b = 0; b < nblocks; b++) {
738 PC block_pc;
739 PetscCall(KSPGetPC(block_ksp[b], &block_pc));
740 PetscCall(PCFactorSetShiftAmount(block_pc, 1.e-10));
741 }
743 PetscFunctionReturn(0);
744}
745
746/**
747 * @brief Builds the multigrid solver for block @p bi and stores it in the finest level.
748 *
749 * Assembles the operator on every level, then configures the outer `ps_` Krylov solver
750 * with a multiplicative V-cycle `PCMG`: shell restriction and interpolation between
751 * levels, block-Jacobi smoothers by default, a coarse solve limited to 40 iterations at
752 * relative tolerance 1e-8, and the Neumann null space on every level. PETSc options
753 * override these defaults.
754 *
755 * Each smoother runs `pre_sweeps` iterations before the coarse correction and
756 * `post_sweeps` after it. When the two differ, the post-smoother is a separate solver
757 * that starts as a copy of the configured pre-smoother and reads further options under
758 * `ps_mg_levels_N_up_`. Everything built here depends only on the grid metrics, the
759 * solid field, and the boundary types; calling it again after one of those changes
760 * rebuilds the solver.
761 */
762static PetscErrorCode PoissonMultigrid_Build(UserMG *usermg, PetscInt bi)
763{
764 MGCtx *mgctx = usermg->mgctx;
765 const PetscInt levels = usermg->mglevels;
766 UserCtx *finest = &mgctx[levels - 1].user[bi];
767 SimCtx *simCtx = finest->simCtx;
768 DualMonitorCtx *monitor;
769 KSP ksp;
770 PC pc;
771
772 PetscFunctionBeginUser;
774 LOG_ALLOW(GLOBAL, LOG_INFO, "Block %" PetscInt_FMT ": building the multigrid Poisson solver on %" PetscInt_FMT " levels.\n", bi, levels);
775
776 for (PetscInt l = levels - 1; l >= 0; l--) PetscCall(AssemblePoissonOperator(&mgctx[l].user[bi]));
777
778 PetscCall(KSPCreate(PETSC_COMM_WORLD, &ksp));
779 PetscCall(KSPAppendOptionsPrefix(ksp, "ps_"));
780
781 /* The convergence log is opened and closed around every solve; see
782 PoissonMultigrid_OpenConvergenceLog(). The monitor owns its context. */
783 PetscCall(PetscNew(&monitor));
784 monitor->block_id = bi;
785 monitor->file_handle = NULL;
786 PetscCall(KSPMonitorSet(ksp, DualKSPMonitor, monitor, DualMonitorDestroy));
787
788 PetscCall(KSPGetPC(ksp, &pc));
789 PetscCall(PCSetType(pc, PCMG));
790 PetscCall(PCMGSetLevels(pc, levels, NULL));
791 PetscCall(PCMGSetCycleType(pc, PC_MG_CYCLE_V));
792 PetscCall(PCMGSetType(pc, PC_MG_MULTIPLICATIVE));
793 PetscCall(PCMGSetNumberSmooth(pc, simCtx->mg_preItr));
794
795 for (PetscInt l = levels - 1; l > 0; l--) {
796 UserCtx *fine = &mgctx[l].user[bi];
797 UserCtx *coarse = &mgctx[l - 1].user[bi];
798 const PetscInt m_c = coarse->info.xm * coarse->info.ym * coarse->info.zm;
799 const PetscInt m_f = fine->info.xm * fine->info.ym * fine->info.zm;
800 const PetscInt M_c = coarse->info.mx * coarse->info.my * coarse->info.mz;
801 const PetscInt M_f = fine->info.mx * fine->info.my * fine->info.mz;
802
803 PetscCall(MatCreateShell(PETSC_COMM_WORLD, m_c, m_f, M_c, M_f, coarse, &fine->MR));
804 PetscCall(MatCreateShell(PETSC_COMM_WORLD, m_f, m_c, M_f, M_c, fine, &fine->MP));
805 PetscCall(MatShellSetOperation(fine->MR, MATOP_MULT, (void (*)(void))PoissonMultigrid_Restrict));
806 PetscCall(MatShellSetOperation(fine->MP, MATOP_MULT, (void (*)(void))PoissonMultigrid_Interpolate));
807 PetscCall(PCMGSetRestriction(pc, l, fine->MR));
808 PetscCall(PCMGSetInterpolation(pc, l, fine->MP));
809 }
810
811 for (PetscInt l = levels - 1; l >= 0; l--) {
812 UserCtx *level = &mgctx[l].user[bi];
813 KSP level_ksp;
814 PC level_pc;
815
816 if (l > 0) {
817 PetscCall(PCMGGetSmoother(pc, l, &level_ksp));
818 } else {
819 PetscCall(PCMGGetCoarseSolve(pc, &level_ksp));
820 PetscCall(KSPSetTolerances(level_ksp, 1.e-8, PETSC_DEFAULT, PETSC_DEFAULT, 40));
821 }
822 PetscCall(KSPSetOperators(level_ksp, level->A, level->A));
823 PetscCall(KSPGetPC(level_ksp, &level_pc));
824 PetscCall(PCSetType(level_pc, PCBJACOBI));
825 PetscCall(KSPSetFromOptions(level_ksp));
826 PetscCall(PoissonMultigrid_ShiftBlockFactors(level_ksp));
827
828 PetscCall(MatNullSpaceCreate(PETSC_COMM_WORLD, PETSC_TRUE, 0, NULL, &level->nullsp));
829 PetscCall(MatNullSpaceSetFunction(level->nullsp, PoissonMultigrid_RemoveNullSpace, level));
830 PetscCall(MatSetNullSpace(level->A, level->nullsp));
831 PetscCall(PCMGSetResidual(pc, l, PCMGResidualDefault, level->A));
832 PetscCall(KSPSetUp(level_ksp));
833
834 if (l > 0 && simCtx->mg_preItr != simCtx->mg_poItr) {
835 KSP post_smoother;
836
837 /* PETSc creates the post-smoother as a copy of the pre-smoother's type,
838 preconditioner and tolerances as configured so far. */
839 PetscCall(PCMGGetSmootherUp(pc, l, &post_smoother));
840 PetscCall(KSPAppendOptionsPrefix(post_smoother, "up_"));
841 PetscCall(KSPSetOperators(post_smoother, level->A, level->A));
842 PetscCall(KSPSetTolerances(post_smoother, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT, simCtx->mg_poItr));
843 PetscCall(KSPSetFromOptions(post_smoother));
844 PetscCall(PoissonMultigrid_ShiftBlockFactors(post_smoother));
845 PetscCall(KSPSetUp(post_smoother));
846 }
847
848 if (l < levels - 1) {
849 PetscCall(MatCreateVecs(level->A, &level->R, NULL));
850 PetscCall(PCMGSetRhs(pc, l, level->R));
851 }
852 }
853
854 PetscCall(KSPSetOperators(ksp, finest->A, finest->A));
855 PetscCall(MatSetNullSpace(finest->A, finest->nullsp));
856 PetscCall(KSPSetFromOptions(ksp));
857 PetscCall(KSPSetUp(ksp));
858 PetscCall(VecDuplicate(finest->P, &finest->B));
859 finest->ksp = ksp;
860
862 PetscFunctionReturn(0);
863}
864
865/**
866 * @brief Prepares the convergence monitor for one solve and opens its log file on rank 0.
867 *
868 * A fresh run's first open, which may be the initial condition's projection at step 0,
869 * truncates the log; every later open appends, and a continued run's first open records
870 * where it resumed.
871 */
872static PetscErrorCode PoissonMultigrid_OpenConvergenceLog(KSP ksp, SimCtx *simCtx, PetscInt bi)
873{
874 DualMonitorCtx *monitor = NULL;
875
876 PetscFunctionBeginUser;
878 PetscCall(KSPGetMonitorContext(ksp, &monitor));
879 monitor->step = simCtx->step;
880 /* The history file always gets the rows; the console echoes them only to a run that asked
881 * for the true residual and runs at INFO or more detail, so a WARNING run's console
882 * carries no per-iteration lines. */
884 monitor->log_to_console = (PetscBool)(simCtx->ps_ksp_pic_monitor_true_residual && get_log_level() >= LOG_INFO);
885 monitor->file_handle = NULL;
886 if (simCtx->rank == 0) {
887 char filename[128];
888
889 PetscCall(PetscSNPrintf(filename, sizeof(filename),
890 "Poisson_Solver_Convergence_History_Block_%" PetscInt_FMT ".csv", bi));
891 /* true_norm and relative_norm are empty unless pic_true_residual asked for them. */
892 PetscCall(PicurvOpenRunCsv(simCtx, simCtx->log_dir, filename,
893 "step,block,iter,unpreconditioned_norm,true_norm,relative_norm",
894 PICURV_CSV_TRUNCATE_ON_FRESH, PETSC_TRUE, &monitor->file_handle));
895 }
897 PetscFunctionReturn(0);
898}
899
900/** @brief Closes the log file opened by PoissonMultigrid_OpenConvergenceLog(). */
901static PetscErrorCode PoissonMultigrid_CloseConvergenceLog(KSP ksp)
902{
903 DualMonitorCtx *monitor = NULL;
904
905 PetscFunctionBeginUser;
907 PetscCall(KSPGetMonitorContext(ksp, &monitor));
908 if (monitor->file_handle) {
909 fclose(monitor->file_handle);
910 monitor->file_handle = NULL;
911 }
913 PetscFunctionReturn(0);
914}
915
916/**
917 * @brief Implementation of \ref PoissonSolver_Multigrid().
918 * @details Full API contract (arguments, ownership, side effects) is documented with
919 * the header declaration in `include/poisson.h`.
920 * @see PoissonSolver_Multigrid()
921 */
922PetscErrorCode PoissonSolver_Multigrid(UserMG *usermg)
923{
924 SimCtx *simCtx = usermg->mgctx[0].user[0].simCtx;
925 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
926
927 PetscFunctionBeginUser;
929 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting Multigrid Poisson Solve...\n");
930
931 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
932 UserCtx *user = &usermg->mgctx[usermg->mglevels - 1].user[bi];
933 KSPConvergedReason reason;
934
935 if (!user->ksp) PetscCall(PoissonMultigrid_Build(usermg, bi));
936
937 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, staggered_fields));
938 PetscCall(ComputePoissonRHS(user, user->B));
939
940 PetscCall(PoissonMultigrid_OpenConvergenceLog(user->ksp, simCtx, bi));
941 PetscCall(KSPSolve(user->ksp, user->B, user->Phi));
943 /* KSPSolve projects only the right-hand side. The residual cannot see a constant in
944 Phi, so iterations near the round-off floor can leave one, and P += Phi would add it
945 up step after step. Projecting the solution the same way fixes the pressure gauge. */
946 PetscCall(MatNullSpaceRemove(user->nullsp, user->Phi));
947
948 /* A non-finite residual or a preconditioner that could not be built leaves Phi
949 meaningless, and the projection would carry it into the next momentum step,
950 where it surfaces as a failure of the wrong solver. Stopping at max_it is this
951 solve's normal mode and stays silent; any other divergence is reported, because
952 the projection proceeds on that Phi. */
953 PetscCall(KSPGetConvergedReason(user->ksp, &reason));
954 PetscCheck(reason != KSP_DIVERGED_NANORINF && reason != KSP_DIVERGED_PC_FAILED,
955 PETSC_COMM_WORLD, PETSC_ERR_NOT_CONVERGED,
956 "Pressure Poisson solve on block %" PetscInt_FMT " failed at step %" PetscInt_FMT
957 " (KSP reason %s). Known causes: a multigrid hierarchy coarsened too far "
958 "(reduce poisson_solver.multigrid.levels or refine the grid), or a momentum "
959 "field that has already diverged, such as an explicit time step beyond its "
960 "stability limit.",
961 bi, simCtx->step, KSPConvergedReasons[reason]);
962 if (reason < 0 && reason != KSP_DIVERGED_ITS) {
963 LOG(GLOBAL, LOG_WARNING, "Pressure Poisson solve on block %" PetscInt_FMT
964 " diverged at step %" PetscInt_FMT " (KSP reason %s); the projection uses the last iterate.\n",
965 bi, simCtx->step, KSPConvergedReasons[reason]);
966 }
967 }
968
969 LOG_ALLOW(GLOBAL, LOG_INFO, "Multigrid Poisson Solve complete.\n");
971 PetscFunctionReturn(0);
972}
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent component-staggered vector fields.
PetscErrorCode FinalizePostProjectionCellFields(UserCtx *user)
Finalizes cell-centered fields after the projection step.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_JETA
@ FIELD_ID_IAJ
@ FIELD_ID_KETA
@ FIELD_ID_JAJ
@ FIELD_ID_KAJ
@ FIELD_ID_KZET
@ FIELD_ID_IETA
@ FIELD_ID_UCONT
@ FIELD_ID_ICSI
@ FIELD_ID_PHI
@ FIELD_ID_JCSI
@ FIELD_ID_JZET
@ FIELD_ID_P
@ FIELD_ID_IZET
@ FIELD_ID_KCSI
Non-owning runtime objects resolved for one field and UserCtx.
Logging utilities and macros for PETSc-based applications.
PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file)
Opens one of the run's CSV records (diagnostics, solver history, profiling) for writing.
Definition logging.c:3552
@ PICURV_CSV_TRUNCATE_ON_FRESH
A fresh run's first write empties the file; a continued run appends.
Definition logging.h:1146
PetscBool true_residual
Definition logging.h:59
PetscErrorCode DualMonitorDestroy(void **ctx)
Destroys the DualMonitorCtx.
Definition logging.c:927
PetscBool log_to_console
Definition logging.h:58
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#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
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
PetscInt step
Definition logging.h:61
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
PetscErrorCode DualKSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx)
A custom KSP monitor that logs to a file and optionally to the console.
Definition logging.c:955
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ 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
FILE * file_handle
Definition logging.h:57
PetscInt block_id
Definition logging.h:62
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Context for a dual-purpose KSP monitor.
Definition logging.h:56
PetscErrorCode PoissonOperator_RestoreFaceMetrics(UserCtx *user, PoissonFaceMetrics *metrics)
Implementation of PoissonOperator_RestoreFaceMetrics().
Definition poisson.c:171
static PetscErrorCode PoissonMultigrid_Restrict(Mat R, Vec X, Vec F)
Restricts a fine-level residual to the next coarser level (MatShell multiply).
Definition poisson.c:658
static PetscInt PoissonOperator_NeighborIndex(PetscInt v, PetscInt d, PetscInt m, PetscBool periodic)
Index of the neighbour at offset d (-1, 0, +1) from v on an axis of m points, wrapping between the in...
Definition poisson.c:193
PetscReal aj
Inverse Jacobian on the face.
Definition poisson.c:48
PoissonTransverseDifference diff[3]
Transverse differences; diff[n] is unused.
Definition poisson.c:49
static PICURV_ALWAYS_INLINE PetscReal PoissonOperator_At(const PetscReal ***field, const PetscInt c[3], const PetscInt d[3])
Value of a cell-centred array at cell c displaced by d.
Definition poisson.c:60
static PetscErrorCode PoissonMultigrid_CloseConvergenceLog(KSP ksp)
Closes the log file opened by PoissonMultigrid_OpenConvergenceLog().
Definition poisson.c:901
PetscErrorCode AssemblePoissonOperator(UserCtx *user)
Implementation of AssemblePoissonOperator().
Definition poisson.c:244
static const PetscInt POISSON_STENCIL_OFFSETS[19][3]
Offsets of the 19 stencil points, in the column order used to insert each row.
Definition poisson.c:27
static void PoissonOperator_AddFaceFlux(const PoissonFaceGradient *face, const PetscInt own[3], PetscInt n, PetscReal sign, PetscScalar coefficients[19])
Adds the signed gradient flux through one face to a row's stencil coefficients.
Definition poisson.c:209
PetscErrorCode PoissonOperator_GetFaceMetrics(UserCtx *user, PoissonFaceMetrics *metrics)
Implementation of PoissonOperator_GetFaceMetrics().
Definition poisson.c:147
static const FieldId POISSON_FACE_AJ_FIELDS[3]
Definition poisson.c:43
static void PoissonMultigrid_InterpolationParent(PetscInt f, PetscInt m, PetscInt semi, PetscInt *coarse, PetscInt *direction)
Coarse cell and interpolation direction along one axis for fine index f.
Definition poisson.c:561
static PetscErrorCode PoissonMultigrid_ShiftBlockFactors(KSP level_ksp)
Gives each block factor of a block-Jacobi level solver a small diagonal shift, so the factorization o...
Definition poisson.c:720
PetscErrorCode UpdatePressure(UserCtx *user)
Implementation of UpdatePressure().
Definition poisson.c:405
static PetscErrorCode PoissonMultigrid_Interpolate(Mat P, Vec X, Vec F)
Prolongs a coarse-level correction to the next finer level (MatShell multiply).
Definition poisson.c:578
PetscErrorCode ProjectVelocity(UserCtx *user)
Implementation of ProjectVelocity().
Definition poisson.c:425
static PetscInt PoissonOperator_StencilSlot(const PetscInt d[3])
Maps the 19 stencil offsets to their slots; corners of the 3x3x3 block are -1.
Definition poisson.c:128
static PetscErrorCode PoissonMultigrid_RemoveNullSpace(MatNullSpace nullsp, Vec X, void *ctx)
Removes the null space of the Neumann pressure problem from a level vector.
Definition poisson.c:496
PetscReal dot[3]
F_b .
Definition poisson.c:47
PetscErrorCode PoissonSolver_Multigrid(UserMG *usermg)
Implementation of PoissonSolver_Multigrid().
Definition poisson.c:922
static const FieldId POISSON_FACE_METRIC_FIELDS[3][3]
Field IDs of the face metric vectors, indexed as PoissonFaceMetrics.
Definition poisson.c:38
static PICURV_ALWAYS_INLINE PoissonTransverseDifference PoissonOperator_TransverseDifference(const PetscReal ***nvert, const PetscInt c[3], PetscInt n, PetscInt t, const PetscInt m[3], const PetscBool periodic[3])
The rows and weight of the transverse difference along axis t at the face between cell c and c + e_n,...
Definition poisson.c:78
static PetscErrorCode PoissonMultigrid_OpenConvergenceLog(KSP ksp, SimCtx *simCtx, PetscInt bi)
Prepares the convergence monitor for one solve and opens its log file on rank 0.
Definition poisson.c:872
PetscErrorCode ComputePoissonRHS(UserCtx *user, Vec B)
Implementation of ComputePoissonRHS().
Definition poisson.c:344
static PICURV_ALWAYS_INLINE PoissonFaceGradient PoissonOperator_FaceGradientStencil(const PoissonFaceMetrics *metrics, const PetscReal ***nvert, const PetscInt c[3], PetscInt n, const PetscInt m[3], const PetscBool periodic[3])
Gathers the metric coefficients and transverse differences of the gradient flux through the face betw...
Definition poisson.c:105
static PetscErrorCode PoissonMultigrid_Build(UserMG *usermg, PetscInt bi)
Builds the multigrid solver for block bi and stores it in the finest level.
Definition poisson.c:762
Everything needed to evaluate the gradient flux through one face.
Definition poisson.c:46
Pressure-Poisson projection: the multigrid pressure-correction solve, the pressure update,...
const PetscReal *** aj[3]
Definition poisson.h:47
PetscReal weight
0.25 central, 0.5 one-sided, 0 when no fluid side remains.
Definition poisson.h:41
const Cmpnts *** metric[3][3]
Definition poisson.h:46
static PoissonTransverseKind PoissonOperator_TransverseKind(const PetscReal ***nvert, const PetscInt c[3], PetscInt n, PetscInt t, const PetscInt m[3], const PetscBool periodic[3])
Chooses the transverse stencil along axis t at the face between cell c and c + e_n.
Definition poisson.h:95
@ POISSON_TRANSVERSE_NONE
Neither side available: the transverse term vanishes.
Definition poisson.h:52
@ POISSON_TRANSVERSE_CENTRAL
Central over rows -1 and +1, weight 0.25.
Definition poisson.h:55
@ POISSON_TRANSVERSE_LOWER
One-sided over rows -1 and 0, weight 0.5.
Definition poisson.h:53
@ POISSON_TRANSVERSE_UPPER
One-sided over rows 0 and +1, weight 0.5.
Definition poisson.h:54
PetscInt hi
Transverse offset of the added row pair.
Definition poisson.h:40
static PetscReal PoissonOperator_FaceGradientFlux(const PoissonFaceMetrics *metrics, const PetscReal ***nvert, const PetscReal ***field, const PetscInt c[3], PetscInt n, const PetscInt m[3], const PetscBool periodic[3])
Gradient flux of a cell-centred field through the face between cell c and c + e_n: sum_b g_nb D_b(fie...
Definition poisson.h:162
#define POISSON_SOLID_THRESHOLD
Cells whose nvert exceeds this value are solid.
Definition poisson.h:29
PetscInt lo
Transverse offset of the subtracted row pair.
Definition poisson.h:39
Read-only face metric arrays: metric[n][b] is F_b on the n-faces.
Definition poisson.h:45
Transverse difference used at one face.
Definition poisson.h:38
static void GetOwnedInteriorCellBounds(const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned rang...
Definition setup.h:378
PetscErrorCode Contra2Cart(UserCtx *user)
Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on...
Definition setup.c:3313
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
PetscInt isc
Definition variables.h:1175
#define PICURV_ALWAYS_INLINE
Forces inlining of a per-cell or per-face kernel whose size defeats the compiler's inlining heuristic...
Definition variables.h:65
UserCtx * user
Definition variables.h:768
PetscMPIInt rank
Definition variables.h:919
MatNullSpace nullsp
Definition variables.h:1228
PetscInt block_number
Definition variables.h:1009
UserCtx * user_f
Definition variables.h:1270
Vec lNvert
Definition variables.h:1197
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscInt ksc
Definition variables.h:1175
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscReal dt
Definition variables.h:933
PetscInt jsc
Definition variables.h:1175
Vec Ucont
Definition variables.h:1197
PetscScalar x
Definition variables.h:145
PetscInt mg_poItr
Definition variables.h:961
UserCtx * user_c
Definition variables.h:1270
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscInt thislevel
Definition variables.h:1269
PetscScalar z
Definition variables.h:145
PetscInt mglevels
Definition variables.h:775
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
DMDALocalInfo info
Definition variables.h:1169
PetscScalar y
Definition variables.h:145
PetscBool ps_ksp_pic_monitor_true_residual
Definition variables.h:976
MGCtx * mgctx
Definition variables.h:778
PetscInt mg_preItr
Definition variables.h:961
#define COEF_TIME_ACCURACY
Coefficient controlling the temporal accuracy scheme (e.g., 1.5 for 2nd Order Backward Difference).
Definition variables.h:96
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Context for Multigrid operations.
Definition variables.h:767
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
User-level context for managing the entire multigrid hierarchy.
Definition variables.h:774