PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Data Structures | Functions | Variables
poisson.c File Reference

Pressure-Poisson projection: operator, right-hand side, multigrid solve, pressure update, and velocity correction. More...

#include "poisson.h"
#include "logging.h"
#include "setup.h"
Include dependency graph for poisson.c:

Go to the source code of this file.

Data Structures

struct  PoissonFaceGradient
 Everything needed to evaluate the gradient flux through one face. More...
 

Functions

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.
 
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, for operator assembly; PoissonOperator_TransverseKind() chooses.
 
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 between cell c and c + e_n.
 
static PetscInt PoissonOperator_StencilSlot (const PetscInt d[3])
 Maps the 19 stencil offsets to their slots; corners of the 3x3x3 block are -1.
 
PetscErrorCode PoissonOperator_GetFaceMetrics (UserCtx *user, PoissonFaceMetrics *metrics)
 Implementation of PoissonOperator_GetFaceMetrics().
 
PetscErrorCode PoissonOperator_RestoreFaceMetrics (UserCtx *user, PoissonFaceMetrics *metrics)
 Implementation of PoissonOperator_RestoreFaceMetrics().
 
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 interior layers 1 and m-2 when periodic.
 
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.
 
PetscErrorCode AssemblePoissonOperator (UserCtx *user)
 Implementation of AssemblePoissonOperator().
 
PetscErrorCode ComputePoissonRHS (UserCtx *user, Vec B)
 Implementation of ComputePoissonRHS().
 
PetscErrorCode UpdatePressure (UserCtx *user)
 Implementation of UpdatePressure().
 
PetscErrorCode ProjectVelocity (UserCtx *user)
 Implementation of ProjectVelocity().
 
static PetscErrorCode PoissonMultigrid_RemoveNullSpace (MatNullSpace nullsp, Vec X, void *ctx)
 Removes the null space of the Neumann pressure problem from a level vector.
 
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.
 
static PetscErrorCode PoissonMultigrid_Interpolate (Mat P, Vec X, Vec F)
 Prolongs a coarse-level correction to the next finer level (MatShell multiply).
 
static PetscErrorCode PoissonMultigrid_Restrict (Mat R, Vec X, Vec F)
 Restricts a fine-level residual to the next coarser level (MatShell multiply).
 
static PetscErrorCode PoissonMultigrid_ShiftBlockFactors (KSP level_ksp)
 Gives each block factor of a block-Jacobi level solver a small diagonal shift, so the factorization of a nearly singular Neumann block does not fail on a zero pivot.
 
static PetscErrorCode PoissonMultigrid_Build (UserMG *usermg, PetscInt bi)
 Builds the multigrid solver for block bi and stores it in the finest level.
 
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.
 
static PetscErrorCode PoissonMultigrid_CloseConvergenceLog (KSP ksp)
 Closes the log file opened by PoissonMultigrid_OpenConvergenceLog().
 
PetscErrorCode PoissonSolver_Multigrid (UserMG *usermg)
 Implementation of PoissonSolver_Multigrid().
 

Variables

static const PetscInt POISSON_STENCIL_OFFSETS [19][3]
 Offsets of the 19 stencil points, in the column order used to insert each row.
 
static const FieldId POISSON_FACE_METRIC_FIELDS [3][3]
 Field IDs of the face metric vectors, indexed as PoissonFaceMetrics.
 
static const FieldId POISSON_FACE_AJ_FIELDS [3] = {FIELD_ID_IAJ, FIELD_ID_JAJ, FIELD_ID_KAJ}
 

Detailed Description

Pressure-Poisson projection: operator, right-hand side, multigrid solve, pressure update, and velocity correction.

Grid layout. Cell-centred quantities live at DMDA indices 1..m-2 on each axis; indices 0 and m-1 are dummy layers that carry no unknown. On a periodic axis the interior wraps from m-2 to 1. The contravariant flux Ucont[k][j][i].x sits on the face between cells i and i+1, and likewise for the other two components.

Face gradient. The flux of grad(Phi) through the face between cell c and c + e_n is

sum_b g_nb D_b(Phi),   g_nb = (F_b . F_n) * aj_n,

