flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_scalars_cutcell.hpp
Go to the documentation of this file.
1
12#ifndef PECLET_FLOW_FLOW_IBM_SCALARS_CUTCELL_HPP
13#define PECLET_FLOW_FLOW_IBM_SCALARS_CUTCELL_HPP
14
15namespace peclet::flow {
16
17template <class Grid>
19 ++scgVersion_;
20 scalarOpenValid_ = false; // WO-5b: the captured open-face planes belong to the old block
21}
22
23template <class Grid>
25 if (!geometryBuilt_)
26 throw std::runtime_error(
27 "scalar cut-cell geometry: no geometry yet -- call set_solid, set_solid_from_scene or "
28 "set_pressure_geometry first");
29 if (scg_.version == scgVersion_)
30 return;
31 const std::size_t nInner = (std::size_t)nx_ * ny_ * nz_;
33 r.kappa = CCField("peclet::flow::scg_kappa", n_);
34 r.sax = CCField("peclet::flow::scg_sax", n_);
35 r.say = CCField("peclet::flow::scg_say", n_);
36 r.saz = CCField("peclet::flow::scg_saz", n_);
37 r.unknown = CCField("peclet::flow::scg_unknown", n_);
38 const CCConst sd(sdf_);
39 // 1. apertures (every face of every inner cell + the high face at ext - G; not exchanged)
40 scg::buildApertures(r.sax, r.say, r.saz, sd, e_, G);
41 // 2. kappa, unknown flags, facet counts
42 scg::CellPass cp{Kokkos::View<std::int8_t*, CCMem>("peclet::flow::scg_nfac", nInner),
43 Kokkos::View<std::int8_t*, CCMem>("peclet::flow::scg_kind", nInner)};
44 scg::buildCells(r.kappa, r.unknown, cp, sd, r.sax, r.say, r.saz, e_, G, u_.hp);
45 // 3. compact facet list in x-fastest cell order + the cut-cell CSR
46 scg::buildFacets(r.fac, cp, sd, r.sax, r.say, r.saz, e_, G, u_.hp);
47 // 4. halo kappa / flags (the ordinary G = 2 exchange, which wraps periodically), then clear the
48 // flags beyond a non-periodic global face (rank rule touchesGlobalFace)
49 fillGhosts(r.kappa);
50 fillGhosts(r.unknown);
51 for (int face = 0; face < 6; ++face)
52 if (bc_[face] != 0 && touchesGlobalFace(face))
53 scg::zeroGhostSlab(r.unknown, e_, G, face);
54 // body id per facet: the scene owner AT the facet centroid (the hydro-force precedent: query at
55 // the point, never from the cell-centred cutOwner_); 0 with raw-SDF geometry (§2.7)
56 if (hasScene_ && sceneQ_ && r.fac.n > 0) {
57 const auto q = sceneQ_->view();
58 const SceneMap sm = sceneMap();
59 const C3 og = og_, e = e_;
60 const int g = G;
61 const double h0 = u_.hp[0], h1 = u_.hp[1], h2 = u_.hp[2];
62 auto fcell = r.fac.cell;
63 auto fcen = r.fac.centroid;
64 auto fbody = r.fac.body;
65 CCExec space;
66 Kokkos::parallel_for(
67 "peclet::flow::scg_body", Kokkos::RangePolicy<CCExec>(space, 0, r.fac.n),
68 KOKKOS_LAMBDA(const long f) {
69 const long i = fcell(f);
70 const long x = i % e.x, y = (i / e.x) % e.y, z = i / ((long)e.x * e.y);
71 const peclet::core::Vec3<double> p{
72 sm.a[0] + sm.b[0] * ((double)(x - g + og.x) + fcen(f, 0) / h0),
73 sm.a[1] + sm.b[1] * ((double)(y - g + og.y) + fcen(f, 1) / h1),
74 sm.a[2] + sm.b[2] * ((double)(z - g + og.z) + fcen(f, 2) / h2)};
75 fbody(f) = q.owner(p);
76 });
77 space.fence();
78 }
79 // 5. the fluid probe ladder per facet (§3.3)
80 scg::buildFluidProbes(r.fac, sd, CCConst(r.unknown), e_, u_.hp);
81 // census, summed over ranks
83 scg::localCensus(r.fac, cp, CCConst(r.kappa), CCConst(r.unknown), CCConst(r.sax),
84 CCConst(r.say), CCConst(r.saz), e_, G, u_.vol);
85#ifdef PECLET_FLOW_MPI
86 if (distributed_) {
87 long cnt[10] = {c.numUnknowns, c.numCutCells, c.numFacets, c.numTwoSided, c.numThinSolid,
88 c.numSealed, c.rungs[0], c.rungs[1], c.rungs[2], c.rungs[3]};
89 long sum[10];
90 MPI_Allreduce(cnt, sum, 10, MPI_LONG, MPI_SUM, comm_);
91 double v = c.sealedVolume, vs = 0.0;
92 MPI_Allreduce(&v, &vs, 1, MPI_DOUBLE, MPI_SUM, comm_);
93 double vf = c.fluidVolume, vfs = 0.0;
94 MPI_Allreduce(&vf, &vfs, 1, MPI_DOUBLE, MPI_SUM, comm_);
95 c.fluidVolume = vfs;
96 c.numUnknowns = sum[0];
97 c.numCutCells = sum[1];
98 c.numFacets = sum[2];
99 c.numTwoSided = sum[3];
100 c.numThinSolid = sum[4];
101 c.numSealed = sum[5];
102 for (int k = 0; k < 4; ++k)
103 c.rungs[k] = sum[6 + k];
104 c.sealedVolume = vs;
105 }
106#endif
107 const double l = u_.lenToPhys();
108 c.sealedVolume *= l * l * l;
109 c.fluidVolume *= l * l * l;
110 r.census = c;
111 r.version = scgVersion_;
112 scg_ = r;
113}
114
115template <class Grid>
120
121template <class Grid>
122std::vector<double> Solver<Grid>::scalarGeometryField(int which) {
124 const CCField f[5] = {scg_.kappa, scg_.sax, scg_.say, scg_.saz, scg_.unknown};
125 if (which < 0 || which > 4)
126 throw std::runtime_error("scalarGeometryField: which must be 0..4");
127 return gatherInner(f[which]);
128}
129
130template <class Grid>
135
136// ================================================================================================
137// WO-3: the single-phase cut-cell operator, the Krylov solve, steady + transient diffusion.
138// ================================================================================================
139
140template <class Grid>
141bool Solver<Grid>::isCutcellScalar(const std::string& name) const {
142 for (const auto& sc : scalars_)
143 if (sc.name == name)
144 return sc.cutcell;
145 return false;
146}
147
148template <class Grid>
149ScalarField& Solver<Grid>::cutcellScalar(const std::string& name, const char* who) {
150 for (auto& sc : scalars_)
151 if (sc.name == name) {
152 if (!sc.cutcell)
153 throw std::invalid_argument(std::string(who) + ": '" + name +
154 "' is not a cut-cell scalar (add_scalar(..., cutcell=True))");
155 return sc;
156 }
157 throw std::invalid_argument(std::string(who) + ": no scalar named '" + name + "'");
158}
159
160template <class Grid>
162 return (hasScene_ && nInst_ > 0) ? nInst_ : 1;
163}
164
165template <class Grid>
166void Solver<Grid>::setScalarWall(const std::string& name, int type, double value,
167 double coefficient, int instance) {
168 ScalarCutState& st = *cutcellScalar(name, "set_scalar_wall").cut;
169 if (type < 0 || type > 2)
170 throw std::invalid_argument("set_scalar_wall: type must be 'neumann', 'dirichlet' or 'robin'");
171 if (!std::isfinite(value))
172 throw std::invalid_argument("set_scalar_wall: value must be finite");
173 if (type == 2 && !(coefficient >= 0.0))
174 throw std::invalid_argument("set_scalar_wall: the robin coefficient k must be >= 0");
175 const ScalarWallSpec w{type, value, type == 2 ? coefficient : 0.0};
176 if (instance < 0) { // every body: the default, and no override survives
177 st.wallDefault = w;
178 st.wallInstance.clear();
179 return;
180 }
181 if (!hasScene_)
182 throw std::invalid_argument(
183 "set_scalar_wall: instance= needs a scene (set_scene + set_solid_from_scene); raw-SDF "
184 "geometry has one body, set with instance=None");
185 if (instance >= nInst_)
186 throw std::invalid_argument("set_scalar_wall: instance " + std::to_string(instance) +
187 " out of range (the scene has " + std::to_string(nInst_) + ")");
188 for (auto it = st.wallInstance.begin(); it != st.wallInstance.end(); ++it)
189 if (it->first == instance) {
190 st.wallInstance.erase(it);
191 break;
192 }
193 st.wallInstance.emplace_back(instance, w);
194}
195
196template <class Grid>
197void Solver<Grid>::setScalarSolid(const std::string& name, double D, double capacity,
198 double partition, double contactResistance, int instance) {
199 ScalarField& sc = cutcellScalar(name, "set_scalar_solid");
200 ScalarCutState& st = *sc.cut;
201 if (!std::isfinite(D) || !(D >= 0.0))
202 throw std::invalid_argument("set_scalar_solid: diffusivity must be finite and >= 0");
203 if (!std::isfinite(capacity) || !(capacity > 0.0))
204 throw std::invalid_argument("set_scalar_solid: capacity must be finite and > 0");
205 if (!std::isfinite(partition) || !(partition > 0.0))
206 throw std::invalid_argument("set_scalar_solid: partition must be finite and > 0");
207 if (!std::isfinite(contactResistance) || !(contactResistance >= 0.0))
208 throw std::invalid_argument("set_scalar_solid: contact_resistance must be finite and >= 0");
209 if (instance >= 0 && !hasScene_)
210 throw std::invalid_argument(
211 "set_scalar_solid: instance= needs a scene (set_scene + set_solid_from_scene); raw-SDF "
212 "geometry has one body, set with instance=None");
213 if (instance >= 0 && instance >= nInst_)
214 throw std::invalid_argument("set_scalar_solid: instance " + std::to_string(instance) +
215 " out of range (the scene has " + std::to_string(nInst_) + ")");
217 w.type = 3;
218 w.solidD = D;
219 w.solidC = capacity;
220 w.solidK = partition;
221 w.solidRc = contactResistance;
222 if (st.solid.extent(0) != n_) // §1.3: the solid field, registered, on the first call
223 st.solid = addField(name + "_solid");
224 if (instance < 0) {
225 st.wallDefault = w;
226 st.wallInstance.clear();
227 return;
228 }
229 for (auto it = st.wallInstance.begin(); it != st.wallInstance.end(); ++it)
230 if (it->first == instance) {
231 st.wallInstance.erase(it);
232 break;
233 }
234 st.wallInstance.emplace_back(instance, w);
235}
236
237template <class Grid>
239 ScalarCutState& st = *sc.cut;
240 const int nb = scalarNumBodies();
241 std::vector<ScalarWallSpec> spec((std::size_t)nb, st.wallDefault);
242 for (const auto& [inst, w] : st.wallInstance)
243 if (inst >= 0 && inst < nb)
244 spec[(std::size_t)inst] = w;
245 conj.assign((std::size_t)nb, 0);
246 st.mtLam.assign((std::size_t)nb, 0.0);
247 st.mtCK.assign((std::size_t)nb, 1.0);
248 st.mtK.assign((std::size_t)nb, 1.0);
249 st.mtRc.assign((std::size_t)nb, 0.0);
250 st.maxSolidD = 0.0;
251 const double dI = u_.diffToInt(), rI = u_.resistToInt();
252 for (int b = 0; b < nb; ++b) {
253 const ScalarWallSpec& w = spec[(std::size_t)b];
254 if (w.type != 3)
255 continue;
256 conj[(std::size_t)b] = 1;
257 // psi form (§1.1): Lam_s = C_s D_s K, capacity C_s K; internal by §1.2 at use time
258 st.mtLam[(std::size_t)b] = (w.solidC * w.solidD * w.solidK) * dI;
259 st.mtCK[(std::size_t)b] = w.solidC * w.solidK;
260 st.mtK[(std::size_t)b] = w.solidK;
261 st.mtRc[(std::size_t)b] = w.solidRc * rI;
262 st.maxSolidD = std::fmax(st.maxSolidD, w.solidD * dI);
263 }
264 if (st.mtConjV.extent(0) != (std::size_t)nb) { // persistent, refilled below (finding 7)
265 st.mtConjV = Kokkos::View<int*, CCMem>("peclet::flow::sco_mt_conj", nb);
266 st.mtLamV = Kokkos::View<double*, CCMem>("peclet::flow::sco_mt_lam", nb);
267 st.mtCKV = Kokkos::View<double*, CCMem>("peclet::flow::sco_mt_ck", nb);
268 st.mtKV = Kokkos::View<double*, CCMem>("peclet::flow::sco_mt_k", nb);
269 st.mtRcV = Kokkos::View<double*, CCMem>("peclet::flow::sco_mt_rc", nb);
270 }
272 mt.nb = nb;
273 mt.conj = st.mtConjV;
274 mt.lam = st.mtLamV;
275 mt.ck = st.mtCKV;
276 mt.kp = st.mtKV;
277 mt.rc = st.mtRcV;
278 auto hc = Kokkos::create_mirror_view(mt.conj);
279 auto hl = Kokkos::create_mirror_view(mt.lam);
280 auto hk = Kokkos::create_mirror_view(mt.ck);
281 auto hp = Kokkos::create_mirror_view(mt.kp);
282 auto hr = Kokkos::create_mirror_view(mt.rc);
283 for (int b = 0; b < nb; ++b) {
284 hc(b) = conj[(std::size_t)b];
285 hl(b) = st.mtLam[(std::size_t)b];
286 hk(b) = st.mtCK[(std::size_t)b];
287 hp(b) = st.mtK[(std::size_t)b];
288 hr(b) = st.mtRc[(std::size_t)b];
289 }
290 Kokkos::deep_copy(mt.conj, hc);
291 Kokkos::deep_copy(mt.lam, hl);
292 Kokkos::deep_copy(mt.ck, hk);
293 Kokkos::deep_copy(mt.kp, hp);
294 Kokkos::deep_copy(mt.rc, hr);
295 return mt;
296}
297
298template <class Grid>
299void Solver<Grid>::ensureScalarSolidRecord(ScalarField& sc, const std::vector<char>& conj) {
301 ScalarCutState& st = *sc.cut;
302 if (st.solidVersion == scg_.version && st.solidKey == conj && st.mat.extent(0) == n_)
303 return;
304 const scg::ScalarCutGeometry& gm = scg_;
305 const auto& fo = gm.fac;
306 if (st.mat.extent(0) != n_) {
307 st.mat = CCField(sc.name + "_cc_mat", n_);
308 st.sunk = CCField(sc.name + "_cc_sunk", n_);
309 }
310 // the material table needs only the conjugate flags here (§2.7)
312 const int nb = (int)conj.size();
313 mt.nb = nb;
314 mt.conj = Kokkos::View<int*, CCMem>("peclet::flow::sco_rec_conj", nb);
315 {
316 auto hc = Kokkos::create_mirror_view(mt.conj);
317 for (int b = 0; b < nb; ++b)
318 hc(b) = conj[(std::size_t)b];
319 Kokkos::deep_copy(mt.conj, hc);
320 }
321 const std::size_t nInner = (std::size_t)nx_ * ny_ * nz_;
322 const bool hasOwner = hasScene_ && cutOwner_.extent(0) == nInner;
323 double svol[2] = {0.0, 0.0};
324 sco::buildSolidMaterial(st.mat, st.sunk, CCConst(gm.kappa), CCConst(gm.sax), CCConst(gm.say),
325 CCConst(gm.saz), fo, Kokkos::View<const int*, CCMem>(cutOwner_), hasOwner,
326 mt, e_, G, svol);
327 fillGhosts(st.mat);
328 fillGhosts(st.sunk);
329 for (int face = 0; face < 6; ++face)
330 if (bc_[face] != 0 && touchesGlobalFace(face))
331 scg::zeroGhostSlab(st.sunk, e_, G, face);
332 // the facets of conjugate bodies, and their solid probes (§3.4)
333 st.conjF = Kokkos::View<std::uint8_t*, CCMem>(sc.name + "_cc_conjF", fo.n);
334 st.sS = Kokkos::View<double*, CCMem>(sc.name + "_cc_sS", fo.n);
335 st.offS = decltype(st.offS)(sc.name + "_cc_offS", fo.n);
336 st.wS = decltype(st.wS)(sc.name + "_cc_wS", fo.n);
337 st.rungS = Kokkos::View<std::uint8_t*, CCMem>(sc.name + "_cc_rungS", fo.n);
338 {
339 auto cf = st.conjF;
340 auto fbody = fo.body;
341 auto cj = mt.conj;
342 CCExec space;
343 Kokkos::parallel_for(
344 "peclet::flow::sco_conj_facets", Kokkos::RangePolicy<CCExec>(space, 0, fo.n),
345 KOKKOS_LAMBDA(const long f) {
346 cf(f) = cj(sco::bodyIndex((double)fbody(f), nb)) != 0 ? 1 : 0;
347 });
348 space.fence();
349 }
350 sco::buildSolidProbes(st.sS, st.offS, st.wS, st.rungS,
351 Kokkos::View<const std::uint8_t*, CCMem>(st.conjF), fo, CCConst(sdf_),
352 CCConst(st.sunk), e_, u_.hp);
353 // census: solid unknowns (inner) and the solid rungs (conjugate facets)
354 long cnt[5] = {0, 0, 0, 0, 0};
355 {
356 CCConst su(st.sunk);
357 const C3 e = e_;
358 const int g = G;
359 double nsu = 0.0;
360 ccReduce3(
361 "peclet::flow::sco_count_solid", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
362 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
363 acc += su((long)x + (long)y * e.x + (long)z * (long)e.x * e.y) > 0.5 ? 1.0 : 0.0;
364 },
365 nsu);
366 cnt[0] = (long)nsu;
367 auto rs = st.rungS;
368 auto cf = st.conjF;
369 for (int k = 0; k < 4; ++k) {
370 long c = 0;
371 Kokkos::parallel_reduce(
372 "peclet::flow::sco_solid_rungs", Kokkos::RangePolicy<CCExec>(0, fo.n),
373 KOKKOS_LAMBDA(const long f, long& acc) {
374 acc += (cf(f) != 0 && (int)rs(f) == k) ? 1 : 0;
375 },
376 c);
377 cnt[1 + k] = c;
378 }
379 }
380#ifdef PECLET_FLOW_MPI
381 if (distributed_) {
382 long o[5];
383 MPI_Allreduce(cnt, o, 5, MPI_LONG, MPI_SUM, comm_);
384 for (int k = 0; k < 5; ++k)
385 cnt[k] = o[k];
386 double ov[2];
387 MPI_Allreduce(svol, ov, 2, MPI_DOUBLE, MPI_SUM, comm_);
388 svol[0] = ov[0];
389 svol[1] = ov[1];
390 }
391#endif
392 const double lv = u_.lenToPhys(); // D-WO7-1: the census's sealed solid volume, physical
393 st.solidVolume = svol[0] * u_.vol * lv * lv * lv;
394 st.sealedSolidVolume = svol[1] * u_.vol * lv * lv * lv;
395 st.numSolidUnknowns = cnt[0];
396 for (int k = 0; k < 4; ++k)
397 st.solidRungs[k] = cnt[1 + k];
398 st.solidVersion = gm.version;
399 st.solidKey = conj;
400}
401
402template <class Grid>
403std::vector<double> Solver<Grid>::getScalarSolid(const std::string& name) {
404 ScalarField& sc = cutcellScalar(name, "get_scalar_solid");
405 ScalarCutState& st = *sc.cut;
406 const std::size_t nInner = (std::size_t)nx_ * ny_ * nz_;
407 std::vector<double> out(nInner, std::numeric_limits<double>::quiet_NaN());
408 if (!st.built || !st.conj || st.solid.extent(0) != n_ || st.sunk.extent(0) != n_)
409 return out;
410 const auto ps = gatherInner(st.solid);
411 const auto su = gatherInner(st.sunk);
412 const auto mt = gatherInner(st.mat);
413 const int nb = (int)st.mtK.size();
414 for (std::size_t i = 0; i < nInner; ++i) {
415 if (!(su[i] > 0.5))
416 continue;
417 int b = (int)mt[i];
418 if (b < 0 || b >= nb)
419 b = 0;
420 out[i] = st.mtK[(std::size_t)b] * ps[i];
421 }
422 return out;
423}
424
425template <class Grid>
426std::vector<double> Solver<Grid>::scalarSolidGeometryField(const std::string& name, int which) {
427 ScalarField& sc = cutcellScalar(name, "scalar_geometry");
428 ScalarCutState& st = *sc.cut;
429 std::vector<char> conj;
430 (void)scalarMaterialTable(sc, conj);
432 if (which == 1)
433 return gatherInner(st.sunk);
434 std::vector<double> k = gatherInner(scg_.kappa);
435 for (auto& v : k)
436 v = 1.0 - v;
437 return k;
438}
439
440template <class Grid>
441void Solver<Grid>::setScalarSource(const std::string& name, double S) {
442 ScalarCutState& st = *cutcellScalar(name, "set_scalar_source").cut;
443 if (!std::isfinite(S))
444 throw std::invalid_argument("set_scalar_source: the source must be finite");
445 st.sourceConst = S;
446 st.sourceField = CCField();
447 st.sourceIsField = false;
448}
449
450template <class Grid>
451void Solver<Grid>::setScalarSourceField(const std::string& name, const std::vector<double>& S) {
452 ScalarCutState& st = *cutcellScalar(name, "set_scalar_source").cut;
453 if (S.size() != (std::size_t)nx_ * ny_ * nz_)
454 throw std::invalid_argument(
455 "set_scalar_source: the array must have this rank's (nx, ny, nz) "
456 "shape");
457 if (st.sourceField.extent(0) != n_)
458 st.sourceField = CCField(name + "_cc_source", n_);
459 scatterInner(st.sourceField, S);
460 st.sourceConst = 0.0;
461 st.sourceIsField = true;
462}
463
464template <class Grid>
465void Solver<Grid>::setScalarResidualTolerance(const std::string& name, double rtol) {
466 ScalarCutState& st = *cutcellScalar(name, "set_scalar_residual_tolerance").cut;
467 if (!(rtol > 0.0) || !std::isfinite(rtol))
468 throw std::invalid_argument("set_scalar_residual_tolerance: rtol must be finite and > 0");
469 st.rtol = rtol;
470}
471
472template <class Grid>
473void Solver<Grid>::setScalarMeanGradient(const std::string& name, const std::array<double, 3>& G) {
474 ScalarCutState& st = *cutcellScalar(name, "set_scalar_mean_gradient").cut;
475 for (double v : G)
476 if (!std::isfinite(v))
477 throw std::invalid_argument("set_scalar_mean_gradient: the gradient must be finite");
478 for (int a = 0; a < 3; ++a)
479 st.meanGrad[a] = G[(std::size_t)a];
480}
481
482template <class Grid>
485 const int og[3] = {og_.x, og_.y, og_.z};
486 for (int a = 0; a < 3; ++a) {
487 p.G[a] = Gphys[a];
488 p.org[a] = u_.org[a];
489 p.h[a] = u_.h[a];
490 p.base[a] = (long)og[a] - G;
491 }
492 p.sy = e_.x;
493 p.sz = (long)e_.x * e_.y;
494 return p;
495}
496
497template <class Grid>
498std::array<double, 3> Solver<Grid>::scalarMeanFlux(const std::string& name) {
499 ScalarField& sc = cutcellScalar(name, "scalar_mean_flux");
500 ScalarCutState& st = *sc.cut;
501 std::array<double, 3> out{0.0, 0.0, 0.0};
502 if (!st.built)
503 return out;
504 const scg::ScalarCutGeometry& gm = scg_;
505 fillGhosts(sc.c);
506 // the face flux of the last solve (read only when it advected; any field otherwise)
507 const bool adv = st.advecting;
508 double d[3], v[3];
510 CCConst(gm.say), CCConst(gm.saz), CCConst(adv ? st.phi[0] : sc.c),
511 CCConst(adv ? st.phi[1] : sc.c), CCConst(adv ? st.phi[2] : sc.c), adv, st.lam,
512 st.gInt, u_.hp, st.ubar, e_, G, d, v);
513 if (st.conj) { // WO-7: the solid faces' diffusive flux (§8.1: "over both phases")
514 double ds[3];
515 fillGhosts(st.solid);
516 sco::solidMeanFluxLocal(CCConst(st.solid), CCConst(st.sunk), CCConst(st.spx), CCConst(st.spy),
517 CCConst(st.spz), st.gInt, u_.hp, e_, G, ds);
518 for (int a = 0; a < 3; ++a)
519 d[a] += ds[a];
520 }
521 double s[6] = {d[0], d[1], d[2], v[0], v[1], v[2]};
522#ifdef PECLET_FLOW_MPI
523 if (distributed_) {
524 double o[6];
525 MPI_Allreduce(s, o, 6, MPI_DOUBLE, MPI_SUM, comm_);
526 for (int j = 0; j < 6; ++j)
527 s[j] = o[j];
528 }
529#endif
530 // the box average: per unit full-cell volume sums over the GLOBAL cell count, then physical
531 const auto gc = globalCells();
532 const double nBox = (double)gc[0] * (double)gc[1] * (double)gc[2];
533 const double toPhys = 1.0 / u_.speedToInt();
534 for (int a = 0; a < 3; ++a)
535 out[(std::size_t)a] = (s[a] + s[3 + a]) / nBox * toPhys;
536 return out;
537}
538
539template <class Grid>
540void Solver<Grid>::setScalarMaxIterations(const std::string& name, int maxit) {
541 ScalarCutState& st = *cutcellScalar(name, "set_scalar_max_iterations").cut;
542 if (maxit < 1)
543 throw std::invalid_argument("set_scalar_max_iterations: max_iter must be >= 1");
544 st.maxit = maxit;
545}
546
547template <class Grid>
548void Solver<Grid>::setScalarBcProfile(const std::string& name, int face,
549 const std::vector<double>& prof, int n1, int n2) {
550 ScalarField& sc = cutcellScalar(name, "set_scalar_bc");
551 if (face < 0 || face > 5)
552 throw std::invalid_argument("set_scalar_bc: face out of range");
553 int t1, t2;
554 sco::faceTangents(face / 2, t1, t2);
555 const int n[3] = {nx_, ny_, nz_};
556 if (n1 != n[t1] || n2 != n[t2] || prof.size() != (std::size_t)n1 * n2)
557 throw std::invalid_argument("set_scalar_bc: a profile must have shape (N_t1, N_t2) = (" +
558 std::to_string(n[t1]) + ", " + std::to_string(n[t2]) +
559 ") -- this rank's face cells in the tangential axes in x, y, z "
560 "order");
561 for (double v : prof)
562 if (!std::isfinite(v))
563 throw std::invalid_argument("set_scalar_bc: the profile must be finite");
564 sc.bc[face] = 2; // a profile is a Dirichlet value
565 sc.bcVal[face] = 0.0;
566 sc.cut->hasProfile[face] = true;
567 sc.cut->profile[face] = prof;
568 sc.cut->profileN[face][0] = n1;
569 sc.cut->profileN[face][1] = n2;
570}
571
572template <class Grid>
574 const std::string who = "cut-cell scalar '" + sc.name + "': ";
575 if (porous_)
576 throw std::runtime_error(who + "porous (volume-averaged) continuity is not supported");
577 if (hasMovingInstance())
578 throw std::runtime_error(who + "moving scene instances are not supported (static geometry)");
579 if (sc.dmask.extent(0) == n_)
580 throw std::runtime_error(who + "the per-cell Dirichlet mask is not supported");
581 // §13 Q13, decided by G9b (WO-5): the ghost projection's constraint is the binary-openness
582 // divergence PLUS wall-anchored closure terms (gpDivergDelta), so no openness-weighted face flux
583 // of its field is discretely divergence-free — a constant concentration drifted by 0.80 in 50
584 // Stokes steps at bulk Courant 0.47 (staggered and every other collocated scheme: 0 exactly).
585 // Covers the collocated 'ghost' scheme (the AUTO default) and the staggered verification path.
586 if (ghostProjection_)
587 throw std::runtime_error(
588 who + "the ghost projection ('ghost' collocated scheme, or diagnostics." +
589 "set_ghost_projection) leaves no discretely divergence-free face flux to advect with " +
590 "(doc/scalar_ibm_design.md §6.1, gate G9b); the accepted projections are the collocated " +
591 "schemes 'gauge-exact', 'plain' and 'embed' (set_collocated_scheme, before set_solid) "
592 "and " +
593 "the staggered Solver without set_ghost_projection");
594 static const char* kFace[6] = {"-x", "+x", "-y", "+y", "-z", "+z"};
595 // §1.5 / §8.1: theta is periodic along every axis the mean gradient has a component on
596 for (int f = 0; f < 6; ++f)
597 if (sc.cut->meanGrad[f / 2] != 0.0 && (bc_[f] != 0 || sc.bc[f] != 0))
598 throw std::runtime_error(who + "the mean gradient has a component along " +
599 std::string(1, "xyz"[f / 2]) + " but the domain face " + kFace[f] +
600 " is not periodic (set_scalar_mean_gradient needs periodic faces "
601 "on every axis it has a component on)");
602 for (int f = 0; f < 6; ++f) {
603 const bool flowPeriodic = bc_[f] == 0, scalarPeriodic = sc.bc[f] == 0;
604 if (flowPeriodic != scalarPeriodic)
605 throw std::runtime_error(
606 who + "face " + kFace[f] + " is " + (scalarPeriodic ? "periodic" : "non-periodic") +
607 " for the scalar but " + (flowPeriodic ? "periodic" : "non-periodic") +
608 " for the flow (set_scalar_bc / set_domain_bc must agree)");
609 if (bc_[f] == 2 && sc.bc[f] != 2)
610 throw std::runtime_error(who + "the inflow face " + kFace[f] +
611 " needs a scalar 'dirichlet' value (set_scalar_bc)");
612 // WO-5b: refused on the collocated grid. The cause it was refused for -- the plain ghost fill
613 // of uf_/vf_/wf_ wrapping the high-side open face plane from the opposite face (a constant
614 // drifted by 0.48 in the outlet column in one step) -- is fixed: every in-place fill of a face
615 // field now goes through fillFaceGhostsKeepBoundary (doc/uf_outlet_fix.md). Lifting the
616 // refusal is a separate decision with its own gate; until then it stands.
617 if constexpr (Grid::collocated)
618 if (bc_[f] == 2 || bc_[f] == 3)
619 throw std::runtime_error(
620 who + "face " + kFace[f] + " is a flow " + (bc_[f] == 2 ? "inflow" : "outflow") +
621 " face: on the collocated grid the projected face field does not keep the boundary "
622 "flux the projection constrained, so open domain faces are not supported for a "
623 "cut-cell scalar there yet -- use the staggered Solver (doc/scalar_ibm_design.md "
624 "§6.5)");
625 }
626}
627
628template <class Grid>
630 ScalarCutState& st = *sc.cut;
631 fillGhosts(x); // one G = 2 exchange covers the 7-point part and the +-2-reach probes
632 applyCutcellOp(y, CCConst(x), sc.AC, sc.AW, sc.AE, sc.AS, sc.AN, sc.AB, sc.AT, e_, G);
633 sco::overlayApply(y, CCConst(x), scg_.fac, st.cw);
634}
635
636template <class Grid>
638 CCField xs) {
639 ScalarCutState& st = *sc.cut;
640 fillGhosts(xf); // one G = 2 exchange per phase field (§4.1)
641 fillGhosts(xs);
642 applyCutcellOp(yf, CCConst(xf), sc.AC, sc.AW, sc.AE, sc.AS, sc.AN, sc.AB, sc.AT, e_, G);
643 applyCutcellOp(ys, CCConst(xs), st.ASC, st.ASW, st.ASE, st.ASS, st.ASN, st.ASB, st.AST, e_, G);
644 sco::conjOverlayApply(yf, ys, CCConst(xf), CCConst(xs), scg_.fac, st.cw, st.cc, st.offS, st.wS);
645}
646
647template <class Grid>
649 // §6.1 (D5): constant preservation needs sum_f F = 0 per cell, and only the projection's own
650 // divergence kernel states which openness that sum carries: `divergOpen(f, oxb_)` (+ the
651 // closure delta) in ghost-projection mode, `constraintDivergence` = `divergOpen(f, ox_)` in every
652 // other non-porous branch of both grids (porous continuity is refused for a cut-cell scalar).
653 const bool gp = ghostProjection_ && oxb_.extent(0) > 0;
654 const CCField o[3] = {gp ? oxb_ : ox_, gp ? oyb_ : oy_, gp ? ozb_ : oz_};
656 f.open = o[a];
657 if constexpr (Grid::collocated)
658 f.vel = a == 0 ? uf_ : (a == 1 ? vf_ : wf_); // the projected MAC face field
659 else
660 f.vel = C[a].u; // the stored staggered velocity IS the projected face velocity
661 return f;
662}
663
664template <class Grid>
666 // WO-5b (§6.5, ruling D-WO5-3). Called right after the projection: the high-side boundary face
667 // is the first GHOST index. A plain ghost fill used to wrap it from the opposite face; the
668 // in-place fills (advanceScalars', the VoF bridge's, the steady solve's) now keep it
669 // (fillFaceGhostsKeepBoundary, doc/uf_outlet_fix.md), and this copy of the flux the projection
670 // constrained there is what the open-face fluxes read. The plane spans the full transverse
671 // extent (its transverse ghost rows fed the locally computed ghost-layer small flags until
672 // D-WOR-6 exchanged them; kept, a plane copy).
673 if (!hasBc_)
674 return;
675 // Captured whether or not a cut-cell scalar exists yet (one plane copy per open face), so a
676 // scalar added to a developed flow can be solved before the next step.
677 bool anyOpen = false;
678 for (int f = 0; f < 6; ++f)
679 anyOpen = anyOpen || bc_[f] == 2 || bc_[f] == 3;
680 if (!anyOpen)
681 return;
682 const int ext[3] = {e_.x, e_.y, e_.z};
683 const long st[3] = {1, (long)e_.x, (long)e_.x * e_.y};
684 for (int f = 0; f < 6; ++f) {
685 if (!(bc_[f] == 2 || bc_[f] == 3) || !touchesGlobalFace(f))
686 continue;
687 const int a = f / 2, side = f % 2;
688 int t1, t2;
689 sco::faceTangents(a, t1, t2);
690 const int m1 = ext[t1], m2 = ext[t2];
691 if (scalarOpenFlux_[f].extent(0) != (std::size_t)m1 * m2)
692 scalarOpenFlux_[f] = CCField("peclet::flow::scalar_open_flux", (std::size_t)m1 * m2);
693 const ScalarFaceFlux ff = scalarFaceFlux(a);
694 const CCConst open(ff.open), vel(ff.vel);
695 CCField pl = scalarOpenFlux_[f];
696 const long sa = st[a], s1 = st[t1], s2 = st[t2];
697 const long bfa = side == 0 ? G : ext[a] - G;
698 CCExec space;
699 Kokkos::parallel_for(
700 "peclet::flow::scalar_capture_open_flux", MDRange2<CCExec>(space, {0, 0}, {m1, m2}),
701 KOKKOS_LAMBDA(int j1, int j2) {
702 const long bf = bfa * sa + (long)j1 * s1 + (long)j2 * s2;
703 pl((long)j1 + (long)j2 * m1) = open(bf) * vel(bf);
704 });
705 space.fence();
706 }
707 scalarOpenValid_ = true;
708}
709
710// ---- the phases of scalarCutAdvection and scalarCutAssembleSolve ------------------------------
711// Free helpers, not members: the class declarations live in flow_ibm.hpp, so each phase takes the
712// solver state it reads as arguments (the private state through `CutContext`, the public members
713// through the solver itself).
714namespace scd {
715
717inline void ensureField(CCField& f, std::size_t n, const std::string& name, const char* tag) {
718 if (f.extent(0) != n)
719 f = CCField(name + tag, n);
720}
721
725 C3 e{0, 0, 0};
726 int g = 0;
727 std::size_t n = 0;
729 bool distributed = false;
730#ifdef PECLET_FLOW_MPI
731 MPI_Comm comm = MPI_COMM_NULL;
732#endif
733
734 void allSum(double* v, int k) const {
735#ifdef PECLET_FLOW_MPI
736 if (distributed) {
737 std::vector<double> o((std::size_t)k);
738 MPI_Allreduce(v, o.data(), k, MPI_DOUBLE, MPI_SUM, comm);
739 for (int j = 0; j < k; ++j)
740 v[j] = o[(std::size_t)j];
741 }
742#endif
743 (void)v;
744 (void)k;
745 }
746 double allMax(double v) const {
747#ifdef PECLET_FLOW_MPI
748 if (distributed) {
749 double o = 0.0;
750 MPI_Allreduce(&v, &o, 1, MPI_DOUBLE, MPI_MAX, comm);
751 return o;
752 }
753#endif
754 return v;
755 }
756};
757
768
770inline CutContext cutContext(C3 e, int g, std::size_t n, const scg::ScalarCutGeometry& gm,
771 bool distributed) {
772 CutContext cx;
773 cx.e = e;
774 cx.g = g;
775 cx.n = n;
776 cx.unk = CCConst(gm.unknown);
777 cx.kap = CCConst(gm.kappa);
778 cx.distributed = distributed;
779 return cx;
780}
781
785 long flux = 0, guarded = 0;
786 double vmax = 0.0;
787};
788
792template <class Grid>
794 const bool openHere[6], const CCField openFlux[6],
795 const CutContext& cx) {
796 ScalarCutState& st = *sc.cut;
797 const CCConst unk = cx.unk;
798 const C3 e = cx.e;
799 const int g = cx.g;
801 for (int a = 0; a < 3; ++a) {
802 const typename Solver<Grid>::ScalarFaceFlux ff = s.scalarFaceFlux(a);
803 if (steady) // IN PLACE on C[a].u / uf_: keep the high-side face (doc/uf_outlet_fix.md)
804 s.fillFaceGhostsKeepBoundary(ff.vel, a);
805 fc.vmax = std::fmax(fc.vmax, sco::maxabsLocal(CCConst(ff.vel), e, g));
806 sco::faceFluxes(st.phi[a], CCConst(ff.vel), CCConst(ff.open), unk, a, e);
807 for (int side = 0; side < 2; ++side)
808 if (openHere[2 * a + side])
809 sco::openFaceFluxes(st.phi[a], CCConst(openFlux[2 * a + side]), unk, a, side, e, g);
810 long n1 = 0, n2 = 0;
811 sco::faceFluxCountsLocal(CCConst(st.phi[a]), CCConst(ff.vel), CCConst(ff.open), a, e, g, n1,
812 n2);
813 fc.flux += n1;
814 fc.guarded += n2;
815 }
816 return fc;
817}
818
821template <class Units>
822inline void advectionMaxima(const ScalarCutState& st, double vmax, double vcell,
823 const CutContext& cx, const Units& u, double mx[4]) {
824 const C3 e = cx.e;
825 const int g = cx.g;
826 mx[0] = sco::maxAbsFluxLocal(CCConst(st.phi[0]), CCConst(st.phi[1]), CCConst(st.phi[2]), e, g);
827 mx[1] = vmax;
828 mx[2] = sco::maxCellPecletLocal(CCConst(st.phi[0]), CCConst(st.phi[1]), CCConst(st.phi[2]),
829 cx.unk, st.lam, u.w, e, g);
830 mx[3] = vcell;
831#ifdef PECLET_FLOW_MPI
832 if (cx.distributed) {
833 double o[4] = {0.0, 0.0, 0.0, 0.0};
834 MPI_Allreduce(mx, o, 4, MPI_DOUBLE, MPI_MAX, cx.comm);
835 for (int k = 0; k < 4; ++k)
836 mx[k] = o[k];
837 }
838#endif
839}
840
844inline void refuseUnadvectable(const std::string& name, const double mx[4], bool noFaceField,
845 bool noProjection, bool noOpenFlux) {
846 // Review finding 1 (ruling D-WOR-1): on the collocated grid the advecting field is the projected
847 // MAC face field uf_/vf_/wf_. set_solid zeroes it and a raw set_field('u', ...) does not seed it,
848 // so before the first projection a moving fluid would read max|uf| = 0 and be silently left
849 // unadvected (the trap advect_vof closed for VoF, ISSUES sweep item 5). Refused, as there.
850 if (noFaceField && mx[3] > 0.0)
851 throw std::runtime_error(
852 "cut-cell scalar '" + name +
853 "': SolverColocated advects with the projected MAC FACE field uf_/vf_/wf_ (the only "
854 "discretely divergence-free field on this grid), and it has never been built since the "
855 "geometry was set -- it is all zeros, so the moving fluid would be silently ignored. "
856 "Call set_state()/set_velocity() (which seed the face field through the same "
857 "centerToFace map project() uses) or step() first (doc/scalar_ibm_design.md §6.1)");
858 // WO-5 (open, reported): without the cut-cell pressure operator no projection runs and no
859 // openness exists (set_solid(..., cutcell_pressure=False)), so there is no discretely
860 // divergence-free face flux to advect with (§6.1); a moving fluid is refused rather than left
861 // silently unadvected. A fluid at rest (diffusion only, WO-3/WO-4) is unaffected.
862 if (noProjection && mx[1] > 0.0)
863 throw std::runtime_error("cut-cell scalar '" + name +
864 "': the fluid moves but no cut-cell projection exists to advect "
865 "with -- use set_solid(..., cutcell_pressure=True) or "
866 "set_pressure_geometry (doc/scalar_ibm_design.md §6.1)");
867 // WO-5b: the flux of an open domain face is the one the projection constrained, captured by
868 // step(); before the first projection there is none to advect with.
869 if (noOpenFlux && mx[1] > 0.0)
870 throw std::runtime_error("cut-cell scalar '" + name +
871 "': the fluid moves and the domain has an inflow/outflow face, but no "
872 "projection has supplied that face's flux yet -- advance with step() "
873 "(doc/scalar_ibm_design.md §6.5)");
874}
875
878 st.numSmall = 0;
879 st.numImplicitFaces = 0;
880 st.bulkCourant = 0.0;
881 st.numFluxFaces = 0;
882 st.numGuardedFaces = 0;
883 st.numBackflowFaces = 0;
884}
885
887inline void countGuardedOnly(ScalarCutState& st, long nGuard, const CutContext& cx) {
888 long cnt[1] = {nGuard};
889#ifdef PECLET_FLOW_MPI
890 if (cx.distributed) {
891 long o[1];
892 MPI_Allreduce(cnt, o, 1, MPI_LONG, MPI_SUM, cx.comm);
893 cnt[0] = o[0];
894 }
895#endif
896 (void)cx;
897 st.numGuardedFaces = cnt[0];
898}
899
902template <class Grid>
904 double dt, const CutContext& cx) {
905 ScalarCutState& st = *sc.cut;
906 const CCConst unk = cx.unk, kap = cx.kap;
907 const C3 e = cx.e;
908 const int g = cx.g;
909 const CCConst px(st.phi[0]), py(st.phi[1]), pz(st.phi[2]);
910 double cb = sco::bulkCourantLocal(px, py, pz, kap, unk, CCConst(gm.sax), CCConst(gm.say),
911 CCConst(gm.saz), dt, e, g);
912#ifdef PECLET_FLOW_MPI
913 if (cx.distributed) {
914 double o = 0.0;
915 MPI_Allreduce(&cb, &o, 1, MPI_DOUBLE, MPI_MAX, cx.comm);
916 cb = o;
917 }
918#endif
919 st.bulkCourant = cb;
920 // Review finding 7 (D-WO5-1): koren with forward Euler is TVD only to bulk Courant 1/2 (min
921 // -21 at C = 0.9 with no solid); legacy-identical, so said once rather than refused.
922 if (sc.scheme == 1 && cb > 0.5 && !st.warnedKoren) {
923 st.warnedKoren = true;
924 if (s.scalarRootRank())
925 std::fprintf(stderr,
926 "peclet.flow: cut-cell scalar '%s': scheme 'koren' at bulk Courant %.3f > 1/2 "
927 "-- the explicit limiter is bounded only to 1/2 and overshoots above it; "
928 "reduce dt or use scheme='fou' (diagnostics.scalar_census 'bulk_courant', "
929 "printed once)\n",
930 sc.name.c_str(), cb);
931 }
932 sco::smallCells(st.small, px, py, pz, kap, unk, dt, std::fmax(0.5, cb), e, g);
933 // Review finding 6 (ruling D-WOR-6): the ghost flags are the OWNER's, by one exchange per
934 // advance, so a face's implicit/explicit split agrees across ranks whatever the ghost fluxes
935 // (formerly ghost layer 1 was recomputed locally, which agreed only through flow's
936 // outflow-correction and ghost-fill ranges). The periodic wrap beyond a non-periodic face is
937 // then cleared with the unknown flags, as the local computation had it.
938 s.fillGhosts(st.small);
939 sco::zeroNonUnknown(st.small, unk, e, 0);
940}
941
944inline void countAdvection(ScalarField& sc, bool steady, const bool openHere[6],
945 const FaceFluxCounts& fc, const CutContext& cx) {
946 ScalarCutState& st = *sc.cut;
947 const CCConst unk = cx.unk;
948 const C3 e = cx.e;
949 const int g = cx.g;
950 long cnt[5] = {sco::countSmallLocal(CCConst(st.small), e, g), 0, fc.flux, fc.guarded, 0};
951 for (int a = 0; a < 3; ++a)
952 cnt[1] += sco::countImplicitLocal(CCConst(st.phi[a]), CCConst(st.small), unk, a, steady, e, g);
953 for (int f = 0; f < 6; ++f) {
954 st.openFace[f] = openHere[f];
955 if (!openHere[f])
956 continue;
957 long n1 = 0, n2 = 0, n3 = 0;
958 sco::openFaceCountsLocal(CCConst(st.phi[f / 2]), CCConst(st.small), unk, st.openInflow[f],
959 f / 2, f % 2, steady, e, g, n1, n2, n3);
960 cnt[2] += n1;
961 cnt[1] += n2;
962 cnt[4] += n3;
963 }
964#ifdef PECLET_FLOW_MPI
965 if (cx.distributed) {
966 long o[5];
967 MPI_Allreduce(cnt, o, 5, MPI_LONG, MPI_SUM, cx.comm);
968 for (int k = 0; k < 5; ++k)
969 cnt[k] = o[k];
970 }
971#endif
972 st.numSmall = cnt[0];
973 st.numImplicitFaces = cnt[1];
974 st.numFluxFaces = cnt[2];
975 st.numGuardedFaces = cnt[3];
976 st.numBackflowFaces = cnt[4];
977}
978
982template <class Grid>
983inline void warnBackflow(const Solver<Grid>& s, ScalarField& sc, bool steady) {
984 ScalarCutState& st = *sc.cut;
985 if (steady && st.numBackflowFaces > 0 && !st.warnedBackflow) {
986 st.warnedBackflow = true;
987 if (s.scalarRootRank())
988 std::fprintf(stderr,
989 "peclet.flow: cut-cell scalar '%s': %ld outflow-face row(s) carry BACKFLOW in "
990 "the steady solve (flow entering through an 'outflow' face). Their inflow "
991 "takes the zero-gradient value c_i, which is not a well-posed inflow condition "
992 "(doc/scalar_ibm_design.md §6.5): the matrix loses column dominance there, and "
993 "the advective preconditioner's coarse mass omega_open is clamped at 0 on those "
994 "rows (A2). Prefer an 'inflow' face where fluid enters "
995 "(diagnostics.scalar_census 'num_backflow_faces', printed once)\n",
996 sc.name.c_str(), st.numBackflowFaces);
997 }
998}
999
1001inline void allocateWork(ScalarField& sc, std::size_t n, long numFacets) {
1002 ScalarCutState& st = *sc.cut;
1003 ensureField(st.SAC, n, sc.name, "_cc_sac");
1004 ensureField(st.kr, n, sc.name, "_cc_r");
1005 ensureField(st.krh, n, sc.name, "_cc_rh");
1006 ensureField(st.kp, n, sc.name, "_cc_p");
1007 ensureField(st.kv, n, sc.name, "_cc_v");
1008 ensureField(st.kt, n, sc.name, "_cc_t");
1009 ensureField(st.kz, n, sc.name, "_cc_z");
1010 ensureField(st.kz2, n, sc.name, "_cc_z2");
1011 if (st.cw.extent(0) != (std::size_t)numFacets) {
1012 st.cw = Kokkos::View<double*, CCMem>(sc.name + "_cc_cw", numFacets);
1013 st.rw = Kokkos::View<double*, CCMem>(sc.name + "_cc_rw", numFacets);
1014 }
1015}
1016
1019template <class Units>
1020inline void operatorScalars(ScalarCutState& st, bool steady, double dt, double D, const Units& u,
1021 long numUnknowns) {
1022 const double lam = D * u.diffToInt();
1023 const double idt = steady ? 0.0 : 1.0 / dt;
1024 const double srcFactor = u.divToInt();
1025 st.lam = lam;
1026 st.idt = idt;
1027 st.dt = steady ? 0.0 : dt;
1028 st.srcFactor = srcFactor;
1029 st.steady = steady;
1030 st.numUnknowns = numUnknowns;
1031 // mean-gradient mode (§1.5): G' = G hRef; every G term below is skipped when G = 0
1032 st.meanGradOn = st.meanGrad[0] != 0.0 || st.meanGrad[1] != 0.0 || st.meanGrad[2] != 0.0;
1033 for (int a = 0; a < 3; ++a) {
1034 st.gPhys[a] = st.meanGrad[a];
1035 st.gInt[a] = st.meanGrad[a] * u.lenToPhys();
1036 st.ubar[a] = 0.0;
1037 }
1038}
1039
1041template <class Units>
1042inline sco::WallTable wallTable(ScalarCutState& st, int nb, const Units& u) {
1043 st.wtType.assign(nb, st.wallDefault.type);
1044 st.wtK.assign(nb, st.wallDefault.coefficient);
1045 st.wtG.assign(nb, st.wallDefault.value);
1046 st.wtQ.assign(nb, st.wallDefault.value);
1047 for (const auto& [inst, w] : st.wallInstance)
1048 if (inst >= 0 && inst < nb) {
1049 st.wtType[inst] = w.type;
1050 st.wtK[inst] = w.coefficient;
1051 st.wtG[inst] = w.value;
1052 st.wtQ[inst] = w.value;
1053 }
1054 const double sp = u.speedToInt();
1055 for (int b = 0; b < nb; ++b) {
1056 st.wtK[b] = st.wtType[b] == 2 ? st.wtK[b] * sp : 0.0;
1057 st.wtQ[b] = st.wtType[b] == 0 ? st.wtQ[b] * sp : 0.0;
1058 st.wtG[b] = st.wtType[b] == 0 ? 0.0 : st.wtG[b];
1059 }
1060 if (st.wtTypeV.extent(0) != (std::size_t)nb) { // persistent, refilled below (finding 7)
1061 st.wtTypeV = Kokkos::View<int*, CCMem>("peclet::flow::sco_wt_type", nb);
1062 st.wtKV = Kokkos::View<double*, CCMem>("peclet::flow::sco_wt_k", nb);
1063 st.wtGV = Kokkos::View<double*, CCMem>("peclet::flow::sco_wt_g", nb);
1064 st.wtQV = Kokkos::View<double*, CCMem>("peclet::flow::sco_wt_q", nb);
1065 }
1066 sco::WallTable wt;
1067 wt.nb = nb;
1068 wt.type = st.wtTypeV;
1069 wt.k = st.wtKV;
1070 wt.gval = st.wtGV;
1071 wt.q = st.wtQV;
1072 {
1073 auto ht = Kokkos::create_mirror_view(wt.type);
1074 auto hk = Kokkos::create_mirror_view(wt.k);
1075 auto hg = Kokkos::create_mirror_view(wt.gval);
1076 auto hq = Kokkos::create_mirror_view(wt.q);
1077 for (int b = 0; b < nb; ++b) {
1078 ht(b) = st.wtType[b];
1079 hk(b) = st.wtK[b];
1080 hg(b) = st.wtG[b];
1081 hq(b) = st.wtQ[b];
1082 }
1083 Kokkos::deep_copy(wt.type, ht);
1084 Kokkos::deep_copy(wt.k, hk);
1085 Kokkos::deep_copy(wt.gval, hg);
1086 Kokkos::deep_copy(wt.q, hq);
1087 }
1088 return wt;
1089}
1090
1092inline void rightHandSide(ScalarField& sc, const scg::ScalarCutGeometry& gm, const CutContext& cx) {
1093 ScalarCutState& st = *sc.cut;
1094 if (st.sourceIsField && st.sourceField.extent(0) != cx.n)
1095 throw std::runtime_error("cut-cell scalar '" + sc.name +
1096 "': the per-cell source no longer matches this rank's block "
1097 "(redistributed?) -- call set_scalar_source again");
1098 const bool useField = st.sourceIsField;
1099 sco::buildRhs(sc.b, CCConst(sc.cOld), cx.kap, cx.unk, st.idt, st.sourceConst,
1100 CCConst(useField ? st.sourceField : sc.cOld), useField, st.srcFactor, cx.e, cx.g);
1101 sco::overlayRhs(sc.b, gm.fac, st.rw);
1102}
1103
1106template <class Units>
1107inline Kokkos::View<double*, CCMem> dirichletFaceValues(ScalarField& sc, int f, const int n[3],
1108 C3 origin, const Units& u) {
1109 ScalarCutState& st = *sc.cut;
1110 const int a = f / 2, side = f % 2;
1111 int t1, t2;
1112 sco::faceTangents(a, t1, t2);
1113 const long nf = (long)n[t1] * n[t2];
1114 if (st.gFace[f].extent(0) != (std::size_t)nf) // persistent, refilled below (finding 7)
1115 st.gFace[f] = Kokkos::View<double*, CCMem>(sc.name + "_cc_gface", nf);
1116 Kokkos::View<double*, CCMem> gv = st.gFace[f];
1117 if (st.hasProfile[f] && (st.profileN[f][0] != n[t1] || st.profileN[f][1] != n[t2]))
1118 throw std::runtime_error("cut-cell scalar '" + sc.name +
1119 "': the domain-face profile no longer matches this rank's block");
1120 if (st.hasProfile[f] || st.meanGradOn) {
1121 // §1.5: in mean-gradient mode the face holds theta_bf = g - G.x_bf (x_bf the boundary face
1122 // centre; G_a = 0 on this non-periodic axis by the refusals)
1123 const int og[3] = {origin.x, origin.y, origin.z};
1124 const double xa = u.org[a] + (double)(og[a] + (side == 0 ? 0 : n[a])) * u.h[a];
1125 auto hv = Kokkos::create_mirror_view(gv);
1126 for (int j2 = 0; j2 < n[t2]; ++j2)
1127 for (int j1 = 0; j1 < n[t1]; ++j1) {
1128 const long k = (long)j1 + (long)j2 * n[t1];
1129 double v = st.hasProfile[f] ? st.profile[f][(std::size_t)k] : sc.bcVal[f];
1130 if (st.meanGradOn) {
1131 double p[3];
1132 p[a] = xa;
1133 p[t1] = u.org[t1] + ((double)(og[t1] + j1) + 0.5) * u.h[t1];
1134 p[t2] = u.org[t2] + ((double)(og[t2] + j2) + 0.5) * u.h[t2];
1135 v -= (st.gPhys[0] * p[0] + st.gPhys[1] * p[1]) + st.gPhys[2] * p[2];
1136 }
1137 hv(k) = v;
1138 }
1139 Kokkos::deep_copy(gv, hv);
1140 } else {
1141 Kokkos::deep_copy(gv, sc.bcVal[f]);
1142 }
1143 return gv;
1144}
1145
1149template <class Grid, class Units>
1150inline void advectionOperator(Solver<Grid>& s, ScalarField& sc, bool steady, const CutContext& cx,
1151 const Units& u) {
1152 ScalarCutState& st = *sc.cut;
1153 const CCConst unk = cx.unk, kap = cx.kap;
1154 const C3 e = cx.e;
1155 const int g = cx.g;
1156 const CCConst px(st.phi[0]), py(st.phi[1]), pz(st.phi[2]);
1157 sco::advectionBands(sc.AC, sc.AW, sc.AE, sc.AS, sc.AN, sc.AB, sc.AT, st.outflow, px, py, pz,
1158 CCConst(st.small), unk, steady, e, g);
1159 if (!steady) {
1160 s.fillGhosts(sc.cOld); // c^n's ghosts: the reconstruction reaches two cells past the face
1161 for (int a = 0; a < 3; ++a) {
1162 if (st.Phi[a].extent(0) != cx.n)
1163 st.Phi[a] = CCField(sc.name + "_cc_Phi", cx.n);
1164 sco::explicitFaceFluxes(st.Phi[a], CCConst(st.phi[a]), CCConst(sc.cOld), unk,
1165 CCConst(st.small), a, sc.scheme, false, e, g);
1166 }
1167 sco::explicitAdvectionRhs(sc.b, CCConst(st.Phi[0]), CCConst(st.Phi[1]), CCConst(st.Phi[2]), unk,
1168 e, g);
1169 }
1170 // WO-5b: the open domain faces' rows (§1.4): inflow F_in g on the rhs, outflow F_out c_i.
1171 // A2: a steady solve also collects their implicit outflow in omega_open (the advective
1172 // surrogate's coarse mass), clamped at 0.
1173 if (steady) {
1174 if (st.omegaOpen.extent(0) != cx.n)
1175 st.omegaOpen = CCField(sc.name + "_cc_omega_open", cx.n);
1176 Kokkos::deep_copy(CCExec(), st.omegaOpen, 0.0);
1177 }
1178 for (int f = 0; f < 6; ++f)
1179 if (st.openFace[f])
1180 sco::openFaceAdvection(sc.AC, sc.b, st.outflow, CCConst(sc.cOld), CCConst(st.phi[f / 2]),
1181 CCConst(st.small), unk, st.gFace[f], st.openInflow[f], f / 2, f % 2,
1182 steady, e, g, st.omegaOpen, steady);
1183 if (steady)
1184 sco::clampNonNegative(st.omegaOpen, e, g);
1185 if (st.meanGradOn) {
1186 // §1.5 advection: theta is advected; the linear part enters exactly as the source
1187 // -G'.(U'_i/V - kappa_i U'bar), U'bar = sum U'_i / sum kappa_i V (the moving frame)
1188 const double hh[3] = {0.5 * u.hp[0], 0.5 * u.hp[1], 0.5 * u.hp[2]};
1189 double m[4];
1190 sco::cellVelocitySumLocal(px, py, pz, unk, hh, e, g, m);
1191 double kc = 0.0;
1192 sco::kappaMomentsLocal(CCConst(sc.c), kap, unk, e, g, kc, m[3]);
1193#ifdef PECLET_FLOW_MPI
1194 if (cx.distributed) {
1195 double o[4];
1196 MPI_Allreduce(m, o, 4, MPI_DOUBLE, MPI_SUM, cx.comm);
1197 for (int j = 0; j < 4; ++j)
1198 m[j] = o[j];
1199 }
1200#endif
1201 for (int a = 0; a < 3; ++a)
1202 st.ubar[a] = m[3] > 0.0 ? m[a] / m[3] : 0.0;
1203 sco::meanGradientAdvectionRhs(sc.b, px, py, pz, kap, unk, st.gInt, hh, st.ubar, e, g);
1204 }
1205}
1206
1210template <class Units>
1212 const sco::MaterialTable& mt, const sco::MeanGradPosition& mgPos,
1213 const CutContext& cx, const Units& u) {
1214 ScalarCutState& st = *sc.cut;
1215 const CCConst unk = cx.unk, kap = cx.kap;
1216 const C3 e = cx.e;
1217 const int g = cx.g;
1218 const double lam = st.lam, idt = st.idt;
1219 const CCConst sunk(st.sunk), matv(st.mat);
1220 ensureField(st.spx, cx.n, sc.name, "_cc_spx");
1221 ensureField(st.spy, cx.n, sc.name, "_cc_spy");
1222 ensureField(st.spz, cx.n, sc.name, "_cc_spz");
1223 ensureField(st.ms, cx.n, sc.name, "_cc_ms");
1224 ensureField(st.ASC, cx.n, sc.name, "_cc_asc");
1225 ensureField(st.ASW, cx.n, sc.name, "_cc_asw");
1226 ensureField(st.ASE, cx.n, sc.name, "_cc_ase");
1227 ensureField(st.ASS, cx.n, sc.name, "_cc_ass");
1228 ensureField(st.ASN, cx.n, sc.name, "_cc_asn");
1229 ensureField(st.ASB, cx.n, sc.name, "_cc_asb");
1230 ensureField(st.AST, cx.n, sc.name, "_cc_ast");
1231 ensureField(st.bS, cx.n, sc.name, "_cc_bs");
1232 ensureField(st.sOld, cx.n, sc.name, "_cc_sold");
1233 ensureField(st.SACs, cx.n, sc.name, "_cc_sacs");
1234 ensureField(st.W0, cx.n, sc.name, "_cc_w0");
1235 if (st.cc.extent(0) != (std::size_t)gm.fac.n)
1236 st.cc = Kokkos::View<double*, CCMem>(sc.name + "_cc_cc", gm.fac.n);
1237 sco::zeroNonUnknown(st.solid, sunk, e, g);
1238 Kokkos::deep_copy(CCExec(), st.sOld, st.solid);
1239 sco::solidFaceProducts(st.spx, st.spy, st.spz, sunk, matv, CCConst(gm.sax), CCConst(gm.say),
1240 CCConst(gm.saz), mt, e);
1241 sco::solidMass(st.ms, kap, sunk, matv, mt, idt, e, g);
1242 sco::solidBands(st.ASC, st.ASW, st.ASE, st.ASS, st.ASN, st.ASB, st.AST, CCConst(st.ms), sunk,
1243 CCConst(st.spx), CCConst(st.spy), CCConst(st.spz), u.w, e, g);
1244 sco::solidRhs(st.bS, CCConst(st.ms), CCConst(st.sOld), e, g);
1245 sco::conjugateCoefficients(st.cc, gm.fac, Kokkos::View<const std::uint8_t*, CCMem>(st.conjF),
1246 Kokkos::View<const double*, CCMem>(st.sS), unk, sunk, mt, lam);
1247 if (st.meanGradOn) {
1248 double gs[3];
1249 for (int a = 0; a < 3; ++a)
1250 gs[a] = u.w[a] * u.hp[a] * st.gInt[a];
1251 sco::solidMeanGradientFaceRhs(st.bS, sunk, CCConst(st.spx), CCConst(st.spy), CCConst(st.spz),
1252 gs, e, g);
1253 sco::conjMeanGradientShift(sc.b, st.bS, gm.fac, st.cc, st.offS, st.wS, mgPos);
1254 }
1255 // the two-field level-0 surrogate (§4.3)
1256 sco::conjSurrogate(st.SAC, st.SACs, st.W0, CCConst(sc.AC), CCConst(st.ASC), gm.fac, st.cw, st.cc);
1257}
1258
1260inline bool singularSolve(const ScalarCutState& st, bool steady, bool anyDir, const int bc[6],
1261 const CutContext& cx) {
1262 double sing[2] = {sco::maxFacetLocal(st.cw), anyDir ? 1.0 : 0.0};
1263#ifdef PECLET_FLOW_MPI
1264 if (cx.distributed) {
1265 double gs[2];
1266 MPI_Allreduce(sing, gs, 2, MPI_DOUBLE, MPI_MAX, cx.comm);
1267 sing[0] = gs[0];
1268 sing[1] = gs[1];
1269 }
1270#endif
1271 (void)cx;
1272 // Review finding 2b (ruling D-WOR-2b): an open domain face carrying flux takes the problem out
1273 // of the uniform-mean case. An outflow face's column sums to its F_out, not 0, so 1 is not a
1274 // left null vector and the uniform-mean projection and gauge below are not the compatibility
1275 // conditions; they are never applied there. (An inflow face needs a scalar Dirichlet value, so
1276 // that case was never singular.) With open faces but no inflow face, continuity forces backflow
1277 // and the operator stays singular (A 1 = 0 up to the projection's divergence) with a NON-uniform
1278 // left null vector: the solve converges for a compatible right-hand side (no source, insulating
1279 // walls) and otherwise reports non-convergence; the backflow warning above names the cause.
1280 // `bc_` is global and `st.advecting` a global MAX, so every rank agrees. Without flux an open
1281 // face is a plain Neumann/Dirichlet scalar face, and the diffusion-only rule stands.
1282 bool anyOpenFlux = false;
1283 for (int f = 0; f < 6; ++f)
1284 anyOpenFlux = anyOpenFlux || bc[f] == 2 || bc[f] == 3;
1285 anyOpenFlux = anyOpenFlux && st.advecting;
1286 return steady && !(sing[0] > 0.0) && !(sing[1] > 0.0) && !anyOpenFlux;
1287}
1288
1290template <class Units>
1292 const CutContext& cx, const Units& u) {
1293 ScalarCutState& st = *sc.cut;
1294 const double lam = st.lam;
1296 in.lam = lam;
1297 in.idt = st.idt;
1298 // the level rule: transient with kappa_A = 1 + 4 dt' D' sum_a w_a < ScalarMG::kFullTableKappa
1299 // -> level 0 alone (WO-7: max(D', D_s') over the conjugate materials, D_s = Lam_s/(C_s K))
1300 const double kA = 1.0 + 4.0 * st.dt * (st.conj ? std::fmax(lam, st.maxSolidD) : lam) *
1301 ((u.w[0] + u.w[1]) + u.w[2]);
1302 in.fullTable = steady || !(kA < ScalarMG::kFullTableKappa);
1303 in.singular = st.singular;
1304 in.SAC = st.SAC;
1305 in.kappa = cx.kap;
1306 in.unknown = cx.unk;
1307 in.sax = CCConst(gm.sax);
1308 in.say = CCConst(gm.say);
1309 in.saz = CCConst(gm.saz);
1310 in.fac = &gm.fac;
1311 in.facetW = st.cw;
1312 for (int f = 0; f < 6; ++f)
1313 in.dirFace[f] = st.dirFace[f];
1314 if (steady && st.advecting) {
1315 // A2 (§6.7): the advective surrogate — the operator's bands (SAC the diagonal), the face
1316 // flux for the coarse advection, omega_open on the coarse mass. `st.advecting` is an
1317 // all-rank MAX, so every rank takes this path.
1318 in.advective = true;
1319 in.AW = sc.AW;
1320 in.AE = sc.AE;
1321 in.AS = sc.AS;
1322 in.AN = sc.AN;
1323 in.AB = sc.AB;
1324 in.AT = sc.AT;
1325 for (int a = 0; a < 3; ++a)
1326 in.phi[a] = CCConst(st.phi[a]);
1327 in.omegaOpen = CCConst(st.omegaOpen);
1328 } else if (st.advecting) { // the lumped implicit outflow onto the coarse levels (§5.2)
1329 in.outflow = CCConst(st.outflow);
1330 in.hasOutflow = true;
1331 }
1332 if (st.conj) { // WO-7: the coupled two-field levels (§5.2)
1333 in.twoPhase = true;
1334 in.SACs = st.SACs;
1335 in.W0 = st.W0;
1336 in.sunk = CCConst(st.sunk);
1337 in.spx = CCConst(st.spx);
1338 in.spy = CCConst(st.spy);
1339 in.spz = CCConst(st.spz);
1340 in.ms0 = CCConst(st.ms);
1341 in.facetC = st.cc;
1342 }
1343 return in;
1344}
1345
1351template <class Grid>
1352inline void warnShallowBottom(const Solver<Grid>& s, ScalarField& sc, bool fullTable) {
1353 ScalarCutState& st = *sc.cut;
1354 if (fullTable && !st.warnedBottom) {
1355 const auto& lc = st.mg->level(st.mg->levelsUsed() - 1);
1356 const int be = s.pressureBottomExtent();
1357 if (lc.gdim.x > be || lc.gdim.y > be || lc.gdim.z > be) {
1358 st.warnedBottom = true;
1359 if (s.scalarRootRank())
1360 std::fprintf(stderr,
1361 "peclet.flow: cut-cell scalar '%s': the ScalarMG level table stops at %d x "
1362 "%d x %d cells (%d levels), larger than the pressure's bottom extent %d on "
1363 "some axis -- an axis that cannot halve (odd or 2-poor size, or an odd MPI "
1364 "block). Its bottom is smoothing only, not an exact solve, so the iteration "
1365 "count grows with the grid (78 iterations at n = 77 against 6 at n = 80). "
1366 "Size the grid and the blocks with factors of two (printed once)\n",
1367 sc.name.c_str(), lc.gdim.x, lc.gdim.y, lc.gdim.z, st.mg->levelsUsed(), be);
1368 }
1369 }
1370}
1371
1373inline void removeMean(const CutContext& cx, CCField a, double nUnk) {
1374 double s[2];
1375 sco::sumUnknownLocal(CCConst(a), cx.unk, cx.e, cx.g, s[0], s[1]);
1376 cx.allSum(s, 1);
1377 if (nUnk > 0.0)
1378 sco::addOnUnknown(a, cx.unk, -s[0] / nUnk, cx.e, cx.g);
1379}
1380
1382inline void removeMeanTwo(const CutContext& cx, CCField a, CCField as, const CCConst& sunk,
1383 double nTot) {
1384 double sf[2], ss[2];
1385 sco::sumUnknownLocal(CCConst(a), cx.unk, cx.e, cx.g, sf[0], sf[1]);
1386 sco::sumUnknownLocal(CCConst(as), sunk, cx.e, cx.g, ss[0], ss[1]);
1387 double v[1] = {sf[0] + ss[0]};
1388 cx.allSum(v, 1);
1389 if (nTot > 0.0) {
1390 sco::addOnUnknown(a, cx.unk, -v[0] / nTot, cx.e, cx.g);
1391 sco::addOnUnknown(as, sunk, -v[0] / nTot, cx.e, cx.g);
1392 }
1393}
1394
1398 ScalarCutState& st = *sc.cut;
1399 const double nUnk = (double)st.numUnknowns;
1400 CCField bK = sc.b;
1401 st.incompatibility = 0.0;
1402 if (st.singular) {
1403 ensureField(st.kb, cx.n, sc.name, "_cc_bproj");
1404 ensureField(st.kq, cx.n, sc.name, "_cc_q");
1405 Kokkos::deep_copy(CCExec(), st.kb, sc.b);
1406 double s[2];
1407 sco::sumUnknownLocal(CCConst(st.kb), cx.unk, cx.e, cx.g, s[0], s[1]);
1408 cx.allSum(s, 2);
1409 st.incompatibility = s[1] > 0.0 ? std::fabs(s[0]) / s[1] : 0.0;
1410 if (nUnk > 0.0)
1411 sco::addOnUnknown(st.kb, cx.unk, -s[0] / nUnk, cx.e, cx.g);
1412 bK = st.kb;
1413 }
1414 return bK;
1415}
1416
1421template <class Grid>
1423 const CutContext& cx = k.cx;
1424 ScalarKrylovOps ops;
1425 ops.e = cx.e;
1426 ops.g = cx.g;
1427 ops.matvec = [&s, &sc](const ScalarVec& y, const ScalarVec& x) {
1428 s.scalarCutMatvec(sc, y.f, x.f);
1429 };
1430 ops.precond = [&k](const ScalarVec& z, const ScalarVec& r) {
1431 ScalarCutState& st = k.st;
1432 CCField rr = r.f;
1433 if (st.singular) {
1434 Kokkos::deep_copy(CCExec(), st.kq, r.f);
1435 removeMean(k.cx, st.kq, k.nUnk);
1436 rr = st.kq;
1437 }
1438 st.mg->apply(z.f, rr);
1439 if (st.singular)
1440 removeMean(k.cx, z.f, k.nUnk);
1441 };
1442 ops.dot = [&cx](const ScalarVec& a, const ScalarVec& b) {
1443 double s = sco::dotLocal(CCConst(a.f), CCConst(b.f), cx.e, cx.g);
1444 cx.allSum(&s, 1);
1445 return s;
1446 };
1447 ops.dot2 = [&cx](const ScalarVec& a, const ScalarVec& b, const ScalarVec& c, double& ab,
1448 double& cc) {
1449 double s[2];
1450 sco::dot2Local(CCConst(a.f), CCConst(b.f), CCConst(c.f), cx.e, cx.g, s[0], s[1]);
1451 cx.allSum(s, 2);
1452 ab = s[0];
1453 cc = s[1];
1454 };
1455 ops.maxabs = [&cx](const ScalarVec& a) {
1456 return cx.allMax(sco::maxabsLocal(CCConst(a.f), cx.e, cx.g));
1457 };
1458 ops.removeMean = [&k](const ScalarVec& a) { removeMean(k.cx, a.f, k.nUnk); };
1459 if (!cx.distributed) { // WO-9b: the device-resident pass (scalar_krylov.hpp), single rank
1460 residentKrylov(k.st, ops);
1461 ops.dotTo = [&cx](const ScalarVec& a, const ScalarVec& b, skr::Slot s) {
1462 sco::dotReduce(CCConst(a.f), CCConst(b.f), cx.e, cx.g, s);
1463 };
1464 ops.dot2To = [&cx](const ScalarVec& a, const ScalarVec& b, const ScalarVec& c, skr::Slot s1,
1465 skr::Slot s2) {
1466 sco::dot2Reduce(CCConst(a.f), CCConst(b.f), CCConst(c.f), cx.e, cx.g, s1, s2);
1467 };
1468 ops.maxabsTo = [&cx](const ScalarVec& a, skr::Slot sf, skr::Slot) {
1469 sco::maxabsReduce(CCConst(a.f), cx.e, cx.g, Kokkos::Max<double, CCMem>(sf));
1470 };
1471 }
1472 return ops;
1473}
1474
1476 ScalarVec v;
1477 v.f = f;
1478 return v;
1479}
1480
1482 ScalarVec v;
1483 v.f = f;
1484 v.s = s2;
1485 v.solid = true;
1486 return v;
1487}
1488
1493 const ScalarVec& t, const ScalarVec& x, const ScalarVec& b,
1494 const ScalarCutState& st, const CutContext& cx) {
1495 if (kr.ref > 0.0) {
1496 ops.matvec(t, x);
1497 skr::residualFrom(t, b, cx.e, cx.g);
1498 ops.removeMean(t);
1499 kr.trueRes = ops.maxabs(t);
1500 kr.converged = kr.trueRes <= 10.0 * (st.rtol * kr.ref);
1501 }
1502}
1503
1506template <class Grid>
1508 ScalarCutState& st = *sc.cut;
1509 const CCField bK = projectedRhs(sc, cx);
1510 // gauge of the singular solve: sum kappa V c is kept at its pre-solve value (§5.1)
1511 // (in mean-gradient mode the target is 0: sum kappa V theta = 0, §5.1)
1512 double kc0 = 0.0, k0 = 0.0;
1513 if (st.singular) {
1514 double m[2];
1515 sco::kappaMomentsLocal(CCConst(sc.c), cx.kap, cx.unk, cx.e, cx.g, m[0], m[1]);
1516 cx.allSum(m, 2);
1517 kc0 = st.meanGradOn ? 0.0 : m[0];
1518 k0 = m[1];
1519 }
1520 const KrylovContext k{st, cx, CCConst(), (double)st.numUnknowns};
1521 ScalarKrylovOps ops = singleFieldOps(s, sc, k);
1523 scalarBiCGStab(ops, fieldVec(bK), fieldVec(sc.c), fieldVec(st.kr), fieldVec(st.krh),
1524 fieldVec(st.kp), fieldVec(st.kv), fieldVec(st.kt), fieldVec(st.kz),
1525 fieldVec(st.kz2), st.maxit, st.rtol, st.singular);
1526 if (st.singular && k0 > 0.0) {
1527 double m[2];
1528 sco::kappaMomentsLocal(CCConst(sc.c), cx.kap, cx.unk, cx.e, cx.g, m[0], m[1]);
1529 cx.allSum(m, 2);
1530 sco::addOnUnknown(sc.c, cx.unk, (kc0 - m[0]) / k0, cx.e, cx.g);
1531 remeasureAfterGauge(kr, ops, fieldVec(st.kt), fieldVec(sc.c), fieldVec(bK), st, cx);
1532 }
1533 return kr;
1534}
1535
1537inline void projectedRhsTwo(ScalarField& sc, const CutContext& cx, CCField& bKf, CCField& bKs) {
1538 ScalarCutState& st = *sc.cut;
1539 const CCConst sunk(st.sunk);
1540 const double nTot = (double)st.numUnknowns + (double)st.numSolidUnknowns;
1541 bKf = sc.b;
1542 bKs = st.bS;
1543 st.incompatibility = 0.0;
1544 if (st.singular) {
1545 ensureField(st.kb, cx.n, sc.name, "_cc_bproj");
1546 ensureField(st.kq, cx.n, sc.name, "_cc_q");
1547 ensureField(st.kbS, cx.n, sc.name, "_cc_bprojs");
1548 ensureField(st.kqS, cx.n, sc.name, "_cc_qs");
1549 Kokkos::deep_copy(CCExec(), st.kb, sc.b);
1550 Kokkos::deep_copy(CCExec(), st.kbS, st.bS);
1551 double sf[2], ss[2];
1552 sco::sumUnknownLocal(CCConst(st.kb), cx.unk, cx.e, cx.g, sf[0], sf[1]);
1553 sco::sumUnknownLocal(CCConst(st.kbS), sunk, cx.e, cx.g, ss[0], ss[1]);
1554 double v[2] = {sf[0] + ss[0], sf[1] + ss[1]};
1555 cx.allSum(v, 2);
1556 st.incompatibility = v[1] > 0.0 ? std::fabs(v[0]) / v[1] : 0.0;
1557 if (nTot > 0.0) {
1558 sco::addOnUnknown(st.kb, cx.unk, -v[0] / nTot, cx.e, cx.g);
1559 sco::addOnUnknown(st.kbS, sunk, -v[0] / nTot, cx.e, cx.g);
1560 }
1561 bKf = st.kb;
1562 bKs = st.kbS;
1563 }
1564}
1565
1567inline void twoFieldMoments(ScalarField& sc, const sco::MaterialTable& mt, const CutContext& cx,
1568 double m[2]) {
1569 const ScalarCutState& st = *sc.cut;
1570 const CCConst sunk(st.sunk), matv(st.mat);
1571 double a[2], b2[2];
1572 sco::kappaMomentsLocal(CCConst(sc.c), cx.kap, cx.unk, cx.e, cx.g, a[0], a[1]);
1573 sco::solidMomentsLocal(CCConst(st.solid), cx.kap, sunk, matv, mt, cx.e, cx.g, b2[0], b2[1]);
1574 m[0] = a[0] + b2[0];
1575 m[1] = a[1] + b2[1];
1576 cx.allSum(m, 2);
1577}
1578
1583template <class Grid>
1585 const CutContext& cx = k.cx;
1586 ScalarKrylovOps ops;
1587 ops.e = cx.e;
1588 ops.g = cx.g;
1589 ops.matvec = [&s, &sc](const ScalarVec& y, const ScalarVec& x) {
1590 s.scalarCutMatvecTwo(sc, y.f, y.s, x.f, x.s);
1591 };
1592 ops.precond = [&k](const ScalarVec& z, const ScalarVec& r) {
1593 ScalarCutState& st = k.st;
1594 CCField rf = r.f, rs = r.s;
1595 if (st.singular) {
1596 Kokkos::deep_copy(CCExec(), st.kq, r.f);
1597 Kokkos::deep_copy(CCExec(), st.kqS, r.s);
1598 removeMeanTwo(k.cx, st.kq, st.kqS, k.sunk, k.nUnk);
1599 rf = st.kq;
1600 rs = st.kqS;
1601 }
1602 st.mg->applyTwo(z.f, z.s, rf, rs);
1603 if (st.singular)
1604 removeMeanTwo(k.cx, z.f, z.s, k.sunk, k.nUnk);
1605 };
1606 ops.dot = [&cx](const ScalarVec& a, const ScalarVec& b) {
1607 double v = sco::dotTwoLocal(CCConst(a.f), CCConst(b.f), CCConst(a.s), CCConst(b.s), cx.e, cx.g);
1608 cx.allSum(&v, 1);
1609 return v;
1610 };
1611 ops.dot2 = [&cx](const ScalarVec& a, const ScalarVec& b, const ScalarVec& c, double& ab,
1612 double& cc) {
1613 double v[2];
1614 sco::dot2TwoLocal(CCConst(a.f), CCConst(b.f), CCConst(c.f), CCConst(a.s), CCConst(b.s),
1615 CCConst(c.s), cx.e, cx.g, v[0], v[1]);
1616 cx.allSum(v, 2);
1617 ab = v[0];
1618 cc = v[1];
1619 };
1620 ops.maxabs = [&cx](const ScalarVec& a) {
1621 return cx.allMax(std::fmax(sco::maxabsLocal(CCConst(a.f), cx.e, cx.g),
1622 sco::maxabsLocal(CCConst(a.s), cx.e, cx.g)));
1623 };
1624 ops.removeMean = [&k](const ScalarVec& a) { removeMeanTwo(k.cx, a.f, a.s, k.sunk, k.nUnk); };
1625 if (!cx.distributed) { // WO-9b: the device-resident pass (scalar_krylov.hpp), single rank
1626 residentKrylov(k.st, ops);
1627 ops.dotTo = [&cx](const ScalarVec& a, const ScalarVec& b, skr::Slot s) {
1628 sco::dotTwoReduce(CCConst(a.f), CCConst(b.f), CCConst(a.s), CCConst(b.s), cx.e, cx.g, s);
1629 };
1630 ops.dot2To = [&cx](const ScalarVec& a, const ScalarVec& b, const ScalarVec& c, skr::Slot s1,
1631 skr::Slot s2) {
1632 sco::dot2TwoReduce(CCConst(a.f), CCConst(b.f), CCConst(c.f), CCConst(a.s), CCConst(b.s),
1633 CCConst(c.s), cx.e, cx.g, s1, s2);
1634 };
1635 ops.maxabsTo = [&cx](const ScalarVec& a, skr::Slot sf, skr::Slot ss) {
1636 sco::maxabsReduce(CCConst(a.f), cx.e, cx.g, Kokkos::Max<double, CCMem>(sf));
1637 sco::maxabsReduce(CCConst(a.s), cx.e, cx.g, Kokkos::Max<double, CCMem>(ss));
1638 };
1639 }
1640 return ops;
1641}
1642
1645template <class Grid>
1647 const CutContext& cx) {
1648 ScalarCutState& st = *sc.cut;
1649 const CCConst sunk(st.sunk);
1650 ensureField(st.krS, cx.n, sc.name, "_cc_rs");
1651 ensureField(st.krhS, cx.n, sc.name, "_cc_rhs");
1652 ensureField(st.kpS, cx.n, sc.name, "_cc_ps");
1653 ensureField(st.kvS, cx.n, sc.name, "_cc_vs");
1654 ensureField(st.ktS, cx.n, sc.name, "_cc_ts");
1655 ensureField(st.kzS, cx.n, sc.name, "_cc_zs");
1656 ensureField(st.kz2S, cx.n, sc.name, "_cc_z2s");
1657 CCField bKf, bKs;
1658 projectedRhsTwo(sc, cx, bKf, bKs);
1659 // gauge (§5.1): sum kappa V c + sum C_s K kappa_s V psi_s kept (0 in mean-gradient mode)
1660 double kc0 = 0.0, k0 = 0.0;
1661 if (st.singular) {
1662 double m[2];
1663 twoFieldMoments(sc, mt, cx, m);
1664 kc0 = st.meanGradOn ? 0.0 : m[0];
1665 k0 = m[1];
1666 }
1667 const KrylovContext k{st, cx, sunk, (double)st.numUnknowns + (double)st.numSolidUnknowns};
1668 ScalarKrylovOps ops = twoFieldOps(s, sc, k);
1670 ops, fieldVecTwo(bKf, bKs), fieldVecTwo(sc.c, st.solid), fieldVecTwo(st.kr, st.krS),
1671 fieldVecTwo(st.krh, st.krhS), fieldVecTwo(st.kp, st.kpS), fieldVecTwo(st.kv, st.kvS),
1672 fieldVecTwo(st.kt, st.ktS), fieldVecTwo(st.kz, st.kzS), fieldVecTwo(st.kz2, st.kz2S),
1673 st.maxit, st.rtol, st.singular);
1674 if (st.singular && k0 > 0.0) {
1675 double m[2];
1676 twoFieldMoments(sc, mt, cx, m);
1677 const double d = (kc0 - m[0]) / k0;
1678 sco::addOnUnknown(sc.c, cx.unk, d, cx.e, cx.g);
1679 sco::addOnUnknown(st.solid, sunk, d, cx.e, cx.g);
1680 // review finding 5: the residual after the gauge shift, as in the single-field solve
1681 remeasureAfterGauge(kr, ops, fieldVecTwo(st.kt, st.ktS), fieldVecTwo(sc.c, st.solid),
1682 fieldVecTwo(bKf, bKs), st, cx);
1683 }
1684 s.fillGhosts(st.solid);
1685 return kr;
1686}
1687
1689inline void recordSolve(ScalarField& sc, const ScalarKrylovResult& kr, const CutContext& cx) {
1690 ScalarCutState& st = *sc.cut;
1691 st.iterations = kr.iterations;
1692 st.residual = kr.ref > 0.0 ? kr.trueRes / kr.ref : 0.0;
1693 st.converged = kr.converged;
1694 if (!kr.converged && !st.warnedNoConv) {
1695 st.warnedNoConv = true;
1696 bool root = true;
1697#ifdef PECLET_FLOW_MPI
1698 if (cx.distributed) {
1699 int r = 0;
1700 MPI_Comm_rank(cx.comm, &r);
1701 root = r == 0;
1702 }
1703#endif
1704 (void)cx;
1705 if (root)
1706 std::fprintf(stderr,
1707 "peclet.flow: cut-cell scalar '%s': the solve did not converge in %d "
1708 "iterations (residual %.3e of the reference, tolerance %.1e); the iterate is "
1709 "kept -- see diagnostics.scalar_census (printed once)\n",
1710 sc.name.c_str(), kr.iterations, st.residual, st.rtol);
1711 }
1712}
1713
1714} // namespace scd
1715
1716template <class Grid>
1718 ScalarCutState& st = *sc.cut;
1719 const scg::ScalarCutGeometry& gm = scg_;
1720 scd::CutContext cx = scd::cutContext(e_, G, n_, gm, distributed_);
1721#ifdef PECLET_FLOW_MPI
1722 cx.comm = comm_;
1723#endif
1724 for (int a = 0; a < 3; ++a)
1725 scd::ensureField(st.phi[a], n_, sc.name, "_cc_phi");
1726 // the face flux of the projection in force, guarded (sco::faceFluxes). A steady solve is called
1727 // outside step(), so it fills the face velocity's ghosts itself (advanceScalars did for an
1728 // advance).
1729 // WO-5b (§6.5): the open (inflow/outflow) global faces this rank touches take the boundary-face
1730 // flux the last projection constrained (scalarCaptureOpenFaceFlux), written over the guard's 0.
1731 bool anyOpen = false, openHere[6];
1732 for (int f = 0; f < 6; ++f) {
1733 const bool o = bc_[f] == 2 || bc_[f] == 3;
1734 anyOpen = anyOpen || o;
1735 openHere[f] = o && scalarOpenValid_ && touchesGlobalFace(f);
1736 st.openFace[f] = false;
1737 st.openInflow[f] = bc_[f] == 2;
1738 }
1739 const scd::FaceFluxCounts fc =
1740 scd::faceFluxPass(*this, sc, steady, openHere, scalarOpenFlux_, cx);
1741 // (the fourth maximum, collocated only: the CELL velocity, which moves while the face field may
1742 // not exist)
1743 double vcell = 0.0;
1744 if constexpr (Grid::collocated)
1745 for (int a = 0; a < 3; ++a)
1746 vcell = std::fmax(vcell, sco::maxabsLocal(CCConst(C[a].u), e_, G));
1747 double mx[4];
1748 scd::advectionMaxima(st, fc.vmax, vcell, cx, u_, mx);
1749 st.maxCellPeclet = mx[2];
1750 scd::refuseUnadvectable(sc.name, mx, Grid::collocated && !faceFieldValid_, !cutcellPressure_,
1751 anyOpen && !scalarOpenValid_);
1752 st.advecting = mx[0] > 0.0;
1754 if (!st.advecting) {
1755 scd::countGuardedOnly(st, fc.guarded, cx);
1756 return;
1757 }
1758 scd::ensureField(st.small, n_, sc.name, "_cc_small");
1759 scd::ensureField(st.outflow, n_, sc.name, "_cc_outflow");
1760 if (steady) // §6.7: implicit FOU on every face; no classification
1761 Kokkos::deep_copy(CCExec(), st.small, 0.0);
1762 else
1763 scd::classifySmallCells(*this, sc, gm, dt_, cx);
1764 scd::countAdvection(sc, steady, openHere, fc, cx);
1765 scd::warnBackflow(*this, sc, steady);
1766}
1767
1768template <class Grid>
1772
1773template <class Grid>
1774void Solver<Grid>::solveScalarSteady(const std::string& name) {
1775 scalarCutAssembleSolve(cutcellScalar(name, "solve_scalar_steady"), true);
1776}
1777
1778template <class Grid>
1782 if (!steady && !(dt_ > 0.0))
1783 throw std::runtime_error("cut-cell scalar '" + sc.name + "': set_dt first");
1784 ScalarCutState& st = *sc.cut;
1785 const scg::ScalarCutGeometry& gm = scg_;
1786 const CCConst unk(gm.unknown), kap(gm.kappa);
1787 scd::CutContext cx = scd::cutContext(e_, G, n_, gm, distributed_);
1788#ifdef PECLET_FLOW_MPI
1789 cx.comm = comm_;
1790#endif
1791 scd::allocateWork(sc, n_, gm.fac.n);
1792 scd::operatorScalars(st, steady, dt_, sc.Dphys, u_, gm.census.numUnknowns);
1793 const double lam = st.lam, idt = st.idt;
1794 const sco::MeanGradPosition mgPos = scalarMeanGradPosition(st.gPhys);
1795 // the field: identity-row cells hold exactly 0 (§1.3), the time base is c^n
1796 sco::zeroNonUnknown(sc.c, unk, e_, G);
1797 Kokkos::deep_copy(CCExec(), sc.cOld, sc.c);
1798 // bands
1799 sco::buildBands(sc.AC, sc.AW, sc.AE, sc.AS, sc.AN, sc.AB, sc.AT, kap, unk, CCConst(gm.sax),
1800 CCConst(gm.say), CCConst(gm.saz), lam, idt, u_.w, e_, G);
1801 const int nb = scalarNumBodies();
1802 const sco::WallTable wt = scd::wallTable(st, nb, u_);
1803 sco::facetCoefficients(st.cw, st.rw, gm.fac, unk, wt, lam);
1804 if (st.meanGradOn) // §1.5: rw = alpha G_phi (g - sum_k w_k G.x_k) on Dirichlet/Robin facets
1805 sco::meanGradientProbeShift(st.rw, gm.fac, st.cw, mgPos);
1806 // WO-7: a conjugate body makes this a two-field solve (§1.1, D8); without one the single-phase
1807 // path below runs unchanged
1808 st.conj = false;
1809 for (int b = 0; b < nb; ++b)
1810 st.conj = st.conj || st.wtType[(std::size_t)b] == 3;
1811 st.conj = st.conj && st.solid.extent(0) == n_;
1813 if (st.conj) {
1814 std::vector<char> conjB;
1815 mt = scalarMaterialTable(sc, conjB);
1816 ensureScalarSolidRecord(sc, conjB);
1817 }
1819 scd::rightHandSide(sc, gm, cx);
1820 // Dirichlet domain faces (§1.4): fold 2 Lam w_a a_bf into the diagonal and the rhs
1821 const CCField saAx[3] = {gm.sax, gm.say, gm.saz};
1822 const int nBlock[3] = {nx_, ny_, nz_};
1823 bool anyDir = false;
1824 for (int f = 0; f < 6; ++f) {
1825 st.dirFace[f] = false;
1826 if (sc.bc[f] != 2 || bc_[f] == 0 || !touchesGlobalFace(f))
1827 continue;
1828 const int a = f / 2, side = f % 2;
1829 const Kokkos::View<double*, CCMem> gv = scd::dirichletFaceValues(sc, f, nBlock, og_, u_);
1830 st.dirFace[f] = true;
1831 anyDir = true;
1832 sco::dirichletFaceFold(sc.AC, sc.b, unk, CCConst(saAx[a]), gv, lam * u_.w[a], a, side, e_, G);
1833 }
1834 if (st.meanGradOn) { // §1.5 faces: the G.x part of every coupled face term on the rhs
1835 double gf[3];
1836 for (int a = 0; a < 3; ++a)
1837 gf[a] = lam * u_.w[a] * u_.hp[a] * st.gInt[a];
1838 sco::meanGradientFaceRhs(sc.b, unk, CCConst(gm.sax), CCConst(gm.say), CCConst(gm.saz), gf, e_,
1839 G);
1840 }
1841 // advection (WO-5, §6): the face flux of the projection, the small-cell split, the implicit FOU
1842 // bands and the explicit faces. Skipped entirely when no face carries flux (the WO-4 operator).
1843 scalarCutAdvection(sc, steady);
1844 if (st.advecting)
1845 scd::advectionOperator(*this, sc, steady, cx, u_);
1846 if (st.conj)
1847 scd::conjugateOperator(sc, gm, mt, mgPos, cx, u_);
1848 else // the level-0 surrogate diagonal (§4.3)
1849 sco::surrogateDiagonal(st.SAC, CCConst(sc.AC), gm.fac, st.cw);
1850 st.singular = scd::singularSolve(st, steady, anyDir, bc_, cx);
1851 st.built = true;
1852 // ScalarMG (§5.2): the level table once per geometry version and block (VelocityMG's rule), the
1853 // surrogate on every level rebuilt with the operator (ruling D-WO3-3)
1854 if (!st.mg || st.mgVersion != gm.version || st.mgN != n_) {
1855 st.mg = std::make_shared<ScalarMG>();
1856 st.mg->setMetric(u_.w, u_.hp);
1857 const bool per[3] = {bc_[0] == 0, bc_[2] == 0, bc_[4] == 0};
1858 st.mg->setPeriodic(per);
1859 ScalarMG::Fill fill0 = [this](CCField f) { fillGhosts(f); };
1860#ifdef PECLET_FLOW_MPI
1861 if (distributed_)
1862 st.mg->initMpi(*dec_, comm_, og_, fill0);
1863 else
1864#endif
1865 {
1866 st.mg->init(nx_, ny_, nz_, fill0);
1867 st.mg->setLevel0Wrap(true); // single rank: fillGhosts = the periodic wrap of x, y, z
1868 }
1869 st.mgVersion = gm.version;
1870 st.mgN = n_;
1871 }
1872 {
1873 const ScalarMG::Inputs in = scd::mgInputs(sc, gm, steady, cx, u_);
1874 st.mg->build(in);
1875 st.mgLevels = st.mg->levelsUsed();
1876 scd::warnShallowBottom(*this, sc, in.fullTable);
1877 }
1878 const ScalarKrylovResult kr =
1879 st.conj ? scd::solveTwo(*this, sc, mt, cx) : scd::solveSingle(*this, sc, cx);
1880 fillGhosts(sc.c);
1881 scd::recordSolve(sc, kr, cx);
1882}
1883
1884template <class Grid>
1886#ifdef PECLET_FLOW_MPI
1887 if (distributed_) {
1888 int r = 0;
1889 MPI_Comm_rank(comm_, &r);
1890 return r == 0;
1891 }
1892#endif
1893 return true;
1894}
1895
1896template <class Grid>
1898 ScalarCutState& st = *sc.cut;
1899 if (st.warnedGeometryVersion == scg_.version)
1900 return;
1901 st.warnedGeometryVersion = scg_.version;
1902 bool root = true;
1903#ifdef PECLET_FLOW_MPI
1904 if (distributed_) {
1905 int r = 0;
1906 MPI_Comm_rank(comm_, &r);
1907 root = r == 0;
1908 }
1909#endif
1910 if (!root)
1911 return;
1912 const scg::ScalarCutCensus& c = scg_.census;
1913 const char* nm = sc.name.c_str();
1914 if (c.numThinSolid > 0)
1915 std::fprintf(
1916 stderr,
1917 "peclet.flow: cut-cell scalar '%s': %ld thin-solid cell(s) -- a solid thinner than "
1918 "about a cell, so one fluid unknown spans both of its sides and the scalar passes "
1919 "through it (a resolution warning; diagnostics.scalar_census 'num_thin_solid', "
1920 "printed once)\n",
1921 nm, c.numThinSolid);
1922 const auto r2Warn = [&](const char* side, long r2, long total) {
1923 if (total > 0 && 100 * r2 > total)
1924 std::fprintf(stderr,
1925 "peclet.flow: cut-cell scalar '%s': %ld of %ld %s probes (%.2f %%, more than "
1926 "1 %%) fell back to the first-order last rung R2 -- contacts, thin gaps or "
1927 "corners under-resolved (diagnostics.scalar_census 'probe_rungs', printed "
1928 "once)\n",
1929 nm, r2, total, side, 100.0 * (double)r2 / (double)total);
1930 };
1931 r2Warn("fluid", c.rungs[3], c.rungs[0] + c.rungs[1] + c.rungs[2] + c.rungs[3]);
1932 if (st.conj)
1933 r2Warn("solid", st.solidRungs[3],
1934 st.solidRungs[0] + st.solidRungs[1] + st.solidRungs[2] + st.solidRungs[3]);
1935 if (c.numSealed > 0 && c.sealedVolume > 1e-6 * c.fluidVolume)
1936 std::fprintf(stderr,
1937 "peclet.flow: cut-cell scalar '%s': %ld sealed cell(s) (fluid behind closed "
1938 "faces, not unknowns) hold %.2e of the fluid volume, more than 1e-6 "
1939 "(diagnostics.scalar_census 'num_sealed' / 'sealed_volume', printed once)\n",
1940 nm, c.numSealed, c.fluidVolume > 0.0 ? c.sealedVolume / c.fluidVolume : 0.0);
1941}
1942
1943template <class Grid>
1944std::vector<double> Solver<Grid>::scalarWallFlux(const std::string& name) {
1945 ScalarField& sc = cutcellScalar(name, "scalar_wall_flux");
1946 ScalarCutState& st = *sc.cut;
1947 const int nb = scalarNumBodies();
1948 std::vector<double> out((std::size_t)nb, 0.0);
1949 if (!st.built)
1950 return out;
1951 const auto& fo = scg_.fac;
1952 Kokkos::View<double*, CCMem> up("peclet::flow::sco_up", fo.n), qin("peclet::flow::sco_qin", fo.n);
1953 fillGhosts(sc.c);
1954 if (st.conj) { // WO-7: a conjugate body's flux into the fluid is its interface flux cc (u_ps -
1955 // u_pf)
1956 Kokkos::View<double*, CCMem> us("peclet::flow::sco_us", fo.n);
1957 fillGhosts(st.solid);
1958 sco::conjFacetFlux(up, us, qin, CCConst(sc.c), CCConst(st.solid), fo, st.cw, st.rw, st.cc,
1959 st.offS, st.wS, scalarMeanGradPosition(st.gPhys), st.meanGradOn);
1960 } else {
1961 sco::facetFlux(up, qin, CCConst(sc.c), fo, st.cw, st.rw);
1962 }
1963 auto hq = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), qin);
1964 auto hb = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.body);
1965 for (long f = 0; f < fo.n; ++f) { // facet order: deterministic
1966 int b = hb(f);
1967 if (b < 0 || b >= nb)
1968 b = 0;
1969 out[(std::size_t)b] += u_.vol * hq(f);
1970 }
1971#ifdef PECLET_FLOW_MPI
1972 if (distributed_) {
1973 std::vector<double> o(out.size());
1974 MPI_Allreduce(out.data(), o.data(), nb, MPI_DOUBLE, MPI_SUM, comm_);
1975 out = o;
1976 }
1977#endif
1978 const double toPhys = u_.volToPhys() * u_.divToPhys();
1979 for (auto& v : out)
1980 v *= toPhys;
1981 return out;
1982}
1983
1984template <class Grid>
1986 ScalarField& sc = cutcellScalar(name, "scalar_budget");
1987 ScalarCutState& st = *sc.cut;
1988 ScalarCutBudget out;
1989 if (!st.built)
1990 return out;
1991 const scg::ScalarCutGeometry& gm = scg_;
1992 const CCConst unk(gm.unknown), kap(gm.kappa);
1993 const double V = u_.vol;
1994 // the residual of the stored system at the stored solution, r = b - A c, in flux form
1995 // (sco::residualFluxForm: the same r in exact arithmetic, round-off at the scale of the fluxes)
1996 fillGhosts(sc.c);
1997 sco::residualFluxForm(st.kt, CCConst(sc.c), CCConst(sc.b), kap, unk, CCConst(gm.sax),
1998 CCConst(gm.say), CCConst(gm.saz), st.lam, st.idt, u_.w, e_, G);
1999 if (st.conj) { // WO-7: the solid rows (flux form) and the two-field overlay, both subtracted
2000 fillGhosts(st.solid);
2001 sco::solidResidualFluxForm(st.ktS, CCConst(st.solid), CCConst(st.bS), CCConst(st.ms),
2002 CCConst(st.sunk), CCConst(st.spx), CCConst(st.spy), CCConst(st.spz),
2003 u_.w, e_, G);
2004 sco::conjOverlayApply(st.kt, st.ktS, CCConst(sc.c), CCConst(st.solid), gm.fac, st.cw, st.cc,
2005 st.offS, st.wS, /*subtract=*/true);
2006 } else {
2007 sco::overlayApply(st.kt, CCConst(sc.c), gm.fac, st.cw, /*subtract=*/true);
2008 }
2009 if (st.advecting) // the implicit faces' outflow (the explicit faces' sits in b)
2010 sco::advectionResidual(st.kt, CCConst(sc.c), CCConst(st.phi[0]), CCConst(st.phi[1]),
2011 CCConst(st.phi[2]), CCConst(st.small), unk, st.steady, e_, G);
2012 if (st.advecting) // WO-5b: the open faces' implicit outflow
2013 for (int f = 0; f < 6; ++f)
2014 if (st.openFace[f])
2015 sco::openFaceResidual(st.kt, CCConst(sc.c), CCConst(st.phi[f / 2]), CCConst(st.small), unk,
2016 st.openInflow[f], f / 2, f % 2, st.steady, e_, G);
2017 {
2018 const CCField saAx[3] = {gm.sax, gm.say, gm.saz};
2019 for (int f = 0; f < 6; ++f)
2020 if (st.dirFace[f])
2021 sco::dirichletFaceResidual(st.kt, CCConst(sc.c), unk, CCConst(saAx[f / 2]),
2022 st.lam * u_.w[f / 2], f / 2, f % 2, e_, G);
2023 }
2024 double v[6] = {0, 0, 0, 0, 0, 0}; // sum r, kappa c, kappa c^n, wall, boundary, source
2025 {
2026 double sumAbs = 0.0, kc = 0.0, k = 0.0;
2027 sco::sumUnknownLocal(CCConst(st.kt), unk, e_, G, v[0], sumAbs); // identity rows: r = 0
2028 sco::kappaMomentsLocal(CCConst(sc.c), kap, unk, e_, G, kc, k);
2029 v[1] = kc;
2030 sco::kappaMomentsLocal(CCConst(sc.cOld), kap, unk, e_, G, kc, k);
2031 v[2] = kc;
2032 }
2033 {
2034 const auto& fo = gm.fac;
2035 Kokkos::View<double*, CCMem> up("peclet::flow::sco_up", fo.n),
2036 qin("peclet::flow::sco_qin", fo.n);
2037 sco::facetFlux(up, qin, CCConst(sc.c), fo, st.cw, st.rw);
2038 auto hq = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), qin);
2039 double w = 0.0;
2040 for (long f = 0; f < fo.n; ++f)
2041 w += hq(f);
2042 v[3] = w;
2043 }
2044 {
2045 const CCField saAx[3] = {gm.sax, gm.say, gm.saz};
2046 double bsum = 0.0;
2047 for (int f = 0; f < 6; ++f)
2048 if (st.dirFace[f])
2049 bsum += sco::dirichletFaceInflux(CCConst(sc.c), unk, CCConst(saAx[f / 2]), st.gFace[f],
2050 st.lam * u_.w[f / 2], 1.0, f / 2, f % 2, e_, G);
2051 if (st.advecting) // WO-5b: the advective flux through the open faces
2052 for (int f = 0; f < 6; ++f)
2053 if (st.openFace[f])
2054 bsum += sco::openFaceInflux(CCConst(sc.c), CCConst(sc.cOld), CCConst(st.phi[f / 2]),
2055 CCConst(st.small), unk, st.gFace[f], st.openInflow[f], 1.0,
2056 f / 2, f % 2, st.steady, e_, G);
2057 v[4] = bsum;
2058 }
2059 {
2060 const bool useField = st.sourceField.extent(0) == n_;
2061 v[5] = sco::sourceSumLocal(kap, unk, st.sourceConst, CCConst(useField ? st.sourceField : sc.c),
2062 useField, st.srcFactor, e_, G);
2063 }
2064#ifdef PECLET_FLOW_MPI
2065 if (distributed_) {
2066 double o[6];
2067 MPI_Allreduce(v, o, 6, MPI_DOUBLE, MPI_SUM, comm_);
2068 for (int j = 0; j < 6; ++j)
2069 v[j] = o[j];
2070 }
2071#endif
2072 // internal: per unit V sums times V
2073 double sumR = V * v[0];
2074 const double mass = V * v[1], massOld = V * v[2], wall = V * v[3], bnd = V * v[4], src = V * v[5];
2075 // WO-7: the solid rows' residual and the solid mass sum C_s K kappa_s V psi_s (now and at the
2076 // time base). The conjugate facets' flux is internal (it enters both rows), so `wall_in` keeps
2077 // the wall facets alone and `d_mass` is the change of the TOTAL (fluid + solid) mass.
2078 double massS = 0.0, massSOld = 0.0;
2079 if (st.conj) {
2081 std::vector<char> conjB;
2082 mt = scalarMaterialTable(sc, conjB);
2083 double vs[3] = {0.0, 0.0, 0.0}, sAbs = 0.0, w = 0.0;
2084 sco::sumUnknownLocal(CCConst(st.ktS), CCConst(st.sunk), e_, G, vs[0], sAbs);
2085 sco::solidMomentsLocal(CCConst(st.solid), kap, CCConst(st.sunk), CCConst(st.mat), mt, e_, G,
2086 vs[1], w);
2087 sco::solidMomentsLocal(CCConst(st.sOld), kap, CCConst(st.sunk), CCConst(st.mat), mt, e_, G,
2088 vs[2], w);
2089#ifdef PECLET_FLOW_MPI
2090 if (distributed_) {
2091 double o[3];
2092 MPI_Allreduce(vs, o, 3, MPI_DOUBLE, MPI_SUM, comm_);
2093 for (int j = 0; j < 3; ++j)
2094 vs[j] = o[j];
2095 }
2096#endif
2097 sumR = V * (v[0] + vs[0]);
2098 massS = V * vs[1];
2099 massSOld = V * vs[2];
2100 }
2101 const double toMass = u_.volToPhys(), toRate = u_.volToPhys() * u_.divToPhys();
2102 out.mass = mass * toMass;
2103 out.massSolid = massS * toMass;
2104 out.wallIn = wall * toRate;
2105 out.boundaryIn = bnd * toRate;
2106 out.sourceIn = src * toRate;
2107 if (st.steady) { // a rate balance: no storage term, the defect is sum V r per unit time
2108 out.dMass = 0.0;
2109 out.defect = sumR * toRate;
2110 out.identityError = (-(wall + bnd + src) + sumR) * toRate;
2111 } else {
2112 const double dm = st.conj ? (mass + massS) - (massOld + massSOld) : mass - massOld;
2113 out.dMass = dm * toMass;
2114 out.defect = st.dt * sumR * toMass;
2115 out.identityError = (dm - st.dt * (wall + bnd + src) + st.dt * sumR) * toMass;
2116 }
2117 return out;
2118}
2119
2120template <class Grid>
2122 ScalarField& sc = cutcellScalar(name, "scalar_facets");
2123 ScalarCutState& st = *sc.cut;
2125 const auto& fo = scg_.fac;
2126 ScalarCutFacets out;
2127 const long n = fo.n;
2128 out.centroid.assign((std::size_t)n * 3, 0.0);
2129 out.normal.assign((std::size_t)n * 3, 0.0);
2130 out.area.assign((std::size_t)n, 0.0);
2131 out.wallValue.assign((std::size_t)n, std::numeric_limits<double>::quiet_NaN());
2132 out.flux.assign((std::size_t)n, 0.0);
2133 out.instance.assign((std::size_t)n, 0);
2134 out.rung.assign((std::size_t)n, 0);
2135 auto hcell = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.cell);
2136 auto halpha = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.alpha);
2137 auto hn = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.normal);
2138 auto hc = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.centroid);
2139 auto hb = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.body);
2140 auto hs = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.sF);
2141 auto hr = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.rungF);
2142 auto hu = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), scg_.unknown);
2143 Kokkos::View<double*, CCMem> up("peclet::flow::sco_up", n), qin("peclet::flow::sco_qin", n);
2144 Kokkos::View<double*, CCMem> usv("peclet::flow::sco_us", n);
2145 const bool have = st.built && st.cw.extent(0) == (std::size_t)n;
2146 const bool conj = have && st.conj && st.cc.extent(0) == (std::size_t)n;
2147 if (have) {
2148 fillGhosts(sc.c);
2149 if (conj) {
2150 fillGhosts(st.solid);
2151 sco::conjFacetFlux(up, usv, qin, CCConst(sc.c), CCConst(st.solid), fo, st.cw, st.rw, st.cc,
2152 st.offS, st.wS, scalarMeanGradPosition(st.gPhys), st.meanGradOn);
2153 } else {
2154 sco::facetFlux(up, qin, CCConst(sc.c), fo, st.cw, st.rw);
2155 }
2156 }
2157 auto hup = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), up);
2158 auto hq = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), qin);
2159 // mean-gradient mode (§1.5): the probe value of c is that of theta plus sum_k w_k G.x_k
2160 const bool mgOn = have && st.meanGradOn;
2161 const sco::MeanGradPosition mgPos = scalarMeanGradPosition(st.gPhys);
2162 auto hoff = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.offF);
2163 auto hw = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), fo.wF);
2164 const int og[3] = {og_.x, og_.y, og_.z};
2165 const double l = u_.lenToPhys();
2166 const int nb = scalarNumBodies();
2167 for (long f = 0; f < n; ++f) {
2168 const long i = hcell(f);
2169 const long xyz[3] = {i % e_.x, (i / e_.x) % e_.y, i / ((long)e_.x * e_.y)};
2170 for (int d = 0; d < 3; ++d) {
2171 out.centroid[(std::size_t)(3 * f + d)] =
2172 u_.org[d] + ((double)(xyz[d] - G + og[d]) + 0.5) * u_.h[d] + hc(f, d) * l;
2173 out.normal[(std::size_t)(3 * f + d)] = hn(f, d);
2174 }
2175 out.area[(std::size_t)f] = halpha(f) * u_.vol * u_.areaToPhys();
2176 out.instance[(std::size_t)f] = hb(f);
2177 out.rung[(std::size_t)f] = (int)hr(f);
2178 if (!have || !(hu(i) > 0.5))
2179 continue;
2180 int b = hb(f);
2181 if (b < 0 || b >= nb)
2182 b = 0;
2183 double u = hup(f);
2184 if (mgOn)
2185 for (int k = 0; k < 8; ++k)
2186 u += hw(f, k) * mgPos(i + (long)hoff(f, k));
2187 const double a = halpha(f), s = hs(f), lam = st.lam;
2188 const int t = st.wtType[(std::size_t)b];
2189 double cG;
2190 if (t == 3) { // WO-7, conjugate: psi_Gamma,f = u_pf + q s_f / Lam_f, q = flux into the fluid
2191 const double q = a > 0.0 ? hq(f) / a : 0.0;
2192 cG = lam > 0.0 ? u + q * s / lam : u;
2193 } else if (t == 1)
2194 cG = st.wtG[(std::size_t)b];
2195 else if (t == 2) {
2196 const double k = st.wtK[(std::size_t)b];
2197 cG = (lam + k * s) > 0.0 ? (lam * u + k * s * st.wtG[(std::size_t)b]) / (lam + k * s) : u;
2198 } else
2199 cG = lam > 0.0 ? u + st.wtQ[(std::size_t)b] * s / lam : u;
2200 out.wallValue[(std::size_t)f] = cG;
2201 out.flux[(std::size_t)f] = a > 0.0 ? hq(f) / a / u_.speedToInt() : 0.0;
2202 }
2203 return out;
2204}
2205
2206} // namespace peclet::flow
2207
2208#endif // PECLET_FLOW_FLOW_IBM_SCALARS_CUTCELL_HPP
std::function< void(CCField)> Fill
static constexpr double kFullTableKappa
The transient level rule (design §5.2, Amendment A3 + ruling D-WO9-3): kappa_A = 1 + 4 dt' D' sum_a w...
void setScalarSource(const std::string &name, double S)
void scalarCutMatvecTwo(ScalarField &sc, CCField yf, CCField ys, CCField xf, CCField xs)
std::vector< double > getScalarSolid(const std::string &name)
void setScalarWall(const std::string &name, int type, double value, double coefficient, int instance)
std::vector< double > scalarGeometryField(int which)
void scatterInner(CCField fld, const std::vector< double > &in)
void setScalarSourceField(const std::string &name, const std::vector< double > &S)
std::array< double, 3 > scalarMeanFlux(const std::string &name)
bool hasMovingInstance() const
True when at least one instance carries a nonzero velocity – i.e.
void fillGhosts(CCField f)
sco::MeanGradPosition scalarMeanGradPosition(const double Gphys[3]) const
std::vector< double > scalarSolidGeometryField(const std::string &name, int which)
CCField addField(const std::string &name)
void scalarCutRefusals(const ScalarField &sc) const
void scalarCutMatvec(ScalarField &sc, CCField y, CCField x)
ScalarField & cutcellScalar(const std::string &name, const char *who)
ScalarCutFacets scalarFacets(const std::string &name)
void scalarCutAssembleSolve(ScalarField &sc, bool steady)
void advanceScalarCutCell(ScalarField &sc)
std::array< long, 3 > globalCells() const
The GLOBAL cell counts (this rank's block single-rank).
void setScalarResidualTolerance(const std::string &name, double rtol)
void setScalarBcProfile(const std::string &name, int face, const std::vector< double > &prof, int n1, int n2)
void scalarCutAdvection(ScalarField &sc, bool steady)
const scg::ScalarCutGeometry & scalarCutGeometry()
ScalarFaceFlux scalarFaceFlux(int a) const
ScalarCutBudget scalarBudget(const std::string &name)
std::vector< double > scalarWallFlux(const std::string &name)
void scalarCutWarnings(ScalarField &sc)
void ensureScalarSolidRecord(ScalarField &sc, const std::vector< char > &conj)
bool scalarRootRank() const
rank 0 (or not distributed): the one that prints a warning
void setScalarMeanGradient(const std::string &name, const std::array< double, 3 > &G)
void setScalarSolid(const std::string &name, double D, double capacity, double partition, double contactResistance, int instance)
scg::ScalarCutCensus scalarCutCensus()
static constexpr int G
Definition flow_ibm.hpp:82
SceneMap sceneMap() const
void solveScalarSteady(const std::string &name)
void setScalarMaxIterations(const std::string &name, int maxit)
sco::MaterialTable scalarMaterialTable(ScalarField &sc, std::vector< char > &conj)
std::vector< double > gatherInner(CCField fld)
bool isCutcellScalar(const std::string &name) const
Definition conj.py:1
void advectionMaxima(const ScalarCutState &st, double vmax, double vcell, const CutContext &cx, const Units &u, double mx[4])
The all-rank maxima of the face flux: max |phi|, the face speed, A2's census max_cell_peclet (max |ph...
ScalarMG::Inputs mgInputs(ScalarField &sc, const scg::ScalarCutGeometry &gm, bool steady, const CutContext &cx, const Units &u)
Everything ScalarMG's build reads from this operator (§5.2; ruling D-WO3-3).
void ensureField(CCField &f, std::size_t n, const std::string &name, const char *tag)
(Re)allocate a per-scalar cell field when the block size changed.
void advectionOperator(Solver< Grid > &s, ScalarField &sc, bool steady, const CutContext &cx, const Units &u)
The advection operator (WO-5, §6) once some face carries flux: the implicit FOU bands (their outflow ...
ScalarVec fieldVecTwo(CCField f, CCField s2)
void rightHandSide(ScalarField &sc, const scg::ScalarCutGeometry &gm, const CutContext &cx)
The right-hand side: kappa (idt c^n + S') + the walls' rw.
ScalarKrylovOps singleFieldOps(Solver< Grid > &s, ScalarField &sc, const KrylovContext &k)
The single-field Krylov operations: the operator, one ScalarMG V-cycle on the surrogate (§5....
void projectedRhsTwo(ScalarField &sc, const CutContext &cx, CCField &bKf, CCField &bKs)
The two-field right-hand side {b, b_s}, or (singular) its projection over both phases.
ScalarVec fieldVec(CCField f)
ScalarKrylovResult solveTwo(Solver< Grid > &s, ScalarField &sc, const sco::MaterialTable &mt, const CutContext &cx)
WO-7: the two-field solve (§5.1 on both phases): the same BiCGStab on {c, psi_s}, the gauge weights k...
void countGuardedOnly(ScalarCutState &st, long nGuard, const CutContext &cx)
No face carries flux: only the guarded faces are counted (all ranks).
void resetAdvectionCensus(ScalarCutState &st)
The advection census of the last advance, zeroed before it is counted.
void removeMean(const CutContext &cx, CCField a, double nUnk)
Subtract the unknowns' mean from a fluid field (the singular projection, §5.1).
FaceFluxCounts faceFluxPass(Solver< Grid > &s, ScalarField &sc, bool steady, const bool openHere[6], const CCField openFlux[6], const CutContext &cx)
The face flux of the projection in force, guarded (sco::faceFluxes); the open (inflow/outflow) global...
sco::WallTable wallTable(ScalarCutState &st, int nb, const Units &u)
The per-body wall table, resolved and converted (§4.2), and its persistent device copy.
CutContext cutContext(C3 e, int g, std::size_t n, const scg::ScalarCutGeometry &gm, bool distributed)
The context of one cut-cell solve on this rank's block; in MPI builds the caller sets comm.
void operatorScalars(ScalarCutState &st, bool steady, double dt, double D, const Units &u, long numUnknowns)
The operator's internal coefficients from the stored physical values (§1.2, at advance time) and the ...
ScalarKrylovOps twoFieldOps(Solver< Grid > &s, ScalarField &sc, const KrylovContext &k)
The two-field Krylov operations: ScalarVec {c, psi_s}; dots and maxima over both fields; the singular...
void warnBackflow(const Solver< Grid > &s, ScalarField &sc, bool steady)
Review finding 2a (ruling D-WOR-2a): A2 requires an implicit backflow row to be reported.
void remeasureAfterGauge(ScalarKrylovResult &kr, const ScalarKrylovOps &ops, const ScalarVec &t, const ScalarVec &x, const ScalarVec &b, const ScalarCutState &st, const CutContext &cx)
Review finding 5 (ruling D-WOR-5): the gauge shift delta adds delta A 1 = delta div to the residual,...
void refuseUnadvectable(const std::string &name, const double mx[4], bool noFaceField, bool noProjection, bool noOpenFlux)
The moving fluids the cut-cell scalar cannot advect, refused rather than silently ignored: noFaceFiel...
void removeMeanTwo(const CutContext &cx, CCField a, CCField as, const CCConst &sunk, double nTot)
The same over both phases' unknowns (the null vector is constant in psi).
void warnShallowBottom(const Solver< Grid > &s, ScalarField &sc, bool fullTable)
Review finding 4 (ruling D-WOR-4): the full table's bottom is a fixed number of smoothing sweeps on w...
void countAdvection(ScalarField &sc, bool steady, const bool openHere[6], const FaceFluxCounts &fc, const CutContext &cx)
The advection census (all ranks): small cells, implicit faces, faces carrying flux,...
void twoFieldMoments(ScalarField &sc, const sco::MaterialTable &mt, const CutContext &cx, double m[2])
gauge (§5.1): sum kappa V c + sum C_s K kappa_s V psi_s over both phases, all ranks.
Kokkos::View< double *, CCMem > dirichletFaceValues(ScalarField &sc, int f, const int n[3], C3 origin, const Units &u)
The Dirichlet value per face cell of domain face f (§1.4), in the persistent gFace[f]: the profile or...
void allocateWork(ScalarField &sc, std::size_t n, long numFacets)
The surrogate diagonal, the Krylov scratch and the per-facet coefficients, sized to the block.
void classifySmallCells(Solver< Grid > &s, ScalarField &sc, const scg::ScalarCutGeometry &gm, double dt, const CutContext &cx)
§6.3, transient: C_bulk = the global MAX over full cells of dt Out / V, then the per-cell small-cell ...
ScalarKrylovResult solveSingle(Solver< Grid > &s, ScalarField &sc, const CutContext &cx)
The single-field solve: BiCGStab on c, and for the singular case the gauge sum kappa V c kept at its ...
bool singularSolve(const ScalarCutState &st, bool steady, bool anyDir, const int bc[6], const CutContext &cx)
The singular case (§5.1): steady, no facet with G > 0, no Dirichlet domain face anywhere.
void recordSolve(ScalarField &sc, const ScalarKrylovResult &kr, const CutContext &cx)
The solve's statistics and the once-per-scalar non-convergence warning (rank 0).
CCField projectedRhs(ScalarField &sc, const CutContext &cx)
The right-hand side the single-field Krylov sees: b, or (singular) its projection onto the range,...
void conjugateOperator(ScalarField &sc, const scg::ScalarCutGeometry &gm, const sco::MaterialTable &mt, const sco::MeanGradPosition &mgPos, const CutContext &cx, const Units &u)
WO-7: the solid phase's operator (§1.4 solid row, §4.1): psi_s^n, the face products,...
void buildFacets(ScalarFacetOverlay &fo, const CellPass &cp, CCConst sdf, CCConst sax, CCConst say, CCConst saz, C3 e, int g, const double hp[3])
Kernel 3 (§2.5): exclusive scans of the facet counts and of the cut-cell indicator in x-fastest inner...
void buildFluidProbes(ScalarFacetOverlay &fo, CCConst sdf, CCConst unknown, C3 e, const double hp[3])
Kernel 5 (§2.5, §3.3): the fluid probe ladder of every facet.
void zeroGhostSlab(CCField f, C3 e, int g, int face)
Zero f on every ghost layer beyond face face (0..5 = -x,+x,-y,+y,-z,+z), full transverse extent: the ...
void buildCells(CCField kappa, CCField unknown, const CellPass &cp, CCConst sdf, CCConst sax, CCConst say, CCConst saz, C3 e, int g, const double hp[3])
Kernel 2 (§2.5): kappa, the unknown flag and the per-cell facet count/kind on the inner cells.
void buildApertures(CCField sax, CCField say, CCField saz, CCConst sdf, C3 e, int g)
Kernel 1 (§2.5): the snapped scalar apertures of every face of every inner cell, including the high-s...
ScalarCutCensus localCensus(const ScalarFacetOverlay &fo, const CellPass &cp, CCConst kappa, CCConst unknown, CCConst sax, CCConst say, CCConst saz, C3 e, int g, double vol)
The census of the record on this rank (not yet summed over ranks); sealedVolume in internal volume un...
double dotTwoLocal(CCConst af, CCConst bf, CCConst as, CCConst bs, C3 e, int g)
void conjugateCoefficients(Kokkos::View< double *, CCMem > cc, const scg::ScalarFacetOverlay &fo, Kokkos::View< const std::uint8_t *, CCMem > conjF, Kokkos::View< const double *, CCMem > sS, CCConst unk, CCConst sunk, const MaterialTable &mt, double lamF)
Per facet (§1.4, §4.1): cc = alpha G_c, G_c = 1/(s_f/Lam_f + R_c + s_s/Lam_s), on a facet of a conjug...
void explicitFaceFluxes(CCField Phi, CCConst phi, CCConst c, CCConst unk, CCConst small, int a, int scheme, bool steady, C3 e, int g)
The explicit face fluxes of §6.2 on the low a-faces of the cells g .
void faceFluxes(CCField phi, CCConst vel, CCConst open, CCConst unk, int a, C3 e)
phi = open * vel on every face whose two cells are inside the block (0 on the block's lowest layer),...
void openFaceResidual(CCField r, CCConst c, CCConst phi, CCConst small, CCConst unk, bool inflow, int a, int side, bool steady, C3 e, int g)
r(i) -= F_out c_i on the implicit outflow faces of (a, side) (the budget's flux-form residual; the in...
void meanFluxLocal(CCConst th, CCConst kappa, CCConst unk, CCConst sax, CCConst say, CCConst saz, CCConst phx, CCConst phy, CCConst phz, bool advecting, double lam, const double gi[3], const double hp[3], const double ub[3], C3 e, int g, double diff[3], double adv[3])
scalar_mean_flux (§8.1), this rank's sums (internal; the caller divides by the global cell count): di...
void cellVelocitySumLocal(CCConst phx, CCConst phy, CCConst phz, CCConst unk, const double hh[3], C3 e, int g, double s[3])
(sum U'_x/V, sum U'_y/V, sum U'_z/V) over the unknown inner cells (the moving frame's numerator; its ...
void zeroNonUnknown(CCField c, CCConst unk, C3 e, int g)
Zero c on every inner cell that is not a fluid unknown (§1.3: re-zeroed at the start of every advance...
double openFaceInflux(CCConst c, CCConst cOld, CCConst phi, CCConst small, CCConst unk, Kokkos::View< const double *, CCMem > gv, bool inflow, double vol, int a, int side, bool steady, C3 e, int g)
Sum over one open face of V times the advective flux INTO the domain through it, per internal time (b...
void conjOverlayApply(CCField yf, CCField ys, CCConst xf, CCConst xs, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw, Kokkos::View< const double *, CCMem > cc, Kokkos::View< int *[8], Kokkos::LayoutLeft, CCMem > offS, Kokkos::View< double *[8], Kokkos::LayoutLeft, CCMem > wS, bool subtract=false)
The two-field overlay (§4.1 step 3), one thread per cut cell, facets in CSR order: y_f(i) += sum cw u...
void dot2TwoReduce(CCConst af, CCConst bf, CCConst cf, CCConst as, CCConst bs, CCConst cs, C3 e, int g, R1 &&r1, R2 &&r2)
(sum a b, sum c c) over inner cells, both fields, in one pass, into (r1, r2).
double sourceSumLocal(CCConst kappa, CCConst unk, double srcConst, CCConst src, bool useField, double srcFactor, C3 e, int g)
sum over unknowns of kappa S' (the source part of the right-hand side, per unit V).
void solidFaceProducts(CCField spx, CCField spy, CCField spz, CCConst sunk, CCConst mat, CCConst sax, CCConst say, CCConst saz, const MaterialTable &mt, C3 e)
The level-0 solid face products P_a(i) = Lam_face a_s on the LOW a-face of cell i when cells i - s_a ...
long countImplicitLocal(CCConst phi, CCConst small, CCConst unk, int a, bool steady, C3 e, int g)
Faces carrying flux that are implicit, over the low faces of the inner cells (census num_implicit_fac...
void dot2Reduce(CCConst a, CCConst b, CCConst c, C3 e, int g, R1 &&r1, R2 &&r2)
(sum a b, sum c c) over inner cells in one pass, into (r1, r2).
void meanGradientFaceRhs(CCField b, CCConst unk, CCConst sax, CCConst say, CCConst saz, const double gf[3], C3 e, int g)
Faces (§1.5): b(i) += sum_a gf_a (a_a^+ - a_a^-) over the coupled faces (the bands' guard),...
void dot2Local(CCConst a, CCConst b, CCConst c, C3 e, int g, double &ab, double &cc)
void solidBands(CCField AC, CCField AW, CCField AE, CCField AS, CCField AN, CCField AB, CCField AT, CCConst ms, CCConst sunk, CCConst spx, CCConst spy, CCConst spz, const double w[3], C3 e, int g)
The solid phase's 7 bands (§4.1): AC = m_s + the six face terms w_a P, off-diagonals -w_a P; identity...
void openFaceAdvection(CCField AC, CCField b, CCField outflow, CCConst cOld, CCConst phi, CCConst small, CCConst unk, Kokkos::View< const double *, CCMem > gv, bool inflow, int a, int side, bool steady, C3 e, int g, CCField omega=CCField(), bool wOmega=false)
The open face's row terms on the unknown inner boundary cells of (a, side) (table above): inflow b +=...
void maxabsReduce(CCConst a, C3 e, int g, Red red)
max over inner cells of |a|, through the Max reducer red (Kokkos::Max over a host double or a device ...
void conjFacetFlux(Kokkos::View< double *, CCMem > up, Kokkos::View< double *, CCMem > us, Kokkos::View< double *, CCMem > qin, CCConst xf, CCConst xs, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw, Kokkos::View< const double *, CCMem > rw, Kokkos::View< const double *, CCMem > cc, Kokkos::View< int *[8], Kokkos::LayoutLeft, CCMem > offS, Kokkos::View< double *[8], Kokkos::LayoutLeft, CCMem > wS, const MeanGradPosition &pos, bool mgOn)
Per facet: the probe values and the flux INTO the fluid per unit cell volume per internal time,...
long countSmallLocal(CCConst small, C3 e, int g)
Count of small inner cells (census num_small_cells).
double maxCellPecletLocal(CCConst phx, CCConst phy, CCConst phz, CCConst unk, double lam, const double w[3], C3 e, int g)
A2 census max_cell_peclet on this rank: the max over the interior flux faces (the low faces of the in...
void sumUnknownLocal(CCConst a, CCConst unk, C3 e, int g, double &sum, double &sumAbs)
(sum a, sum |a|) over the inner cells that are unknowns.
void solidRhs(CCField bs, CCConst ms, CCConst sOld, C3 e, int g)
The solid right-hand side b_s = m_s psi_s^n (no solid source in v1, §13 Q17); 0 elsewhere.
void openFaceFluxes(CCField phi, Kokkos::View< const double *, CCMem > plane, CCConst unk, int a, int side, C3 e, int g)
phi(bf) = plane value on the boundary face of (a, side), over the full transverse extent,...
double dotLocal(CCConst a, CCConst b, C3 e, int g)
double bulkCourantLocal(CCConst phx, CCConst phy, CCConst phz, CCConst kappa, CCConst unk, CCConst sax, CCConst say, CCConst saz, double dt, C3 e, int g)
C_bulk of §6.3 on this rank: max over the inner FULL cells (an unknown with kappa = 1 and all six sna...
void solidMomentsLocal(CCConst xs, CCConst kappa, CCConst sunk, CCConst mat, const MaterialTable &mt, C3 e, int g, double &m, double &w)
(sum C_s K kappa_s psi_s, sum C_s K kappa_s) over the solid unknowns (times V by the caller): the sol...
double dirichletFaceInflux(CCConst c, CCConst unk, CCConst saA, Kokkos::View< const double *, CCMem > gv, double lamW, double vol, int a, int side, C3 e, int g)
Sum over one Dirichlet domain face of V t (g_bf - c_i): the flux INTO the domain through it,...
void solidResidualFluxForm(CCField r, CCConst x, CCConst b, CCConst ms, CCConst sunk, CCConst spx, CCConst spy, CCConst spz, const double w[3], C3 e, int g)
The solid residual in FLUX form (the budget, §9): r = b - m_s psi - sum_faces t (psi_i - psi_nb); the...
void solidMeanGradientFaceRhs(CCField bs, CCConst sunk, CCConst spx, CCConst spy, CCConst spz, const double gs[3], C3 e, int g)
Mean-gradient mode, solid faces (§1.5): b_s(i) += sum_a gs_a (P_a(i + s_a) - P_a(i)),...
void dot2TwoLocal(CCConst af, CCConst bf, CCConst cf, CCConst as, CCConst bs, CCConst cs, C3 e, int g, double &ab, double &cc)
void clampNonNegative(CCField omega, C3 e, int g)
omega = max(omega, 0) on the inner cells (A2: implicit backflow never enters the coarse mass).
void buildSolidProbes(Kokkos::View< double *, CCMem > sS, Kokkos::View< int *[8], Kokkos::LayoutLeft, CCMem > offS, Kokkos::View< double *[8], Kokkos::LayoutLeft, CCMem > wS, Kokkos::View< std::uint8_t *, CCMem > rungS, Kokkos::View< const std::uint8_t *, CCMem > conjF, const scg::ScalarFacetOverlay &fo, CCConst sdf, CCConst sunk, C3 e, const double hp[3])
The solid probe ladder (§3.4): per facet of a conjugate body (conjF), the ladder of §3....
void solidMass(CCField ms, CCConst kappa, CCConst sunk, CCConst mat, const MaterialTable &mt, double idt, C3 e, int g)
The solid mass m_s = C_s K kappa_s idt on the solid unknowns, 0 elsewhere (inner cells).
void facetFlux(Kokkos::View< double *, CCMem > up, Kokkos::View< double *, CCMem > qin, CCConst x, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw, Kokkos::View< const double *, CCMem > rw)
Per facet: the probe value u_p of x and the wall flux INTO the fluid per unit cell volume per interna...
void overlayApply(CCField y, CCConst x, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw, bool subtract=false)
y(i) += sum over the facets of cut cell i of cw * (probe interpolation of x): the overlay pass of the...
double maxAbsFluxLocal(CCConst phx, CCConst phy, CCConst phz, C3 e, int g)
max |phi| over the low faces of the inner cells (0: no advection this step).
void solidMeanFluxLocal(CCConst th, CCConst sunk, CCConst spx, CCConst spy, CCConst spz, const double gi[3], const double hp[3], C3 e, int g, double diff[3])
The solid part of scalar_mean_flux's diffusive sum (§8.1): over the low faces of the inner cells whos...
void faceFluxCountsLocal(CCConst phi, CCConst vel, CCConst open, int a, C3 e, int g, long &nFlux, long &nGuarded)
(faces carrying flux, faces whose nonzero open * vel the guard zeroed) over the low faces of the inne...
void dotTwoReduce(CCConst af, CCConst bf, CCConst as, CCConst bs, C3 e, int g, R &&result)
sum over inner cells of af bf + as bs (the two-field dot).
void conjSurrogate(CCField SACf, CCField SACs, CCField W0, CCConst ACf, CCConst ACs, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw, Kokkos::View< const double *, CCMem > cc)
The two-field level-0 surrogate (§4.3): SAC_f = AC_f + sum (cw + cc), SAC_s = AC_s + sum cc,...
void residualFluxForm(CCField r, CCConst c, CCConst b, CCConst kappa, CCConst unk, CCConst sax, CCConst say, CCConst saz, double lam, double idt, const double w[3], C3 e, int g)
The budget's residual r = b - A c in FLUX form (§9): r = b - kappa idt c - sum_faces t (c_i - c_nb) w...
void smallCells(CCField small, CCConst phx, CCConst phy, CCConst phz, CCConst kappa, CCConst unk, double dt, double thr, C3 e, int g)
The small-cell flags of §6.3 over the inner cells: small(i) = 1 iff i is an unknown,...
void meanGradientAdvectionRhs(CCField b, CCConst phx, CCConst phy, CCConst phz, CCConst kappa, CCConst unk, const double gi[3], const double hh[3], const double ub[3], C3 e, int g)
Advection (§1.5): b(i) -= G'.
double maxabsLocal(CCConst a, C3 e, int g)
void buildSolidMaterial(CCField mat, CCField sunk, CCConst kappa, CCConst sax, CCConst say, CCConst saz, const scg::ScalarFacetOverlay &fo, Kokkos::View< const int *, CCMem > owner, bool hasOwner, const MaterialTable &mt, C3 e, int g, double vol[2])
The material per cell and the solid-unknown flags on the inner cells (§1.3, §2.7).
void advectionBands(CCField AC, CCField AW, CCField AE, CCField AS, CCField AN, CCField AB, CCField AT, CCField outflow, CCConst phx, CCConst phy, CCConst phz, CCConst small, CCConst unk, bool steady, C3 e, int g)
The implicit FOU part of the operator (§1.4, §6.3; all faces when steady, §6.7): on every unknown inn...
void buildBands(CCField AC, CCField AW, CCField AE, CCField AS, CCField AN, CCField AB, CCField AT, CCConst kappa, CCConst unk, CCConst sax, CCConst say, CCConst saz, double lam, double idt, const double w[3], C3 e, int g)
The 7 bands (§4.1): AC = kappa idt + sum of the six face terms Lam w_a a (guarded toward a cell that ...
void dirichletFaceFold(CCField AC, CCField b, CCConst unk, CCConst saA, Kokkos::View< const double *, CCMem > gv, double lamW, int a, int side, C3 e, int g)
Dirichlet domain face (§1.4 B_i): for the inner boundary cell i of face (a, side),...
int bodyIndex(double m, int nb)
A body id clamped into the table (out of range -> 0, as facetCoefficients does).
void explicitAdvectionRhs(CCField b, CCConst Px, CCConst Py, CCConst Pz, CCConst unk, C3 e, int g)
b(i) -= the net explicit outflow sum_a (Phi_a(i + s_a) - Phi_a(i)) on the unknown inner cells.
void kappaMomentsLocal(CCConst c, CCConst kappa, CCConst unk, C3 e, int g, double &kc, double &k)
(sum kappa c, sum kappa) over the unknowns (times V by the caller).
void openFaceCountsLocal(CCConst phi, CCConst small, CCConst unk, bool inflow, int a, int side, bool steady, C3 e, int g, long &nFlux, long &nImpl, long &nBack)
The census counts of one open face over this rank's inner boundary cells: (faces carrying flux on the...
void dirichletFaceResidual(CCField r, CCConst c, CCConst unk, CCConst saA, double lamW, int a, int side, C3 e, int g)
r(i) -= 2 Lam w_a a_bf c_i on the inner boundary cells of a Dirichlet domain face (the LHS part of di...
void facetCoefficients(Kokkos::View< double *, CCMem > cw, Kokkos::View< double *, CCMem > rw, const scg::ScalarFacetOverlay &fo, CCConst unk, const WallTable &wt, double lam)
Per-facet overlay coefficients (§4.1): cw = alpha G, rw = alpha G g (Dirichlet/Robin) or cw = 0,...
double maxFacetLocal(Kokkos::View< const double *, CCMem > cw)
max over facets of cw (0 when there is no Dirichlet/Robin facet: the steady singular test).
void faceTangents(int a, int &t1, int &t2)
The tangential axes of face axis a, in x, y, z order (t1 < t2): the layout of a domain-face profile (...
void surrogateDiagonal(CCField SAC, CCConst AC, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw)
The level-0 surrogate diagonal (§4.3): SAC = AC + sum of the cut cell's cw (the probe weights lumped,...
void dotReduce(CCConst a, CCConst b, C3 e, int g, R &&result)
sum over inner cells of a(i) b(i), into result.
void buildRhs(CCField b, CCConst cOld, CCConst kappa, CCConst unk, double idt, double srcConst, CCConst src, bool useField, double srcFactor, C3 e, int g)
Base right-hand side: b = kappa (idt c^n + S'), identity rows 0.
void advectionResidual(CCField r, CCConst c, CCConst phx, CCConst phy, CCConst phz, CCConst small, CCConst unk, bool steady, C3 e, int g)
r(i) -= the implicit faces' net outflow sum F_out c_up at c (the budget's flux-form residual,...
void meanGradientProbeShift(Kokkos::View< double *, CCMem > rw, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cw, const MeanGradPosition &pos)
Dirichlet/Robin probes (§1.5): rw(f) -= cw(f) sum_k w_k G.x_k, so that rw = alpha G_phi (g - sum_k w_...
void addOnUnknown(CCField a, CCConst unk, double d, C3 e, int g)
a(i) += d on the inner cells that are unknowns.
void overlayRhs(CCField b, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > rw)
b(i) += sum over the facets of cut cell i of rw (the wall part of the right-hand side).
void conjMeanGradientShift(CCField bf, CCField bs, const scg::ScalarFacetOverlay &fo, Kokkos::View< const double *, CCMem > cc, Kokkos::View< int *[8], Kokkos::LayoutLeft, CCMem > offS, Kokkos::View< double *[8], Kokkos::LayoutLeft, CCMem > wS, const MeanGradPosition &pos)
Mean-gradient mode, conjugate facets (§1.5): the fluid row carries + cc (u_pf - u_ps) with u = theta ...
Kokkos::View< double, CCMem > Slot
void residualFrom(CCField y, CCConst b, C3 e, int g)
y = b - y over inner cells (the residual from a matvec result held in y).
Kokkos::DefaultExecutionSpace CCExec
ScalarKrylovResult scalarBiCGStab(Ops &ops, const ScalarVec &b, const ScalarVec &x, const ScalarVec &r, const ScalarVec &rh, const ScalarVec &p, const ScalarVec &v, const ScalarVec &t, const ScalarVec &z, const ScalarVec &z2, int maxit, double rtol, bool singular)
BiCGStab on A x = b.
Kokkos::View< const double *, CCMem > CCConst
void ccReduce3(const char *name, C3 lo, C3 hi, F f, R &&... reducers)
void residentKrylov(State &st, ScalarKrylovOps &ops)
Arm ops for the resident pass with the persistent slots of st (ks, pk, allocated once).
void applyCutcellOp(CCField y, CCConst x, OpV AC, OpV AW, OpV AE, OpV AS, OpV AN, OpV AB, OpV AT, C3 e, int g)
Kokkos::View< double *, CCMem > CCField
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
Definition prof.py:1
The per-cut-cell-scalar state (ScalarField::cut).
The injected pieces as callables (host-side calls that launch kernels; the overhead of the indirectio...
Outcome of one scalarBiCGStab call.
int iterations
BiCGStab iterations (both passes when it restarted).
double trueRes
max|b - A x| at exit (after the restart, if any)
double ref
max(max|b|, max|A x0|)
bool converged
trueRes <= 10 rtol ref
Everything build reads from the scalar operator and the geometry record.
bool fullTable
the level rule (false: level 0 alone)
bool advective
A2 (§6.7): steady with advection -> the V-cycle runs on the ADVECTIVE surrogate S_adv on every level ...
CCConst phi[3]
F/V through the low a-face (st.phi, guarded).
double idt
1/dt' (0 steady)
bool twoPhase
Conjugate (WO-7, §5.2): the coupled two-field levels.
Kokkos::View< const double *, CCMem > facetC
bool singular
steady pure-Neumann: the mean is removed on every level
CCField AT
the operator's level-0 bands
const scg::ScalarFacetOverlay * fac
CCConst outflow
WO-5: the lumped implicit-FOU outflow per level-0 cell (§4.3; already inside SAC),...
CCField SAC
level-0 surrogate diagonal (§4.3)
Kokkos::View< const double *, CCMem > facetW
level-0 wall term per facet (cw = alpha G)
CCConst omegaOpen
the open faces' implicit outflow per level-0 cell
A Krylov vector (§5.1): the fluid field and, for a conjugate scalar, the solid field (WO-7).
Wall condition per body (§1.1, §8.1 set_scalar_wall), in the caller's PHYSICAL units; the conversion ...
diagnostics.scalar_budget (§8.2), physical; collective under MPI.
diagnostics.scalar_facets (§8.2): this rank's facets, physical; per facet 3 values for the centroid a...
The ONE predicate for the cut-cell scalar's advective face flux (doc/scalar_ibm_design....
CCField vel
face-normal index velocity at the low a-face of cell i (internal)
CCField open
the projection's openness of that face
The map between the solver's INDEX coordinates and the coordinate system the analytic scene is writte...
Definition flow_ibm.hpp:243
The solver state the phases of one cut-cell solve read: the block, the operator's unknown and kappa m...
std::size_t n
the block's cell count (with ghosts)
void allSum(double *v, int k) const
What the face-flux pass counted: the faces carrying flux, those the guard zeroed, and the largest fac...
What the Krylov closures of one solve read beyond cx: the state, and the singular projection's solid ...
CCConst sunk
two-field: the solid phase's unknown mask
double nUnk
the unknowns the mean is removed over (two-field: both phases)
Per-cell flags of the record pass, on the INNER grid (x fastest).
The geometry part of diagnostics.scalar_census (§8.2).
The whole record: per-cell fields on the extended block (kappa and unknown haloed; the apertures comp...
long version
the Solver's geometry version this record was built for
The per-body material of a conjugate scalar, internal units (§4.2): conj 1 on a conjugate body; lam =...
Kokkos::View< double *, CCMem > lam
G.x at the centre of extended-block cell j (physical; cellCentres' formula, unwrapped).
Device copy of the per-body wall table, resolved (instance override or default) and converted to inte...
static double value(int gx, int gy, int gz)