flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_diagnostics.hpp
Go to the documentation of this file.
1
8#ifndef PECLET_FLOW_FLOW_IBM_DIAGNOSTICS_HPP
9#define PECLET_FLOW_FLOW_IBM_DIAGNOSTICS_HPP
10
11namespace peclet::flow {
12
13template <class Grid>
16 if (!hasOutflow_)
17 return ob;
18 CCExec space;
19 const C3 e = e_;
20 const int dims[3] = {e.x, e.y, e.z};
21 const long st[3] = {1, e.x, (long)e.x * e.y};
22 // Phase 2 C2 (doc/anisotropic_metric.md §4.2, trap 10): `energyInflux` mixes three velocity
23 // COMPONENTS, which on anisotropic cells carry three different velocity scales, so it cannot
24 // be converted after the fact -- each component is taken to physical units inside the reduce
25 // (k_a = velToPhys(a)) and the density with it. `maxReverse` is scaled there too, i.e. before
26 // the max over face planes whose axes have different velocity scales. Phase 1 left this
27 // diagnostic in index units and the Python binding converts nothing, so in cell units every
28 // factor here is exactly 1.0 and the reported numbers do not move.
29 const double rho = u_.rhoRef * rho_;
30 for (int a = 0; a < 3; ++a)
31 for (int s = 0; s < 2; ++s) {
32 if (bc_[2 * a + s] != 3 || !touchesGlobalFace(2 * a + s))
33 continue;
34 const int b = (a + 1) % 3, c = (a + 2) % 3;
35 const double ka = u_.velToPhys(a), kb = u_.velToPhys(b), kc = u_.velToPhys(c);
36 const long sa = st[a], sb = st[b], sc = st[c];
37 const int bf = (s == 0) ? G : (dims[a] - G); // the boundary normal-velocity plane
38 const int bic = (s == 0) ? G : (dims[a] - G - 1); // the outlet-adjacent inner cell
39 const double sgn = (s == 0) ? 1.0 : -1.0; // u.n < 0 <-> sgn*u > 0
40 CCConst un = Grid::collocated ? CCConst(a == 0 ? uf_ : a == 1 ? vf_ : wf_) : CCConst(C[a].u);
41 CCConst ub = CCConst(C[b].u), uc = CCConst(C[c].u);
42 using MD = MDRange2<CCExec>;
43 double mx = 0.0, en = 0.0;
44 long nrev = 0;
45 Kokkos::parallel_reduce(
46 "peclet::flow::backflow_census", MD(space, {G, G}, {dims[b] - G, dims[c] - G}),
47 KOKKOS_LAMBDA(int p0, int p1, double& lmx, double& len, long& lnr) {
48 const long base = (long)p0 * sb + (long)p1 * sc;
49 const double back = sgn * un(base + (long)bf * sa);
50 if (back > 0.0) {
51 const long ic = base + (long)bic * sa;
52 const double tb = kb * ub(ic), tc = kc * uc(ic);
53 const double bp = ka * back;
54 lmx = Kokkos::fmax(lmx, bp);
55 len += rho * bp * 0.5 * (bp * bp + tb * tb + tc * tc);
56 lnr += 1;
57 }
58 },
59 Kokkos::Max<double>(mx), Kokkos::Sum<double>(en), Kokkos::Sum<long>(nrev));
60 ob.maxReverse = std::max(ob.maxReverse, mx);
61 ob.energyInflux += en;
62 ob.reversed += nrev;
63 ob.total += (long)(dims[b] - 2 * G) * (dims[c] - 2 * G);
64 }
65#ifdef PECLET_FLOW_MPI
66 if (distributed_) {
67 double d[2] = {ob.energyInflux, 0.0}, dg[2];
68 MPI_Allreduce(&ob.maxReverse, &d[1], 1, MPI_DOUBLE, MPI_MAX, comm_);
69 MPI_Allreduce(&d[0], &dg[0], 1, MPI_DOUBLE, MPI_SUM, comm_);
70 long l[2] = {ob.reversed, ob.total}, lg[2];
71 MPI_Allreduce(l, lg, 2, MPI_LONG, MPI_SUM, comm_);
72 ob.maxReverse = d[1];
73 ob.energyInflux = dg[0];
74 ob.reversed = lg[0];
75 ob.total = lg[1];
76 }
77#endif
78 ob.fraction = ob.total > 0 ? (double)ob.reversed / (double)ob.total : 0.0;
79 return ob;
80}
81
82template <class Grid>
83std::vector<double> Solver<Grid>::getVelocity(int c) {
84 std::vector<double> out = gatherInner(C[c].u);
85 const double k = u_.velToPhys(c); // exactly 1.0 in cell units
86 if (k != 1.0)
87 for (double& x : out)
88 x *= k;
89 return out;
90}
91
92template <class Grid>
93void Solver<Grid>::setVelocity(int c, const std::vector<double>& v) {
94 pguessCount_ = 0; // E: a state write (doc/vof_projection_cost_design.md §5.3)
95 const double k = u_.velToInt(c);
96 if (k != 1.0) {
97 std::vector<double> vi(v.size());
98 for (std::size_t i = 0; i < v.size(); ++i)
99 vi[i] = v[i] * k;
100 scatterInner(C[c].u, vi);
101 } else {
102 scatterInner(C[c].u, v);
103 }
104 maskVelocity(c);
105 seedFaceFieldFromCells(); // ISSUES sweep item 5 (collocated only; a no-op staggered)
106}
107
108template <class Grid>
109std::vector<double> Solver<Grid>::getFaceVelocity(int c) {
110 std::vector<double> out;
111 if constexpr (Grid::collocated) {
112 CCField fa[3] = {uf_, vf_, wf_};
113 out = gatherInner(fa[c]);
114 } else {
115 out = gatherInner(C[c].u);
116 }
117 const double k = u_.velToPhys(c); // exactly 1.0 in cell units
118 if (k != 1.0)
119 for (double& x : out)
120 x *= k;
121 return out;
122}
123
124template <class Grid>
125std::vector<double> Solver<Grid>::getOpenness(int c) {
126 CCField o[3] = {ox_, oy_, oz_};
127 return gatherInner(o[c]);
128}
129
130template <class Grid>
131std::vector<double> Solver<Grid>::getMomentumDiagonal(int c) {
132 auto h = Kokkos::create_mirror_view(C[c].AC);
133 Kokkos::deep_copy(h, C[c].AC);
134 std::vector<double> out((std::size_t)nx_ * ny_ * nz_);
135 for (int z = 0; z < nz_; ++z)
136 for (int y = 0; y < ny_; ++y)
137 for (int x = 0; x < nx_; ++x)
138 out[(std::size_t)x + (std::size_t)y * nx_ + (std::size_t)z * (std::size_t)nx_ * ny_] =
139 (double)h((long)(x + G) + (long)(y + G) * e_.x + (long)(z + G) * (long)e_.x * e_.y);
140 return out;
141}
142
143template <class Grid>
144std::vector<double> Solver<Grid>::getOpennessProj(int c) {
145 const bool gp = ghostProjection_ && oxb_.extent(0) > 0;
146 CCField o[3] = {gp ? oxb_ : ox_, gp ? oyb_ : oy_, gp ? ozb_ : oz_};
147 return gatherInner(o[c]);
148}
149
150template <class Grid>
151std::vector<double> Solver<Grid>::getPressure() {
152 // Incremental scheme: P_ accumulates the physical pressure. Classical Chorin (!incremental_):
153 // derive it on demand from the last projection potential, p = (rho/dt)*phi (CUDA
154 // press_from_phi_k).
155 std::vector<double> out = gatherInner(incremental_ ? P_ : phi_);
156 // Internal pressure -> the caller's units; the Chorin branch first derives p' = (rho'/dt')*phi.
157 const double ct = (incremental_ ? 1.0 : rho_ / dt_) * u_.pToPhys();
158 if (ct != 1.0)
159 for (double& x : out)
160 x *= ct;
161 return out;
162}
163
164template <class Grid>
168
169template <class Grid>
171 if (!cutcellPressure_)
172 return 0.0;
173 if constexpr (Grid::collocated)
174 return maxOpenDivergenceInternal(); // the collocated branch already measures the face
175 // field
176 // `doOutflow = false` keeps the mass-conserving outflow face the projection wrote -- that is the
177 // whole point of this sibling, and distributed it is `fillVelGhostsTo` that has to defend the
178 // plane against the halo's periodic wrap (SCALING_ISSUES #3/#8). Before that, this diagnostic
179 // returned ~|U_inlet| under MPI on every bed, converged or not.
180 for (int c = 0; c < 3; ++c)
181 fillVelGhostsTo(C[c].u, c, 0, false);
182 divergOpen(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), CCConst(ox_), CCConst(oy_),
183 CCConst(oz_), div_, e_, G);
185 double m = reduceMaxAbsInner(CCConst(div_));
186#ifdef PECLET_FLOW_MPI
187 if (distributed_) {
188 double g = 0;
189 MPI_Allreduce(&m, &g, 1, MPI_DOUBLE, MPI_MAX, comm_);
190 return g;
191 }
192#endif
193 return m;
194}
195
196template <class Grid>
198 return maxOpenDivergenceInternal() * u_.divToPhys();
199}
200
201template <class Grid>
203 if (!cutcellPressure_)
204 return 0.0;
205 if constexpr (Grid::collocated) {
206 // Report the residual of the PROJECTED face field uf_ (made divergence-free by project(),
207 // ghosts filled). Re-averaging the central-difference-corrected CELL field would instead show
208 // the inherent O(h^2) approximate-projection cell divergence -- a property of the scheme, not
209 // the solver residual. At an outflow, re-impose the zero-gradient face (matching the
210 // staggered diagnostic, whose fillVelGhosts overwrites the mass-conserving outflow
211 // correction): the operator zeroes the alpha-divergence, but the raw beta-divergence at the
212 // open-boundary corner is otherwise spurious.
213 // ...through `openFaceView`, the field `buildOpenFaceField` already prepared for exactly
214 // this -- the advection reads the same one. This diagnostic used to apply the re-imposition
215 // to `uf_` IN PLACE, which is live state between steps (the next predictor's advecting
216 // velocity, and the flux the colour / scalar transport ride), so reading the diagnostic
217 // would have changed the next step's answer for a caller who only asked to look.
218 CCConst du = openFaceView(0), dv = openFaceView(1), dw = openFaceView(2);
219 if (ghostProjection_ && gpNRows_ >= 0) {
220 // Ghost mode: the closed point divergence of the projected face field (same kernel pair
221 // as the RHS) — the mode's true residual.
222 divergOpen(du, dv, dw, CCConst(oxb_), CCConst(oyb_), CCConst(ozb_), div_, e_, G);
223 gpDivergDelta(div_, du, dv, dw, gpOv_, gpNRows_, C3{nx_, ny_, nz_}, e_, G, distributed_);
224 } else
225 divergOpen(du, dv, dw, CCConst(ox_), CCConst(oy_), CCConst(oz_), div_, e_, G);
226 } else {
227 for (int c = 0; c < 3; ++c)
228 fillVelGhosts(c, 0); // ghosts incl. outflow zero-gradient before the divergence
229 if (ghostProjection_ && gpNRows_ >= 0) {
230 // Ghost mode: the closed point divergence (same kernels as the RHS) IS the true residual
231 // of the mode. (EXPLICIT sliver faces read the corrected stored value here vs u* in the
232 // RHS — the only, and rare, departure from the exact identity.)
233 divergOpen(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), CCConst(oxb_), CCConst(oyb_),
234 CCConst(ozb_), div_, e_, G);
235 gpDivergDelta(div_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), gpOv_, gpNRows_,
236 C3{nx_, ny_, nz_}, e_, G, distributed_);
237 } else
238 divergOpen(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), CCConst(ox_), CCConst(oy_),
239 CCConst(oz_), div_, e_, G);
240 }
241 // The diagnostic must measure the residual of the constraint the projection actually
242 // solved, so it carries the same wall-flux source (rung 3). Without this the moving case
243 // would report a "divergence error" that is really the wall flux the solve balances.
245 double m = reduceMaxAbsInner(CCConst(div_));
246#ifdef PECLET_FLOW_MPI
247 if (distributed_) {
248 double g = 0;
249 MPI_Allreduce(&m, &g, 1, MPI_DOUBLE, MPI_MAX, comm_);
250 return g;
251 }
252#endif
253 return m;
254}
255
256template <class Grid>
258 if (!porous_ || !cutcellPressure_)
259 return 0.0;
260 for (int c = 0; c < 3; ++c)
261 fillVelGhosts(c, 0);
262 fillPorousEpsGhosts(); // the SAME eps ghost policy the projection used (the coupling deposit
263 // rewrites the ghosts between project() and this diagnostic)
264 divergOpenEps(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), CCConst(ox_), CCConst(oy_),
265 CCConst(oz_), CCConst(epsField_), div_, e_, G);
266 { // add back the SAME d(eps)/dt source the projection used (depsdt_ from the last project())
267 CCExec space;
268 C3 e = e_; // local copy — capturing e_ in the KOKKOS_LAMBDA would read this-> on the device
269 CCField d = div_, dd = depsdt_;
270 const bool useDt = porousDepsDt_;
271 using MD = MDRange3<CCExec>;
272 Kokkos::parallel_for(
273 "peclet::flow::porous_resid", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
274 KOKKOS_LAMBDA(int x, int y, int z) {
275 const long i = (long)x + (long)y * e.x + (long)z * e.x * e.y;
276 if (useDt)
277 d(i) += dd(i); // residual of the SAME constraint the projection solved
278 });
279 }
280 double m = reduceMaxAbsInner(CCConst(div_));
281#ifdef PECLET_FLOW_MPI
282 if (distributed_) {
283 double g = 0;
284 MPI_Allreduce(&m, &g, 1, MPI_DOUBLE, MPI_MAX, comm_);
285 return g;
286 }
287#endif
288 return m;
289}
290
291template <class Grid>
293 return lastPressureIters_;
294}
295
296template <class Grid>
297std::vector<std::array<int, 3>> Solver<Grid>::pressureMgLevelRatios() const {
298 std::vector<std::array<int, 3>> out;
299 for (const C3& r : mg_.levelRatios())
300 out.push_back({r.x, r.y, r.z});
301 return out;
302}
303
304template <class Grid>
306 return lastPressureFailed_;
307}
308
309template <class Grid>
311 using peclet::core::solver::AndersonRole;
312 // doc/steady_acceleration.md §5.3: each refusal has its own message. Phase change is tested
313 // before VoF because enable_phase_change turns VoF on itself, so in the note's order its own
314 // message could never be reached; drag precedes the cell forces for the same reason (it
315 // registers force_*).
316 auto refuse = [](const std::string& why) {
317 throw std::runtime_error("steady acceleration (march_to_steady / anderson_accelerator): " +
318 why + "; pass accelerate=False");
319 };
320 if constexpr (Grid::collocated) {
321 if (!(ghostProjection_ && faceInterp_ == 0))
322 refuse(
323 "the collocated scheme is not the fluid-only 'ghost' projection -- for this scheme the "
324 "fixed point is not unique / the march is unstable (select "
325 "set_collocated_scheme('ghost') before the geometry)");
326 }
327 if (pcEnabled_)
328 refuse("phase change (enable_phase_change) has no steady fixed point");
329 if (vofEnabled_ || vofMomEnabled_ || vofBlocks_)
330 refuse("VoF (enable_vof / enable_vof_momentum / VoF blocks) is time-accurate, not steady");
331 if (!scalars_.empty())
332 refuse("a transported scalar (add_scalar) is not in the march state");
333 if (porous_)
334 refuse("the porous (volume-averaged) continuity is not supported");
335 bool propClosure = false;
336 for (const auto& cl : closures_)
337 propClosure = propClosure || cl.outName == "rho" || cl.outName == "mu";
338 if (varRho_ || varProps_ || propClosure || hasField("rho") || hasField("mu"))
339 refuse("variable density or viscosity (a property closure or a rho/mu field) is not supported");
340 if (hasDrag_)
341 refuse("a drag_beta field (implicit drag, CFD-DEM) is not supported");
342 if (hasCellForce_)
343 refuse("cell force fields (force_x/force_y/force_z) are not supported");
344 if (hasMotion_)
345 refuse("moving scene instances have no steady fixed point");
346 if (superficialAxis_ >= 0)
347 refuse("set_superficial_velocity is not supported");
348 if (pwarm_)
349 refuse("the pressure warm start (set_pressure_warmstart(True)) diverges on the steady march");
351 refuse("the balanced-force projection is not supported");
352
353 MarchState ms;
354 for (int c = 0; c < 3; ++c) {
355 ms.fields.push_back(C[c].u);
356 ms.roles.push_back(AndersonRole::Velocity);
357 }
358 ms.fields.push_back(P_);
359 ms.roles.push_back(AndersonRole::Carried);
360 if constexpr (Grid::collocated) {
361 // §3.1 row 3, decided from the CONFIGURATION, not from faceFieldValid_.
362 if (advectsMomentum() && ufAdvect_)
363 for (CCField f : {uf_, vf_, wf_}) {
364 ms.fields.push_back(f);
365 ms.roles.push_back(AndersonRole::Carried);
366 }
367 }
368 ms.e = e_;
369 ms.G = G;
370 ms.signature = {dt_,
371 rho_,
372 mu_,
373 f_[0],
374 f_[1],
375 f_[2],
376 advectsMomentum() ? 1.0 : 0.0,
377 static_cast<double>(advScheme_),
378 implicitFou_ ? 1.0 : 0.0};
379#ifdef PECLET_FLOW_MPI
380 ms.comm = comm_;
381 ms.distributed = distributed_;
382#endif
383 return ms;
384}
385
386template <class Grid>
388 return tStep_;
389}
390
391template <class Grid>
393 return tPredictor_;
394}
395
396template <class Grid>
398 return tMomentum_;
399}
400
401template <class Grid>
403 return tProjection_;
404}
405
406template <class Grid>
408 return mg_.allreduceSeconds();
409}
410
411template <class Grid>
413 return mg_.allreduceCount();
414}
415
416} // namespace peclet::flow
417
418#endif // PECLET_FLOW_FLOW_IBM_DIAGNOSTICS_HPP
std::vector< double > getFaceVelocity(int c)
void fillVelGhosts(int comp, int fold)
double maxOpenDivergenceInternal()
The same diagnostic in INDEX units (per tRef), which is what the solver's own guards read.
void scatterInner(CCField fld, const std::vector< double > &in)
bool advectsMomentum() const
std::vector< std::array< int, 3 > > pressureMgLevelRatios() const
double lastPressureAllreduceSeconds() const
OutflowBackflow outflowBackflow()
double maxOpenDivergenceProjectedInternal()
The same diagnostic in INDEX units (per tRef), which is what the solver's own guards read.
CCConst openFaceView(int c) const
Component c of the face field AS THE ADVECTION AND THE DIVERGENCE DIAGNOSTIC MUST READ IT: advFaceVie...
void addWallFluxDivergence(CCField d)
std::vector< double > getOpenness(int c)
static constexpr int G
Definition flow_ibm.hpp:82
std::vector< double > getMomentumDiagonal(int c)
void setVelocity(int c, const std::vector< double > &v)
Write a component's inner velocity from a host vector (x-fastest, inner region) and re-impose the sol...
std::vector< double > getOpennessProj(int c)
std::vector< double > getVelocity(int c)
void fillVelGhostsTo(CCField f, int comp, int fold, bool doOutflow=true, bool faceEdges=false)
bool hasField(const std::string &name) const
double reduceMaxAbsInner(CCConst f)
std::vector< double > gatherInner(CCField fld)
std::vector< double > getPressure()
Kokkos::DefaultExecutionSpace CCExec
void gpDivergDelta(CCField d, CCConst u, CCConst v, CCConst w, const GpOverlayReal< Real > &ov, int nOv, C3 nn, C3 extb, int gb, bool useGhost=false)
Overlay divergence correction: d(r) = rho_r * (d(r) + closure/BC/explicit face values),...
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
void divergOpen(CCConst u, CCConst v, CCConst w, CCConst ox, CCConst oy, CCConst oz, CCField d, C3 e, int g)
Kokkos::View< double *, CCMem > CCField
void divergOpenEps(CCConst u, CCConst v, CCConst w, CCConst ox, CCConst oy, CCConst oz, CCConst eps, CCField d, C3 e, int g)
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
OUTFLOW REVERSAL CENSUS – the regime in which the zero-gradient (do-nothing) outflow is only conditio...
static constexpr double AC