flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
mac_cutcell.hpp
Go to the documentation of this file.
1
9#ifndef PECLET_FLOW_MAC_CUTCELL_HPP
10#define PECLET_FLOW_MAC_CUTCELL_HPP
11
12#include <cstdlib>
13#include <Kokkos_Core.hpp>
14#include <Kokkos_MathematicalFunctions.hpp>
15#include <string>
16#include <tuple>
17#include <type_traits>
18#include <utility>
19
20#include "policy.hpp"
21
22namespace peclet::flow {
23
24using CCExec = Kokkos::DefaultExecutionSpace;
25using CCMem = CCExec::memory_space;
26using CCField = Kokkos::View<double*, CCMem>;
27using CCConst = Kokkos::View<const double*, CCMem>;
28
29// The EXACT level-0 operator apply — P1 of the defect-correction campaign
30// (docs/DEFECT_CORRECTION_PLAN.md). PER SOLVER (`set_pressure_exact_residual`): off at
31// construction, byte-identical when off, and turned ON by `enable_vof`.
32//
33// The rule: the residual and the Krylov matvec use the EXACT operator in double, in flux form;
34// everything below that line is a preconditioner and may stay float. With the gate on, the
35// level-0 matvec (matvecOverlap, the choke point for solvePCG and the flexible PCG) applies
36// applyCutcellOpExact -- matrix-free from the double face openness Level::ox/oy/oz that
37// buildCutcellOp assembles the float bands from -- so the Krylov fixed point becomes A_exact by
38// construction and the float hierarchy is demoted to a pure preconditioner, whose errors change
39// the convergence RATE and never the fixed point.
40//
41// Nothing inside vcycle() changes: residualCutcell, the smoother, restriction, the CA ring and
42// the AMG bottom all keep the float bands on purpose.
43//
44// `IbmSolver::enableVof` turns it ON (measured: on Hysing case 2 it removes 7.5 orders of the
45// projected flux divergence, 1.85e-03 -> 5.15e-11, and moves the iteration count, the step count,
46// the dt-limit census and both published functionals by nothing at all — the float `A*1 != 0`
47// defect is exactly what a moving interface's coefficient contrast amplifies).
48// `set_pressure_exact_residual(False)` after `enable_vof` is the ablation.
49
50// P2 shares this gate: the star overlay's additive delta (star_elimination.hpp) is part of the
51// same level-0 operator, so "the matvec is exact" has to mean the overlay too or the composed
52// operator is still the float one.
53
54struct C3 {
55 int x, y, z;
56};
57
58// Masked fluid fraction of a face from its SDF samples (centre + 6 axis neighbours). type 1/2/3 =
59// x/y/z face. (sd<=0 => closed.) Verbatim from cc_fraction_core.
60KOKKOS_INLINE_FUNCTION double ccFractionCore(double sd, double sxp, double sxm, double syp,
61 double sym, double szp, double szm, int type,
62 double dx, double dy, double dz) {
63 if (sd <= 0.0)
64 return 0.0;
65 const double gx = (sxp - sxm) / (2.0 * dx), gy = (syp - sym) / (2.0 * dy),
66 gz = (szp - szm) / (2.0 * dz);
67 double gmag = Kokkos::sqrt(gx * gx + gy * gy + gz * gz);
68 if (gmag < 1e-6)
69 gmag = 1e-6;
70 const double nx = gx / gmag, ny = gy / gmag, nz = gz / gmag;
71 double denom = (type == 1) ? (Kokkos::fabs(ny) * dy + Kokkos::fabs(nz) * dz)
72 : (type == 2) ? (Kokkos::fabs(nx) * dx + Kokkos::fabs(nz) * dz)
73 : (Kokkos::fabs(nx) * dx + Kokkos::fabs(ny) * dy);
74 if (denom < 1e-9)
75 denom = 1e-9;
76 double frac = 0.5 + sd / denom;
77 if (frac < 0.0)
78 frac = 0.0;
79 if (frac > 1.0)
80 frac = 1.0;
81 return frac;
82}
83
84KOKKOS_INLINE_FUNCTION double ccSampleExt(CCConst sdf, C3 ext, double x, double y, double z) {
85 const double fx = Kokkos::floor(x), fy = Kokkos::floor(y), fz = Kokkos::floor(z);
86 const double wx = x - fx, wy = y - fy, wz = z - fz;
87 int x0 = (int)fx, y0 = (int)fy, z0 = (int)fz;
88 auto cl = [](int v, int n) { return v < 0 ? 0 : (v >= n ? n - 1 : v); };
89 const int x1 = cl(x0 + 1, ext.x), y1 = cl(y0 + 1, ext.y), z1 = cl(z0 + 1, ext.z);
90 x0 = cl(x0, ext.x);
91 y0 = cl(y0, ext.y);
92 z0 = cl(z0, ext.z);
93 const long sy = ext.x, sz = static_cast<long>(ext.x) * ext.y;
94 auto F = [&](int xx, int yy, int zz) {
95 return sdf(static_cast<long>(xx) + static_cast<long>(yy) * sy + static_cast<long>(zz) * sz);
96 };
97 const double c00 = F(x0, y0, z0) * (1 - wx) + F(x1, y0, z0) * wx;
98 const double c10 = F(x0, y1, z0) * (1 - wx) + F(x1, y1, z0) * wx;
99 const double c01 = F(x0, y0, z1) * (1 - wx) + F(x1, y0, z1) * wx;
100 const double c11 = F(x0, y1, z1) * (1 - wx) + F(x1, y1, z1) * wx;
101 const double c0 = c00 * (1 - wy) + c10 * wy, c1 = c01 * (1 - wy) + c11 * wy;
102 return c0 * (1 - wz) + c1 * wz;
103}
104
105KOKKOS_INLINE_FUNCTION double ccFaceOpen(CCConst sdf, C3 ext, double fx, double fy, double fz,
106 int type, double dx, double dy, double dz) {
107 const double sd = ccSampleExt(sdf, ext, fx, fy, fz);
108 if (sd <= 0.0)
109 return 0.0;
110 const double e = 1.0;
111 return ccFractionCore(
112 sd, ccSampleExt(sdf, ext, fx + e, fy, fz), ccSampleExt(sdf, ext, fx - e, fy, fz),
113 ccSampleExt(sdf, ext, fx, fy + e, fz), ccSampleExt(sdf, ext, fx, fy - e, fz),
114 ccSampleExt(sdf, ext, fx, fy, fz + e), ccSampleExt(sdf, ext, fx, fy, fz - e), type, dx, dy,
115 dz);
116}
117
118// Fluid fraction (sd >= 0 = fluid) of a triangle with linear vertex values (a, b, c): the exact
119// linear-simplex level-set area fraction. Denominators (x-y)(x-z) are strictly positive whenever
120// the signs are mixed (x is the odd one out), guarded against exact-zero degeneracies.
121KOKKOS_INLINE_FUNCTION double ccTriFrac(double a, double b, double c) {
122 const bool pa = a >= 0.0, pb = b >= 0.0, pc = c >= 0.0;
123 const int np = (pa ? 1 : 0) + (pb ? 1 : 0) + (pc ? 1 : 0);
124 if (np == 3)
125 return 1.0;
126 if (np == 0)
127 return 0.0;
128 double x, y, z;
129 if (np == 1) { // rotate the positive vertex into x
130 if (pa) {
131 x = a;
132 y = b;
133 z = c;
134 } else if (pb) {
135 x = b;
136 y = c;
137 z = a;
138 } else {
139 x = c;
140 y = a;
141 z = b;
142 }
143 const double den = (x - y) * (x - z);
144 return den > 1e-300 ? (x * x) / den : 1.0;
145 }
146 // np == 2: rotate the negative vertex into x
147 if (!pa) {
148 x = a;
149 y = b;
150 z = c;
151 } else if (!pb) {
152 x = b;
153 y = c;
154 z = a;
155 } else {
156 x = c;
157 y = a;
158 z = b;
159 }
160 const double den = (x - y) * (x - z);
161 return 1.0 - (den > 1e-300 ? (x * x) / den : 1.0);
162}
163
164// MARCHING-SQUARES face openness (setApertureOrder(2), 2026-08-26): the O(h^2) upgrade of
165// ccFaceOpen motivated by the measured convexity bias of the one-sample linear model (the
166// tangent-plane estimate over-closes apertures on convex solids by +0.59%/+0.27% in bed
167// permeability at R=8/12, decaying ~h^2 -- flow doc/collocated_paper_plan.md row 51). Five
168// trilinear samples per face (4 corners + center), triangle-fan decomposition (4 triangles of
169// area 1/4 around the center sample -- no marching-squares saddle ambiguity), exact linear
170// fraction per triangle. Sub-resolution floor 1e-6 (measured lesson: alpha ~ 1e-12 rows from
171// exact geometry destroy the operator conditioning; the crude model's clip was an accidental
172// regularizer -- the floor makes the regularization explicit). Floor VALUE 1e-3 (2026-08-26):
173// 1e-6 measured insufficient -- alpha in [1e-6, 1e-2] rows drag plain RB-GS (levels=1) to a
174// ~1e-4 divergence floor within test budgets (redistribute_mpi_np4); a face open by <0.1% of
175// its area carries no resolved flux, so snapping it closed costs nothing measurable.
176KOKKOS_INLINE_FUNCTION double ccFaceOpenMS(CCConst sdf, C3 ext, double fx, double fy, double fz,
177 int type) {
178 const double e = 0.5;
179 double t1x = 0, t1y = 0, t1z = 0, t2x = 0, t2y = 0, t2z = 0; // tangent half-offsets
180 if (type == 1) {
181 t1y = e;
182 t2z = e;
183 } else if (type == 2) {
184 t1x = e;
185 t2z = e;
186 } else {
187 t1x = e;
188 t2y = e;
189 }
190 const double ccg = ccSampleExt(sdf, ext, fx, fy, fz);
191 if (ccg <= 0.0)
192 return 0.0; // CENTER GATE (DOF-support consistency, kept from order 1): a face whose
193 // staggered velocity point is solid has a MASKED u DOF -- an alpha > 0 aperture
194 // there is a constraint the projection cannot act on (measured: dropping this
195 // gate leaves an uncorrectable ~1.6e-4 divergence floor under plain RB-GS,
196 // redistribute_mpi_np4). The marching-squares fraction below only refines the
197 // AREA of center-fluid faces -- which is where the convexity bias lived.
198 const double c00 = ccSampleExt(sdf, ext, fx - t1x - t2x, fy - t1y - t2y, fz - t1z - t2z);
199 const double c10 = ccSampleExt(sdf, ext, fx + t1x - t2x, fy + t1y - t2y, fz + t1z - t2z);
200 const double c11 = ccSampleExt(sdf, ext, fx + t1x + t2x, fy + t1y + t2y, fz + t1z + t2z);
201 const double c01 = ccSampleExt(sdf, ext, fx - t1x + t2x, fy - t1y + t2y, fz - t1z + t2z);
202 const double cc = ccg;
203 const double frac = 0.25 * (ccTriFrac(c00, c10, cc) + ccTriFrac(c10, c11, cc) +
204 ccTriFrac(c11, c01, cc) + ccTriFrac(c01, c00, cc));
205 if (frac < 1e-3)
206 return 0.0;
207 if (frac > 1.0 - 1e-12)
208 return 1.0;
209 return frac;
210}
211
212// Fill staggered face openness over the whole extended block (ox[i] = -x face of cell i, etc.).
213// order 1 = the shipped one-sample linear model (byte-identical default); order 2 =
214// marching-squares (ccFaceOpenMS).
215inline void buildOpenness(CCField ox, CCField oy, CCField oz, CCConst sdf, C3 ext, double dx,
216 double dy, double dz, int order = 1) {
217 CCExec space;
218 using MD = MDRange3<CCExec>;
219 if (order >= 2) {
220 Kokkos::parallel_for(
221 "peclet::flow::cc_open_ms", MD(space, {0, 0, 0}, {ext.x, ext.y, ext.z}),
222 KOKKOS_LAMBDA(int lx, int ly, int lz) {
223 const long i = static_cast<long>(lx) + static_cast<long>(ly) * ext.x +
224 static_cast<long>(lz) * static_cast<long>(ext.x) * ext.y;
225 ox(i) = ccFaceOpenMS(sdf, ext, lx - 0.5, ly, lz, 1);
226 oy(i) = ccFaceOpenMS(sdf, ext, lx, ly - 0.5, lz, 2);
227 oz(i) = ccFaceOpenMS(sdf, ext, lx, ly, lz - 0.5, 3);
228 });
229 return;
230 }
231 Kokkos::parallel_for(
232 "peclet::flow::cc_open", MD(space, {0, 0, 0}, {ext.x, ext.y, ext.z}),
233 KOKKOS_LAMBDA(int lx, int ly, int lz) {
234 const long i = static_cast<long>(lx) + static_cast<long>(ly) * ext.x +
235 static_cast<long>(lz) * static_cast<long>(ext.x) * ext.y;
236 ox(i) = ccFaceOpen(sdf, ext, lx - 0.5, ly, lz, 1, dx, dy, dz);
237 oy(i) = ccFaceOpen(sdf, ext, lx, ly - 0.5, lz, 2, dx, dy, dz);
238 oz(i) = ccFaceOpen(sdf, ext, lx, ly, lz - 0.5, 3, dx, dy, dz);
239 });
240}
241
242// Re-derive ONE staggered face-openness plane: component `a` at the HIGH domain-face index
243// (ext.a - g) along axis a. SCALING_ISSUES #3: that index is a GHOST index, so the distributed
244// openness halo exchange overwrites it with the periodic wrap of the opposite boundary -- which at
245// a non-periodic domain face is another boundary's aperture, not this one's. It is the face the
246// divergence weights the outgoing flux by AND (since the Dirichlet row carries the aperture) the
247// one the operator reads, so it has to be the geometry's own value. `buildOpenness` had it right
248// before the exchange; this re-derives it from the same (already exchanged, already
249// domain-extended) SDF rather than keeping a save buffer alive across a per-step set_solid.
250inline void buildOpennessHighFace(CCField oa, CCConst sdf, C3 ext, int g, int a, double dx,
251 double dy, double dz, int order = 1) {
252 CCExec space;
253 const int dims[3] = {ext.x, ext.y, ext.z};
254 const long st[3] = {1, (long)ext.x, (long)ext.x * ext.y};
255 const int b = (a + 1) % 3, c = (a + 2) % 3;
256 const long sa = st[a], sb = st[b], sc = st[c];
257 const int bf = dims[a] - g;
258 const int type = a + 1;
259 using MD = MDRange2<CCExec>;
260 Kokkos::parallel_for(
261 "peclet::flow::cc_open_high_face", MD(space, {0, 0}, {dims[b], dims[c]}),
262 KOKKOS_LAMBDA(int p0, int p1) {
263 double q[3];
264 q[a] = (double)bf - 0.5;
265 q[b] = (double)p0;
266 q[c] = (double)p1;
267 const long i = (long)p0 * sb + (long)p1 * sc + (long)bf * sa;
268 oa(i) = (order >= 2) ? ccFaceOpenMS(sdf, ext, q[0], q[1], q[2], type)
269 : ccFaceOpen(sdf, ext, q[0], q[1], q[2], type, dx, dy, dz);
270 });
271}
272
273// HOST-only serial cutoff: below this many cells an OpenMP launch costs more than the work it does
274// (fork/join is ~20-30 us at 24 threads), so run the loop sequentially instead. That is
275// BIT-IDENTICAL for elementwise kernels and for colored sweeps (same-color cells are independent,
276// so the order within a sweep is irrelevant); reductions are deliberately NOT cut over — that would
277// change the FP summation order with the block size, and the multi-rank bit-exactness contract is
278// worth more than the microseconds. The device path never sees this (hostRunSerial is false there).
279//
280// MEASURED (5965WX, 24 threads, per-level V-cycle timer): the win lives almost entirely in the MG's
281// BOTTOM level, which fires ~24 trivial launches per V-cycle — 64^3/rank L4(4^3): 0.018 -> 0.007 s
282// per 50 V-cycles, ~8% of the whole V-cycle; 128^3/rank ~1.5%; 256^3/rank (the fat-rank target
283// size) ~0.2%, i.e. below run-to-run noise. A LARGER cutoff back-fires (131072 serializes levels
284// with real work: 64^3 projection 16.6 -> 20.6 ms/step), so keep it small.
285inline constexpr long kHostSerialCellCutoff = 8192L;
286// A one-cell x-run costs about 8 streamed cells (5965WX: serial pass 54 us = 7936 cells x 1.5 ns
287// + 3840 runs x 11 ns); ccBoxShellRuns' shell branch adds this per x-run to its serial test
288// (doc/vof_distributed_partition_design.md §13.4(1), WO-A).
289inline constexpr long kShellRunCells = 8L;
290// True when a host launch of `cells` cells should run sequentially instead (always false on
291// device).
292inline bool hostRunSerial(long cells) {
293 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>)
294 return cells > 0 && cells < kHostSerialCellCutoff;
295 else
296 return false;
297}
298
299// WO-T (doc/vof_distributed_partition_design.md §13.6): names a host serial run in the profile.
300// A hostRunSerial(...) true branch runs its loop outside any Kokkos launch, so a tool sees no
301// kernel there; this guard brackets the loop in the region "<launch name>@serial" when a profiling
302// library is loaded, and does nothing otherwise (one bool test, no allocation). It touches no data:
303// the loop's bits are unchanged.
305 public:
306 // `region` is the full region name, a string literal ("peclet::flow::<launch>@serial").
307 explicit HostSerialRegion(const char* region) : on_(Kokkos::Tools::profileLibraryLoaded()) {
308 if (on_)
309 Kokkos::Profiling::pushRegion(region);
310 }
311 // A helper whose launch name is its caller's: the region is launch + "@serial", built only
312 // when a tool is loaded.
313 HostSerialRegion(const char* launch, const char* suffix)
314 : on_(Kokkos::Tools::profileLibraryLoaded()) {
315 if (on_)
316 Kokkos::Profiling::pushRegion(std::string(launch) + suffix);
317 }
319 if (on_)
320 Kokkos::Profiling::popRegion();
321 }
324
325 private:
326 bool on_;
327};
328
329// The host launch rule (doc/vof_step_performance_design.md §4.5, "rule H"): a 3-D elementwise
330// kernel is ONE cell body `f(x, y, z)`, launched
331// * on a device backend as MDRange3 with the default tiling (unchanged), and
332// * on a host backend as a RangePolicy over the (y, z) ROWS of the box, with the x loop inside
333// (a "pencil"), serially below kHostSerialCellCutoff cells.
334// The host MDRange it replaces (even with the {nx,2,2} row tiles this helper used to pass) cost
335// 2.4x a flat x loop in the MDRange tile machinery. The rows are statically partitioned over the
336// threads, identically for every kernel of the same box, so a thread keeps touching the same rows.
337// Elementwise kernels are order-independent, so every launch form is byte-identical.
338//
339// ccFor3 marks the x loop `omp simd`. CONTRACT (§4.5 item 4): an iteration writes only its own
340// cell(s) and reads no cell that another iteration of the same row writes (red-black colour passes
341// qualify: same-colour cells are independent). A body that breaks it -- a ghost copy whose source
342// and destination rows overlap -- uses ccForRows3, the same launch without the simd mark. With
343// -ffp-contract=off (the host flags, A1) vectorizing a non-reduction loop is bit-identical to the
344// scalar code.
345#if defined(_OPENMP)
346#define PECLET_FLOW_OMP_SIMD _Pragma("omp simd")
347#else
348#define PECLET_FLOW_OMP_SIMD
349#endif
350namespace ccdetail {
351template <bool Simd, class F>
352inline void ccRows3(const char* name, C3 lo, C3 hi, F f) {
353 CCExec space;
354 using MD = MDRange3<CCExec>;
355 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
356 const int ny = hi.y - lo.y, nz = hi.z - lo.z;
357 if (ny <= 0 || nz <= 0 || hi.x <= lo.x)
358 return;
359 const long rows = (long)ny * nz;
360 auto row = [=](long r) {
361 const int y = lo.y + (int)(r % ny), z = lo.z + (int)(r / ny);
362 if constexpr (Simd) {
364 for (int x = lo.x; x < hi.x; ++x)
365 f(x, y, z);
366 } else {
367 for (int x = lo.x; x < hi.x; ++x)
368 f(x, y, z);
369 }
370 };
371 if (hostRunSerial(rows * (hi.x - lo.x))) {
372 const HostSerialRegion serialRegion(name, "@serial"); // WO-T
373 for (long r = 0; r < rows; ++r) // too small to be worth a fork/join (bit-identical)
374 row(r);
375 return;
376 }
377 Kokkos::parallel_for(name, Kokkos::RangePolicy<CCExec>(space, 0, rows), row);
378 } else {
379 Kokkos::parallel_for(name, MD(space, {lo.x, lo.y, lo.z}, {hi.x, hi.y, hi.z}), f);
380 }
381}
382} // namespace ccdetail
383
384template <class F>
385inline void ccFor3(const char* name, C3 lo, C3 hi, F f) {
386 ccdetail::ccRows3<true>(name, lo, hi, f);
387}
388// ccFor3 without the `omp simd` mark on the host x loop (see the contract above).
389template <class F>
390inline void ccForRows3(const char* name, C3 lo, C3 hi, F f) {
391 ccdetail::ccRows3<false>(name, lo, hi, f);
392}
393
394// H-7 (doc/vof_step_performance_design.md §14.3): the HOST launch of a distributed box pass, the
395// box [rlo, rhi) minus the skip box [slo, shi). `run(ly, lz, x0, x1)` processes the cells
396// x0 <= lx < x1 of row (ly, lz). The skip box is clipped to the box (the per-cell test it replaces
397// selects exactly the clipped cells). With an empty skip box (the interior launch) every row of the
398// box is one run [rlo.x, rhi.x), with no skip test. Otherwise only the shell is visited: the two
399// z-slabs (every row), then the two y-slabs inside them, then the two x-runs of the remaining rows
400// -- the same cells as the per-cell skip test over every row of the box. One launch either way,
401// serial below kHostSerialCellCutoff cells VISITED, the shell counting each of its x-runs as
402// kShellRunCells more (WO-A: 3840 one-cell runs made a 7936-cell shell cost a parallel launch's
403// worth, serially). A body that ccFor3's contract admits (cells
404// independent within the launch: elementwise, or one colour of a red-black pass) gives the same
405// bits in any visiting order. Host backends only; on a device backend this is a no-op (the callers
406// keep their MDRange device branch).
407template <class Run>
408inline void ccBoxShellRuns(const char* name, C3 rlo, C3 rhi, C3 slo, C3 shi, Run run) {
409 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
410 if (rhi.x <= rlo.x || rhi.y <= rlo.y || rhi.z <= rlo.z)
411 return;
412 auto clip = [](int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); };
413 const C3 sl{clip(slo.x, rlo.x, rhi.x), clip(slo.y, rlo.y, rhi.y), clip(slo.z, rlo.z, rhi.z)};
414 const C3 sh{clip(shi.x, rlo.x, rhi.x), clip(shi.y, rlo.y, rhi.y), clip(shi.z, rlo.z, rhi.z)};
415 const bool skip = sl.x < sh.x && sl.y < sh.y && sl.z < sh.z;
416 const int nx = rhi.x - rlo.x, ny = rhi.y - rlo.y, nz = rhi.z - rlo.z;
417 CCExec space;
418 if (!skip) { // the interior launch: whole rows, no skip test
419 const long rows = (long)ny * nz;
420 auto row = [=](long t) { run(rlo.y + (int)(t % ny), rlo.z + (int)(t / ny), rlo.x, rhi.x); };
421 if (hostRunSerial(rows * nx)) {
422 const HostSerialRegion serialRegion(name, "@serial"); // WO-T
423 for (long t = 0; t < rows; ++t)
424 row(t);
425 return;
426 }
427 Kokkos::parallel_for(name, Kokkos::RangePolicy<CCExec>(space, 0, rows), row);
428 return;
429 }
430 const int nzLo = sl.z - rlo.z, nzHi = rhi.z - sh.z, nzS = sh.z - sl.z;
431 const int nyLo = sl.y - rlo.y, nyHi = rhi.y - sh.y, nyS = sh.y - sl.y;
432 const int nxLo = sl.x - rlo.x, nxHi = rhi.x - sh.x;
433 const long nA = (long)(nzLo + nzHi) * ny; // z-slab rows (whole)
434 const long nB = (long)nzS * (nyLo + nyHi); // y-slab rows (whole)
435 const long nC = (nxLo + nxHi > 0) ? (long)nzS * nyS : 0; // rows with two x-runs
436 const long tasks = nA + nB + nC;
437 const long cells = (nA + nB) * nx + nC * (nxLo + nxHi);
438 const long runs = nC * ((nxLo > 0) + (nxHi > 0)); // the shell's x-runs (WO-A)
439 if (tasks == 0)
440 return;
441 auto task = [=](long t) {
442 if (t < nA) {
443 const int zz = (int)(t / ny);
444 run(rlo.y + (int)(t % ny), zz < nzLo ? rlo.z + zz : sh.z + (zz - nzLo), rlo.x, rhi.x);
445 return;
446 }
447 t -= nA;
448 if (t < nB) {
449 const int nyb = nyLo + nyHi, yy = (int)(t % nyb);
450 run(yy < nyLo ? rlo.y + yy : sh.y + (yy - nyLo), sl.z + (int)(t / nyb), rlo.x, rhi.x);
451 return;
452 }
453 t -= nB;
454 const int ly = sl.y + (int)(t % nyS), lz = sl.z + (int)(t / nyS);
455 if (nxLo > 0)
456 run(ly, lz, rlo.x, sl.x);
457 if (nxHi > 0)
458 run(ly, lz, sh.x, rhi.x);
459 };
460 if (hostRunSerial(cells + kShellRunCells * runs)) {
461 const HostSerialRegion serialRegion(name, "@serial"); // WO-T
462 for (long t = 0; t < tasks; ++t)
463 task(t);
464 return;
465 }
466 Kokkos::parallel_for(name, Kokkos::RangePolicy<CCExec>(space, 0, tasks), task);
467 } else {
468 (void)name, (void)rlo, (void)rhi, (void)slo, (void)shi, (void)run;
469 }
470}
471
472// K3 (doc/vof_distributed_host_comm_design.md §5.2): the stencil halo's rank-local periodic axes.
473// On an axis whose bit is set in the wrap mask `m` (1 = x, 2 = y, 4 = z) the level's block is the
474// whole global axis, so the neighbour of a boundary cell across the block face is the inner cell at
475// the opposite face -- the very cell the full (periodic) exchange copies into that ghost (A3's
476// ccWrapNbrs, per axis): for inner coordinate k in [g, g + n_a), minus = (k == g) ? i + (n_a-1) s_a
477// : i - s_a, plus = (k == g + n_a - 1) ? i - (n_a-1) s_a : i + s_a. On every other axis the plain
478// i +- s_a (the ghost). n = the level's inner dims (even on a masked axis: a red-black pass then
479// reads only the other colour across the wrap), g = its ghost width. m = 0: i +- s everywhere.
480struct CcNbrs {
481 long xp, xm, yp, ym, zp, zm;
482};
483KOKKOS_INLINE_FUNCTION CcNbrs ccMaskNbrs(int lx, int ly, int lz, C3 n, int g, long i, long sy,
484 long sz, int m) {
485 CcNbrs w;
486 w.xm = ((m & 1) && lx == g) ? i + (long)(n.x - 1) : i - 1;
487 w.xp = ((m & 1) && lx == g + n.x - 1) ? i - (long)(n.x - 1) : i + 1;
488 w.ym = ((m & 2) && ly == g) ? i + (long)(n.y - 1) * sy : i - sy;
489 w.yp = ((m & 2) && ly == g + n.y - 1) ? i - (long)(n.y - 1) * sy : i + sy;
490 w.zm = ((m & 4) && lz == g) ? i + (long)(n.z - 1) * sz : i - sz;
491 w.zp = ((m & 4) && lz == g + n.z - 1) ? i - (long)(n.z - 1) * sz : i + sz;
492 return w;
493}
494// The host row of a masked box pass (ccBoxShellRuns' `run` body): the cells lx = lx0, lx0 + step,
495// ... < x1 of row (ly, lz). The y/z neighbour offsets once per row; with x masked, the row's
496// x-face cells peeled (ccMaskNbrs), the rest at i +- 1 (ccWrapRowPeeled's structure). Same cells,
497// same body, same operands as ccMaskNbrs per cell. `cell(i, xp, xm, yp, ym, zp, zm)`.
498template <class Cell>
499KOKKOS_INLINE_FUNCTION void ccMaskRow(int ly, int lz, int lx0, int x1, int step, C3 e, C3 n, int g,
500 int m, const Cell& cell) {
501 if (lx0 >= x1)
502 return;
503 const long sy = e.x, sz = (long)e.x * e.y;
504 const long base = (long)ly * sy + (long)lz * sz;
505 const long dym = ((m & 2) && ly == g) ? (long)(n.y - 1) * sy : -sy;
506 const long dyp = ((m & 2) && ly == g + n.y - 1) ? -(long)(n.y - 1) * sy : sy;
507 const long dzm = ((m & 4) && lz == g) ? (long)(n.z - 1) * sz : -sz;
508 const long dzp = ((m & 4) && lz == g + n.z - 1) ? -(long)(n.z - 1) * sz : sz;
509 auto scalar = [&](int lx) {
510 const long i = (long)lx + base;
511 const CcNbrs w = ccMaskNbrs(lx, ly, lz, n, g, i, sy, sz, m);
512 cell(i, w.xp, w.xm, w.yp, w.ym, w.zp, w.zm);
513 };
514 const int lxLast = g + n.x - 1;
515 int lo = lx0, hi = lx0 + ((x1 - 1 - lx0) / step) * step; // inclusive
516 if ((m & 1) && lo == g) {
517 scalar(lo);
518 lo += step;
519 }
520 const bool peelLast = (m & 1) && hi == lxLast && hi >= lo;
521 if (peelLast)
522 hi -= step;
523 PECLET_FLOW_OMP_SIMD // independent cells (ccFor3's contract)
524 for (int lx = lo; lx <= hi; lx += step) {
525 const long i = (long)lx + base;
526 cell(i, i + 1, i - 1, i + dyp, i + dym, i + dzp, i + dzm);
527 }
528 if (peelLast)
529 scalar(lxLast);
530}
531
532// Reduction sibling of ccFor3. On a host backend it is the PENCIL reduction of B2
533// (doc/vof_step_performance_design.md §5.8, a recorded order): a RangePolicy over the (y, z) rows
534// of the box -- the same static row partition as ccFor3 -- each thread reducing its rows in (y, z)
535// order with x ascending inside a row, scalar (no `omp simd` reduction), and the per-thread
536// partials combined by Kokkos in thread order. Sum results therefore depend on the thread count
537// only, as before; max/min reductions are order-free and unchanged. Unlike ccFor3 a reduction is
538// never cut over to a serial loop below kHostSerialCellCutoff (that would make the summation
539// order a function of the block size). The device branch is the MDRange reduction, unchanged.
540namespace ccdetail {
541template <class R, bool = Kokkos::is_reducer_v<std::decay_t<R>>>
543 using type = typename std::decay_t<R>::value_type;
544};
545template <class R>
546struct ReduceValue<R, false> { // a scalar result, or a View holding it
547 using D = std::decay_t<R>;
548 template <class T, bool = Kokkos::is_view_v<T>>
549 struct Pick {
550 using type = T;
551 };
552 template <class T>
553 struct Pick<T, true> {
554 using type = typename T::non_const_value_type;
555 };
556 using type = typename Pick<D>::type;
557};
558} // namespace ccdetail
559template <class F, class... R>
560inline void ccReduce3(const char* name, C3 lo, C3 hi, F f, R&&... reducers) {
561 CCExec space;
562 using MD = MDRange3<CCExec>;
563 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
564 const int ny = hi.y - lo.y > 0 ? hi.y - lo.y : 0, nz = hi.z - lo.z > 0 ? hi.z - lo.z : 0;
565 const long rows = hi.x > lo.x ? (long)ny * nz : 0;
566 Kokkos::parallel_reduce(
567 name, Kokkos::RangePolicy<CCExec>(space, 0, rows),
568 [=](long r, typename ccdetail::ReduceValue<R>::type&... acc) {
569 const int y = lo.y + (int)(r % ny), z = lo.z + (int)(r / ny);
570 for (int x = lo.x; x < hi.x; ++x)
571 f(x, y, z, acc...);
572 },
573 std::forward<R>(reducers)...);
574 } else {
575 Kokkos::parallel_reduce(name, MD(space, {lo.x, lo.y, lo.z}, {hi.x, hi.y, hi.z}), f,
576 std::forward<R>(reducers)...);
577 }
578}
579
580// The 4-LANE pencil order (doc/vof_projection_cost_design.md §6 amendment 1, WO-C0, a recorded
581// order) for the Krylov SUM reductions of CutcellMG and the kernels fused with them. Host: the
582// same row partition as ccReduce3; within a row, lane l = (x - lo.x) & 3 accumulates its cells in
583// ascending x from 0, the row value is (s0 + s1) + (s2 + s3), the thread accumulator adds the row
584// values in row order and Kokkos combines the thread partials in thread order (as B2). A cell the
585// functor masks out adds nothing to its lane (no +0.0). Four independent add chains instead of
586// one: the reduction is no longer bound by the loop-carried scalar add. Sums only (a value, a
587// View, or Kokkos::Sum); max/min reductions keep ccReduce3. The device branch IS ccReduce3's
588// (same policy, same functor: device bits unchanged, §2 device caveat).
589namespace ccdetail {
590template <class R, bool = Kokkos::is_reducer_v<R>>
591struct IsLaneSum : std::true_type {}; // a scalar result, or a View holding it
592template <class R>
593struct IsLaneSum<R, true> : std::false_type {};
594template <class T, class S>
595struct IsLaneSum<Kokkos::Sum<T, S>, true> : std::true_type {};
596template <class T>
597struct Lanes4 {
598 T v[4] = {T(0), T(0), T(0), T(0)};
599 T row() const { return (v[0] + v[1]) + (v[2] + v[3]); }
600};
601template <class F, class... T>
602inline void laneRow(const F& f, int x0, int x1, int y, int z, T&... acc) {
603 std::tuple<Lanes4<T>...> lanes;
604 std::apply(
605 [&](Lanes4<T>&... l) {
606 int x = x0;
607 for (; x + 3 < x1; x += 4) {
608 f(x, y, z, l.v[0]...);
609 f(x + 1, y, z, l.v[1]...);
610 f(x + 2, y, z, l.v[2]...);
611 f(x + 3, y, z, l.v[3]...);
612 }
613 for (int k = 0; x < x1; ++x, ++k)
614 f(x, y, z, l.v[k]...);
615 ((acc += l.row()), ...);
616 },
617 lanes);
618}
619} // namespace ccdetail
620template <class F, class... R>
621inline void ccReduce3Lanes(const char* name, C3 lo, C3 hi, F f, R&&... reducers) {
622 static_assert((ccdetail::IsLaneSum<std::decay_t<R>>::value && ...),
623 "ccReduce3Lanes: sum reductions only (max/min keep ccReduce3)");
624 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
625 CCExec space;
626 const int ny = hi.y - lo.y > 0 ? hi.y - lo.y : 0, nz = hi.z - lo.z > 0 ? hi.z - lo.z : 0;
627 const long rows = hi.x > lo.x ? (long)ny * nz : 0;
628 Kokkos::parallel_reduce(
629 name, Kokkos::RangePolicy<CCExec>(space, 0, rows),
630 [=](long r, typename ccdetail::ReduceValue<R>::type&... acc) {
631 const int y = lo.y + (int)(r % ny), z = lo.z + (int)(r / ny);
632 ccdetail::laneRow(f, lo.x, hi.x, y, z, acc...);
633 },
634 std::forward<R>(reducers)...);
635 } else {
636 ccReduce3(name, lo, hi, f, std::forward<R>(reducers)...);
637 }
638}
639
640} // namespace peclet::flow
641
642#endif // PECLET_FLOW_MAC_CUTCELL_HPP
HostSerialRegion & operator=(const HostSerialRegion &)=delete
HostSerialRegion(const char *launch, const char *suffix)
HostSerialRegion(const HostSerialRegion &)=delete
HostSerialRegion(const char *region)
#define PECLET_FLOW_OMP_SIMD
void ccRows3(const char *name, C3 lo, C3 hi, F f)
void laneRow(const F &f, int x0, int x1, int y, int z, T &... acc)
Kokkos::DefaultExecutionSpace CCExec
void ccForRows3(const char *name, C3 lo, C3 hi, F f)
CcNbrs ccMaskNbrs(int lx, int ly, int lz, C3 n, int g, long i, long sy, long sz, int m)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 3, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange3
3-D range, x (the first index) fastest (both the tile order and the order within a tile).
Definition policy.hpp:36
Kokkos::View< const double *, CCMem > CCConst
double ccFaceOpen(CCConst sdf, C3 ext, double fx, double fy, double fz, int type, double dx, double dy, double dz)
void ccReduce3(const char *name, C3 lo, C3 hi, F f, R &&... reducers)
constexpr long kHostSerialCellCutoff
double ccFaceOpenMS(CCConst sdf, C3 ext, double fx, double fy, double fz, int type)
double ccFractionCore(double sd, double sxp, double sxm, double syp, double sym, double szp, double szm, int type, double dx, double dy, double dz)
double ccTriFrac(double a, double b, double c)
void ccBoxShellRuns(const char *name, C3 rlo, C3 rhi, C3 slo, C3 shi, Run run)
void buildOpennessHighFace(CCField oa, CCConst sdf, C3 ext, int g, int a, double dx, double dy, double dz, int order=1)
constexpr long kShellRunCells
CCExec::memory_space CCMem
Kokkos::View< double *, CCMem > CCField
void ccFor3(const char *name, C3 lo, C3 hi, F f)
void ccMaskRow(int ly, int lz, int lx0, int x1, int step, C3 e, C3 n, int g, int m, const Cell &cell)
void ccReduce3Lanes(const char *name, C3 lo, C3 hi, F f, R &&... reducers)
double ccSampleExt(CCConst sdf, C3 ext, double x, double y, double z)
void buildOpenness(CCField ox, CCField oy, CCField oz, CCConst sdf, C3 ext, double dx, double dy, double dz, int order=1)
bool hostRunSerial(long cells)
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
flow — the multidimensional iteration policies: iteration order follows storage.
typename std::decay_t< R >::value_type type
static double value(int gx, int gy, int gz)
static constexpr double F
static int run(int bc)
static constexpr double R