flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_closures.hpp
Go to the documentation of this file.
1
8#ifndef PECLET_FLOW_FLOW_IBM_CLOSURES_HPP
9#define PECLET_FLOW_FLOW_IBM_CLOSURES_HPP
10
11namespace peclet::flow {
12
13template <class Grid>
15 fillGhosts(f);
16 for (int face = 0; face < 6; ++face)
17 if (bc_[face] != 0 && touchesGlobalFace(face))
18 applyScalarBcFace(f, face / 2, face % 2, 1, 0.0, edges); // type 1 = Neumann copy
19 vofBcPropGhosts(f); // WO-R item 5; a no-op unless a VoF inflow colour is set
20}
21
22template <class Grid>
24 // edges: the staggered cross-face viscosity reads mu at i - s_c +- s_a, a diagonal ghost at a
25 // wall row -- which must be the zero-gradient copy, not the opposite wall's periodic wrap.
26 fillPropGhosts(muField_, /*edges=*/true);
27}
28
29template <class Grid>
31 if (!hasCellForce_)
32 return;
33 for (int c = 0; c < 3; ++c)
34 fillPropGhosts(cellForce_[c]);
35}
36
37template <class Grid>
39 if (!hasDrag_)
40 return;
41 fillPropGhosts(dragBeta_);
42}
43
44template <class Grid>
46 fillGhosts(epsField_);
47 for (int face = 0; face < 6; ++face) {
48 const int t = bc_[face];
49 if (t == 0 || !touchesGlobalFace(face))
50 continue; // rank-owned faces only (see fillPropGhosts)
51 if (t == 2 || t == 3)
52 applyScalarBcFace(epsField_, face / 2, face % 2, 2, 1.0); // open face: face eps == 1
53 else
54 applyScalarBcFace(epsField_, face / 2, face % 2, 1, 0.0); // wall: zero-gradient
55 }
56}
57
58template <class Grid>
60 return varRho_ || (porous_ && porousCons_);
61}
62
63template <class Grid>
65 return varRho_ ? rhoField_ : epsRho_;
66}
67
68template <class Grid>
70 CCExec space;
71 CCField er = epsRho_;
72 CCConst ep = CCConst(epsField_);
73 const double rho = rho_;
74 Kokkos::parallel_for(
75 "peclet::flow::eps_rho", Kokkos::RangePolicy<CCExec>(space, 0, n_),
76 KOKKOS_LAMBDA(std::size_t i) { er(i) = ep(i) * rho; });
77}
78
79template <class Grid>
81 VarFaceProps fp;
82 fp.haveMu = varProps_;
83 if (varProps_) {
84 fp.mu = CCConst(muField_);
85 fp.msc = Grid::collocated ? 0 : strideOf(c); // mu on the staggered unknown's own faces
86 } else
87 fp.muC = mu_;
88 fp.harmMu = harmonicMu_;
89 fp.haveRho = effVarRho();
90 if (effVarRho()) {
91 fp.rho = CCConst(effRhoField());
92 fp.idt = 1.0 / dt_;
93 // Placement of the velocity unknown: the staggered unknown sits on the -c FACE, so its time
94 // diagonal is the arithmetic face mean of rho; the COLLOCATED unknown sits at the cell CENTRE
95 // (Grid::offset == 0), so it is rho(i) itself — which is what stride 0 gives,
96 // 0.5*(rho(i)+rho(i)) == rho(i) exactly in floating point. Inert until rung V8: `haveRho` was
97 // unreachable on the collocated grid (set_density_mode and set_porous_continuity both threw).
98 fp.sc = Grid::collocated ? 0 : strideOf(c);
99 } else
100 fp.rhoIdtC = rho_ / dt_;
101 return fp;
102}
103
104template <class Grid>
105void Solver<Grid>::setViscousStress(const std::string& form) {
106 if (form == "auto") {
107 viscousStressAuto_ = true;
108 fullStress_ = false;
109 return;
110 }
111 if (form == "laplacian") {
112 viscousStressAuto_ = false;
113 fullStress_ = false;
114 fullStressAuto_ = false;
115 return;
116 }
117 if (form != "full")
118 throw std::invalid_argument(
119 "set_viscous_stress: form must be 'auto', 'full' or 'laplacian', got '" + form + "'");
120 if constexpr (Grid::collocated)
121 throw std::runtime_error(
122 "SolverColocated.set_viscous_stress('full'): the full viscous stress is staggered-only in "
123 "v1 (doc/full_viscous_stress.md §9); use peclet.flow.Solver");
124 viscousStressAuto_ = false;
125 fullStressAuto_ = false;
126 fullStress_ = true;
127}
128
129template <class Grid>
131 return (fullStress_ || fullStressAuto_) && varProps_ && !Grid::collocated;
132}
133
134template <class Grid>
136 // WO-7 (doc/full_viscous_stress.md §12): AUTO = full on the staggered grid when mu is variable,
137 // arithmetic, not porous, not moving and free of immersed solids (review B1: the regular-node
138 // rule drops the transpose flux across the STAIRCASE face, not the wall -- an O(gamma h)
139 // near-wall error on oblique walls that does not scale with the mu variation; the repair is
140 // open); otherwise laplacian with a one-time stderr notice. A constant mu has nothing to resolve
141 // (the two forms coincide). Re-decided every step: the flags it reads are final at the step head,
142 // as for the explicit "full" refusals.
143 fullStressAuto_ = false;
144 if (!varProps_)
145 return;
146 const char* why = nullptr;
147 if constexpr (Grid::collocated)
148 why = "the collocated grid (staggered-only in v1, §9)";
149 else if (harmonicMu_)
150 why = "the harmonic face viscosity";
151 else if (porous_)
152 why = "porous (eps-weighted) momentum";
153 else if (hasMotion_)
154 why = "moving scene instances";
155 else if (hasSolid_)
156 why =
157 "an immersed solid (the staircase drops the transpose flux, an O(gamma h) near-wall error "
158 "on oblique walls; repair open)";
159 if (why == nullptr) {
160 fullStressAuto_ = true;
161 return;
162 }
163 if (!fullStressAutoNotice_) {
164 fullStressAutoNotice_ = true;
165 fprintf(stderr,
166 "peclet::flow %s: AUTO viscous stress fell back to the Laplacian form div(mu grad u) "
167 "(%s is outside the full stress's v1 scope, doc/full_viscous_stress.md §5.6). Select "
168 "explicitly with set_viscous_stress to silence this notice.\n",
169 Grid::collocated ? "SolverColocated" : "Solver", why);
170 }
171}
172
173template <class Grid>
174void Solver<Grid>::requireFullStressScope(const char* who) const {
175 const auto refuse = [&](const char* why) {
176 throw std::runtime_error(std::string(who) + ": set_viscous_stress('full') " + why +
177 " (doc/full_viscous_stress.md §5.6); call "
178 "set_viscous_stress('laplacian') for this configuration");
179 };
180 if (harmonicMu_)
181 refuse(
182 "does not support the harmonic face viscosity (the series direction is "
183 "component-dependent and breaks the symmetry of the transpose term)");
184 if (porous_)
185 refuse(
186 "does not support porous (eps-weighted) momentum: the eps-weighted stress is a "
187 "different equation");
188 if (hasMotion_)
189 refuse(
190 "does not support moving scene instances (the regular-node masks would have to follow "
191 "them)");
192}
193
194template <class Grid>
196 // 1. mu ghosts: rebuildStencils() filled them unless this is the implicit-FOU path (which fills
197 // them later, in buildAdvStencilVar -- after the uniformity test below would read them).
198 if (implicitAdv())
199 fillMuGhosts();
200 // 2. The exact GLOBAL uniformity test over the inner cells plus the ring T reads: T is either the
201 // complete conservative term or nothing (§4.4 (C)). One reduction + host read per step.
202 double lo = 0.0, hi = 0.0;
203 muRangeInner(CCConst(muField_), e_, G, lo, hi);
204#ifdef PECLET_FLOW_MPI
205 if (distributed_) {
206 double g[2] = {lo, -hi}, r[2];
207 MPI_Allreduce(g, r, 2, MPI_DOUBLE, MPI_MIN, comm_);
208 lo = r[0];
209 hi = -r[1];
210 }
211#endif
212 muUniform_ = (lo == hi);
213 if (muUniform_)
214 return;
215 // 3. The u^n ghosts incl. the (a, c) edges, written into old_ only (C[c].u is untouched);
216 // doOutflow = false keeps the projected outflow face, faceEdges its transverse ghost ring
217 // (the edge T reads at the last inner row; distributed only, review S1).
218 for (int c = 0; c < 3; ++c)
219 fillVelGhostsTo(old_[c], c, 0, /*doOutflow=*/false, /*faceEdges=*/true);
220 // 4. The regular-node masks of a static solid geometry, rebuilt after every geometry build.
221 if (hasSolid_ && regDirty_)
223}
224
225template <class Grid>
227 CCExec space;
228 const std::size_t n = (std::size_t)n_;
229 // A transient double carrier for the ghost exchange (the halo is GridHalo<double>); freed on
230 // return, so the persistent cost is the three uint8 masks.
231 CCField tmp(
232 Kokkos::view_alloc(space, "peclet::flow::full_stress_reg_tmp", Kokkos::WithoutInitializing),
233 n);
234 for (int c = 0; c < 3; ++c) {
235 if (fsReg_[c].extent(0) != n)
236 fsReg_[c] = RegMask(
237 Kokkos::view_alloc(space, "peclet::flow::full_stress_reg", Kokkos::WithoutInitializing),
238 n);
239 CCConst m = CCConst(C[c].mask);
240 Kokkos::parallel_for(
241 "peclet::flow::full_stress_reg_mask", Kokkos::RangePolicy<CCExec>(space, 0, n),
242 KOKKOS_LAMBDA(std::size_t i) { tmp(i) = (m(i) == 0.0) ? 1.0 : 0.0; });
243 const auto ov = C[c].ov;
244 Kokkos::parallel_for(
245 "peclet::flow::full_stress_reg_cut", Kokkos::RangePolicy<CCExec>(space, 0, C[c].nCut),
246 KOKKOS_LAMBDA(int k) { tmp(ov.cell_index(k)) = 0.0; });
247 fillPropGhosts(tmp, /*edges=*/true);
248 RegMask r = fsReg_[c];
249 Kokkos::parallel_for(
250 "peclet::flow::full_stress_reg_pack", Kokkos::RangePolicy<CCExec>(space, 0, n),
251 KOKKOS_LAMBDA(std::size_t i) { r(i) = (tmp(i) != 0.0) ? 1 : 0; });
252 }
253 space.fence(); // tmp is released on return
254 regDirty_ = false;
255}
256
257template <class Grid>
259 // §5.5: the low-face node of component c on a non-periodic global c-face is BC-imposed data.
260 const bool skipLo = bc_[2 * c] != 0 && touchesGlobalFace(2 * c);
261 const CCConst v[3] = {CCConst(old_[0]), CCConst(old_[1]), CCConst(old_[2])};
262 if (sharpActive_) { // the band transpose with the row's own face mu, then the band terms
263 addFullStressRhs<vof::SharpFaceProps, false>(c, C[c].b, CCConst(C[c].rscale), v,
265 G, u_.w[c], skipLo);
266 const CCConst t[3] = {CCConst(svTau_[0]), CCConst(svTau_[1]), CCConst(svTau_[2])};
267 vof::addSharpViscousRhs(c, C[c].b, CCConst(C[c].rscale), v, sharpGeom_, t, CCConst(svDnn_), G,
268 u_.w[c], skipLo, svRhsList_, svRhsN_);
269 return;
270 }
271 if (hasSolid_) {
272 const RegConst reg[3] = {fsReg_[0], fsReg_[1], fsReg_[2]};
273 addFullStressRhs<VarFaceProps, true>(c, C[c].b, CCConst(C[c].rscale), v, makeFaceProps(c), e_,
274 G, u_.w[c], skipLo, reg);
275 } else {
276 addFullStressRhs<VarFaceProps, false>(c, C[c].b, CCConst(C[c].rscale), v, makeFaceProps(c), e_,
277 G, u_.w[c], skipLo);
278 }
279}
280
281template <class Grid>
283 CCExec space;
284 C3 e = e_;
285 CCField dv = divAdv_;
286 CCConst U = CCConst(C[0].u), V = CCConst(C[1].u), W = CCConst(C[2].u);
287 using MD = MDRange3<CCExec>;
288 Kokkos::parallel_for(
289 "peclet::flow::div_adv",
290 MD(space, {G - 1, G - 1, G - 1}, {e.x - G + 1, e.y - G + 1, e.z - G + 1}),
291 KOKKOS_LAMBDA(int x, int y, int z) {
292 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
293 const long i = (long)x + (long)y * sy + (long)z * sz;
294 dv(i) = (U(i + sx) - U(i)) + (V(i + sy) - V(i)) + (W(i + sz) - W(i));
295 });
296}
297
298template <class Grid>
299void Solver<Grid>::setPropertyModel(const std::string& target, ClosureKind kind,
300 const std::string& in0, const std::string& in1,
301 const std::vector<double>& params) {
302 if (target == "mu" && vmgExplicit_ && useVelocityMg_) // before anything is registered
303 throwVelocityMgVariableMu("set_property_model('mu', ...)");
304 Closure cl;
305 cl.kind = kind;
306 cl.out = ensureTarget(target);
307 cl.in0 = CCConst(fields_.at(in0).data);
308 if (!in1.empty())
309 cl.in1 = CCConst(fields_.at(in1).data);
310 cl.outName = target; // kept so a redistribute can re-resolve the handles (rebindFieldAliases)
311 cl.in0Name = in0;
312 cl.in1Name = in1;
313 // UNITS. A closure writes a registered field, and registered fields carry the solver's
314 // INTERNAL units. Its inputs are UNSCALED fields (a phase fraction, a temperature, a
315 // concentration — the solver never rescales a transported scalar), so the output's dimension
316 // sits in the parameters, and on a target of known dimension the ones carrying it convert by
317 // that target's factor: all of LinearMix's (`out = p0 + p1*in0 + p2*in1`, which is what makes
318 // set_property_model("rho", "linear", "C", [rho_gas, rho_liquid - rho_gas]) take PHYSICAL
319 // densities), Boussinesq's rho0 (`out = rho0*g*beta*(T - T0)` into force_a), Arrhenius' mu_ref.
320 // The physical values are kept, so a scale pinned later re-derives them. Exactly the identity
321 // in cell units.
322 for (int k = 0; k < 4 && k < (int)params.size(); ++k)
323 cl.pPhys[k] = params[k];
324 closureUnitsNotice(target);
326 closures_.push_back(cl);
327 if (target == "mu") // a closure driving mu turns on variable viscosity
328 setPropertyMode(true, harmonicMu_);
329 if (target == "rho") // a closure driving rho turns on the variable-density path
330 setDensityMode(true);
331}
332
333template <class Grid>
334void Solver<Grid>::setDensityMode(bool variable) {
335 if (variable)
336 collocatedV8AutoFallback("variable density on the collocated grid");
337 varRho_ = variable;
338 if (variable) {
339 if (fields_.has("rho"))
340 rhoField_ = fields_.at("rho").data;
341 else {
342 rhoField_ = addField("rho");
343 Kokkos::deep_copy(rhoField_, rho_);
344 }
345 if (rho1_.extent(0) == 0) { // g=1 MG-block scratch for the projection coefficients
346 rho1_ = CCField("rho1", n1_);
347 cx1_ = CCField("cx1", n1_);
348 cy1_ = CCField("cy1", n1_);
349 cz1_ = CCField("cz1", n1_);
350 }
351 ensureCellForceAll(); // buildRhsVar reads the per-cell force (zero until a closure sets it)
352 useVelocityMg_ = false; // scalar-coefficient velocity MG (variable-coeff deferred)
353 // Pressure driver: CHEBYSHEV by default under variable density — but NOT for the reason this
354 // comment used to give ("MG-PCG stalls on the rho-scaled coefficient operator"), which WO-B
355 // refuted: the stall it described is a DOMAIN-BC defect at constant density, repaired by
356 // WO-H (CutcellMG::applyNeumannGhost), and on the periodic pore-scale operator MG-PCG beats
357 // Chebyshev ~10x at density ratio 1e4. The reason that survives measurement is narrower and
358 // real: at a high density CONTRAST the arithmetic coarsening of the face coefficient makes
359 // the V-cycle preconditioner INDEFINITE (measured on a dense sym(M): a negative pivot from
360 // ratio ~1e3), and no Krylov CG survives that, while Chebyshev — which needs only real
361 // spectrum bounds, re-estimated on every coefficient rebuild — is healthy on every
362 // configuration measured. Coefficient-aware coarsening (VOF_PLAN S3) is what would lift it.
363 // An explicit set_pressure_pcg/_fcg/_chebyshev AFTER set_density_mode still wins (last set),
364 // and since WO-H set_pressure_pcg's `on` flag genuinely honours that promise.
365 useChebyshev_ = true;
366 chebBoundsSet_ = false;
367 chebWarmOk_ = false;
368 bfpChebSet_ = false;
369 }
370 registerBalancedForceState(); // V8 turns the balanced-force projection on by default
371}
372
373template <class Grid>
375 return cutcellPressure_;
376}
377
378template <class Grid>
380 if constexpr (Grid::collocated) {
381 if (on)
382 throw std::runtime_error("set_porous_continuity: staggered-only (v1)");
383 }
384 porous_ = on;
385 if (on) {
386 if (fields_.has("eps"))
387 epsField_ = fields_.at("eps").data;
388 else {
389 epsField_ = addField("eps");
390 Kokkos::deep_copy(epsField_, 1.0); // no particles -> eps=1 -> reduces to div(u)=0
391 }
392 if (epsPrev_.extent(0) == 0) {
393 epsPrev_ = CCField("epsPrev", n_);
394 depsdt_ = CCField("depsdt", n_);
395 }
396 if (divAdv_.extent(0) == 0)
397 divAdv_ = CCField("divAdv", n_); // cell div(u) for the porous advection-form compensation
398 if (epsRho_.extent(0) == 0)
399 epsRho_ = CCField("epsRho", n_); // rho_eff = eps*rho (eps-conservative momentum)
400 // The eps-conservative momentum path (porousCons_) routes through buildRhsVar, which reads
401 // the per-cell force unconditionally — allocate it (zero) like setDensityMode does. Without
402 // this a porous run with NO drag/closure (never the coupled case, which enables drag and
403 // thereby the force fields) dereferences an empty device View.
404 ensureCellForceAll();
405 Kokkos::deep_copy(epsPrev_, epsField_); // d(eps)/dt=0 on the first step
406 if (eps1_.extent(0) == 0)
407 eps1_ = CCField("eps1", n1_);
408 if (beta1_.extent(0) == 0)
409 beta1_ = CCField("beta1", n1_);
410 if (rho1_.extent(0) == 0) { // share the g=1 coefficient scratch with the varRho path
411 rho1_ = CCField("rho1", n1_);
412 cx1_ = CCField("cx1", n1_);
413 cy1_ = CCField("cy1", n1_);
414 cz1_ = CCField("cz1", n1_);
415 }
416 // CHEBYSHEV by default (as for variable density). CAVEAT on the original justification
417 // ("MG-PCG stalls on the eps-scaled coefficient operator"): it rests on the same kind of
418 // observation WO-B refuted for varRho, and it was recorded through the setter whose `on` flag
419 // was a no-op until WO-H — so a "PCG" run made that way actually measured Chebyshev. The
420 // default is kept because it is safe (Chebyshev needs only real spectrum bounds and is the
421 // one driver healthy on every high-contrast coefficient configuration measured), NOT because
422 // the eps-scaled PCG stall has been re-measured; that re-measurement is still owed
423 // (doc/vof_workorders.md, WO-B escalation #1). Bounds re-estimated on every coefficient
424 // rebuild (chebBoundsSet_ invalidation in project()). An explicit driver set afterwards wins.
425 useChebyshev_ = true;
426 chebBoundsSet_ = false;
427 chebWarmOk_ = false;
428 bfpChebSet_ = false;
429 configurePorousDragSolver(); // if drag already on, switch to GraphAMG+PCG (Chebyshev
430 // diverges)
431 }
432}
433
434template <class Grid>
436 if (porous_)
437 Kokkos::deep_copy(epsPrev_, epsField_);
438}
439
440template <class Grid>
442 porousDepsDt_ = on;
443}
444
445template <class Grid>
447 porousCons_ = on;
448}
449
450template <class Grid>
452 pressUnderRelax_ = w;
453}
454
455template <class Grid>
456void Solver<Grid>::setPropertyMode(bool variable, bool harmonic) {
457 // An EXPLICIT velocity multigrid is refused in either order; the AUTO rule is simply re-decided
458 // (setSolidVelocityMgAuto excludes varProps_), so only an explicit request can conflict.
459 if (variable && vmgExplicit_ && useVelocityMg_)
460 throwVelocityMgVariableMu("set_property_mode('variable')");
461 varProps_ = variable;
462 harmonicMu_ = harmonic;
463 if (variable) {
464 if (fields_.has("mu"))
465 muField_ = fields_.at("mu").data;
466 else {
467 muField_ = addField("mu");
468 Kokkos::deep_copy(muField_,
469 mu_); // default to the scalar mu until a closure/set_field sets it
470 }
471 useVelocityMg_ =
472 false; // the velocity multigrid takes a scalar mu (variable-coeff vmg deferred)
473 }
474}
475
476template <class Grid>
477void Solver<Grid>::setVariableRotational(int mode, double chi) {
478 varRotMode_ = mode < 0 ? 0 : (mode > 2 ? 2 : mode);
479 varRotChi_ = chi < 0.0 ? 0.0 : chi;
480}
481
482template <class Grid>
483void Solver<Grid>::setPropertyTable(const std::string& target, const std::string& in0,
484 const std::vector<double>& xs, const std::vector<double>& ys) {
485 Closure cl;
487 cl.out = ensureTarget(target);
488 cl.in0 = CCConst(fields_.at(in0).data);
489 cl.outName = target; // see setPropertyModel
490 cl.in0Name = in0;
491 cl.nTab = (int)std::min(xs.size(), ys.size());
492 cl.tabX = CCField(target + "_tabx", cl.nTab);
493 cl.tabY = CCField(target + "_taby", cl.nTab);
494 auto hx = Kokkos::create_mirror_view(cl.tabX);
495 auto hy = Kokkos::create_mirror_view(cl.tabY);
496 for (int k = 0; k < cl.nTab; ++k) {
497 hx(k) = xs[k];
498 hy(k) = ys[k];
499 }
500 Kokkos::deep_copy(cl.tabX, hx);
501 Kokkos::deep_copy(cl.tabY, hy);
502 cl.tabYPhys.assign(ys.begin(), ys.begin() + cl.nTab);
503 closureUnitsNotice(target);
504 closureRefreshUnits(cl); // ys are in the target's physical units (identity in cell units)
505 closures_.push_back(cl);
506}
507
508template <class Grid>
509double Solver<Grid>::closureTargetToInt(const std::string& target) const {
510 if (target == "rho")
511 return u_.rhoToInt();
512 if (target == "mu")
513 return u_.muToInt();
514 if (target == "force_x" || target == "force_y" || target == "force_z")
515 return u_.forceToInt(target[6] - 'x');
516 return 0.0;
517}
518
519template <class Grid>
520void Solver<Grid>::closureUnitsNotice(const std::string& target) const {
521 if (u_.physical && closureTargetToInt(target) == 0.0)
522 std::fprintf(stderr,
523 "peclet.flow set_property_model NOTICE: a physical domain is armed and target "
524 "'%s' is not rho/mu/force_x/y/z, so this closure's parameters are taken in "
525 "that field's INTERNAL units (see the `unit_scales` property).\n",
526 target.c_str());
527}
528
529template <class Grid>
531 double kp = closureTargetToInt(cl.outName);
532 if (kp == 0.0)
533 kp = 1.0; // a field of unknown dimension: the caller's numbers are internal
534 if (cl.kind == ClosureKind::Table1D) {
535 if (!u_.physical)
536 return; // cell units: the table was uploaded verbatim at registration
537 auto hy = Kokkos::create_mirror_view(cl.tabY);
538 for (int k = 0; k < cl.nTab; ++k)
539 hy(k) = cl.tabYPhys[(std::size_t)k] * kp;
540 Kokkos::deep_copy(cl.tabY, hy);
541 return;
542 }
543 // the parameters that carry the output's dimension; the others are kept as given
544 const int nScaled = (cl.kind == ClosureKind::LinearMix) ? 3 : 1;
545 for (int k = 0; k < 4; ++k)
546 cl.p[k] = (k < nScaled) ? cl.pPhys[k] * kp : cl.pPhys[k];
547}
548
549template <class Grid>
551 for (auto& cl : closures_)
552 applyClosure(cl, e_, G);
553}
554
555template <class Grid>
557 ensureCellForceAll();
558}
559
560template <class Grid>
562 if (!fields_.has("drag_beta"))
563 dragBeta_ = addField("drag_beta");
564 else
565 dragBeta_ = fields_.at("drag_beta").data;
566 ensureCellForceAll(); // force_* carries beta*u_p (the implicit-drag RHS target)
567 hasDrag_ = true;
569}
570
571template <class Grid>
573 if (!(porous_ && hasDrag_))
574 return;
575 pressGraphAmg_ = true; // GraphAMG bottom (domain-BC operators: buildAmg skips
576 // the wrap across non-periodic faces and pcgAmg keeps the
577 // mean only when the operator is singular)
578 if (cutcellPressure_) // MG already built (set_solid ran) -> apply now
579 mg_.setAgglomerationMode(1);
580 useChebyshev_ = false; // PCG, not Chebyshev (diverges on the high w_f ratio)
581 chebBoundsSet_ = false;
582 chebWarmOk_ = false;
583 bfpChebSet_ = false;
584}
585
586template <class Grid>
588 CCExec space;
589 C3 e = e_;
590 FV AC = C[c].AC;
591 CCConst beta = CCConst(dragBeta_);
592 const long sc = strideOf(c);
593 // Porous continuity: the projection's operator/correction carry the FACE drag relaxation
594 // w_f = idt/(idt + beta_f), beta_f = 1/2(beta(i)+beta(i-sc)) (buildPorousCoeffDrag /
595 // projectCorrectPorousDrag). The staggered momentum diagonal of u_c(i) — the face between cells
596 // i-sc and i — must carry the SAME beta_f: then a pressure perturbation deltaP produces
597 // du* = -grad(deltaP)/(idt+beta_f) and the projection returns phi = -deltaP/idt exactly (same
598 // operator), so the incremental predictor cancels pressure errors in one step. With the cell
599 // value beta(i) the loop has gain (idt+beta_f)/(idt+beta_cell) at a beta jump (bed top: ~3) and
600 // the accumulated pressure diverges exponentially.
601 // The drag is VOLUMETRIC, so beta is placed where the unknown lives by the GRID, not by the
602 // continuity model: the face mean on the MAC grid (porous or not -- the non-porous path used the
603 // cell value, half a cell off the face, while its RHS target beta*u_p in force_* is placed by the
604 // same Grid::atVelocity), the cell value collocated. Target and diagonal must agree, or a uniform
605 // particle velocity does not give a uniform steady gas velocity.
606 using MD = MDRange3<CCExec>;
607 Kokkos::parallel_for(
608 "peclet::flow::add_drag_diag", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
609 KOKKOS_LAMBDA(int x, int y, int z) {
610 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
611 const double bd = Grid::atVelocity(beta, i, sc);
612 AC(i) = (MReal)((double)AC(i) + bd);
613 });
614}
615
616// ---- sharp viscous interface (doc/vof_sharp_viscous_stress.md) -------------------------------
617
618template <class Grid>
619void Solver<Grid>::setVofViscousInterface(const std::string& mode) {
620 if (mode == "auto") {
621 sharpMode_ = SharpMode::kAuto;
622 return;
623 }
624 if (mode == "sharp") {
625 if constexpr (Grid::collocated)
626 throw std::runtime_error(
627 "SolverColocated.set_vof_viscous_interface('sharp'): the sharp viscous interface is "
628 "staggered-only (doc/vof_sharp_viscous_stress.md §8; 'auto' resolves to 'averaged' "
629 "here); use peclet.flow.Solver");
630 sharpMode_ = SharpMode::kSharp;
631 return;
632 }
633 if (mode == "averaged") {
634 sharpMode_ = SharpMode::kAveraged;
635 sharpActive_ = false;
636 return;
637 }
638 throw std::invalid_argument("set_vof_viscous_interface: unknown mode '" + mode +
639 "' (expected 'auto', 'sharp' or 'averaged')");
640}
641
642template <class Grid>
644 switch (sharpMode_) {
645 case SharpMode::kSharp:
646 return "sharp";
647 case SharpMode::kAveraged:
648 return "averaged";
649 default:
650 return "auto";
651 }
652}
653
654template <class Grid>
656 // Re-decided every step, like the viscous-stress AUTO: the flags it reads are final at the step
657 // head. An explicit "sharp" raises outside the v1 scope (§1, §9); AUTO (the default, USER
658 // 2026-11-04) falls back to "averaged" there with a one-time stderr notice. Nothing to sharpen
659 // (no VoF, a constant or uniform mu) is silent under AUTO and inert under "sharp".
660 sharpActive_ = false;
661 if (sharpMode_ == SharpMode::kAveraged)
662 return;
663 const bool expl = sharpMode_ == SharpMode::kSharp;
664 const char* why = nullptr; // the refusal / fallback reason
665 const Closure* cl = nullptr; // the LAST closure writing mu is the one in force
666 for (const auto& c : closures_)
667 if (c.outName == "mu")
668 cl = &c;
669 if (!vofEnabled_) {
670 if (!expl)
671 return;
672 why = "needs the VoF colour field (enable_vof)";
673 } else if (expl && harmonicMu_)
674 why = "replaces the harmonic face viscosity; it does not combine with it";
675 else if (!varProps_)
676 return; // a constant mu: nothing to sharpen (inert)
677 else if (Grid::collocated)
678 why = "is staggered-only (doc/vof_sharp_viscous_stress.md §8)";
679 else if (harmonicMu_)
680 why = "replaces the harmonic face viscosity; it does not combine with it";
681 else if (hasSolid_)
682 why = "does not support immersed solids (v1)";
683 else if (porous_)
684 why = "does not support porous (eps-weighted) momentum";
685 else if (hasMotion_)
686 why = "does not support moving scene instances";
687 else if (pcEnabled_)
688 why = "does not support phase change ([u] != 0 breaks the kink model)";
689 else if (!fullStressActive())
690 why = "needs the full viscous stress (set_viscous_stress('auto' or 'full'))";
691 else if (!cl || cl->kind != ClosureKind::LinearMix || cl->in0Name != "C" || !cl->in1Name.empty())
692 why =
693 "supports mu = LinearMix(C) only, set_property_model('mu', 'linear', 'C', [mu_0, mu_1 - "
694 "mu_0]) (v1, §12 Q7)";
695 vof::SharpGeom& g = sharpGeom_;
696 if (why == nullptr) {
697 g.p0 = cl->p[0];
698 g.p1 = cl->p[1];
699 g.muB = g.p0; // mu(0)
700 g.muA = g.p0 + g.p1; // mu(1)
701 if (g.muA == g.muB)
702 return; // uniform mu: inert, the skip rule of the full stress
703 if (!(g.muA > 0.0 && g.muB > 0.0))
704 why = "needs positive phase viscosities";
705 }
706 if (why != nullptr) {
707 if (expl)
708 throw std::runtime_error(std::string("set_vof_viscous_interface('sharp') ") + why +
709 " (doc/vof_sharp_viscous_stress.md §1, §9); call "
710 "set_vof_viscous_interface('averaged') for this configuration");
711 if (!sharpAutoNotice_) {
712 sharpAutoNotice_ = true;
713 fprintf(stderr,
714 "peclet::flow %s: AUTO viscous interface fell back to 'averaged' (the sharp "
715 "interface %s; doc/vof_sharp_viscous_stress.md §9). Select explicitly with "
716 "set_vof_viscous_interface to silence this notice.\n",
717 Grid::collocated ? "SolverColocated" : "Solver", why);
718 }
719 return;
720 }
721 g.lowA = g.muA < g.muB;
722 g.mulo = g.lowA ? g.muA : g.muB;
723 g.r = g.lowA ? g.muA / g.muB : g.muB / g.muA;
724 sharpActive_ = true;
725}
726
727template <class Grid>
729 // §7 / Q9: the planes of the CURRENT colour. The curvature cascade has just reconstructed them
730 // on vofCurv_ when the single-field CSF ran this step; otherwise reconstruct them here, on the
731 // same block, with the same predicate (VofCurvature::interfaceEps).
732 const bool fresh = csfActive() && !vofBlockCsf() && !kappaFrozen_;
733 if (!fresh) {
735 if (vofCurv_.useWorklist)
736 vofCurv_.compact(vofAdv_.colour());
737 vofCurv_.reconstructPlanes(vofAdv_.colour());
738 }
739 const std::size_t n = (std::size_t)n_;
740 if (svCls_.extent(0) != n) {
741 CCExec space;
742 svCls_ = vof::SvByte(
743 Kokkos::view_alloc(space, "peclet::flow::sharp_cls", Kokkos::WithoutInitializing), n);
744 svFb_ = vof::SvByte(Kokkos::view_alloc(space, "peclet::flow::sharp_fb"), n);
745 svFit_ = CCField(Kokkos::view_alloc(space, "peclet::flow::sharp_fit"), 4 * n);
746 for (int a = 0; a < 3; ++a)
747 svTau_[a] = Kokkos::subview(svFit_, std::make_pair(a * n, (a + 1) * n));
748 svDnn_ = Kokkos::subview(svFit_, std::make_pair(3 * n, 4 * n));
749#ifdef PECLET_FLOW_MPI
750 svDev_.reset(); // the stacked exchange's stride is n
751#endif
752 svList_ = vof::SvList(
753 Kokkos::view_alloc(space, "peclet::flow::sharp_list", Kokkos::WithoutInitializing), n);
754 svRhsList_ = vof::SvList(
755 Kokkos::view_alloc(space, "peclet::flow::sharp_rhs_list", Kokkos::WithoutInitializing), n);
756 }
757 vof::SharpGeom& g = sharpGeom_;
758 const int ee[3] = {e_.x, e_.y, e_.z};
759 g.e[0] = e_.x;
760 g.e[1] = e_.y;
761 g.e[2] = e_.z;
762 g.st[0] = 1;
763 g.st[1] = e_.x;
764 g.st[2] = (long)e_.x * e_.y;
765 g.st3[0] = 1;
766 g.st3[1] = e3_.x;
767 g.st3[2] = (long)e3_.x * e3_.y;
768 g.d = kVofG - G;
769 g.col = CCConst(vofAdv_.colour());
770 for (int a = 0; a < 3; ++a)
771 g.pm[a] = CCConst(vofCurv_.planeM(a));
772 g.pa = CCConst(vofCurv_.planeAlpha());
773 g.cls = svCls_;
774 // The physical domain (§5.3, §5.7 Q-B): the cells beyond a non-periodic global face this rank
775 // touches are outside it.
776 constexpr int kOpen = 1 << 28;
777 for (int a = 0; a < 3; ++a) {
778 g.dlo[a] = (bc_[2 * a] != 0 && touchesGlobalFace(2 * a)) ? G : -kOpen;
779 g.dhi[a] = (bc_[2 * a + 1] != 0 && touchesGlobalFace(2 * a + 1)) ? ee[a] - G : kOpen;
780 }
781 // The interfacial predicate's threshold is the solver's wisp guard, whatever sigma is
782 // (coordinator D1, 2026-10-31): `vofCurv_.interfaceEps` is 0 unless set_surface_tension ran,
783 // and at 0 the round-off residue Weymouth-Yue leaves becomes 'interfacial' (walled N=24, mu
784 // ratio 1e-2: band 934 -> 5510, NaN at step 7). With sigma > 0 the two are the same value
785 // (set_surface_tension / set_vof_interface_eps keep them equal). The reconstruction above may
786 // use the smaller threshold: a plane is per-cell, so every cell this predicate admits has one.
787 g.eps = csfInterfaceEps_;
788 const vof::VofMetric gm = u_.vofMetric();
789 g.gm = gm;
790 for (int a = 0; a < 3; ++a)
791 g.ell[a] = gm.h[a];
792 vof::sharpClassify(g, svCls_);
793 svRhsN_ = vof::sharpRhsCompact(g, G, svRhsList_);
794}
795
796template <class Grid>
798 if (muUniform_)
799 return; // the full stress skips every term: so does the sharp interface
800 const CCConst v[3] = {CCConst(old_[0]), CCConst(old_[1]), CCConst(old_[2])};
801 vof::sharpFit(sharpGeom_, v, svTau_[0], svTau_[1], svTau_[2], svDnn_, svFb_, C3{G, G, G},
802 C3{e_.x - G, e_.y - G, e_.z - G}, svList_);
803 // §7: tau_hat at an edge on the block boundary may be a first-ghost cell's -- one exchange.
804#ifdef PECLET_FLOW_MPI
805 if (distributed_) {
806 if (!svDev_) { // the four fields stacked at stride n, ghosts within kSvHaloDepth
807 int rank = 0;
808 MPI_Comm_rank(comm_, &rank);
809 svHalo_ = std::make_shared<GridHaloTopology<3>>();
810 svHalo_->buildTopology(*dec_, rank, G, {true, true, true}, comm_,
811 peclet::core::halo::Neighborhood::Full, kSvHaloDepth);
812 svDev_ = std::make_shared<GridHalo<double>>();
813 svDev_->setLabel("sharp fit");
814 svDev_->init(*svHalo_, 4, (long)n_);
815 }
816 svDev_->exchange(svFit_);
817 return;
818 }
819#endif
820 for (int a = 0; a < 3; ++a)
821 fillGhosts(svTau_[a]);
822 fillGhosts(svDnn_);
823}
824
825template <class Grid>
828 fp.base = makeFaceProps(c);
829 fp.geo = sharpGeom_;
830 fp.c = c;
831 fp.role = role;
832 return fp;
833}
834
835template <class Grid>
837 if (!sharpActive_ || svCls_.extent(0) != (std::size_t)n_)
838 return vof::SharpCensus{};
839 return vof::sharpCensus(sharpGeom_, svFb_, C3{G, G, G}, C3{e_.x - G, e_.y - G, e_.z - G});
840}
841
842template <class Grid>
843std::array<std::vector<double>, 5> Solver<Grid>::vofViscousInterfaceFit() {
844 std::array<std::vector<double>, 5> out;
845 if (!sharpActive_ || svCls_.extent(0) != (std::size_t)n_)
846 return out;
847 for (int a = 0; a < 3; ++a)
848 out[a] = gatherInner(svTau_[a]);
849 out[3] = gatherInner(svDnn_);
850 CCExec space;
851 CCField f(Kokkos::view_alloc(space, "peclet::flow::sharp_fb_out", Kokkos::WithoutInitializing),
852 (std::size_t)n_);
853 const vof::SvByte fb = svFb_;
854 Kokkos::parallel_for(
855 "peclet::flow::sharp_fb_out", Kokkos::RangePolicy<CCExec>(space, 0, (long)n_),
856 KOKKOS_LAMBDA(long i) { f(i) = fb(i) ? 1.0 : 0.0; });
857 out[4] = gatherInner(f);
858 return out;
859}
860
861} // namespace peclet::flow
862
863#endif // PECLET_FLOW_FLOW_IBM_CLOSURES_HPP
static constexpr int kVofG
void fillGhosts(CCField f)
void fillPropGhosts(CCField f, bool edges=false)
void setPropertyMode(bool variable, bool harmonic)
CCField addField(const std::string &name)
std::string vofViscousInterface() const
void requireFullStressScope(const char *who) const
vof::SharpCensus vofViscousInterfaceCensus() const
void setPropertyModel(const std::string &target, ClosureKind kind, const std::string &in0, const std::string &in1, const std::vector< double > &params)
void applyScalarBcFace(CCField c, int a, int side, int type, double val, bool edges=false)
void setVariableRotational(int mode, double chi)
void setPressureUnderRelax(double w)
void closureUnitsNotice(const std::string &target) const
Under a physical domain, say on stderr that a closure on a target of unknown dimension takes its para...
static constexpr int G
Definition flow_ibm.hpp:82
void closureRefreshUnits(Closure &cl)
Re-derive a closure's internal p / tabY from its physical pPhys / tabYPhys with the current reference...
void setPorousConservative(bool on)
std::array< std::vector< double >, 5 > vofViscousInterfaceFit()
long strideOf(int c) const
void fillVelGhostsTo(CCField f, int comp, int fold, bool doOutflow=true, bool faceEdges=false)
void collocatedV8AutoFallback(const char *why)
void setVofViscousInterface(const std::string &mode)
void setViscousStress(const std::string &form)
void throwVelocityMgVariableMu(const char *who) const
void setDensityMode(bool variable)
Kokkos::View< MReal *, CCMem > FV
Definition flow_ibm.hpp:81
void setPropertyTable(const std::string &target, const std::string &in0, const std::vector< double > &xs, const std::vector< double > &ys)
double closureTargetToInt(const std::string &target) const
The internal-per-physical factor of a closure TARGET: rho, mu, force_x/y/z; 0.0 for any other field (...
vof::SharpFaceProps makeSharpFaceProps(int c, vof::SvRole role)
VarFaceProps makeFaceProps(int c)
void vofBcPropGhosts(CCField f)
WO-R item 5 — the Neumann property policy at an inflow face.
void setPorousContinuity(bool on)
std::vector< double > gatherInner(CCField fld)
void sharpFit(const SharpGeom &gg, const CCConst(&v)[3], CCField t0, CCField t1, CCField t2, CCField dnn, SvByte fb, C3 lo, C3 hi, SvList list)
The τ̂/D̂_nn fit (§5.3) over the cells [lo, hi) of the solver block: interfacial cells get their fit ...
SharpCensus sharpCensus(const SharpGeom &gg, SvByteConst fb, C3 lo, C3 hi)
Kokkos::View< std::uint8_t *, CCMem > SvByte
Per-cell byte fields on the solver block: the band class and the fit-fallback flag.
Kokkos::View< long *, CCMem > SvList
The compacted interfacial cells of a fit (local linear indices), the device fit's worklist.
void sharpClassify(const SharpGeom &gg, SvByte cls)
The band classes over the WHOLE solver block (§5.2, §5.7 Q-B).
void addSharpViscousRhs(int c, CCField bb, CCConst rs, const CCConst(&v)[3], const SharpGeom &gg, const CCConst(&tau)[3], CCConst dnn, int g, double wc, bool skipLoC, SvList list, long nl)
The explicit band terms of the u_c rows over the inner cells [g, e−g)³ (§5.4): the τ-terms of the fou...
long sharpRhsCompact(const SharpGeom &gg, int g, SvList list)
The cells of the inner box [g, e−g)³ whose band terms (addSharpViscousRhs) can be nonzero for some co...
SvRole
Which half of the time split a SharpFaceProps feeds (§6.1, WO-5b): the implicit band (ibmBuildDiffusi...
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
Kokkos::View< const double *, CCMem > CCConst
Kokkos::View< const std::uint8_t *, CCMem > RegConst
void addFullStressRhs(int c, CCField bb, CCConst rs, const CCConst(&v)[3], FaceProps fp, C3 e, int g, double wc, bool skipLoC, const RegConst(&reg)[3]={RegConst(), RegConst(), RegConst()})
Add rs_c · T_c(uⁿ) to the momentum RHS bb of component c over the inner cells [g, e−g)³.
Kokkos::View< double *, CCMem > CCField
void muRangeInner(CCConst mu, C3 e, int g, double &lo, double &hi)
The local min and max of mu over [g−1, e−g+1)³ — the inner cells plus the one ghost ring the transpos...
void applyClosure(const Closure &cl, C3 e, int g)
Kokkos::View< std::uint8_t *, CCMem > RegMask
Per-component regular-node mask (§5.4): 1 = a velocity node with neither a solid nor a cut row.
std::array< double, 4 > p
std::vector< double > tabYPhys
std::array< double, 4 > pPhys
The census of the band (§9, G-SV10) over [lo, hi), LOCAL to this block: interfacial cells,...
The face viscosity under the sharp interface (§5.4 a, §6): a band edge across a (a ≠ c) takes μ̄_c,...
The band geometry and the closure constants, by value into every kernel.
static constexpr double AC
static constexpr double U