flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_geometry.hpp
Go to the documentation of this file.
1
8#ifndef PECLET_FLOW_FLOW_IBM_GEOMETRY_HPP
9#define PECLET_FLOW_FLOW_IBM_GEOMETRY_HPP
10
11namespace peclet::flow {
12
13template <class Grid>
14void Solver<Grid>::setPressureGeometry(const std::vector<double>& sdfInner) {
15 setSolid(sdfInner, true);
16}
17
18template <class Grid>
19void Solver<Grid>::setSolid(const std::vector<double>& sdfInner, bool cutcellPressure) {
20 const std::size_t n = (std::size_t)nx_ * ny_ * nz_;
21 if (sdfInner.size() != n)
22 throw std::runtime_error("set_solid: expected nx*ny*nz values");
23 CCField din("peclet::flow::sdfInner_d", n);
24 using HostConst =
25 Kokkos::View<const double*, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>;
26 // The caller's SDF is a PHYSICAL signed distance sampled at cellCentres(); the solver's
27 // geometry lives on the unit lattice, where a distance is measured in cells. (Isotropic in
28 // Phase 1: one hRef divides all three axes. Anisotropic cells need the metric of Phase 2,
29 // because the level set's gradient then stops being the index-space normal.)
30 const double k = u_.lenToInt(); // exactly 1.0 in cell units
31 if (k != 1.0) {
32 std::vector<double> scaled(n);
33 for (std::size_t i = 0; i < n; ++i)
34 scaled[i] = sdfInner[i] * k;
35 Kokkos::deep_copy(din, HostConst(scaled.data(), n));
36 } else {
37 Kokkos::deep_copy(din, HostConst(sdfInner.data(), n));
38 }
39 setSolidDevice(din, cutcellPressure);
40}
41
42template <class Grid>
44 regDirty_ = true; // the full-stress regular-node masks follow the overlay (§5.4)
45 const bool useEx = hasExactCross_ && !Grid::collocated; // exact-theta arrays are for the
46 // staggered point placement
47 const mreal lam = (mreal)(wallSlip_ ? slipLambda_ : 0.0);
48 if (lam > 0.0f && slipSkipDev_.data() == nullptr)
49 slipSkipDev_ = Kokkos::View<int, CCMem>("peclet::flow::slipSkip");
50 for (int c = 0; c < 3; ++c) {
51 const Off3 off =
52 Grid::offset(c); // velocity-unknown placement (staggered: -1/2 face; collocated: 0)
53 C[c].nCut = buildIbmOverlay<0>(
54 CCConst(sdf_), e_, G, off, /*Dirichlet*/ 0, C[c].ov, C[c].idMap, C[c].counter,
55 useEx ? CCConst(tEx_[c][0]) : CCConst(), useEx ? CCConst(tEx_[c][1]) : CCConst(),
56 useEx ? CCConst(tEx_[c][2]) : CCConst(), C3{nx_, ny_, nz_}, lam, lam > 0.0f ? c : -1,
57 lam > 0.0f ? slipSkipDev_ : Kokkos::View<int, CCMem>(), // SCHEME 0 = point-value (matches
58 // CUDA ibm_geometry_ext_k<0>)
59 (mreal)u_.hp[0], (mreal)u_.hp[1], (mreal)u_.hp[2]); // §6.4 slip metric (trap 9)
60 if (lam > 0.0f) {
61 int sk = 0;
62 Kokkos::deep_copy(sk, slipSkipDev_);
63 slipSandwich_[(std::size_t)c] = sk;
64 } else {
65 slipSandwich_[(std::size_t)c] = 0;
66 }
67 ibmSolidMask(C[c].mask, CCConst(sdf_), e_, off);
68 // Gate 7: ibmSolidMask samples the sdf at the staggered offset through the CLAMPING
69 // sampler, so on the outermost ghost plane the mask can disagree with the neighbour's
70 // interior value. The moving-geometry advection fill reads the ghost mask (it decides
71 // which ghost rows carry the wall velocity), so take the owner's mask there. Static
72 // scenes never consume ghost masks: keep them byte-identical by gating on motion.
73 if (hasMotion_)
74 exchangeExtRaw(C[c].mask);
75 if (resetU)
76 Kokkos::deep_copy(C[c].u, 0.0);
77 }
78 if constexpr (Grid::collocated)
79 if (resetU) {
80 // The collocated MAC face field is NOT a registry field and nothing above rebuilds it, so
81 // zeroing the cell velocity here (setSolid is the initial-geometry setup) would otherwise
82 // leave `uf_` holding the PREVIOUS geometry's projected field while `u` is 0 -- a stale
83 // advecting velocity for `cadv` (ufAdvVelocity()) and a stale flux for the colour /
84 // scalar transport that also ride it. Drop it and say so: `faceFieldValid_ = false`
85 // sends momentum advection back to the cell->face average (of a zero field: the same
86 // zero) for one step, and makes `advect_vof`'s guard refuse instead of accepting a field
87 // that is only "solenoidal" because it is zero.
88 Kokkos::deep_copy(uf_, 0.0);
89 Kokkos::deep_copy(vf_, 0.0);
90 Kokkos::deep_copy(wf_, 0.0);
91 faceFieldValid_ = false;
92 }
93}
94
95template <class Grid>
97 if (!hasBc_)
98 return;
99 B3 e{e_.x, e_.y, e_.z};
100 for (int face = 0; face < 6; ++face) {
101 if (!touchesGlobalFace(face))
102 continue;
103 const int a = face / 2, s = face % 2;
104 if (bc_[face] == 4)
105 bcMirrorGhost(f, e, G, a, s); // symmetry plane: the mirror IS what the BC asserts
106 else if (bc_[face] != 0)
107 bcNeumannGhost(f, e, G, a, s); // wall / inflow / outflow: constant normal extension
108 }
109}
110
111template <class Grid>
112void Solver<Grid>::setSolidDevice(CCField din, bool cutcellPressure) {
113 // Every geometry path (set_solid, set_pressure_geometry, set_solid_from_scene, redistribute)
114 // lands here: the cut-cell scalar record is stale from now on (rebuilt lazily, §2.5).
116 pguessCount_ = 0; // E: a geometry / hierarchy rebuild (doc/vof_projection_cost_design.md §5.3)
117 cutcellPressure_ = cutcellPressure;
121 // set_solid changes eligibility (hasSolid_), so re-decide at the next step(),
122 // where dt/mu/rho are final. Deciding HERE would read a dt the caller has not set yet.
123 vmgDecided_ = false;
124 if (cutcellPressure_) {
129 }
130 // Rung V5a (WO-Q): the colour block's cut-cell geometry is derived from the openness and the
131 // SDF that were just rebuilt, so set_solid AFTER enable_vof must rebuild it — the same reason
132 // initMpi rebuilds the block. Inert (and byte-identical) when VoF is off.
133 if (vofEnabled_)
135 geometryBuilt_ = true;
136}
137
138template <class Grid>
140 if constexpr (Grid::collocated) {
141 // DEFAULT SWITCH (2026-08-25, user decision after the attractor campaign): the collocated
142 // scheme default is AUTO = the GHOST (fluid-only) projection — family-free, unconditionally
143 // stable, protocol-independent (doc/collocated_invisible_subspace.md; clean ladders both
144 // beds) — falling back to gauge-exact with a stderr notice on the configurations the ghost
145 // v1 does not support (porous / variable-rho / domain-BC / Chebyshev / analytic overrides).
146 // Any explicit scheme selection (set_collocated_scheme / set_face_interp /
147 // set_ghost_projection / set_fluid_only_constraint) disables AUTO.
148 if (colSchemeAuto_) {
149 const bool ok = !(porous_ || varRho_ || hasBc_ || useChebyshev_ || hasExactCross_ ||
150 hasOpenOverride_ || fluidOnlyMode_ != 0);
151 if (ok) {
152 ghostProjection_ = true;
153 gpMatrixOrder_ = 2;
154 gpRhsOrder_ = 2;
155 faceInterp_ = 0; // the ghost owns the operators the face-interp modes replace
156 gpNRows_ = -1;
157 } else {
158 if (ghostProjection_)
159 gpNRows_ = -1;
160 ghostProjection_ = false;
161 faceInterp_ = 9;
162 fprintf(stderr,
163 "peclet::flow SolverColocated: AUTO scheme fell back to gauge-exact "
164 "(configuration unsupported by the ghost projection v1). Select explicitly "
165 "with set_collocated_scheme to silence this notice.\n");
166 }
167 }
168 }
169}
170
171template <class Grid>
173#ifdef PECLET_FLOW_MPI
174 for (bool& d : momStencilDirty_) // stencil ring re-exchange for the CA momentum sweeps
175 d = true;
176#endif
177 // Does the geometry actually contain solid? (all-fluid set_pressure_geometry passes sd>0
178 // everywhere -> stays false, keeping the channel/BFS path.) Device reduction: din lives on
179 // device now, and pulling it back just to scan it would defeat the point.
180 {
181 const std::size_t nInner = (std::size_t)nx_ * ny_ * nz_;
182 int anySolid = 0;
183 CCConst dinC(din);
184 Kokkos::parallel_reduce(
185 "peclet::flow::has_solid", Kokkos::RangePolicy<CCExec>(0, nInner),
186 KOKKOS_LAMBDA(const std::size_t i, int& acc) { acc = acc || (dinC(i) < 0.0); }, anySolid);
187 hasSolid_ = anySolid != 0;
188 }
189#ifdef PECLET_FLOW_MPI
190 if (distributed_) { // a solid anywhere in the global domain enables the IBM momentum path
191 int local = hasSolid_ ? 1 : 0, global = 0;
192 MPI_Allreduce(&local, &global, 1, MPI_INT, MPI_MAX, comm_);
193 hasSolid_ = global != 0;
194 }
195#endif
196#ifdef PECLET_FLOW_MPI
197 if (distributed_) {
198 // Multi-rank: din is THIS rank's LOCAL inner block; fill the inner cells ON DEVICE, then
199 // halo-exchange the ghosts (cross-rank + periodic) so the overlay/openness read the
200 // neighbour's SDF at the block boundary. (Was a host mirror + triple loop + full H2D.)
201 CCExec space;
202 const int ex = e_.x, ey = e_.y, nx = nx_, ny = ny_, nz = nz_, g = G;
203 CCField sdf = sdf_;
204 CCConst dinC(din);
205 Kokkos::parallel_for(
206 "peclet::flow::sdf_fill_inner", MDRange3<CCExec>(space, {0, 0, 0}, {nx, ny, nz}),
207 KOKKOS_LAMBDA(int x, int y, int z) {
208 sdf((long)(x + g) + (long)(y + g) * ex + (long)(z + g) * (long)ex * ey) =
209 dinC((std::size_t)x + (std::size_t)y * nx + (std::size_t)z * (std::size_t)nx * ny);
210 });
211 space.fence();
212 velDev_->exchange(sdf_);
213 } else
214#endif
215 {
216 // Single-rank: periodic-wrap gather on device (G4) — fills the whole extended block
217 // (inner + periodic ghosts) in one kernel. `din` is already device-resident.
218 CCExec space;
219 const int ex = e_.x, ey = e_.y, ez = e_.z, nx = nx_, ny = ny_, nz = nz_, g = G;
220 CCField sdf = sdf_;
221 Kokkos::parallel_for(
222 "peclet::flow::sdf_periodic_wrap", MDRange3<CCExec>(space, {0, 0, 0}, {ex, ey, ez}),
223 KOKKOS_LAMBDA(int x, int y, int z) {
224 const int ix = (((x - g) % nx) + nx) % nx, iy = (((y - g) % ny) + ny) % ny,
225 iz = (((z - g) % nz) + nz) % nz;
226 sdf((long)x + (long)y * ex + (long)z * (long)ex * ey) =
227 din((std::size_t)ix + (std::size_t)iy * nx + (std::size_t)iz * (std::size_t)nx * ny);
228 });
229 space.fence();
230 }
231}
232
233template <class Grid>
235 // NON-PERIODIC domain faces: the periodic/halo fill above wrapped the OPPOSITE side of the
236 // domain into the ghost band, so the geometry a boundary face sees is teleported from the far
237 // side. On a FREE-SLIP face (type 4) that made a far wall a phantom solid ON the symmetry plane
238 // (measured: a half Poiseuille channel closed by a type-4 face read u ~ 0 there) and the mirror
239 // is what the BC asserts. On a WALL / INFLOW / OUTFLOW face (types 1/2/3) the same wrap decides
240 // the BOUNDARY-FACE APERTURE, because `ccFaceOpen` samples the SDF AT the face, i.e. halfway
241 // between the last inner cell and that ghost: a solid cell against an inflow plane was handed
242 // the far side's fluid and came out as a fully OPEN face, so the prescribed inflow velocity was
243 // pushed into a cell whose pressure row is entirely closed -- an inconsistent row, and the
244 // iteration cap and max|div| = U of SCALING_ISSUES #3 (doc/cutcell_openbc_convergence.md).
245 // The constant normal extension is the geometric reading of "the domain plane cuts the solid":
246 // the solid continues straight out, so the boundary face's aperture is the fluid fraction of the
247 // boundary plane itself. Rank-owned faces only (touchesGlobalFace); a bed clear of the open
248 // faces is byte-identical either way (the aperture is 1 whichever value the ghost carries).
250 buildVelocityOverlays(/*resetU=*/true);
251 // MOVING GEOMETRY (rung 2): the wall-velocity fields must exist BEFORE the momentum operator
252 // is assembled -- rebuildStencils folds them into the inhomogeneous term. sdf_ and its ghosts
253 // are final at this point, which is what the central-difference normals read.
256 // Staggered domain BCs bake an implicit-diffusion wall fold; the collocated grid instead uses
257 // explicit reflection ghosts (refreshed each smoother sweep), so it needs no fold.
258 if (hasBc_ && !Grid::collocated)
260}
261
262template <class Grid>
264 // WHICH MOMENTUM SOLVER, and the criterion is the PHYSICS, not the configuration. Decided
265 // 2026-09-15; it replaces two earlier rules, both of which keyed on the wrong thing:
266 // * 1.0.0: red-black by default, V-cycle only BELOW 65536 cells/rank and only at np > 1 --
267 // the sign of the block-size effect was backwards (the V-cycle's margin is LARGEST on big
268 // blocks: 2.23x at 147k cells/rank, 2.19x on one H100 at 56.6 M).
269 // * the same day, briefly: V-cycle always, for any configuration carrying a solid -- which
270 // made the solver depend on whether an immersed body happened to be present, even though
271 // IBM is also just a way of sculpting geometry and the momentum equation is the same one
272 // either way.
273 //
274 // The momentum operator is a screened Helmholtz whose condition number is a property of the
275 // TIMESTEP, not of the mesh or the geometry:
276 // kappa = lambda_max / lambda_min = 1 + 4 dt mu (w_x + w_y + w_z) / rho,
277 // which is 1 + 12 D on an isotropic grid in the diffusion number D = mu dt / (rho h^2), and
278 // stays correct on an anisotropic one because it reads the metric. A smoother removes error at
279 // a rate set by kappa, so it needs O(kappa) sweeps; the V-cycle does not.
280 //
281 // Measured crossover (96^3 and 64^3, channel with domain BCs and no solid, and the 384^3
282 // cut-cell bed): below kappa ~ 13 the smoother converges in a few tens of sweeps and the
283 // V-cycle's hierarchy is pure overhead (0.86x at D = 0.25); above it the V-cycle pulls away
284 // (1.88x at D = 4) and -- the reason this is a correctness threshold and not a tuning one --
285 // red-black stops MEETING ITS TOLERANCE, hitting velIters_ and returning a residual of 6.8e-08
286 // at D = 6 and 7.7e-06 at D = 12 against a 1e-10 target.
287 //
288 // The rule therefore names no geometry at all. It declines only for cause: an explicit
289 // set_velocity_multigrid() always wins; an operator mode the velocity MG is not validated for;
290 // and a per-rank block too short to coarsen, where the V-cycle degenerates to its bottom
291 // smoother and only adds setup.
292 if (vmgExplicit_ || vmgAutoCells_ == 0)
293 return;
294 const bool eligible = !varProps_ && !varRho_ && !hasDrag_ && !porous_ && !Grid::collocated &&
295 (!hasBc_ || hasSolid_ || !implicitFou_);
296 // Gershgorin condition number of the implicit-diffusion operator, from the metric the solver
297 // will actually use. dt, mu and rho are final here: the decision is taken at the head of the
298 // first step(), never at set_solid time, precisely so that a set_dt() after set_solid cannot
299 // leave the choice stale.
300 const double kappa =
301 1.0 + 4.0 * dt_ * mu_ * (u_.w[0] + u_.w[1] + u_.w[2]) / (rho_ > 0.0 ? rho_ : 1.0);
302 int minExt = std::min({e_.x - 2 * G, e_.y - 2 * G, e_.z - 2 * G});
303 // Serial (or a non-MPI build): the local block IS the global grid.
304 double global = (double)(e_.x - 2 * G) * (e_.y - 2 * G) * (e_.z - 2 * G);
305 double perRank = global;
306#ifdef PECLET_FLOW_MPI
307 if (distributed_) {
308 int np = 1, g = minExt;
309 MPI_Comm_size(comm_, &np);
310 MPI_Allreduce(&minExt, &g, 1, MPI_INT, MPI_MIN, comm_);
311 minExt = g;
312 global = (double)gnx_ * gny_ * gnz_;
313 perRank = global / (double)np;
314 }
315#endif
316 useVelocityMg_ = eligible && kappa >= vmgAutoMinCond_ && minExt >= vmgAutoMinExtent_ &&
317 global >= (double)vmgAutoMinGlobal_ && perRank < (double)vmgAutoCells_;
318 if (useVelocityMg_) {
319 vmgLevels_ = 3;
320 vmgVcycles_ = 40;
321 }
322}
323
324template <class Grid>
326 // Nothing here needs the solid: the hierarchy is a property of the grid, the metric and the
327 // boundary conditions. It lived under set_solid only because that was the one caller, which is
328 // why enabling the velocity MG on a configuration WITHOUT an immersed solid used to build no
329 // levels and segfault on the first solve (pre-existing; fixed 2026-09-15).
330 if (useVelocityMg_ &&
331 vmg_.levels() == 0) { // velocity-MG hierarchy: IBM (staircase/upwind), domain-BC
332 // (const-coeff) or mixed (staircase + folds) mode
333 // The per-axis metric BEFORE the hierarchy is built (doc/anisotropic_metric.md trap 5):
334 // every level's b_a^L = mu' * w_a / cfac_a^2, and C3's aspect-ratio level rule reads it too.
335 vmg_.setMetric(u_.w, u_.hp);
336#ifdef PECLET_FLOW_MPI
337 // Distributed: level 0 on the solver's own decomposition (the g=2 velocity block), coarse
338 // levels coarsened in place with the even-block gate (no telescoping here yet -- measured
339 // first, see docs/SCALING_ISSUES.md issue 5).
340 if (distributed_)
341 vmg_.initMpi(*dec_, vmgLevels_, comm_);
342 else
343#endif
344 vmg_.init(nx_, ny_, nz_, vmgLevels_);
345 if (hasBc_)
346 vmg_.setBC(bc_);
347 if (!hasBc_ || hasSolid_) { // the staircase (IBM / mixed) paths classify by volume fraction
348 vmgTheta_ = CCField("vmgTheta", n_);
349 vmgClean_ = CCField("vmgClean", n_);
350 }
351 }
352}
353
354template <class Grid>
356 // Phase 2 C2 (doc/anisotropic_metric.md §4.5, trap 7): buildOpenness has taken dx,dy,dz
357 // all along and was handed 1.0 — `ccFractionCore` (the order-1 aperture model) forms the
358 // gradient (s+ - s-)/(2 dx) and the face extent |n_b| dy + |n_c| dz on the index lattice, so
359 // the right metric is h_a' (the marching-squares path, order 2, ignores them).
360 buildOpenness(ox_, oy_, oz_, CCConst(sdf_), e_, u_.hp[0], u_.hp[1], u_.hp[2],
361 apertureOrder_); // on the g=2 velocity block
362 if (hasOpenOverride_) {
363 // Analytic-SDF exact apertures (setOpennessOverride): overwrite the sampled-SDF openness
364 // with the user-provided inner fields + periodic wrap into the ghost ring (single-rank).
365 const std::vector<double>* src[3] = {&oxOverride_, &oyOverride_, &ozOverride_};
366 CCField dst[3] = {ox_, oy_, oz_};
367 for (int f = 0; f < 3; ++f) {
368 CCField din("peclet::flow::openOv_d", (std::size_t)nx_ * ny_ * nz_);
369 Kokkos::deep_copy(
370 din,
371 Kokkos::View<const double*, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>(
372 src[f]->data(), src[f]->size()));
373 CCExec space;
374 const int ex = e_.x, ey = e_.y, ez = e_.z, nx = nx_, ny = ny_, nz = nz_, g = G;
375 CCField o = dst[f];
376 Kokkos::parallel_for(
377 "peclet::flow::open_override_wrap", MDRange3<CCExec>(space, {0, 0, 0}, {ex, ey, ez}),
378 KOKKOS_LAMBDA(int x, int y, int z) {
379 const int ix = (((x - g) % nx) + nx) % nx, iy = (((y - g) % ny) + ny) % ny,
380 iz = (((z - g) % nz) + nz) % nz;
381 o((long)x + (long)y * ex + (long)z * (long)ex * ey) = din(
382 (std::size_t)ix + (std::size_t)iy * nx + (std::size_t)iz * (std::size_t)nx * ny);
383 });
384 space.fence();
385 }
386 }
387 if constexpr (Grid::collocated) { // static open-centroid wall distances (wall-aware map)
388 buildFaceCentroidDist(xcx_, xcy_, xcz_, CCConst(sdf_), e_);
389 buildCellFraction(cs_, CCConst(sdf_), e_, G); // cell fluid fraction (embed)
390 if (faceInterp_ >= 5 && faceInterp_ <= 7) { // EMBED: a solid-CENTRED cut cell (cs>0) is
391 // partially fluid and holds
392 // its reconstructed near-wall velocity — masking it to 0 (the sdf<0 IBM mask) drops the
393 // near-wall closure and shifts the whole channel. Re-mask from cs: pin ONLY fully-solid
394 // cells (cs≈0), keeping every partial-fluid cut cell live in the embed solve +
395 // projection.
396 CCConst cs = CCConst(cs_);
397 const std::size_t nn = n_;
398 for (int c = 0; c < 3; ++c) {
399 CCField m = C[c].mask;
400 Kokkos::parallel_for(
401 "peclet::flow::embed_solid_mask", Kokkos::RangePolicy<CCExec>(0, nn),
402 KOKKOS_LAMBDA(std::size_t i) { m(i) = cs(i) < 1e-6 ? 1.0 : 0.0; });
403 }
404 }
405 }
406 if (fluidOnlyMode_ == 1) {
407 // Mode-14a FLUID-ONLY constraint (setFluidOnlyConstraint): close every face with a
408 // solid-CENTERED side in the openness the pressure stack consumes. The aperture operator,
409 // the divergence, the face correction and the MG rediscretization all read these fields,
410 // so one filter makes constraint/operator/correction consistent by construction: pressure
411 // DOFs decouple at solid-centered cells (their rows go empty like solid cells), the
412 // invisible multiplier subspace of collocated_invisible_subspace.md S4 ceases to exist,
413 // and the operator stays SPD + 7-point (CG + CutcellMG untouched). Closure quality is
414 // Neumann-zero at the closed faces (the crude end of the fluid-only family -- measured,
415 // not assumed); the consistent-closure variants ride on the gp row machinery instead.
416 CCConst sd = CCConst(sdf_);
417 CCField oa[3] = {ox_, oy_, oz_};
418 C3 e = e_;
419 for (int a = 0; a < 3; ++a) {
420 CCField o = oa[a];
421 const long sa = (a == 0) ? 1 : (a == 1) ? (long)e.x : (long)e.x * e.y;
422 Kokkos::parallel_for(
423 "peclet::flow::fluid_only_openness",
424 MDRange3<CCExec>(CCExec(), {1, 1, 1}, {e.x, e.y, e.z}),
425 KOKKOS_LAMBDA(int x, int y, int z) {
426 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
427 if (sd(i) < 0.0 || sd(i - sa) < 0.0)
428 o(i) = 0.0;
429 });
430 }
431 }
432#ifdef PECLET_FLOW_MPI
433 // openness ghosts (the operator + divergence read the +neighbour face) -> exchange across
434 // ranks
435 if (distributed_) {
436 velDev_->exchange(ox_);
437 velDev_->exchange(oy_);
438 velDev_->exchange(oz_);
439 // SCALING_ISSUES #3: the HIGH domain face of each axis sits at a GHOST index, so the exchange
440 // just overwrote it with the periodic wrap of the opposite boundary -- on a rank owning that
441 // global face, another boundary's aperture. Re-derive it from the SDF. (The LOW face is an
442 // inner index and survives.) Invisible until this fix, because the Dirichlet row overwrote the
443 // value with the literal 1.0, and a bed clear of the open faces wraps 1.0 onto 1.0 anyway.
444 CCField oa[3] = {ox_, oy_, oz_};
445 for (int a = 0; a < 3; ++a)
446 if (bc_[2 * a + 1] != 0 && touchesGlobalFace(2 * a + 1))
447 buildOpennessHighFace(oa[a], CCConst(sdf_), e_, G, a, u_.hp[0], u_.hp[1], u_.hp[2],
448 apertureOrder_);
449 }
450#endif
451 if (hasBc_) { // FLUX openness (beta): a face is OPEN only where it carries normal flux --
452 // outflow, or
453 B3 e2{e_.x, e_.y, e_.z};
454 CCField oa[3] = {ox_, oy_, oz_}; // an inflow with nonzero normal velocity. Walls
455 for (int a = 0; a < 3; ++a)
456 for (int s = 0; s < 2; ++s) { // and tangential-only Dirichlet faces (e.g. a
457 const int t = bc_[2 * a + s]; // lid: type 2 with zero normal vel) are CLOSED.
458 const bool open = (t == 3) || (t == 2 && (bcProf_[2 * a + s].extent(0) > 0 ||
459 std::fabs(bcVel_[2 * a + s][a]) > 1e-12));
460 if (t != 0 && !open && touchesGlobalFace(2 * a + s))
461 bcZeroOpenness(oa[a], e2, G, a, s); // rank-owned global face only
462 }
463 } // the MG re-derives the OPERATOR openness alpha (inflow Neumann -> closed) per level via
464 // setBC.
465 if (hasBc_)
467 copyInner(ox1_, e1_, 1, CCConst(ox_), e_, G); // bridge openness g=2 -> g=1 for the MG
468 copyInner(oy1_, e1_, 1, CCConst(oy_), e_, G);
469 copyInner(oz1_, e1_, 1, CCConst(oz_), e_, G);
470}
471
472// The two sides of an axis are ASYMMETRIC in the face-index convention (mac_cutcell_mg.hpp): the
473// LOW domain face is the INNER index that `copyInner` above already wrote, the HIGH one is the
474// first GHOST index, which no kernel writes and the MG's periodic fill wraps over. At a Dirichlet
475// OUTFLOW face the MG now carries the true cut-cell aperture instead of the literal 1.0 (the WO-R2
476// item 1 save/restore/coarsen machinery, generalized from the variable-density coefficient to the
477// openness itself), so the g=1 bridge has to carry that plane across too.
478template <class Grid>
480 if (!hasOutflow_)
481 return;
482 const bool gp = ghostProjection_ && oxb_.extent(0) > 0; // the MG rails carry the BINARY
483 CCField dst[3] = {ox1_, oy1_, oz1_}; // openness in ghost mode
484 CCField src[3] = {gp ? oxb_ : ox_, gp ? oyb_ : oy_, gp ? ozb_ : oz_};
485 const int de[3] = {e1_.x, e1_.y, e1_.z}, se[3] = {e_.x, e_.y, e_.z};
486 const long dst3[3] = {1, (long)e1_.x, (long)e1_.x * e1_.y};
487 const long sst3[3] = {1, (long)e_.x, (long)e_.x * e_.y};
488 for (int a = 0; a < 3; ++a) {
489 if (bc_[2 * a + 1] != 3 || !touchesGlobalFace(2 * a + 1))
490 continue;
491 const int b = (a + 1) % 3, c = (a + 2) % 3;
492 const long dsa = dst3[a], dsb = dst3[b], dsc = dst3[c];
493 const long ssa = sst3[a], ssb = sst3[b], ssc = sst3[c];
494 const long dbf = de[a] - 1, sbf = se[a] - G; // the high boundary face on each block
495 const int nb = de[b] - 2, nc = de[c] - 2; // inner extent of the g=1 block
496 CCField d = dst[a];
497 CCConst sv = CCConst(src[a]);
498 Kokkos::parallel_for(
499 "peclet::flow::bridge_outflow_plane", MDRange2<CCExec>(CCExec(), {0, 0}, {nb, nc}),
500 KOKKOS_LAMBDA(int p0, int p1) {
501 d((long)(p0 + 1) * dsb + (long)(p1 + 1) * dsc + dbf * dsa) =
502 sv((long)(p0 + G) * ssb + (long)(p1 + G) * ssc + sbf * ssa);
503 });
504 }
505}
506
507// SCALING_ISSUES #3, the configuration the fix does NOT make solvable. A cell whose pressure row
508// is entirely closed (every one of its six OPERATOR apertures is 0) but which a prescribed inflow
509// face still feeds is an INCONSISTENT row: the row says "nothing may leave this cell", the
510// constraint says "this much enters", and no pressure satisfies both. MG-PCG cannot converge — it
511// runs to its iteration cap with max|div| stuck at exactly the prescribed influx — so the
512// geometry, not the solver, has to be rejected. It means a pocket of fluid that the solid seals
513// off from the rest of the domain and that opens only onto the inlet, which is a physically
514// impossible thing to ask of an incompressible fluid whatever the discretization.
515//
516// Before the ghost-extension fix above this fired on ordinary geometry, because a SOLID cell
517// against the inlet was handed a fully open inflow face by the periodic wrap. It now takes a
518// genuinely sealed pocket.
519template <class Grid>
521 const int dims[3] = {e_.x, e_.y, e_.z};
522 const long st[3] = {1, (long)e_.x, (long)e_.x * e_.y};
523 int bct[6];
524 int own[6];
525 for (int f = 0; f < 6; ++f) {
526 bct[f] = bc_[f];
527 own[f] = touchesGlobalFace(f) ? 1 : 0;
528 }
529 long sealedOn[6] = {0, 0, 0, 0, 0, 0};
530 for (int a = 0; a < 3; ++a)
531 for (int s = 0; s < 2; ++s) {
532 if (bct[2 * a + s] != 2 || !own[2 * a + s])
533 continue;
534 const int b = (a + 1) % 3, c = (a + 2) % 3;
535 const long sa = st[a], sb = st[b], sc = st[c];
536 const long base = (long)((s == 0) ? G : dims[a] - G - 1) * sa;
537 const long inflowFace = (s == 0) ? 0 : sa;
538 const int nb = dims[b] - 2 * G, nc = dims[c] - 2 * G;
539 CCConst oc[3] = {CCConst(ox_), CCConst(oy_), CCConst(oz_)};
540 const int dd[3] = {dims[0], dims[1], dims[2]};
541 const long ss[3] = {st[0], st[1], st[2]};
542 const int cA = a, cB = b, cC = c, cS = s;
543 long sealed = 0;
544 Kokkos::parallel_reduce(
545 "peclet::flow::sealed_inflow", MDRange2<CCExec>(CCExec(), {0, 0}, {nb, nc}),
546 KOKKOS_LAMBDA(int pb, int pc, long& acc) {
547 const long i = base + (long)(pb + G) * sb + (long)(pc + G) * sc;
548 if (oc[cA](i + inflowFace) <= 0.0)
549 return; // the inflow face carries no flux into this cell
550 int idx[3]; // the cell's index along each axis: a global face is an extreme one
551 idx[cA] = (cS == 0) ? G : (dd[cA] - G - 1);
552 idx[cB] = pb + G;
553 idx[cC] = pc + G;
554 double alpha = 0.0;
555 for (int a2 = 0; a2 < 3; ++a2)
556 for (int s2 = 0; s2 < 2; ++s2) {
557 const bool global = own[2 * a2 + s2] != 0 &&
558 ((s2 == 0) ? (idx[a2] == G) : (idx[a2] == dd[a2] - G - 1));
559 const int t = bct[2 * a2 + s2];
560 if (global && (t == 1 || t == 2 || t == 4))
561 continue; // Neumann domain face: the operator closes it whatever the aperture
562 alpha += oc[a2](i + ((s2 == 0) ? 0 : ss[a2]));
563 }
564 if (alpha <= 0.0)
565 ++acc;
566 },
567 sealed);
568 sealedOn[2 * a + s] = sealed;
569 }
570#ifdef PECLET_FLOW_MPI
571 if (distributed_) { // ONE reduction for all six faces: set_solid is per-step on moving geometry
572 long g[6];
573 MPI_Allreduce(sealedOn, g, 6, MPI_LONG, MPI_SUM, comm_);
574 for (int f = 0; f < 6; ++f)
575 sealedOn[f] = g[f];
576 }
577#endif
578 for (int f = 0; f < 6; ++f) {
579 if (sealedOn[f] == 0)
580 continue;
581 static const char* kFace[6] = {"-x", "+x", "-y", "+y", "-z", "+z"};
582 throw std::runtime_error(
583 std::string("set_solid: the immersed solid seals ") + std::to_string(sealedOn[f]) +
584 " fluid cell(s) against the " + kFace[f] +
585 " INFLOW face off from the rest of the domain: their pressure row is entirely closed "
586 "yet the inflow still feeds them, which no pressure field can satisfy (the pressure "
587 "solve would run to its iteration cap with max|div| stuck at the inflow velocity). "
588 "Either pull the solid clear of that face, refine the grid so the pocket connects, or "
589 "make the face a wall. See doc/cutcell_openbc_convergence.md.");
590 }
591}
592
593template <class Grid>
595 if (fluidOnlyMode_ == 2) {
596 // Design B: the MG hierarchy is built from the FILTERED openness (Design A's operator,
597 // the symmetric surrogate preconditioner + the 7-point part of the true operator); the
598 // geometric ox_/oy_/oz_ stay ORIGINAL for the divergence and the face correction. Filter
599 // the g=1 bridge in place, then build the star overlay from the original apertures.
600 if (porous_ || varRho_ || hasBc_ || ghostProjection_ || distributed_ || !Grid::collocated)
601 throw std::runtime_error(
602 "set_fluid_only_constraint(2): v1 is single-rank periodic collocated only");
603 CCExec space;
604 CCConst sd = CCConst(sdf_);
605 CCField oa1[3] = {ox1_, oy1_, oz1_};
606 const C3 e1 = e1_, e2 = e_;
607 for (int a = 0; a < 3; ++a) {
608 CCField o1 = oa1[a];
609 const long sa2 = (a == 0) ? 1 : (a == 1) ? (long)e2.x : (long)e2.x * e2.y;
610 Kokkos::parallel_for(
611 "peclet::flow::star_filter_bridge", MDRange3<CCExec>(space, {0, 0, 0}, {nx_, ny_, nz_}),
612 KOKKOS_LAMBDA(int x, int y, int z) {
613 const long i2 =
614 (long)(x + G) + (long)(y + G) * e2.x + (long)(z + G) * (long)e2.x * e2.y;
615 if (sd(i2) < 0.0 || sd(i2 - sa2) < 0.0)
616 o1((long)(x + 1) + (long)(y + 1) * e1.x + (long)(z + 1) * (long)e1.x * e1.y) = 0.0;
617 });
618 }
619 space.fence();
620 starCounter_ = Kokkos::View<int, CCMem>("star_counter");
621 const C3 nn{nx_, ny_, nz_};
622 nStar_ = buildStarOverlay(CCConst(sdf_), CCConst(ox_), CCConst(oy_), CCConst(oz_), e_, G, nn,
623 StarOverlay{}, starCounter_);
624 starOv_ = starMakeOverlay(std::max(nStar_, 1));
625 buildStarOverlay(CCConst(sdf_), CCConst(ox_), CCConst(oy_), CCConst(oz_), e_, G, nn, starOv_,
626 starCounter_);
627 }
628}
629
630// Ghost-projection fragmentation guard (setSolidGhostProjectionOverlay): BFS over the COUPLED
631// graph of the periodic nx*ny*nz sdf `work`; fluid cells outside the largest component are
632// marked solid in place (pockets decoupled for the projection only).
633inline void gpDecouplePockets(std::vector<double>& work, int nx, int ny, int nz, bool verbose) {
634 const std::size_t nTot = work.size();
635 auto id = [&](int x, int y, int z) {
636 return (std::size_t)((x + nx) % nx) + (std::size_t)((y + ny) % ny) * nx +
637 (std::size_t)((z + nz) % nz) * (std::size_t)nx * ny;
638 };
639 std::vector<int> comp(nTot, -1);
640 std::vector<std::size_t> stack;
641 int ncomp = 0, mainComp = -1;
642 std::size_t mainSize = 0, nActive = 0;
643 for (std::size_t seed = 0; seed < nTot; ++seed) {
644 if (comp[seed] >= 0 || work[seed] < 0.0)
645 continue;
646 std::size_t size = 0;
647 comp[seed] = ncomp;
648 stack.assign(1, seed);
649 while (!stack.empty()) {
650 const std::size_t c = stack.back();
651 stack.pop_back();
652 ++size;
653 const int x = (int)(c % nx), y = (int)((c / nx) % ny), z = (int)(c / ((std::size_t)nx * ny));
654 const int nb[6][3] = {{x - 1, y, z}, {x + 1, y, z}, {x, y - 1, z},
655 {x, y + 1, z}, {x, y, z - 1}, {x, y, z + 1}};
656 for (auto& q : nb) {
657 const std::size_t j = id(q[0], q[1], q[2]);
658 if (comp[j] >= 0 || work[j] < 0.0)
659 continue;
660 // COUPLED face: mean-of-centers face sdf fluid AND both centers fluid
661 if (0.5 * (work[c] + work[j]) < 0.0)
662 continue;
663 comp[j] = ncomp;
664 stack.push_back(j);
665 }
666 }
667 if (size > mainSize) {
668 mainSize = size;
669 mainComp = ncomp;
670 }
671 nActive += size;
672 ++ncomp;
673 }
674 if (ncomp > 1) {
675 std::size_t pockets = 0;
676 for (std::size_t i = 0; i < nTot; ++i)
677 if (work[i] >= 0.0 && comp[i] != mainComp) {
678 work[i] = -(std::abs(work[i]) * 1.001 + 1e-30);
679 ++pockets;
680 }
681 if (verbose)
682 printf(
683 "peclet::flow ghost projection: %d fluid components; decoupled %zu pocket "
684 "cells outside the main component (%zu of %zu fluid cells)\n",
685 ncomp, pockets, mainSize, nActive);
686 }
687}
688
689template <class Grid>
690std::vector<double> Solver<Grid>::gpPocketGuardSdf(CCField din) {
691 // A few setup paths below (the ghost-projection pocket decoupling) are host-side
692 // connected-component analyses and genuinely need the inner SDF on the host. Materialise it
693 // ONCE, lazily, so the common path keeps the device-resident benefit.
694 std::vector<double> sdfInnerHost_;
695 auto sdfInner_ = [&]() -> const std::vector<double>& {
696 if (sdfInnerHost_.empty()) {
697 const std::size_t nI = (std::size_t)nx_ * ny_ * nz_;
698 sdfInnerHost_.resize(nI);
699 Kokkos::deep_copy(
700 Kokkos::View<double*, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>(
701 sdfInnerHost_.data(), nI),
702 din);
703 }
704 return sdfInnerHost_;
705 };
706 std::vector<double> sdfGpHost;
707 std::vector<double> work;
708 int fx = nx_, fy = ny_, fz = nz_;
709 bool verbose = true;
710#ifdef PECLET_FLOW_MPI
711 int myRank = 0;
712 if (distributed_) {
713 MPI_Comm_rank(comm_, &myRank);
714 int nRanks = 1;
715 MPI_Comm_size(comm_, &nRanks);
716 fx = gnx_;
717 fy = gny_;
718 fz = gnz_;
719 verbose = myRank == 0;
720 std::vector<int> cnts(nRanks), disp(nRanks);
721 long acc = 0;
722 for (int r = 0; r < nRanks; ++r) {
723 const auto b = dec_->block(r);
724 cnts[r] = (int)(b.size[0] * b.size[1] * b.size[2]);
725 disp[r] = (int)acc;
726 acc += cnts[r];
727 }
728 std::vector<double> flat((std::size_t)acc);
729 MPI_Allgatherv(sdfInner_().data(), (int)sdfInner_().size(), MPI_DOUBLE, flat.data(),
730 cnts.data(), disp.data(), MPI_DOUBLE, comm_);
731 work.assign((std::size_t)fx * fy * fz, 0.0);
732 for (int r = 0; r < nRanks; ++r) {
733 const auto b = dec_->block(r);
734 const double* src = flat.data() + disp[r];
735 for (int z = 0; z < (int)b.size[2]; ++z)
736 for (int y = 0; y < (int)b.size[1]; ++y)
737 for (int x = 0; x < (int)b.size[0]; ++x)
738 work[(std::size_t)(x + b.origin[0]) + (std::size_t)(y + b.origin[1]) * fx +
739 (std::size_t)(z + b.origin[2]) * (std::size_t)fx * fy] =
740 src[(std::size_t)x + (std::size_t)y * b.size[0] +
741 (std::size_t)z * (std::size_t)b.size[0] * b.size[1]];
742 }
743 } else
744#endif
745 work = sdfInner_();
746 gpDecouplePockets(work, fx, fy, fz, verbose);
747#ifdef PECLET_FLOW_MPI
748 if (distributed_) {
749 const auto b = dec_->block(myRank);
750 sdfGpHost.resize(sdfInner_().size());
751 for (int z = 0; z < nz_; ++z)
752 for (int y = 0; y < ny_; ++y)
753 for (int x = 0; x < nx_; ++x)
754 sdfGpHost[(std::size_t)x + (std::size_t)y * nx_ +
755 (std::size_t)z * (std::size_t)nx_ * ny_] =
756 work[(std::size_t)(x + b.origin[0]) + (std::size_t)(y + b.origin[1]) * fx +
757 (std::size_t)(z + b.origin[2]) * (std::size_t)fx * fy];
758 } else
759#endif
760 sdfGpHost = std::move(work);
761 return sdfGpHost;
762}
763
764template <class Grid>
765void Solver<Grid>::gpUploadSdf(const std::vector<double>& sdfGpHost, std::size_t nInner,
766 CCField sdfGp) {
767#ifdef PECLET_FLOW_MPI
768 if (distributed_) {
769 // local inner block + halo exchange (cross-rank + periodic), same as the sdf_ upload:
770 // the overlay build reads sdfGp ghosts up to +/-2 = G across block boundaries.
771 auto h = Kokkos::create_mirror_view(sdfGp_);
772 Kokkos::deep_copy(h, sdfGp_);
773 for (int z = 0; z < nz_; ++z)
774 for (int y = 0; y < ny_; ++y)
775 for (int x = 0; x < nx_; ++x)
776 h((long)(x + G) + (long)(y + G) * e_.x + (long)(z + G) * (long)e_.x * e_.y) =
777 sdfGpHost[(std::size_t)x + (std::size_t)y * nx_ +
778 (std::size_t)z * (std::size_t)nx_ * ny_];
779 Kokkos::deep_copy(sdfGp_, h);
780 velDev_->exchange(sdfGp_);
781 } else
782#endif
783 { // upload + periodic wrap (same pattern as the sdf upload above)
784 CCField din("peclet::flow::sdfGpInner_d", nInner);
785 Kokkos::deep_copy(
786 din,
787 Kokkos::View<const double*, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>(
788 sdfGpHost.data(), sdfGpHost.size()));
789 CCExec space;
790 const int ex = e_.x, ey = e_.y, ez = e_.z, nx = nx_, ny = ny_, nz = nz_, g = G;
791 Kokkos::parallel_for(
792 "peclet::flow::sdfgp_wrap", MDRange3<CCExec>(space, {0, 0, 0}, {ex, ey, ez}),
793 KOKKOS_LAMBDA(int x, int y, int z) {
794 const int ix = (((x - g) % nx) + nx) % nx, iy = (((y - g) % ny) + ny) % ny,
795 iz = (((z - g) % nz) + nz) % nz;
796 sdfGp((long)x + (long)y * ex + (long)z * (long)ex * ey) =
797 din((std::size_t)ix + (std::size_t)iy * nx + (std::size_t)iz * (std::size_t)nx * ny);
798 });
799 space.fence();
800 }
801}
802
803template <class Grid>
804void Solver<Grid>::gpBuildOverlay(CCField sdfGp) {
805 gpBinaryOpenness(oxb_, oyb_, ozb_, CCConst(sdfGp), e_);
806 gpNRows_ =
807 buildGpOverlay(CCConst(sdfGp), e_, G, C3{nx_, ny_, nz_}, gpOv_, gpIdMap_, gpCounter_,
808 gpMatrixOrder_, gpRhsOrder_, hasExactCross_ ? CCConst(tEx_[0][0]) : CCConst(),
809 hasExactCross_ ? CCConst(tEx_[1][1]) : CCConst(),
810 hasExactCross_ ? CCConst(tEx_[2][2]) : CCConst(),
811 /*useGhost=*/distributed_);
812 if (gpDebugLevel() > 0) { // PECLET_FLOW_GP_DEBUG row forensics (analysis only)
813 int gpDbgRank = 0;
814#ifdef PECLET_FLOW_MPI
815 if (distributed_)
816 MPI_Comm_rank(comm_, &gpDbgRank);
817#endif
818 gpDebugReport(gpOv_, gpNRows_, C3{nx_, ny_, nz_}, gpIdMap_, gpDbgRank);
819 }
820 copyInner(ox1_, e1_, 1, CCConst(oxb_), e_, G); // MG surrogate = binary openness
821 copyInner(oy1_, e1_, 1, CCConst(oyb_), e_, G);
822 copyInner(oz1_, e1_, 1, CCConst(ozb_), e_, G);
823}
824
825template <class Grid>
827 if (ghostProjection_) {
828 // Directional ghost-cell projection: build the closure overlay + the binary (COUPLED)
829 // openness. The binary field replaces the geometric openness on the MG rails (the MG
830 // hierarchy becomes the symmetric surrogate preconditioner; the overlay delta enters only
831 // the fine-level BiCGStab matvec). The geometric ox_/oy_/oz_ above stay for diagnostics.
832 if (porous_ || varRho_ || hasBc_)
833 throw std::runtime_error(
834 "ghost projection: incompatible with porous/variable-rho/domain-BC (v1)");
835 const std::size_t nInner = (std::size_t)nx_ * ny_ * nz_;
836 gpOv_ = gpMakeOverlay<MReal>((long)nInner); // worst-case sizing, like the momentum overlay
837 gpIdMap_ = Kokkos::View<int*, CCMem>("gp_idmap", nInner);
838 gpCounter_ = Kokkos::View<int, CCMem>("gp_counter");
839 oxb_ = CCField("oxb", n_);
840 oyb_ = CCField("oyb", n_);
841 ozb_ = CCField("ozb", n_);
842 gpRh_ = CCField("gpRh", n1_);
843 gpT_ = CCField("gpT", n1_);
844 gpZ2_ = CCField("gpZ2", n1_);
845 if (distributed_)
846 gpX2_ = CCField("gpXg2", n_); // g=2 staging block for the distributed BiCGStab matvec
847 // Fragmentation guard: the binary COUPLED-face condition is stricter than aperture
848 // connectivity, so tight-throat geometries (e.g. a random close packing with touching
849 // spheres) fragment the fluid graph into a main component + tiny pockets at the
850 // contacts. Each pocket adds its own null vector that the single global mean-removal
851 // cannot handle, and BiCGStab breaks down (measured: fields to ~1e152 on the RCP
852 // example). Host BFS over the coupled graph of the INNER sdf; fluid cells outside the
853 // largest component are treated as SOLID for the PROJECTION ONLY (sdfGp), decoupling
854 // their rows; the momentum step keeps the true sdf.
855 // Distributed: connectivity is a GLOBAL property (a pocket can span rank boundaries) and
856 // every rank must agree on the main component, so allgather the inner sdf, run the
857 // deterministic guard on the global grid identically on every rank, and keep this
858 // rank's block of the result.
859 const std::vector<double> sdfGpHost = gpPocketGuardSdf(din);
860 sdfGp_ = CCField("peclet::flow::sdfGp", n_);
861 CCField sdfGp = sdfGp_; // the projection's sdf view (pockets decoupled); persisted for
862 // the collocated gpCenterGrad predictor/correction
863 gpUploadSdf(sdfGpHost, nInner, sdfGp);
864 gpBuildOverlay(sdfGp);
865 }
866}
867
868template <class Grid>
870 bridgeOutflowFacePlanes(); // after every writer of the g=1 openness rails (ghost-mode surrogate
871 // included), before the hierarchy reads them
872 mg_.setBoundaryConditions(bc_); // per-level wall openness + null-space gating (no-op if
873 // periodic); BEFORE initMpi — the per-level ghost width
874 // (CA smoothing) is chosen for the periodic operator only
875 // Phase 2 C3 (doc/anisotropic_metric.md §5, trap 5): the per-axis spacings BEFORE the level
876 // table is built — the aspect-ratio rule defers an axis that is already theta times coarser
877 // than the finest coarsenable one. Exactly (1,1,1) on the isotropic path, where the rule
878 // returns today's decision verbatim.
879 mg_.setMetric(u_.hp);
880 // Coarse-solve policy: an explicit set_pressure_graph_amg(True) forces agglomeration,
881 // otherwise the mode set by set_pressure_bottom (default auto) decides. BEFORE the hierarchy:
882 // the AUTO depth reads it (doc/mg_depth_policy.md §4.2); it only assigns the mode.
883 mg_.setAgglomerationMode(pressGraphAmg_ ? 1 : pressAgglomMode_);
884#ifdef PECLET_FLOW_MPI
885 if (distributed_) { // share the level-0 decomposition so the MG block matches this rank's
886 // block; a weighted one (rebalanceByWeights) gets Repartition stages
887 mg_.setRepartition(weightedDec_);
888 mg_.initMpi(gnx_, gny_, gnz_, nLevels_, comm_, dec_.get());
889 } else
890#endif
891 mg_.init(nx_, ny_, nz_,
892 nLevels_); // geometric multigrid on the cut-cell openness (MG-PCG pressure)
893 bfpChebSet_ =
894 false; // a new hierarchy: the balanced-force pre-projection re-estimates its bounds
895 // Phase 2 C2 (doc/anisotropic_metric.md §1.3/§3): the per-axis pressure weight
896 // w_a = 1/h_a'^2 IS `setOpenness`'s idx2/idy2/idz2 (the coarse levels already form
897 // w_a/cfac_a^2). Exactly 1.0 on the isotropic path.
898 // SCALING_ISSUES #3: a Dirichlet (outflow) domain face row carries the face's own cut-cell
899 // APERTURE, not the literal openness 1.0. With a solid cutting the outlet the two differ, and
900 // the operator then solved a different constraint from the one the divergence imposes: the
901 // projection pushed flux through a face that carries none (measured max|div| 1.5e-2 against
902 // 4.7e-4 for the same bed pulled clear). `set_outflow_operator_coefficient(False)` is the
903 // ablation back to the literal 1.0; a bed clear of the open faces is byte-identical either way.
904 mg_.setOutflowCoefficient(hasOutflow_ && outflowOpCoeff_);
905 mg_.setOpenness(CCConst(ox1_), CCConst(oy1_), CCConst(oz1_), u_.w[0], u_.w[1], u_.w[2]);
906 Kokkos::deep_copy(phi_, 0.0);
907 Kokkos::deep_copy(P_, 0.0);
908}
909
910template <class Grid>
912 return geometryBuilt_;
913}
914
915template <class Grid>
916void Solver<Grid>::requireNoGeometry(const char* who) const {
917 if (geometryBuilt_)
918 throw std::runtime_error(
919 std::string(who) +
920 ": call BEFORE the geometry (set_solid / set_pressure_geometry / set_solid_from_scene) "
921 "-- this setting is folded into the operators when the geometry is built, so a later "
922 "call would be silently ignored");
923}
924
925} // namespace peclet::flow
926
927#endif // PECLET_FLOW_FLOW_IBM_GEOMETRY_HPP
void setSolidUploadSdf(CCField din)
void extendSdfDomainGhosts(CCField f)
Repair a cell-centred geometry field's ghost band on every rank-owned NON-PERIODIC domain face,...
void setSolid(const std::vector< double > &sdfInner, bool cutcellPressure)
Host entry point: upload the inner SDF once and delegate.
void bridgeOutflowFacePlanes()
Bridge the HIGH-side boundary-face openness plane of every rank-owned outflow axis from the g=2 block...
void copyInner(CCField dst, C3 de, int dg, CCConst src, C3 se, int sg)
void requireNoGeometry(const char *who) const
void exchangeExtRaw(CCField f)
Raw ghost fill of an extended-block field: the rank halo exchange under MPI, the periodic wrap single...
void setSolidGhostProjectionOverlay(CCField din)
void buildVelocityOverlays(bool resetU)
Build the three per-component Robust-Scaled cut-cell overlays + solid masks from the CURRENT sdf_ (ex...
void setPressureGeometry(const std::vector< double > &sdfInner)
static constexpr int G
Definition flow_ibm.hpp:82
void setSolidDevice(CCField din, bool cutcellPressure)
Device entry point (Layer 2): the inner SDF is ALREADY on device, so geometry never round-trips throu...
void gpUploadSdf(const std::vector< double > &sdfGpHost, std::size_t nInner, CCField sdfGp)
void checkSealedInflowCells()
Reject geometry that seals fluid cells against a prescribed INFLOW face off from the rest of the doma...
y
Definition cmp.py:24
dict fx
Definition mgd_case.py:457
Kokkos::DefaultExecutionSpace CCExec
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 3, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange3
3-D range, x (the first index) fastest (both the tile order and the order within a tile).
Definition policy.hpp:36
void buildFaceCentroidDist(CCField xcx, CCField xcy, CCField xcz, CCConst sdf, C3 e)
void ibmSolidMask(CCField mask, CCConst sdf, C3 ext, Off3 off)
Definition mac_ibm.hpp:249
void gpBinaryOpenness(CCField ox, CCField oy, CCField oz, CCConst sdf, C3 ext)
Binary openness for the symmetric MG surrogate, on the extended-block layout of buildOpenness: o(face...
Kokkos::View< const double *, CCMem > CCConst
StarOverlay starMakeOverlay(long n)
void buildCellFraction(CCField cs, CCConst sdf, C3 e, int g)
void bcZeroOpenness(BField oa, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:504
GpOverlayReal< Real > gpMakeOverlay(long n)
int buildStarOverlay(CCConst sdf, CCConst ox, CCConst oy, CCConst oz, C3 ext, int g, C3 nn, const StarOverlay &ov, Kokkos::View< int, CCMem > counter)
Count + fill the star overlay from the cell-centered sdf and the ORIGINAL (unfiltered) apertures on t...
int gpDebugLevel()
0 = off (default). Read once per call; cheap enough, and keeps the flag hot-swappable in tests.
MReal mreal
Definition mac_ibm.hpp:24
void buildOpennessHighFace(CCField oa, CCConst sdf, C3 ext, int g, int a, double dx, double dy, double dz, int order=1)
int buildGpOverlay(CCConst sdf, C3 ext, int g, C3 nn, const GpOverlayReal< Real > &ov, Kokkos::View< int *, CCMem > idMap, Kokkos::View< int, CCMem > counter, int matrixOrder=2, int rhsOrder=2, CCConst tx=CCConst(), CCConst ty=CCConst(), CCConst tz=CCConst(), bool useGhost=false)
Build the overlay over the inner grid nn from the cell-centered sdf on the extended block (ext,...
Kokkos::View< double *, CCMem > CCField
void bcMirrorGhost(BField f, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:169
int buildIbmOverlay(CCConst sdf, C3 ext, int g, Off3 off, int bc_type, const IbmOverlay &ov, Kokkos::View< int *, CCMem > idMap, Kokkos::View< int, CCMem > counter, CCConst tx=CCConst(), CCConst ty=CCConst(), CCConst tz=CCConst(), C3 nn=C3{0, 0, 0}, mreal slipLambda=mreal(0), int comp=-1, Kokkos::View< int, CCMem > sandwichSkipped=Kokkos::View< int, CCMem >(), mreal hpx=mreal(1), mreal hpy=mreal(1), mreal hpz=mreal(1))
slipLambda (WO-V6b, in CELLS, 0 = the validated no-slip closure) + comp (which velocity component thi...
Definition mac_ibm.hpp:88
void gpDecouplePockets(std::vector< double > &work, int nx, int ny, int nz, bool verbose)
void gpDebugReport(const GpOverlayReal< Real > &ov, int nRows, C3 nn, Kokkos::View< int *, CCMem > idMap, int rank=0)
Census + optional per-row dump of the built overlay.
void buildOpenness(CCField ox, CCField oy, CCField oz, CCConst sdf, C3 ext, double dx, double dy, double dz, int order=1)
void bcNeumannGhost(BField f, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:265
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 2, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange2
2-D range, first index fastest (both the tile order and the order within a tile).
Definition policy.hpp:31
One entry per eliminated solid-centered cell: packed INNER flat index + the apertures of its (up to 6...
Kokkos::View< const double *, CCMem > CCConst
Kokkos::View< double *, CCMem > CCField
static constexpr int G