where F_b are the contravariant base vectors stored on the n-faces, aj_n is the inverse Jacobian there, D_n is the difference across the face, and D_b (b != n) is the transverse difference chosen by PoissonOperator_TransverseDifference(). The operator assembles the divergence of this flux, and the projection subtracts it from Ucont, so the two are consistent by construction.

Definition in file poisson.c.


Data Structure Documentation

◆ PoissonFaceGradient

struct PoissonFaceGradient

Everything needed to evaluate the gradient flux through one face.

Definition at line 46 of file poisson.c.

Collaboration diagram for PoissonFaceGradient:
[legend]
Data Fields
PetscReal dot[3] F_b .

F_n on the face, b = 0..2.

PetscReal aj Inverse Jacobian on the face.
PoissonTransverseDifference diff[3] Transverse differences; diff[n] is unused.

Function Documentation

◆ PoissonOperator_At()

static PICURV_ALWAYS_INLINE PetscReal PoissonOperator_At ( const PetscReal ***  field,
const PetscInt  c[3],
const PetscInt  d[3] 
)
static

Value of a cell-centred array at cell c displaced by d.

Parameters
[in]fieldGhosted cell-centred array, indexed [k][j][i].
[in]cCell (i, j, k).
[in]dDisplacement (di, dj, dk).
Returns
The value at c + d.

Definition at line 60 of file poisson.c.

62{
63 return field[c[2] + d[2]][c[1] + d[1]][c[0] + d[0]];
64}
Here is the caller graph for this function:

◆ PoissonOperator_TransverseDifference()

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] 
)
static

The rows and weight of the transverse difference along axis t at the face between cell c and c + e_n, for operator assembly; PoissonOperator_TransverseKind() chooses.

Parameters
[in]nvertGhosted solid field.
[in]cCell on the low side of the face.
[in]nFace orientation (0, 1, 2 for i, j, k).
[in]tTransverse axis, not n.
[in]mGrid sizes (mx, my, mz).
[in]periodicWhether each axis is periodic.
Returns
The rows and weight of the difference.

Definition at line 78 of file poisson.c.

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}
PetscReal weight
0.25 central, 0.5 one-sided, 0 when no fluid side remains.
Definition poisson.h:41
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
PetscInt lo
Transverse offset of the subtracted row pair.
Definition poisson.h:39
Transverse difference used at one face.
Definition poisson.h:38
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonOperator_FaceGradientStencil()

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] 
)
static

Gathers the metric coefficients and transverse differences of the gradient flux through the face between cell c and c + e_n.

Parameters
[in]metricsFace metric arrays from PoissonOperator_GetFaceMetrics().
[in]nvertGhosted solid field.
[in]cCell on the low side of the face.
[in]nFace orientation (0, 1, 2 for i, j, k).
[in]mGrid sizes (mx, my, mz).
[in]periodicWhether each axis is periodic.
Returns
The face's metric products, inverse Jacobian and transverse differences.

Definition at line 105 of file poisson.c.

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}
PetscReal aj
Inverse Jacobian on the face.
Definition poisson.c:48
PoissonTransverseDifference diff[3]
Transverse differences; diff[n] is unused.
Definition poisson.c:49
PetscReal dot[3]
F_b .
Definition poisson.c:47
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
Everything needed to evaluate the gradient flux through one face.
Definition poisson.c:46
const PetscReal *** aj[3]
Definition poisson.h:47
const Cmpnts *** metric[3][3]
Definition poisson.h:46
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
PetscScalar y
Definition variables.h:145
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonOperator_StencilSlot()

static PetscInt PoissonOperator_StencilSlot ( const PetscInt  d[3])
static

Maps the 19 stencil offsets to their slots; corners of the 3x3x3 block are -1.

Definition at line 128 of file poisson.c.

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}
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
Here is the caller graph for this function:

◆ PoissonOperator_GetFaceMetrics()

PetscErrorCode PoissonOperator_GetFaceMetrics ( UserCtx *  user,
PoissonFaceMetrics *  metrics 
)

Implementation of PoissonOperator_GetFaceMetrics().

Borrows read access to the face metric arrays of user.

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

