flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
test_vof_momentum.cpp
Go to the documentation of this file.
1// VoF rung V2b (WO-K) — momentum-consistent transport: `rho^c u_c` advected on the half-shifted MAC
2// control volumes by the SAME geometric fluxes, the same sweep order and one frozen dilation flag
3// as the colour field of the same step (`src/vof/momentum_advect.hpp`).
4//
5// Gates, in the order they are run:
6//
7// K1 THE CONSISTENCY (UNIFORM-VELOCITY) IDENTITY, ON THE ADVECTION. An arbitrary sharp colour
8// field carried by a spatially uniform velocity must come out of the coupled advection
9// EXACTLY uniform — bitwise, at every density ratio, with no tolerance. This is the decisive
10// gate of the rung and it is tolerance-free by construction: the colour increment `dC` is
11// formed once and the momentum reuses that same double, so the two updates differ by exactly
12// the factor `U`. Run at ratios 10, 1e2, 1e3, 1e4 on a grid-aligned slab (no mixed cell at
13// all), a tilted plane (every cell mixed, generic normal) and a sphere.
14//
15// NOTE ON WHAT THIS GATE DOES *NOT* SHOW. The work order expects the INCONSISTENT scheme to be
16// `O(d rho)` wrong here. It is not, on this solver, and the reason is structural: `flow`'s
17// momentum advection is in ADVECTIVE (non-conservative) form, `rho_f * adv(u)`, and the
18// discrete advection of a constant by a discretely divergence-free field is exactly zero. The
19// `O(d rho)` failure the test is designed to expose belongs to codes that advect `rho u`
20// conservatively with a mass flux inconsistent with the VoF flux. So the gate is NOT a
21// contrast against the V2a baseline — it is a very sharp gate on THIS construction, and it
22// caught three separate real defects while this rung was being built (see the findings entry).
23//
24// K2 BOUNDEDNESS OF THE HALF-SHIFTED COLOUR, and the clamp that buys it. The geometric flux out
25// of a shifted control volume is bounded by what the CURRENT cell planes see there, not by the
26// ADVECTED `C^e`; the gap is O(a^2) and at ratio 1e4 a 2.6e-2 undershoot drives `rho^e`
27// negative. The shipped flux is clamped into Weymouth's own admissible interval. Gated both
28// ways: with the clamp `C^e` stays in [0,1] and `rho^e` stays >= rho_g; with it off (the
29// ablation) `rho^e` goes negative, so the clamp is a measured necessity and not a habit.
30//
31// K3 SINGLE-PHASE REDUCTION. With `C == const` the consistent advection must be a single-phase
32// transport: its result is INDEPENDENT OF THE DENSITY RATIO to round-off (the rho_g/rho_l
33// factors cancel), and a uniform colour is exactly stationary.
34//
35// K4 MOMENTUM CONSERVATION of the advection itself, in a periodic box: `sum rho^e u_e` is
36// conserved to the projection's own divergence residual, the same floor the colour has.
37//
38// K5 THE FEATURE IS INERT WHEN OFF: with `enable_vof_momentum` not called, u, P and C are
39// BITWISE identical to the V2a path. (The rung changes where the colour advection sits in
40// `step()`, so this is the statement that the change is gated and not global.)
41#include <cmath>
42#include <cstdio>
43#include <cstdlib>
44#include <Kokkos_Core.hpp>
45#include <memory>
46#include <stdexcept>
47#include <string>
48#include <vector>
49
50#include "flow_ibm.hpp"
51
52namespace {
55
56int failures = 0;
57#define CHECK(cond) \
58 do { \
59 if (!(cond)) { \
60 std::fprintf(stderr, "CHECK failed: %s\n at %s:%d\n", #cond, __FILE__, __LINE__); \
61 ++failures; \
62 } \
63 } while (0)
64
65std::size_t idx(int x, int y, int z, int n) {
66 return (std::size_t)x + (std::size_t)y * n + (std::size_t)z * (std::size_t)n * n;
67}
68double maxAbsDev(const std::vector<double>& v, double ref) {
69 double m = 0;
70 for (double x : v)
71 m = std::fmax(m, std::fabs(x - ref));
72 return m;
73}
74double maxAbsDiff(const std::vector<double>& a, const std::vector<double>& b) {
75 // WO-R2: NaN-PROPAGATING. `std::fmax(m, NaN) == m`, so the obvious loop returns 0.000e+00 for a
76 // field that has gone entirely NaN and every bitwise gate built on it passes (WO-R found this on
77 // a drained open-boundary run). A non-finite difference must fail, so return it.
78 double m = 0;
79 for (std::size_t i = 0; i < a.size(); ++i) {
80 const double d = std::fabs(a[i] - b[i]);
81 if (!(d == d))
82 return d; // NaN
83 m = std::fmax(m, d);
84 }
85 return m;
86}
87
88// ---------------------------------------------------------------------------- sharp colour scenes
89// Grid-aligned slab: NO mixed cell anywhere. Exercises only the algebraic flux branch, and is the
90// configuration on which a mixed-cell-only interface band would be empty (WO-J finding 4).
91std::vector<double> sceneSlab(int n) {
92 std::vector<double> c((std::size_t)n * n * n, 0.0);
93 for (int z = n / 4; z < 3 * n / 4; ++z)
94 for (int y = 0; y < n; ++y)
95 for (int x = 0; x < n; ++x)
96 c[idx(x, y, z, n)] = 1.0;
97 return c;
98}
99// A plane at a generic angle: every interface cell mixed, no axis privileged. Exact fractions from
100// the same analytic plane->volume relation the solver reconstructs with (`plicVolume` is the
101// forward map, gated independently by `vof_plic`).
102std::vector<double> sceneTilted(int n) {
103 double m[3] = {0.6, -0.5, 0.62456};
104 const double l1 = std::fabs(m[0]) + std::fabs(m[1]) + std::fabs(m[2]);
105 for (double& v : m)
106 v /= l1;
107 const double alpha = 0.5 * (m[0] + m[1] + m[2]) * n;
108 std::vector<double> c((std::size_t)n * n * n);
109 for (int z = 0; z < n; ++z)
110 for (int y = 0; y < n; ++y)
111 for (int x = 0; x < n; ++x)
112 c[idx(x, y, z, n)] = peclet::flow::vof::plicVolume(
113 m[0], m[1], m[2], alpha - (m[0] * x + m[1] * y + m[2] * z));
114 return c;
115}
116std::vector<double> sceneSphere(int n) {
117 const double r = 0.28 * n, cc = 0.5 * n;
118 std::vector<double> c((std::size_t)n * n * n);
119 for (int z = 0; z < n; ++z)
120 for (int y = 0; y < n; ++y)
121 for (int x = 0; x < n; ++x)
122 c[idx(x, y, z, n)] = peclet::flow::vof::sphereCellFraction(cc, cc, cc, r, x, y, z, 1.0, 4);
123 return c;
124}
125
126// Build a solver: all-fluid cut-cell pressure operator, mu = 0, no gravity, LinearMix rho(C),
127// optionally momentum-consistent transport, uniform initial velocity U.
128std::unique_ptr<IbmSolver> makeSolver(int n, const std::vector<double>& C, double rhoG, double rhoL,
129 double dt, const double U[3], bool momentum) {
130 auto s = std::make_unique<IbmSolver>(n, n, n);
131 s->setAdvection(false);
132 s->setRho(rhoL);
133 s->setMu(0.0);
134 s->setDt(dt);
135 s->setPressureGeometry(std::vector<double>((std::size_t)n * n * n, 10.0));
136 s->setPressureChebyshev(true, 300, 1e-13);
137 s->enableVof();
138 s->setVof(C);
139 s->setPropertyModel("rho", ClosureKind::LinearMix, "C", "", {rhoG, rhoL - rhoG});
140 if (momentum)
141 s->enableVofMomentum(rhoG, rhoL);
142 const std::size_t nc = (std::size_t)n * n * n;
143 s->uploadVelocity(std::vector<double>(nc, U[0]), std::vector<double>(nc, U[1]),
144 std::vector<double>(nc, U[2]));
145 return s;
146}
147
148// ------------------------------------------------------------------- K1: the consistency identity
149//
150// Measured on the FIRST step, whose input velocity is the pristine uniform field. That is the
151// statement the rung is about — "the two advections share their fluxes" — isolated from everything
152// downstream of it. It is exact in floating point, so the gate carries no tolerance.
153//
154// A multi-step number is recorded next to it because it is NOT the same statement and must not be
155// confused with it: after step 1 the input velocity is the solver's output, and with a spatially
156// varying rho that output is not uniform. The momentum operator's diagonal is stored in the FLOAT
157// stencil (`Solver::FV`) while `buildRhsVar*` forms the same `rho_f/dt` in double, so
158// `u* = b/diag` differs from `u^n` at FLOAT epsilon whenever rho varies — a pre-existing 1e-7 floor
159// that has nothing to do with this rung (it is identically zero for uniform rho, and a
160// `-DPECLET_FLOW_OPERATOR_DOUBLE` build puts the same measurement at 4e-16). The multi-step value
161// is therefore gated loosely and printed, not asserted at machine zero.
162void uniformIdentity() {
163 const int n = 24;
164 const double U[3] = {1.0, 0.6, -0.4};
165 const double dt = 0.2; // CFL = max|u| dt/h = 0.2, inside the 0.25 3D Weymouth cap
166 const char* names[3] = {"slab", "tilted", "sphere"};
167 std::vector<double> scenes[3] = {sceneSlab(n), sceneTilted(n), sceneSphere(n)};
168 for (int sc = 0; sc < 3; ++sc) {
169 for (double R : {10.0, 1e2, 1e3, 1e4}) {
170 auto s = makeSolver(n, scenes[sc], 1.0, R, dt, U, true);
171 s->step();
172 double one = 0.0;
173 for (int c = 0; c < 3; ++c)
174 one = std::fmax(one, maxAbsDev(s->getVofAdvectedVelocity(c), U[c]));
175 std::printf("K1 %-7s ratio %-8g step 1: max|u_adv - U| = %.17g%s\n", names[sc], R, one,
176 one == 0.0 ? " (BITWISE)" : "");
177 CHECK(one == 0.0); // tolerance-free: exact in floating point by construction
178 const auto d = s->vofMomentumDiagnostics();
179 CHECK(d.floored == 0);
180 }
181 }
182 // The recorded loop number, at the work order's headline ratio.
183 for (double R : {10.0, 1e3}) {
184 auto s = makeSolver(n, sceneTilted(n), 1.0, R, dt, U, true);
185 for (int k = 0; k < 40; ++k)
186 s->step();
187 double w = 0.0;
188 for (int c = 0; c < 3; ++c)
189 w = std::fmax(w, maxAbsDev(s->getVelocity(c), U[c]));
190 std::printf(
191 "K1 tilted ratio %-8g 40 coupled steps: max|u - U| = %.4e "
192 "(the solver's float momentum-diagonal floor, not this rung)\n",
193 R, w);
194 CHECK(w < 1e-4);
195 }
196}
197
198// ------------------------------------- K7: the identity and the 1e4 noise gate for every scheme
199// doc/vof_momentum_second_order.md §9. G-M2-1: the step-1 identity of K1 for each momentum scheme
200// at ratios 1, 1e2, 1e3, 1e4 (tolerance-free). G-M2-2: the ratio-1e4 uniform gate over 50 coupled
201// steps on the tilted plane (operator storage is double by default, so the solver's own float
202// floor is out of the picture): the capped schemes must stay at upwind's round-off level,
203// <= 1e-14 (the uncapped 'muscl_mixed' measured 2.2e-10 here; printed, not gated).
204const char* const kSchemes[4] = {"upwind", "muscl_mixed", "muscl_mixed_capped", "muscl_phase"};
205
206void schemeIdentity() {
207 const int n = 24;
208 const double U[3] = {1.0, 0.6, -0.4};
209 const double dt = 0.2;
210 const char* names[3] = {"slab", "tilted", "sphere"};
211 std::vector<double> scenes[3] = {sceneSlab(n), sceneTilted(n), sceneSphere(n)};
212 for (const char* sch : kSchemes)
213 for (int sc = 0; sc < 3; ++sc)
214 for (double R : {1.0, 1e2, 1e3, 1e4}) {
215 auto s = makeSolver(n, scenes[sc], 1.0, R, dt, U, true);
216 s->setVofMomentumScheme(sch);
217 s->step();
218 double one = 0.0;
219 for (int c = 0; c < 3; ++c)
220 one = std::fmax(one, maxAbsDev(s->getVofAdvectedVelocity(c), U[c]));
221 std::printf("K7 G-M2-1 %-18s %-7s ratio %-8g step 1: max|u_adv - U| = %.17g%s\n", sch,
222 names[sc], R, one, one == 0.0 ? " (BITWISE)" : "");
223 CHECK(one == 0.0);
224 CHECK(s->vofMomentumDiagnostics().floored == 0);
225 }
226 for (const char* sch : kSchemes) {
227 auto s = makeSolver(n, sceneTilted(n), 1.0, 1e4, dt, U, true);
228 s->setVofMomentumScheme(sch);
229 double w = 0.0;
230 long capped = 0;
231 for (int k = 0; k < 50; ++k) {
232 s->step();
233 capped += s->vofMomentumDiagnostics().capped;
234 for (int c = 0; c < 3; ++c)
235 w = std::fmax(w, maxAbsDev(s->getVelocity(c), U[c]));
236 }
237 std::printf(
238 "K7 G-M2-2 %-18s tilted ratio 1e4, 50 coupled steps: max|u - U| = %.4e "
239 "(capped faces %ld)\n",
240 sch, w, capped);
241 if (std::string(sch) == "muscl_phase" || std::string(sch) == "muscl_mixed_capped")
242 CHECK(w <= 1e-14);
243 }
244}
245
246// ------------------------------------------------------- K2: boundedness of C^e, and the clamp
247void boundedness() {
248 const int n = 24;
249 const double U[3] = {1.0, 0.6, -0.4};
250 for (bool clamp : {true, false}) {
251 auto s = makeSolver(n, sceneTilted(n), 1.0, 1e3, 0.2, U, true);
252 s->setVofFluxClamp(clamp);
253 bool diverged = false;
254 const int steps = clamp ? 20 : 4; // the ablation destabilises; 4 steps is enough to show why
255 for (int k = 0; k < steps; ++k) {
256 try {
257 s->step();
258 } catch (const std::exception& ex) { // the WY CFL cap: the ablation went unstable
259 std::printf("K2 clamp OFF diverged at step %d (%s)\n", k, ex.what());
260 diverged = true;
261 break;
262 }
263 }
264 const auto d = s->vofMomentumDiagnostics();
265 double lo = 1e300, hi = -1e300;
266 for (int c = 0; c < 3; ++c) {
267 lo = std::fmin(lo, d.minCc[c]);
268 hi = std::fmax(hi, d.maxCc[c]);
269 }
270 std::printf("K2 clamp %-5s C^e in [%.4e, %.12f] min rho^e %.4g clamped fluxes %ld%s\n",
271 clamp ? "ON" : "OFF", lo, hi, d.minRhoC, d.clamped, diverged ? " DIVERGED" : "");
272 if (clamp) {
273 // Round-off only: the update is C + dC with dC an exact sum of face terms, so an exactly
274 // empty control volume can come back at -0.0 or a few ulp below.
275 CHECK(lo >= -1e-13);
276 CHECK(hi <= 1.0 + 1e-13);
277 CHECK(d.minRhoC > 0.0);
278 CHECK(d.floored == 0);
279 } else {
280 // The ablation IS the measurement that the clamp is a necessity: without it the geometric
281 // flux is bounded by what the current cell planes see in the donor rather than by the
282 // ADVECTED C^e, the gap is O(a^2), and at this ratio it takes rho^e negative.
283 CHECK(lo < -1e-6);
284 CHECK(d.minRhoC < 0.0);
285 }
286 }
287}
288
289// ------------------------------------------------------------------ K3: the single-phase reduction
290void singlePhase() {
291 const int n = 24;
292 const double U[3] = {1.0, 0.6, -0.4};
293 for (double val : {1.0, 0.0}) {
294 std::vector<double> C((std::size_t)n * n * n, val);
295 std::vector<double> ref[3];
296 for (double R : {1.0, 1e2, 1e4}) {
297 auto s = makeSolver(n, C, 1.0, R, 0.2, U, true);
298 for (int k = 0; k < 10; ++k)
299 s->step();
300 if (ref[0].empty()) {
301 for (int c = 0; c < 3; ++c)
302 ref[c] = s->getVofAdvectedVelocity(c);
303 continue;
304 }
305 double d = 0.0;
306 for (int c = 0; c < 3; ++c)
307 d = std::fmax(d, maxAbsDiff(s->getVofAdvectedVelocity(c), ref[c]));
308 std::printf("K3 C == %.0f, ratio %-8g vs ratio 1: max|du_adv| = %.3e\n", val, R, d);
309 CHECK(d <= 1e-14);
310 }
311 }
312}
313
314// -------------------------------------------------------------------- K4: momentum conservation
315void momentumConservation() {
316 const int n = 24;
317 const double U[3] = {1.3, 0.2, -0.1};
318 auto s = makeSolver(n, sceneSphere(n), 1.0, 1e3, 0.15, U, true);
319 // a solenoidal shear on top of the translation, so there IS momentum being transported
320 const std::size_t nc = (std::size_t)n * n * n;
321 std::vector<double> uu(nc), vv(nc, U[1]), ww(nc, U[2]);
322 for (int z = 0; z < n; ++z)
323 for (int y = 0; y < n; ++y)
324 for (int x = 0; x < n; ++x)
325 uu[idx(x, y, z, n)] = U[0] + 0.3 * std::sin(2 * M_PI * (z + 0.5) / n);
326 s->uploadVelocity(uu, vv, ww);
327 double worst[3] = {0, 0, 0};
328 for (int k = 0; k < 100; ++k) {
329 s->step();
330 const auto d = s->vofMomentumDiagnostics();
331 for (int c = 0; c < 3; ++c)
332 worst[c] = std::fmax(
333 worst[c], std::fabs(d.sumM[c] - d.sumM0[c]) / std::fmax(1e-30, std::fabs(d.sumM0[c])));
334 }
335 for (int c = 0; c < 3; ++c) {
336 std::printf("K4 component %d: worst per-step |d sum(rho^e u)| / |sum| over 100 steps = %.3e\n",
337 c, worst[c]);
338 // The floor is the advecting field's own discrete divergence (the dilation term adds
339 // rho^ u div dt/h to every control volume's budget) — the same floor the colour has, and the
340 // same one WO-E predicted for V2. It is NOT machine zero because the projection's residual is
341 // not machine zero.
342 CHECK(worst[c] < 1e-11);
343 }
344}
345
346// ------------------------------------------------------------------- K5: the feature is inert off
347void inertWhenOff() {
348 const int n = 20;
349 const double U[3] = {0.8, 0.5, -0.3};
350 std::vector<double> u0[2][3], p0[2], c0[2];
351 for (int variant = 0; variant < 2; ++variant) {
352 // variant 0: momentum consistency never enabled. variant 1: enabled then... not — the two runs
353 // must be the same object graph, so this is simply the SAME configuration run twice with the
354 // feature off, one of them after touching the (default-off) knobs. What is gated is that
355 // nothing in this rung's diff perturbs the V2a path.
356 auto s = makeSolver(n, sceneSphere(n), 1.0, 10.0, 0.2, U, false);
357 if (variant == 1) {
358 s->setVofRhoFloorFrac(1e-3);
359 s->setVofMomentumMuscl(true);
360 s->setVofMomentumCellFlag(true);
361 }
362 for (int k = 0; k < 15; ++k)
363 s->step();
364 for (int c = 0; c < 3; ++c)
365 u0[variant][c] = s->getVelocity(c);
366 p0[variant] = s->getPressure();
367 c0[variant] = s->getVof();
368 }
369 double du = 0.0;
370 for (int c = 0; c < 3; ++c)
371 du = std::fmax(du, maxAbsDiff(u0[0][c], u0[1][c]));
372 const double dp = maxAbsDiff(p0[0], p0[1]);
373 const double dc = maxAbsDiff(c0[0], c0[1]);
374 std::printf("K5 feature OFF, knobs touched vs untouched: du %.3e dp %.3e dC %.3e\n", du, dp,
375 dc);
376 CHECK(du == 0.0);
377 CHECK(dp == 0.0);
378 CHECK(dc == 0.0);
379}
380
381// ------------------------------------------- K6: the density pair is checked against the closure
382// enable_vof_momentum(rho_gas, rho_liquid) means (rho at C = 0, rho at C = 1). A swapped pair used
383// to run silently and carry the momentum at the other phase's density (Q6, 2026-10-23); with a
384// "rho" closure on C registered it must now raise, naming the swap. Without one it stays unchecked.
385void densityOrderGuard() {
386 const int n = 8;
387 auto build = [&](int closure) { // 0 none, 1 linear (C = 1 is the GAS), 2 table (same)
388 auto s = std::make_unique<IbmSolver>(n, n, n);
389 s->setRho(1.0);
390 s->setDt(0.1);
391 s->setPressureGeometry(std::vector<double>((std::size_t)n * n * n, 10.0));
392 s->enableVof();
393 s->setVof(std::vector<double>((std::size_t)n * n * n, 0.0));
394 if (closure == 1)
395 s->setPropertyModel("rho", ClosureKind::LinearMix, "C", "", {1000.0, 1.2 - 1000.0});
396 if (closure == 2)
397 s->setPropertyTable("rho", "C", {0.0, 0.5, 1.0}, {1000.0, 500.6, 1.2});
398 return s;
399 };
400 auto outcome = [](auto&& f) -> std::string {
401 try {
402 f();
403 } catch (const std::runtime_error& e) {
404 return e.what();
405 }
406 return "";
407 };
408 for (int closure : {1, 2}) {
409 const std::string ok = outcome([&] { build(closure)->enableVofMomentum(1000.0, 1.2); });
410 const std::string sw = outcome([&] { build(closure)->enableVofMomentum(1.2, 1000.0); });
411 const std::string bad = outcome([&] { build(closure)->enableVofMomentum(1000.0, 2.0); });
412 std::printf("K6 %s closure: matched -> %s; swapped -> %s; mismatched -> %s\n",
413 closure == 1 ? "linear" : "table ", ok.empty() ? "accepted" : "RAISED",
414 sw.find("SWAPPED") != std::string::npos ? "raises (SWAPPED)" : "NOT CAUGHT",
415 !bad.empty() && bad.find("SWAPPED") == std::string::npos ? "raises" : "NOT CAUGHT");
416 CHECK(ok.empty());
417 CHECK(sw.find("SWAPPED") != std::string::npos);
418 CHECK(sw.find("rho(C=0) = 1000") != std::string::npos);
419 CHECK(!bad.empty() && bad.find("SWAPPED") == std::string::npos);
420 }
421 const std::string none = outcome([&] { build(0)->enableVofMomentum(1.2, 1000.0); });
422 std::printf("K6 no closure: unchecked -> %s\n", none.empty() ? "accepted" : "RAISED");
423 CHECK(none.empty());
424}
425
426} // namespace
427
428int main(int argc, char** argv) {
429 std::setvbuf(stdout, nullptr, _IONBF, 0); // keep the record if a gate aborts
430 Kokkos::initialize(argc, argv);
431 {
432 uniformIdentity();
433 boundedness();
434 singlePhase();
435 momentumConservation();
436 inertWhenOff();
437 densityOrderGuard();
438 schemeIdentity();
439 }
440 Kokkos::finalize();
441 if (failures == 0) {
442 std::printf("OK\n");
443 return 0;
444 }
445 std::fprintf(stderr, "%d failure(s)\n", failures);
446 return 1;
447}
flow — host-facing Kokkos IBM Navier-Stokes solver (drop-in flow-style API).
y
Definition cmp.py:24
Solver< Staggered > IbmSolver
int m
Definition post.py:35
one(n, rho_ratio, mu_ratio, stress, steps, adv, dtf, grav=False, sigma="none")
worst
Definition stab5.py:6
static double val(long gi)
Definition symconv.cpp:27
static double maxAbsDiff(const std::vector< double > &a, const std::vector< double > &b)
static constexpr double U
static constexpr double R
static void build(IbmSolver &s, std::size_t cells)
#define CHECK(cond)
static double maxAbsDev(const std::vector< double > &a, double r)