flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_mpi.hpp
Go to the documentation of this file.
1
8#ifndef PECLET_FLOW_FLOW_IBM_MPI_HPP
9#define PECLET_FLOW_FLOW_IBM_MPI_HPP
10
11#if defined(PECLET_FLOW_MPI) && defined(__linux__) && defined(KOKKOS_ENABLE_OPENMP)
12#include <omp.h>
13#include <sched.h>
14
15#include <fstream>
16#endif
17
18namespace peclet::flow {
19
20#ifdef PECLET_FLOW_MPI
21namespace detail {
22// doc/vof_distributed_partition_design.md §5.4 (WO-5): this rank's OpenMP placement against the
23// L3 (CCD) domains -- 0 unknown (not a host OpenMP build, not Linux, a thread not pinned to ONE
24// cpu, or sysfs unreadable), 1 every thread in one L3 domain, 2 threads in more than one. Each
25// thread of one host parallel region reads its own affinity mask. No result depends on it.
26inline int hostL3PlacementStatus() {
27#if defined(__linux__) && defined(KOKKOS_ENABLE_OPENMP)
28 if constexpr (!std::is_same_v<Kokkos::DefaultExecutionSpace, Kokkos::OpenMP>) {
29 return 0;
30 } else {
31 const int T = Kokkos::OpenMP().concurrency(); // the Kokkos pool, not omp_get_max_threads()
32 std::vector<int> cpu(T, -1);
33#pragma omp parallel num_threads(T)
34 {
35 cpu_set_t m;
36 CPU_ZERO(&m);
37 if (sched_getaffinity(0, sizeof m, &m) == 0 && CPU_COUNT(&m) == 1)
38 for (int c = 0; c < CPU_SETSIZE; ++c)
39 if (CPU_ISSET(c, &m)) {
40 cpu[omp_get_thread_num()] = c;
41 break;
42 }
43 }
44 long first = -1;
45 bool many = false;
46 for (int c : cpu) {
47 if (c < 0)
48 return 0;
49 std::ifstream f("/sys/devices/system/cpu/cpu" + std::to_string(c) + "/cache/index3/id");
50 long id = -1;
51 if (!(f >> id))
52 return 0;
53 if (first < 0)
54 first = id;
55 else if (id != first)
56 many = true;
57 }
58 return many ? 2 : 1;
59 }
60#else
61 return 0;
62#endif
63}
64// Collective over `comm` (one MPI_Gather): rank 0 prints one stderr line, once per process, if
65// any rank's OpenMP threads span more than one L3 domain. No API, no flag, no result effect.
66// One rank stays silent: it has no better layout to move to (design §5.4, ruling 2026-10-19).
67inline void warnL3Placement(MPI_Comm comm) {
68 static bool printed = false;
69 int rank = 0, size = 1;
70 MPI_Comm_rank(comm, &rank);
71 MPI_Comm_size(comm, &size);
72 if (size < 2)
73 return; // the same answer on every rank of `comm`, so no rank waits in the gather
74 const int mine = hostL3PlacementStatus();
75 std::vector<int> all(rank == 0 ? size : 0);
76 MPI_Gather(&mine, 1, MPI_INT, all.data(), 1, MPI_INT, 0, comm);
77 if (rank != 0 || printed)
78 return;
79 std::string list;
80 int n = 0;
81 for (int r = 0; r < size; ++r)
82 if (all[r] == 2) {
83 if (n < 8)
84 list += (n ? "," : "") + std::to_string(r);
85 else if (n == 8)
86 list += ",...";
87 ++n;
88 }
89 if (n == 0)
90 return;
91 printed = true;
92 std::fprintf(stderr,
93 "peclet.flow: rank%s %s run%s OpenMP threads on more than one L3 cache domain "
94 "(measured up to +18 %% step time); use threads per rank dividing the cores per L3 "
95 "domain (AMD EPYC Zen 4: 8), ideally one rank per domain.\n",
96 n > 1 ? "s" : "", list.c_str(), n > 1 ? "" : "s");
97 std::fflush(stderr);
98}
99} // namespace detail
100
101template <class Grid>
102void Solver<Grid>::initMpi(int gnx, int gny, int gnz, MPI_Comm comm) {
103 int size = 1;
104 MPI_Comm_size(comm, &size);
105 detail::warnL3Placement(comm); // WO-5: one stderr line on rank 0 for a CCD-straddling placement
106 weightedDec_ = false; // the equal-weight partition; rebalanceByWeights sets it
107 // Build the shared decomposition so the pressure MG can derive nested coarse levels
108 // (CutcellMG::coarsened) — the auto policy by default (set_decomposition(0)), the legacy
109 // aligned ORB at 1, coarse-first at >= 2. Depends only on the global grid and that setting, so
110 // it matches mpi_block()'s sizing exactly when the same values are passed there.
111 initMpi(CutcellMG::decomposition(static_cast<std::size_t>(size), gnx, gny, gnz, decompLevels_,
112 decompMaxImbalance_),
113 comm);
114}
115
116template <class Grid>
117void Solver<Grid>::initMpi(const peclet::core::decomp::BlockDecomposer<3>& dec, MPI_Comm comm) {
118 // The FIRST initMpi must precede the geometry. setSolid builds the pressure MG, the velocity MG,
119 // the SDF ghost ring and the cut-cell overlays for the partition in force when it runs; before
120 // initMpi that is the single-rank one, so each rank's hierarchy treats its own block as a
121 // periodic domain of its own. Nothing below rebuilds it, and the step then runs with a
122 // distributed momentum solve but P independent pressure solves: every PCG converges, and the
123 // velocity leaves each rank carrying the divergence of its block-local mean (measured, one
124 // step: a Gaussian cell force at np = 4, 2x2x1, max|du| 4.0e-2 of max|u| 0.36; a pure-gradient
125 // force at np = 2, max|div u| 7.5e-2 where single-rank gives 2e-15). np = 1 is exact by
126 // accident -- its block IS the domain -- so the order is enforced at every rank count.
127 // redistribute() re-enters here with distributed_ already set and rebuilds the geometry itself.
128 if (geometryBuilt_ && !distributed_)
129 throw std::runtime_error(
130 "init_mpi: call BEFORE the geometry (set_solid / set_pressure_geometry / "
131 "set_solid_from_scene) -- the geometry builds the pressure and velocity multigrids for the "
132 "partition in force when it runs, so a geometry built first gives every rank an "
133 "independent, block-periodic pressure solve (a wrong answer at np > 1, with no error)");
134 // The fields were sized by the constructor (or allocateBlock) from SOME partition; the halo is
135 // built from `dec`. If the two differ -- a block sized from another ORB, or ranks holding
136 // different decompositions -- the exchange would read and write the wrong cells with no error.
137 // One collective agrees both: a local mismatch flag (LOR) and the decomposition fingerprint
138 // (MIN == MAX), as MAX over {flag, fp, ~fp}. Every rank throws together.
139 {
140 int csize = 1, crank = 0;
141 MPI_Comm_size(comm, &csize);
142 MPI_Comm_rank(comm, &crank);
143 bool bad = dec.numBlocks() != static_cast<std::size_t>(csize);
144 if (!bad) {
145 const auto b = dec.block(static_cast<std::size_t>(crank));
146 bad = (int)b.size[0] != nx_ || (int)b.size[1] != ny_ || (int)b.size[2] != nz_;
147 }
148 const std::uint64_t fp = CutcellMG::fingerprint(dec);
149 std::uint64_t loc[3] = {bad ? 1ull : 0ull, fp, ~fp}, all[3] = {0, 0, 0};
150 MPI_Allreduce(loc, all, 3, MPI_UINT64_T, MPI_MAX, comm);
151 if (all[0] != 0 || all[1] != ~all[2])
152 throw std::runtime_error(
153 all[0] != 0
154 ? "init_mpi: the solver's local block does not match the decomposition on at least "
155 "one rank -- size Solver(*size) from flow.mpi_block(gnx, gny, gnz, levels=, "
156 "max_imbalance=) with the SAME values given to set_decomposition (C++: "
157 "CutcellMG::decomposition(np, gnx, gny, gnz, levels, max_imbalance).block(rank))"
158 : "init_mpi: the ranks hold different decompositions -- every rank must pass the "
159 "same set_decomposition(levels, max_imbalance) and flow.mpi_block(...) values");
160 }
161 pcInDomain_ = CCField(); // WO-P3g: which ghosts carry a row depends on the decomposition
162 pguessCount_ = 0; // E-dist (doc/vof_projection_distributed_design.md §6 item 4): a new partition
163 distributed_ = true;
164 comm_ = comm;
165 const auto& gs = dec.globalSize();
166 gnx_ = (int)gs[0];
167 gny_ = (int)gs[1];
168 gnz_ = (int)gs[2];
169 int rank = 0;
170 MPI_Comm_rank(comm, &rank);
171 std::array<bool, 3> per{true, true, true};
172 velHalo_ = std::make_shared<GridHaloTopology<3>>();
173 velHalo_->buildTopology(dec, rank, G, per, comm);
174 velDev_ = std::make_shared<GridHalo<double>>();
175 velDev_->setLabel("velocity g2");
176 velDev_->init(*velHalo_);
177 // Communication-avoiding momentum sweeps (see smoothComp): the velocity block is g=2 already,
178 // so the CA pair needs no new topology — only this float exchange for the stencil ring
179 // (operator coefficients are float). Eligible when every rank's block is >= 4 on every axis
180 // (rank-uniform: the decomposition is replicated), gated by `set_comm_avoiding`.
181 velDevF_ = std::make_shared<GridHalo<MReal>>();
182 velDevF_->init(*velHalo_);
183 svDev_.reset(); // the sharp fit's stacked exchange follows the partition (rebuilt at the fit)
184 svHalo_.reset();
185 long minExt = std::numeric_limits<long>::max();
186 for (const auto& s : dec.sizes())
187 for (int k = 0; k < 3; ++k)
188 minExt = std::min(minExt, (long)s[k]);
189 // Also off on an ODD periodic global extent: the wrap ring slot then has the opposite parity of
190 // its image, so the colour-0 ring sweep would update it in the wrong colour (per-colour path).
191 bool oddPeriodic = false;
192 for (int a = 0; a < 3; ++a)
193 oddPeriodic = oddPeriodic || (per[a] && gs[a] % 2 != 0);
194 caMomentum_ = (caMode_ & kCaMomentum) && minExt >= 4 && !oddPeriodic;
195 for (bool& d : momStencilDirty_)
196 d = true;
197 dec_ = std::make_shared<peclet::core::decomp::BlockDecomposer<3>>(dec); // remember the partition
198 const auto oig = velHalo_->indexer().originInclGhost();
199 og_ = {(int)oig[0] + G, (int)oig[1] + G, (int)oig[2] + G}; // block inner origin -> global parity
200 // The colour field's OWN g=3 topology follows the same partition (VOF_PLAN §3 rule 1). Rebuilt
201 // here rather than only in enableVof() so the order enable_vof/init_mpi does not matter — and
202 // because a redistribute() re-inits through this path. The advector's block carries no state
203 // between steps (C's canonical storage is the G=2 registry field "C"), so reallocating it is
204 // free of consequence.
205 if (vofEnabled_)
206 buildVofBlock();
207}
208
209template <class Grid>
210void Solver<Grid>::redistribute(const peclet::core::decomp::BlockDecomposer<3>& newDec) {
211 if (!distributed_ || !dec_)
212 return;
213 int rank = 0;
214 MPI_Comm_rank(comm_, &rank);
215 const auto ob = dec_->block(rank), nb = newDec.block(rank);
216 const int oex = (int)ob.size[0] + 2 * G, oey = (int)ob.size[1] + 2 * G,
217 oez = (int)ob.size[2] + 2 * G;
218 const int nex = (int)nb.size[0] + 2 * G, ney = (int)nb.size[1] + 2 * G,
219 nez = (int)nb.size[2] + 2 * G;
220
221 // 1. gather the surviving registered fields to host padded buffers on the OLD block.
222 const auto names = fields_.names();
223 std::vector<std::vector<double>> oldHost(names.size()), newHost(names.size());
224 for (std::size_t k = 0; k < names.size(); ++k) {
225 CCField f = fields_.at(names[k]).data;
226 auto h = Kokkos::create_mirror_view(f);
227 Kokkos::deep_copy(h, f);
228 oldHost[k].assign(h.data(), h.data() + (std::size_t)oex * oey * oez);
229 newHost[k].assign((std::size_t)nex * ney * nez, 0.0);
230 }
231 // 2. redistribute each field OLD -> NEW (host, bit-exact pure data movement).
232 std::vector<const double*> op(names.size());
233 std::vector<double*> np(names.size());
234 for (std::size_t k = 0; k < names.size(); ++k) {
235 op[k] = oldHost[k].data();
236 np[k] = newHost[k].data();
237 }
238 // 2b. The Chebyshev driver's kept power iterates (D3, doc/vof_step_performance_design.md §5.13)
239 // are cross-step state of the pressure MG, held on its g = 1 level-0 block: carried along
240 // in the same exchange (inner cells re-padded to G), handed back after the MG rebuild (5b).
241 // Dropping them would make the next re-estimate cold, and an np = 1 rebalance would stop
242 // being bit-exact. Collective decision: every rank carries them or none does.
243 int warmLocal = mg_.eigenWarmReady() ? 1 : 0, warmAll = 0;
244 MPI_Allreduce(&warmLocal, &warmAll, 1, MPI_INT, MPI_MIN, comm_);
245 std::vector<double> eigOld[2], eigNew[2];
246 if (warmAll) {
247 const CCField src[2] = {mg_.eigenWarmMax(), mg_.eigenWarmMin()};
248 const int o1x = (int)ob.size[0] + 2, o1y = (int)ob.size[1] + 2;
249 for (int v = 0; v < 2; ++v) {
250 auto h = Kokkos::create_mirror_view(src[v]);
251 Kokkos::deep_copy(h, src[v]);
252 eigOld[v].assign((std::size_t)oex * oey * oez, 0.0);
253 eigNew[v].assign((std::size_t)nex * ney * nez, 0.0);
254 for (int z = 0; z < (int)ob.size[2]; ++z)
255 for (int y = 0; y < (int)ob.size[1]; ++y)
256 for (int x = 0; x < (int)ob.size[0]; ++x)
257 eigOld[v][(std::size_t)(x + G) + (std::size_t)(y + G) * oex +
258 (std::size_t)(z + G) * oex * oey] =
259 h((std::size_t)(x + 1) + (std::size_t)(y + 1) * o1x +
260 (std::size_t)(z + 1) * o1x * o1y);
261 op.push_back(eigOld[v].data());
262 np.push_back(eigNew[v].data());
263 }
264 }
265 peclet::core::decomp::redistributeGridFields<double>(*dec_, newDec, rank, G, op, np, comm_);
266
267 // 3. reallocate every buffer to the new block; re-init the halo + MG on the new partition.
268 // `resizeForBlock` must run BETWEEN the two: `allocateBlock` only re-creates the buffers it
269 // owns by name, and `initMpi` -> `buildVofBlock` already writes through `cField_`, which is
270 // a registry alias. Without it the scatter below memcpy's the new padded extent into the
271 // old allocation (ASan heap-buffer-overflow -> `free(): invalid pointer`).
272 allocateBlock((int)nb.size[0], (int)nb.size[1], (int)nb.size[2]);
273 resizeForBlock();
274 initMpi(newDec, comm_);
275 // scatter a padded host buffer into a registered field's device buffer.
276 auto scatterPadded = [&](const std::string& name, const std::vector<double>& src) {
277 CCField f = fields_.at(name).data;
278 auto h = Kokkos::create_mirror_view(f);
279 std::memcpy(h.data(), src.data(), sizeof(double) * (std::size_t)nex * ney * nez);
280 Kokkos::deep_copy(f, h);
281 };
282 // 4. scatter all migrated fields into the fresh (new-block) buffers.
283 for (std::size_t k = 0; k < names.size(); ++k)
284 scatterPadded(names[k], newHost[k]);
285 // 5. rebuild geometry-derived state (openness/IBM/stencils/MG) from the migrated SDF. setSolid
286 // zeroes the velocity + pressure (it is the initial-geometry setup), so re-instate every
287 // non-SDF field afterward from the migrated data.
288 {
289 // A repartition is not an operator change: the balanced-force pre-projection keeps its
290 // Chebyshev bounds across it, as the main solve keeps its own (setSolid's MG rebuild would
291 // otherwise force a re-estimate, and an np = 1 rebalance would stop being bit-exact).
292 const bool keepBfpBounds = bfpChebSet_;
293 setSolid(gatherInner(sdf_), cutcellPressure_);
294 bfpChebSet_ = keepBfpBounds;
295 }
296 for (std::size_t k = 0; k < names.size(); ++k)
297 if (names[k] != "sdf")
298 scatterPadded(names[k], newHost[k]);
299 // 5b. hand the migrated Chebyshev power iterates back to the rebuilt MG (see 2b): inner cells
300 // into a fresh g = 1 level-0 vector (ghosts zero; no consumer reads them before a refill).
301 if (warmAll) {
302 const int n1x = (int)nb.size[0] + 2, n1y = (int)nb.size[1] + 2, n1z = (int)nb.size[2] + 2;
303 CCField dst[2];
304 for (int v = 0; v < 2; ++v) {
305 dst[v] = CCField(v == 0 ? "ev_vmax" : "ev_vmin", (std::size_t)n1x * n1y * n1z);
306 auto h = Kokkos::create_mirror_view(dst[v]);
307 Kokkos::deep_copy(h, 0.0);
308 for (int z = 0; z < (int)nb.size[2]; ++z)
309 for (int y = 0; y < (int)nb.size[1]; ++y)
310 for (int x = 0; x < (int)nb.size[0]; ++x)
311 h((std::size_t)(x + 1) + (std::size_t)(y + 1) * n1x +
312 (std::size_t)(z + 1) * n1x * n1y) =
313 eigNew[v][(std::size_t)(x + G) + (std::size_t)(y + G) * nex +
314 (std::size_t)(z + G) * nex * ney];
315 Kokkos::deep_copy(dst[v], h);
316 }
317 mg_.setEigenWarm(dst[0], dst[1]);
318 }
319 // 6. REFILL THE GHOSTS. `redistributeGridFields` moves the INNER cells only and says so
320 // ("the caller refills ghosts with a halo exchange afterwards"); the padded destination
321 // buffers were zero-initialised in step 1, so without this every migrated field enters the
322 // next step with a zero halo on the new partition. Measured at np = 4 on the VoF gate: one
323 // step after the move, du = 1.01e-01 against the single-rank reference (a run started
324 // directly on the SAME weighted partition reproduces it to 6.5e-17), and 0.00e+00 with the
325 // refill. np = 1/2 hid it because the new neighbour set happened to reproduce the old one.
326 for (std::size_t k = 0; k < names.size(); ++k)
327 fillGhosts(fields_.at(names[k]).data);
328 for (auto& sc : scalars_)
329 applyScalarBc(sc); // a scalar's own domain BCs override the halo/periodic base
330 // 6b. RE-SEED eps^n. It is STATE, not scratch: a re-partition is not a time step, so the
331 // porosity must not appear to have jumped across it -- eps^n := the migrated eps^{n+1}, i.e.
332 // d(eps)/dt = 0 over the redistribute, the only choice that leaves the projection RHS
333 // unchanged. It must happen HERE, after step 4 scattered the migrated eps into `epsField_`:
334 // it used to happen in `resizeForBlock` (step 3), where `epsField_` is the freshly allocated
335 // ZERO buffer whenever the block changes size, so eps^n = 0 and the first porous projection
336 // after a rebalance saw d(eps)/dt = eps/dt. Measured on coupling's test_mpi_rebalance (a
337 // 32^3 heap, np = 2 and 4): pressure off by 2.2e+02 and velocity by 2.4 (|u| <= 0.07) one
338 // step after the move; a rebalance that keeps every block's size hid it (no reallocation).
339 if (epsPrev_.extent(0) == n_ && epsField_.extent(0) == n_)
340 Kokkos::deep_copy(epsPrev_, epsField_);
341 // 7. RE-SEED THE COLLOCATED FACE FIELD. `uf_/vf_/wf_` are block scratch, not registry fields:
342 // step 3's `allocateBlock` handed us fresh ZERO buffers and nothing above migrates them, so
343 // the projected face field of the old partition is simply gone. Everything that rides it --
344 // momentum advection (ufAdvVelocity()), the colour transport, the scalars -- would read
345 // zeros on the step after a rebalance, and `advect_vof`'s divergence guard would wave them
346 // through (a zero field is perfectly solenoidal). Seeding from the migrated cell velocity
347 // with the same `centerToFace` map `project()` uses restores a consistent (not yet
348 // divergence-free) field, exactly as `set_state` does; the next `project()` makes it
349 // solenoidal again. A no-op on the staggered grid.
350 seedFaceFieldFromCells();
351}
352
353template <class Grid>
354int Solver<Grid>::rebalanceByWeights(const std::vector<peclet::core::Real>& w) {
355 if (!distributed_)
356 return 1;
357 int size = 1, rank = 0;
358 MPI_Comm_size(comm_, &size);
359 MPI_Comm_rank(comm_, &rank);
360 // The ALIGNED weighted ORB (amr/docs/amr_mg_core_boundary.md §6, §9.2, §11.4): split planes on
361 // multiples of 2^a, a the largest alignment whose weight imbalance stays within the 1.05 budget
362 // (a = 0: the plain weighted ORB, bit for bit). Every split is then even for a lifts, so the
363 // pressure MG coarsens in place for a levels before any telescope stage can fire, and whatever
364 // stage fires does so on a level 8^a smaller. A pure function of (ranks, grid, weights): every
365 // rank computes the same partition, and so must any code that co-decomposes from `w` -- which is
366 // why the chosen alignment is RETURNED: dem rebuilds this partition as the aligned weighted ORB
367 // `init(size, G, w, {2^a,...})`, and at a = 0 as the plain weighted ORB (core guarantees the
368 // two coincide bit for bit at align 1).
369 const auto c = peclet::core::decomp::chooseAlignedWeighted(
370 (std::size_t)size, peclet::core::IVec<3>{gnx_, gny_, gnz_}, w);
371 if (mgDebugLevel() && rank == 0) {
372 std::printf(
373 "[mg] rebalanceByWeights: aligned weighted ORB a = %d (align %d), weight imbalance "
374 "%.4f\n",
375 c.a, 1 << c.a, (double)c.imbalance);
376 std::fflush(stdout);
377 }
378 weightedDec_ = true; // before redistribute: its setSolid rebuilds the pressure MG
379 redistribute(c.dec);
380 return 1 << c.a;
381}
382
383template <class Grid>
384std::vector<CutcellMG::PlanRow> Solver<Grid>::pressureMgPlan() const {
385 return mg_.builtPlan();
386}
387#endif
388
389template <class Grid>
390void Solver<Grid>::resizeForBlock() {
391 reallocOwnedFields();
392 rebindFieldAliases();
393 resizeBlockScratch();
394 for (int f = 0; f < 6; ++f)
395 resampleBcProfile(f); // the resampled inlet profile is indexed by LOCAL face position
396}
397
398template <class Grid>
399void Solver<Grid>::reallocOwnedFields() {
400 for (const auto& nm : fields_.names()) {
401 auto& rec = fields_.at(nm);
402 if (!rec.ownStorage || rec.data.extent(0) == n_)
403 continue;
404 rec.data = CCField(nm, n_);
405 }
406}
407
408template <class Grid>
409void Solver<Grid>::rebindFieldAliases() {
410 auto bind = [this](CCField& f, const std::string& nm) {
411 if (fields_.has(nm))
412 f = fields_.at(nm).data;
413 };
414 bind(cField_, "C"); // VoF: the canonical G=2 colour mirror
415 bind(kappaField_, "kappa"); // VoF: the curvature mirrors
416 bind(kappaBranch_, "kappa_branch");
417 bind(rhoField_, "rho"); // property closures
418 bind(Pb_, "p_balanced"); // balanced-force projection split (doc/collocated_varrho_forces.md)
419 bind(muField_, "mu");
420 bind(epsField_, "eps"); // CFD-DEM: porosity + drag
421 bind(dragBeta_, "drag_beta");
422 bind(pcMdot_, "mdot"); // phase change
423 bind(pcSrc_, "pc_source");
424 bind(pcUser_, "div_source");
425 bind(pcSink_, "div_sink");
426 static const char* fn[3] = {"force_x", "force_y", "force_z"};
427 for (int c = 0; c < 3; ++c)
428 bind(cellForce_[c], fn[c]);
429 for (auto& sc : scalars_) {
430 bind(sc.c, sc.name);
431 if (sc.cut && sc.cut->solid.extent(0) > 0) // WO-7: a conjugate scalar's solid field
432 bind(sc.cut->solid, sc.name + "_solid");
433 }
434 for (auto& cl : closures_) { // property_closures.hpp keeps the registry keys for exactly this
435 if (fields_.has(cl.outName))
436 cl.out = fields_.at(cl.outName).data;
437 if (fields_.has(cl.in0Name))
438 cl.in0 = CCConst(fields_.at(cl.in0Name).data);
439 if (!cl.in1Name.empty() && fields_.has(cl.in1Name))
440 cl.in1 = CCConst(fields_.at(cl.in1Name).data);
441 }
442}
443
444template <class Grid>
445void Solver<Grid>::resizeIfAllocated(CCField& f, const char* label, std::size_t n) {
446 if (f.extent(0) != 0 && f.extent(0) != n)
447 f = CCField(label, n);
448}
449
450template <class Grid>
451void Solver<Grid>::resizeBlockScratch() {
452 const std::size_t n = n_, n1 = n1_;
453 // --- velocity / pressure scratch --------------------------------------------------------
454 resizeIfAllocated(velRes_, "velRes", n);
455 resizeIfAllocated(zp1_, "zp1", n1);
456 resizeIfAllocated(vmgTheta_, "vmgTheta", n);
457 resizeIfAllocated(vmgClean_, "vmgClean", n);
458 for (int c = 0; c < 3; ++c) {
459 resizeIfAllocated(uStar_[c], "uStar", n);
460 resizeIfAllocated(advRhs_[c], "advRhs", n);
461 resizeIfAllocated(uBc_[c], "uBc", n);
462 resizeIfAllocated(uwCell_[c], "uwCell", n);
463 resizeIfAllocated(uwAdv_[c], "uwAdv", n);
464 resizeIfAllocated(faceAcc_[c], "faceAcc", n);
465 }
466 resizeIfAllocated(pb1_, "pb1",
467 n1); // balanced-force projection scratch (P_b itself is registered)
468 haveUStar_ = false; // u* belonged to the old block's last momentum solve
469 haveAdvRhs_ = false;
470 // --- ghost projection (its overlay is rebuilt by setSolid) ------------------------------
471 resizeIfAllocated(oxb_, "oxb", n);
472 resizeIfAllocated(oyb_, "oyb", n);
473 resizeIfAllocated(ozb_, "ozb", n);
474 resizeIfAllocated(sdfGp_, "peclet::flow::sdfGp", n);
475 resizeIfAllocated(gpRh_, "gpRh", n1);
476 resizeIfAllocated(gpT_, "gpT", n1);
477 resizeIfAllocated(gpZ2_, "gpZ2", n1);
478 resizeIfAllocated(gpX2_, "gpXg2", n);
479 // --- VoF (the g=3 block itself is rebuilt by buildVofBlock) -----------------------------
480 resizeIfAllocated(vofCs_, "vofCs", n);
481 resizeIfAllocated(vofSolidG2_, "vofSolidG2", n);
482 for (int c = 0; c < 3; ++c) {
483 resizeIfAllocated(uAdv_[c], "uAdv", n);
484 resizeIfAllocated(vofDynVel_[c], "vofDynVel", n);
485 resizeIfAllocated(csfBlkF_[c], "vof::blockcsf", n);
486 }
487 // --- phase change -----------------------------------------------------------------------
488 resizeIfAllocated(pcArea_, "pc_area", n);
489 for (int c = 0; c < 3; ++c) {
490 resizeIfAllocated(pcNrm_[c], "pc_nrm", n);
491 resizeIfAllocated(pcGn_[c], "pc_gn", n);
492 }
493 resizeIfAllocated(pcDep_, "pc_dep", n);
494 resizeIfAllocated(pcTgt_, "pc_tgt", n);
495 resizeIfAllocated(pcCnew_, "pc_cnew", n);
496 resizeIfAllocated(pcDefic_, "pc_defic", n);
497 resizeIfAllocated(pcKcell_, "pc_k", n);
498 resizeIfAllocated(pcRcp_, "pc_rcp", n);
499 resizeIfAllocated(pcClsPrev_, "pc_cls_prev", n);
500 resizeIfAllocated(pcCarrySrc_, "pc_carry_src", n);
501 resizeIfAllocated(pcMdotFit_, "pc_mdot_fit", n);
502 resizeIfAllocated(pcKappa_, "pc_kappa", n);
503 resizeIfAllocated(pcAreaCg2_, "pc_area_cascade", n);
504 resizeIfAllocated(pcTgam_, "pc_tgam", n);
505 resizeIfAllocated(pcGphi_, "pc_gphi", n);
506 pcInDomain_ = CCField(); // which ghosts carry a row depends on the decomposition (WO-P3g)
507 pcMaskFresh_ = false;
508 // --- sharp viscous interface (doc/vof_sharp_viscous_stress.md) --------------------------
509 // `sharpActive_` and `sharpGeom_` are per-step state of the OLD block: the geometry's views,
510 // extents and strides index the old colour/plane blocks. Left set, `setSolid`'s
511 // `rebuildStencils` (redistribute step 5) assembled the band edges through them on the new
512 // block -- an out-of-bounds read (host SEGFAULT in `vof_redistribute_mpi`). Back to the
513 // initial-setup state instead: `resolveSharpViscous` re-decides at the next step head and
514 // `sharpViscousGeometry` re-allocates the band buffers at the new n (zero-initialised fallback
515 // flags, as at the first step). Inert under 'averaged' (never active, buffers never allocated).
516 sharpActive_ = false;
517 sharpGeom_ = vof::SharpGeom{};
518 svCls_ = vof::SvByte();
519 svFb_ = vof::SvByte();
520 svFit_ = CCField();
521 for (int a = 0; a < 3; ++a)
522 svTau_[a] = CCField();
523 svDnn_ = CCField();
524 svList_ = vof::SvList();
525 svRhsList_ = vof::SvList();
526 svRhsN_ = 0;
527 // --- transported scalars (their operator is rebuilt; the solution rides the registry) -----
528 for (auto& sc : scalars_) {
529 resizeIfAllocated(sc.cOld, "scalar_old", n);
530 resizeIfAllocated(sc.b, "scalar_b", n);
531 resizeIfAllocated(sc.AC, "scalar_AC", n);
532 resizeIfAllocated(sc.AW, "scalar_AW", n);
533 resizeIfAllocated(sc.AE, "scalar_AE", n);
534 resizeIfAllocated(sc.AS, "scalar_AS", n);
535 resizeIfAllocated(sc.AN, "scalar_AN", n);
536 resizeIfAllocated(sc.AB, "scalar_AB", n);
537 resizeIfAllocated(sc.AT, "scalar_AT", n);
538 resizeIfAllocated(sc.dmask, "scalar_dmask", n);
539 resizeIfAllocated(sc.dval, "scalar_dval", n);
540 resizeIfAllocated(sc.gfmB, "scalar_gfmb", n);
541 sc.stencilBuilt = false; // the operator is a property of the block
542 }
543 // `ScalarField::kcell`/`rcp` are NOT the scalar's own storage: they ALIAS `pcKcell_`/`pcRcp_`
544 // (set at `set_phase_change_energy`). Resizing them independently would give the energy
545 // operator a different buffer from the one `pcUpdateEnergyProps` fills every step — measured
546 // as dP 3.09e-04 against the never-rebalanced control at np = 4. Re-alias instead.
547 if (pcEnergy_ && !pcTName_.empty() && hasScalar(pcTName_)) {
548 ScalarField& sc = scalarField(pcTName_);
549 sc.kcell = pcKcell_;
550 sc.rcp = pcRcp_;
551 }
552 // --- variable density / porous (CFD-DEM) -------------------------------------------------
553 resizeIfAllocated(rho1_, "rho1", n1);
554 resizeIfAllocated(cx1_, "cx1", n1);
555 resizeIfAllocated(cy1_, "cy1", n1);
556 resizeIfAllocated(cz1_, "cz1", n1);
557 resizeIfAllocated(eps1_, "eps1", n1);
558 resizeIfAllocated(beta1_, "beta1", n1);
559 resizeIfAllocated(depsdt_, "depsdt", n);
560 resizeIfAllocated(divAdv_, "divAdv", n);
561 resizeIfAllocated(epsRho_, "epsRho", n);
562 resizeIfAllocated(epsPrev_, "epsPrev", n); // eps^n is STATE: `redistribute` re-seeds it (6b)
563 for (int c = 0; c < 3; ++c)
564 for (int k = 0; k < 3; ++k)
565 if (tEx_[c][k].extent(0) != 0 && tEx_[c][k].extent(0) != (std::size_t)nx_ * ny_ * nz_) {
566 tEx_[c][k] = CCField(); // exact crossings are single-rank only; drop the stale set
567 hasExactCross_ = false;
568 }
569 // `cutOwner_` is deliberately NOT resized: every consumer guards on
570 // `extent(0) == nx_*ny_*nz_` and skips, so a stale-sized owner map is inert, while a
571 // freshly-zeroed one would silently name instance 0 as the owner of every cut cell.
572}
573
574} // namespace peclet::flow
575
576#endif // PECLET_FLOW_FLOW_IBM_MPI_HPP
y
Definition cmp.py:24
Kokkos::View< std::uint8_t *, CCMem > SvByte
Per-cell byte fields on the solver block: the band class and the fit-fallback flag.
Kokkos::View< long *, CCMem > SvList
The compacted interfacial cells of a fit (local linear indices), the device fit's worklist.
Kokkos::View< const double *, CCMem > CCConst
Kokkos::View< double *, CCMem > CCField
int m
Definition post.py:35
The band geometry and the closure constants, by value into every kernel.
static constexpr int G