See also
PoissonOperator_GetFaceMetrics()

Definition at line 147 of file poisson.c.

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}
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
Non-owning runtime objects resolved for one field and UserCtx.
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static const FieldId POISSON_FACE_AJ_FIELDS[3]
Definition poisson.c:43
static const FieldId POISSON_FACE_METRIC_FIELDS[3][3]
Field IDs of the face metric vectors, indexed as PoissonFaceMetrics.
Definition poisson.c:38
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonOperator_RestoreFaceMetrics()

PetscErrorCode PoissonOperator_RestoreFaceMetrics ( UserCtx *  user,
PoissonFaceMetrics *  metrics 
)

Implementation of PoissonOperator_RestoreFaceMetrics().

Returns the arrays borrowed by PoissonOperator_GetFaceMetrics().

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

See also
PoissonOperator_RestoreFaceMetrics()

Definition at line 171 of file poisson.c.

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}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonOperator_NeighborIndex()

static PetscInt PoissonOperator_NeighborIndex ( PetscInt  v,
PetscInt  d,
PetscInt  m,
PetscBool  periodic 
)
inlinestatic

Index of the neighbour at offset d (-1, 0, +1) from v on an axis of m points, wrapping between the interior layers 1 and m-2 when periodic.

Definition at line 193 of file poisson.c.

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}
Here is the caller graph for this function:

◆ PoissonOperator_AddFaceFlux()

static void PoissonOperator_AddFaceFlux ( const PoissonFaceGradient *  face,
const PetscInt  own[3],
PetscInt  n,
PetscReal  sign,
PetscScalar  coefficients[19] 
)
static

Adds the signed gradient flux through one face to a row's stencil coefficients.

Parameters
[in]faceFace gradient from PoissonOperator_FaceGradientStencil().
[in]ownOffset of the face's lower cell from the row cell.
[in]nNormal axis of the face.
[in]sign+1 for the row's upper face on the axis, -1 for its lower face.
[in,out]coefficientsThe row's 19 coefficients.

Definition at line 209 of file poisson.c.

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}
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
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AssemblePoissonOperator()

PetscErrorCode AssemblePoissonOperator ( UserCtx *  user)

Implementation of AssemblePoissonOperator().

Assembles the pressure-correction operator on one multigrid level.

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

See also
AssemblePoissonOperator()

Definition at line 244 of file poisson.c.

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}
#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
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
PetscErrorCode PoissonOperator_RestoreFaceMetrics(UserCtx *user, PoissonFaceMetrics *metrics)
Implementation of PoissonOperator_RestoreFaceMetrics().
Definition poisson.c:171
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
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 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 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
#define POISSON_SOLID_THRESHOLD
Cells whose nvert exceeds this value are solid.
Definition poisson.h:29
Read-only face metric arrays: metric[n][b] is F_b on the n-faces.
Definition poisson.h:45
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
Vec lNvert
Definition variables.h:1197
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscInt thislevel
Definition variables.h:1269
DMDALocalInfo info
Definition variables.h:1169
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputePoissonRHS()

PetscErrorCode ComputePoissonRHS ( UserCtx *  user,
Vec  B 
)

Implementation of ComputePoissonRHS().

Forms the right-hand side of the pressure-correction equation.

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

See also
ComputePoissonRHS()

Definition at line 344 of file poisson.c.

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}
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscReal dt
Definition variables.h:933
Vec lUcont
Definition variables.h:1197
#define COEF_TIME_ACCURACY
Coefficient controlling the temporal accuracy scheme (e.g., 1.5 for 2nd Order Backward Difference).
Definition variables.h:96
The master context for the entire simulation.
Definition variables.h:916
Here is the caller graph for this function:

◆ UpdatePressure()

PetscErrorCode UpdatePressure ( UserCtx *  user)

Implementation of UpdatePressure().

Adds the pressure correction to the pressure, P += Phi, and refreshes both fields' periodic images and ghosts.

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

See also
UpdatePressure()

Definition at line 405 of file poisson.c.

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}
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_PHI
@ FIELD_ID_P
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProjectVelocity()

PetscErrorCode ProjectVelocity ( UserCtx *  user)

Implementation of ProjectVelocity().

Corrects the contravariant flux with the gradient of Phi.

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

See also
ProjectVelocity()

Definition at line 425 of file poisson.c.

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}
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.
@ FIELD_ID_UCONT
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
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
Vec Ucont
Definition variables.h:1197
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonMultigrid_RemoveNullSpace()

static PetscErrorCode PoissonMultigrid_RemoveNullSpace ( MatNullSpace  nullsp,
Vec  X,
void *  ctx 
)
static

Removes the null space of the Neumann pressure problem from a level vector.

PETSc first removes the global constant. This callback then subtracts the mean over the interior fluid cells and zeroes the dummy layers and solid cells, which carry no unknown.

Definition at line 496 of file poisson.c.

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}
#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
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonMultigrid_InterpolationParent()

static void PoissonMultigrid_InterpolationParent ( PetscInt  f,
PetscInt  m,
PetscInt  semi,
PetscInt *  coarse,
PetscInt *  direction 
)
static

Coarse cell and interpolation direction along one axis for fine index f.

Each fine cell takes 3/4 of its parent coarse cell and 1/4 of the coarse neighbour on the side it lies towards. The first and last interior cells and semi-coarsened axes use the parent only, as does a neighbour that is solid on the coarse grid.

Definition at line 561 of file poisson.c.

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}
Here is the caller graph for this function:

◆ PoissonMultigrid_Interpolate()

static PetscErrorCode PoissonMultigrid_Interpolate ( Mat  P,
Vec  X,
Vec  F 
)
static

Prolongs a coarse-level correction to the next finer level (MatShell multiply).

The shell context is the fine-level UserCtx.

Definition at line 578 of file poisson.c.

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}
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
PetscInt isc
Definition variables.h:1175
PetscInt ksc
Definition variables.h:1175
PetscInt jsc
Definition variables.h:1175
UserCtx * user_c
Definition variables.h:1270
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonMultigrid_Restrict()

static PetscErrorCode PoissonMultigrid_Restrict ( Mat  R,
Vec  X,
Vec  F 
)
static

Restricts a fine-level residual to the next coarser level (MatShell multiply).

Each coarse cell averages the eight fine cells it covers, weighting each by its fluid fraction; coarse dummy and solid cells receive zero. The shell context is the coarse-level UserCtx.

Definition at line 658 of file poisson.c.

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}
UserCtx * user_f
Definition variables.h:1270
Here is the caller graph for this function:

◆ PoissonMultigrid_ShiftBlockFactors()

static PetscErrorCode PoissonMultigrid_ShiftBlockFactors ( KSP  level_ksp)
static

Gives each block factor of a block-Jacobi level solver a small diagonal shift, so the factorization of a nearly singular Neumann block does not fail on a zero pivot.

Does nothing for any other preconditioner.

Definition at line 720 of file poisson.c.

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}
Here is the caller graph for this function:

◆ PoissonMultigrid_Build()

static PetscErrorCode PoissonMultigrid_Build ( UserMG *  usermg,
PetscInt  bi 
)
static

Builds the multigrid solver for block bi and stores it in the finest level.

Assembles the operator on every level, then configures the outer ps_ Krylov solver with a multiplicative V-cycle PCMG: shell restriction and interpolation between levels, block-Jacobi smoothers by default, a coarse solve limited to 40 iterations at relative tolerance 1e-8, and the Neumann null space on every level. PETSc options override these defaults.

Each smoother runs pre_sweeps iterations before the coarse correction and post_sweeps after it. When the two differ, the post-smoother is a separate solver that starts as a copy of the configured pre-smoother and reads further options under ps_mg_levels_N_up_. Everything built here depends only on the grid metrics, the solid field, and the boundary types; calling it again after one of those changes rebuilds the solver.

Definition at line 762 of file poisson.c.

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}
PetscErrorCode DualMonitorDestroy(void **ctx)
Destroys the DualMonitorCtx.
Definition logging.c:927
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
FILE * file_handle
Definition logging.h:57
PetscInt block_id
Definition logging.h:62
Context for a dual-purpose KSP monitor.
Definition logging.h:56
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
PetscErrorCode AssemblePoissonOperator(UserCtx *user)
Implementation of AssemblePoissonOperator().
Definition poisson.c:244
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
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
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
UserCtx * user
Definition variables.h:768
MatNullSpace nullsp
Definition variables.h:1228
PetscInt mg_poItr
Definition variables.h:961
PetscInt mglevels
Definition variables.h:775
MGCtx * mgctx
Definition variables.h:778
PetscInt mg_preItr
Definition variables.h:961
Context for Multigrid operations.
Definition variables.h:767
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonMultigrid_OpenConvergenceLog()

static PetscErrorCode PoissonMultigrid_OpenConvergenceLog ( KSP  ksp,
SimCtx *  simCtx,
PetscInt  bi 
)
static

Prepares the convergence monitor for one solve and opens its log file on rank 0.

A fresh run's first open, which may be the initial condition's projection at step 0, truncates the log; every later open appends, and a continued run's first open records where it resumed.

Definition at line 872 of file poisson.c.

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}
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
PetscBool log_to_console
Definition logging.h:58
PetscInt step
Definition logging.h:61
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
PetscMPIInt rank
Definition variables.h:919
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscInt step
Definition variables.h:924
PetscBool ps_ksp_pic_monitor_true_residual
Definition variables.h:976
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PoissonMultigrid_CloseConvergenceLog()

static PetscErrorCode PoissonMultigrid_CloseConvergenceLog ( KSP  ksp)
static

Closes the log file opened by PoissonMultigrid_OpenConvergenceLog().

Definition at line 901 of file poisson.c.

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}
Here is the caller graph for this function:

◆ PoissonSolver_Multigrid()

PetscErrorCode PoissonSolver_Multigrid ( UserMG *  usermg)

Implementation of PoissonSolver_Multigrid().

Solves the pressure-correction equation for every block with geometric multigrid.

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

See also
PoissonSolver_Multigrid()

Definition at line 922 of file poisson.c.

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}
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
static PetscErrorCode PoissonMultigrid_CloseConvergenceLog(KSP ksp)
Closes the log file opened by PoissonMultigrid_OpenConvergenceLog().
Definition poisson.c:901
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 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
PetscInt block_number
Definition variables.h:1009
Here is the call graph for this function:
Here is the caller graph for this function:

Variable Documentation

◆ POISSON_STENCIL_OFFSETS

const PetscInt POISSON_STENCIL_OFFSETS[19][3]
static
Initial value:
= {
{ 0, 0, 0},
{ 1, 0, 0}, {-1, 0, 0}, { 0, 1, 0}, { 0, -1, 0},
{ 0, 0, 1}, { 0, 0, -1},
{ 1, 1, 0}, { 1, -1, 0}, {-1, 1, 0}, {-1, -1, 0},
{ 0, 1, 1}, { 0, 1, -1}, { 0, -1, 1}, { 0, -1, -1},
{ 1, 0, 1}, { 1, 0, -1}, {-1, 0, 1}, {-1, 0, -1},
}

Offsets of the 19 stencil points, in the column order used to insert each row.

Definition at line 27 of file poisson.c.

27 {
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};

◆ POISSON_FACE_METRIC_FIELDS

const FieldId POISSON_FACE_METRIC_FIELDS[3][3]
static
Initial value:
= {
}
@ FIELD_ID_JETA
@ FIELD_ID_KETA
@ FIELD_ID_KZET
@ FIELD_ID_IETA
@ FIELD_ID_ICSI
@ FIELD_ID_JCSI
@ FIELD_ID_JZET
@ FIELD_ID_IZET
@ FIELD_ID_KCSI

Field IDs of the face metric vectors, indexed as PoissonFaceMetrics.

Definition at line 38 of file poisson.c.

◆ POISSON_FACE_AJ_FIELDS

const FieldId POISSON_FACE_AJ_FIELDS[3] = {FIELD_ID_IAJ, FIELD_ID_JAJ, FIELD_ID_KAJ}
static

Definition at line 43 of file poisson.c.

@ FIELD_ID_IAJ
@ FIELD_ID_JAJ
@ FIELD_ID_KAJ