flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_bindings_scalar.hpp
Go to the documentation of this file.
1
8#pragma once
9
11
12namespace peclet::flow::bindings {
13
15template <class Grid, class C>
16inline void bindSolverScalar(C& cls) {
17 using S = BoundSolver<Grid>;
18 // --- Scalar transport (advection-diffusion) ----------------------------------------------
19 cls.def(
20 "add_scalar",
21 [](S& s, const std::string& name, double diffusivity, const std::string& scheme,
22 std::optional<int> iters, bool cutcell) {
23 chk::scalarArgs(diffusivity, iters);
24 if (cutcell && iters)
25 throw std::invalid_argument(
26 "add_scalar: iters must be None for a cut-cell scalar (it solves to a residual "
27 "tolerance, set_scalar_residual_tolerance)");
28 s.addScalar(name, diffusivity, enum_index(scheme, kScalarSchemes, "add_scalar", "scheme"),
29 iters ? *iters : 50, cutcell);
30 },
31 nb::arg("name"), nb::arg("diffusivity") = 0.0, nb::arg("scheme") = "koren",
32 nb::arg("iters") = nb::none(), nb::arg("cutcell") = false,
33 "Register a transported scalar (temperature/concentration/...): constant diffusivity "
34 "(length^2/time, in the solver's physical units -- cells^2 per time unit without an "
35 "extent), advection scheme 'fou' (first-order upwind), 'koren' (Koren TVD, the "
36 "default) or 'sou' (second-order upwind), and RB-GS diffusion sweeps (iters, default "
37 "50). The scalar is a registered field (get_field/set_field/diagnostics.field_view). "
38 "Requires geometry (set_solid/set_pressure_geometry) for the openness-weighted "
39 "operators.\n\n"
40 "cutcell=True selects the cut-cell discretization (doc/scalar_ibm_design.md): kappa "
41 "(fluid fraction) storage, the scalar's own apertures, wall conditions per body "
42 "(set_scalar_wall, default insulating), sources (set_scalar_source), BiCGStab to a "
43 "residual tolerance (set_scalar_residual_tolerance; iters must then be None), a steady solve "
44 "(solve_scalar_steady) and per-body wall fluxes (scalar_wall_flux). Cells that are not "
45 "fluid unknowns hold 0. Advection is not yet part of the cut-cell operator.");
46 cls.def(
47 "set_scalar_bc",
48 [](S& s, const std::string& name, const std::string& face, const std::string& type,
49 double value) {
50 chk::finite("set_scalar_bc", "value", value, "the scalar's units");
51 s.setScalarBc(name, face_index(face, "set_scalar_bc"),
52 enum_index(type, kScalarBcTypes, "set_scalar_bc", "type"), value);
53 },
54 nb::arg("name"), nb::arg("face"), nb::arg("type"), nb::arg("value") = 0.0,
55 "Scalar boundary condition on a domain face ('-x', '+x', '-y', '+y', '-z', '+z'): "
56 "type 'periodic', 'neumann' (zero flux, adiabatic) or 'dirichlet' (the given value, in "
57 "the scalar's own units: the solver never rescales a transported scalar). Single-rank "
58 "for a legacy scalar; a cut-cell scalar takes it under MPI too, and its periodic / "
59 "non-periodic faces must match set_domain_bc (checked at the first advance). For a "
60 "cut-cell scalar `value` may also be a per-face profile (next overload).");
61 cls.def(
62 "set_scalar_bc",
63 [](S& s, const std::string& name, const std::string& face, const std::string& type,
64 nb::ndarray<double, nb::ndim<2>, nb::device::cpu> value) {
65 if (enum_index(type, kScalarBcTypes, "set_scalar_bc", "type") != 2)
66 throw std::invalid_argument("set_scalar_bc: a profile is a 'dirichlet' value");
67 const int n1 = static_cast<int>(value.shape(0)), n2 = static_cast<int>(value.shape(1));
68 std::vector<double> prof(static_cast<std::size_t>(n1) * n2);
69 auto v = value.view();
70 for (int j2 = 0; j2 < n2; ++j2)
71 for (int j1 = 0; j1 < n1; ++j1)
72 prof[static_cast<std::size_t>(j1) + static_cast<std::size_t>(j2) * n1] = v(j1, j2);
73 s.setScalarBcProfile(name, face_index(face, "set_scalar_bc"), prof, n1, n2);
74 },
75 nb::arg("name"), nb::arg("face"), nb::arg("type"), nb::arg("value"),
76 "Cut-cell scalars: a Dirichlet domain face with a per-face PROFILE, shape (N_t1, N_t2) "
77 "over this rank's face cells in the face's tangential axes in x, y, z order (-x/+x: "
78 "(ny, nz); -y/+y: (nx, nz); -z/+z: (nx, ny)), as set_domain_bc_profile. The value is "
79 "the scalar at the boundary face centre.");
80 cls.def(
81 "set_scalar_wall",
82 [](S& s, const std::string& name, const std::string& type, double value, double coefficient,
83 std::optional<int> instance) {
84 s.setScalarWall(name, enum_index(type, kScalarWallTypes, "set_scalar_wall", "type"), value,
85 coefficient, instance ? *instance : -1);
86 },
87 nb::arg("name"), nb::arg("type"), nb::arg("value") = 0.0, nb::arg("coefficient") = 0.0,
88 nb::arg("instance") = nb::none(),
89 "Cut-cell scalars: the condition on the immersed walls of one scene instance "
90 "(instance=int, needs a scene) or of every body (instance=None, which also clears the "
91 "per-instance settings). 'neumann': value = the flux INTO the fluid per area (c L/T; 0, "
92 "the default for every body, is insulating). 'dirichlet': value = the wall "
93 "concentration. 'robin': flux into the fluid = coefficient * (value - c_wall), "
94 "coefficient = k (L/T, >= 0; a first-order surface reaction is k_r with value 0). "
95 "Physical units under an extent; takes effect at the next advance or steady solve.");
96 cls.def(
97 "set_scalar_solid",
98 [](S& s, const std::string& name, double diffusivity, double capacity, double partition,
99 double contact_resistance, std::optional<int> instance) {
100 s.setScalarSolid(name, diffusivity, capacity, partition, contact_resistance,
101 instance ? *instance : -1);
102 },
103 nb::arg("name"), nb::arg("diffusivity"), nb::arg("capacity") = 1.0,
104 nb::arg("partition") = 1.0, nb::arg("contact_resistance") = 0.0,
105 nb::arg("instance") = nb::none(),
106 "Cut-cell scalars, conjugate transport (doc/scalar_ibm_design.md §1.1): the solid "
107 "interior of one scene instance (instance=int, needs a scene) or of every body "
108 "(instance=None, which also clears the per-instance settings) carries the scalar too. "
109 "diffusivity = D_s (L^2/T, the solid's own, >= 0), capacity = C_s (> 0; heat: "
110 "(rho c_p)_s/(rho c_p)_f, a porous particle: its porosity), partition = K (> 0; c_s = K c "
111 "at equilibrium), contact_resistance = R_c (T/L, >= 0; the interface flux is "
112 "(c_s/K - c)/R_c). The solid field is the registered field '<name>_solid' (it holds "
113 "c_s/K, internal; get_scalar_solid returns c_s). A later set_scalar_wall for the same "
114 "instance makes it a wall again (last call wins). Takes effect at the next advance or "
115 "steady solve. Physical units under an extent.");
116 cls.def(
117 "get_scalar_solid",
118 [](S& s, const std::string& name) { return field_out(s, s.getScalarSolid(name)); },
119 nb::arg("name"),
120 "Cut-cell scalars: a copy of the solid concentration c_s = K psi_s of a conjugate scalar, "
121 "(nx, ny, nz) F-order on this rank's block, NaN outside the solid unknowns (all NaN before "
122 "the first advance or steady solve with a conjugate body).");
123 cls.def(
124 "set_scalar_source",
125 [](S& s, const std::string& name, double source) { s.setScalarSource(name, source); },
126 nb::arg("name"), nb::arg("source"),
127 "Cut-cell scalars: a uniform volumetric source S (c/T, physical), weighted by the fluid "
128 "fraction kappa.");
129 cls.def(
130 "set_scalar_source",
131 [](S& s, const std::string& name, nb::ndarray<double, nb::f_contig> source) {
132 s.setScalarSourceField(name, grid_in(source));
133 },
134 nb::arg("name"), nb::arg("source"),
135 "Cut-cell scalars: a per-cell volumetric source S (c/T, physical), an (nx, ny, nz) "
136 "F-order array on this rank's block, weighted by kappa.");
137 cls.def(
138 "set_scalar_residual_tolerance",
139 [](S& s, const std::string& name, double rtol) { s.setScalarResidualTolerance(name, rtol); },
140 nb::arg("name"), nb::arg("rtol"),
141 "Cut-cell scalars: the max-norm relative residual tolerance of the solve, "
142 "max|b - A c| <= rtol * max(max|b|, max|A c0|) (default 1e-10).");
143 cls.def(
144 "set_scalar_mean_gradient",
145 [](S& s, const std::string& name, const std::array<double, 3>& gradient) {
146 s.setScalarMeanGradient(name, gradient);
147 },
148 nb::arg("name"), nb::arg("gradient"),
149 "Cut-cell scalars: the closure (mean-gradient) mode. The field then holds the periodic "
150 "fluctuation theta of c = G.x + theta, written in the frame moving with the fluid's mean "
151 "velocity; G = `gradient` (c/L, physical; x the cell_centers() coordinates). Every axis "
152 "with a nonzero component must be periodic (checked at the next advance or solve). "
153 "(0, 0, 0) turns it off. Read the result with scalar_mean_flux.");
154 cls.def(
155 "scalar_mean_flux",
156 [](S& s, const std::string& name) {
157 const auto j = s.scalarMeanFlux(name);
158 return peclet::core::python::vector_to_ndarray(std::vector<double>(j.begin(), j.end()), {3},
159 {1});
160 },
161 nb::arg("name"),
162 "Cut-cell scalars: the box-averaged total flux vector (3,), c L/T (physical), of the "
163 "last advance or steady solve: the diffusive face sum of -D a A (c_j - c_i) with "
164 "c = theta + G.x (the face's true displacement), plus the advective (1/V_box) sum_i "
165 "(U_i - kappa_i V Ubar) theta_i in the moving frame, V_box the whole box (solid "
166 "included). Exact as a plane average for steady fields without wall sources. Effective "
167 "diffusivity k* = -J.G/(D|G|^2); dispersion D* = -J/(phi G), phi the discrete porosity. "
168 "Collective under MPI.");
169 cls.def(
170 "solve_scalar_steady", [](S& s, const std::string& name) { s.solveScalarSteady(name); },
171 nb::arg("name"),
172 "Cut-cell scalars: solve the steady problem now (no storage term) from the current "
173 "field as the initial guess. Statistics in diagnostics.scalar_census.");
174 cls.def(
175 "scalar_wall_flux",
176 [](S& s, const std::string& name) {
177 std::vector<double> v = s.scalarWallFlux(name);
178 const std::size_t n = v.size();
179 return peclet::core::python::vector_to_ndarray(std::move(v), {n}, {1});
180 },
181 nb::arg("name"),
182 "Cut-cell scalars: the integrated flux INTO the fluid per body over the last advance or "
183 "steady solve, shape (num_bodies,) (one body without a scene), in c L^3/T (physical). "
184 "Collective under MPI.");
185 cls.def(
186 "has_scalar", [](S& s, const std::string& name) { return s.hasScalar(name); },
187 nb::arg("name"), "Whether a transported scalar of this name is registered.");
188 cls.def(
189 "advance_scalars", [](S& s) { s.advanceScalars(); },
190 "Advance all registered scalars one dt with the current velocity (also done by step()).");
191}
192
194template <class Grid, class C>
195inline void bindDiagnosticsScalar(C& cls) {
196 using D = Diagnostics<Grid>;
197 cls.def(
198 "scalar_geometry",
199 [](D& diag, const std::string& name) {
200 diag.s->cutcellScalar(name, "scalar_geometry");
201 nb::dict d;
202 d["kappa"] = field_out(*diag.s, diag.s->scalarGeometryField(0));
203 d["aperture_x"] = field_out(*diag.s, diag.s->scalarGeometryField(1));
204 d["aperture_y"] = field_out(*diag.s, diag.s->scalarGeometryField(2));
205 d["aperture_z"] = field_out(*diag.s, diag.s->scalarGeometryField(3));
206 d["unknown"] = field_out(*diag.s, diag.s->scalarGeometryField(4));
207 if (diag.s->cutcellScalar(name, "scalar_geometry").cut->solid.extent(0) > 0) {
208 d["kappa_solid"] = field_out(*diag.s, diag.s->scalarSolidGeometryField(name, 0));
209 d["solid_unknown"] = field_out(*diag.s, diag.s->scalarSolidGeometryField(name, 1));
210 }
211 return d;
212 },
213 nb::arg("name"),
214 "The cut-cell scalar geometry record (doc/scalar_ibm_design.md §2) as F-order (nx, ny, "
215 "nz) arrays of this rank's block: 'kappa' (fluid fraction of the fan-tetrahedron PL "
216 "model), 'aperture_x/y/z' (the SNAPPED, ungated scalar aperture of the -x/-y/-z face of "
217 "each cell -- the scalar's own, never the pressure openness), 'unknown' (1 where the "
218 "cell is a fluid unknown: kappa > 1e-14 with an open face). Built on first use after "
219 "the geometry; shared by every cut-cell scalar. A scalar with a solid field "
220 "(set_scalar_solid) also gets 'kappa_solid' (1 - kappa) and 'solid_unknown' (1 where the "
221 "cell is a solid unknown: kappa_solid > 0 and the cell's material conjugate, §2.7).");
222 cls.def(
223 "scalar_census",
224 [](D& diag, const std::string& name) {
225 const auto& st = *diag.s->cutcellScalar(name, "scalar_census").cut;
226 const auto c = diag.s->scalarCutCensus();
227 nb::dict d;
228 d["num_unknowns"] = c.numUnknowns;
229 d["num_cut_cells"] = c.numCutCells;
230 d["num_facets"] = c.numFacets;
231 d["num_two_sided"] = c.numTwoSided;
232 d["num_thin_solid"] = c.numThinSolid;
233 d["num_sealed"] = c.numSealed;
234 d["sealed_volume"] = c.sealedVolume;
235 nb::dict rungs;
236 rungs["fluid"] = nb::make_tuple(c.rungs[0], c.rungs[1], c.rungs[2], c.rungs[3]);
237 d["probe_rungs"] = rungs;
238 d["num_solid_unknowns"] = st.conj ? st.numSolidUnknowns : 0L;
239 d["solid_volume"] = st.conj ? st.solidVolume : 0.0;
240 d["sealed_solid_volume"] = st.conj ? st.sealedSolidVolume : 0.0;
241 if (st.conj)
242 rungs["solid"] = nb::make_tuple(st.solidRungs[0], st.solidRungs[1], st.solidRungs[2],
243 st.solidRungs[3]);
244 d["krylov_iterations"] = st.iterations;
245 d["krylov_residual"] = st.residual;
246 d["krylov_converged"] = st.converged;
247 d["num_mg_levels"] = st.mgLevels;
248 d["steady_incompatibility"] = st.incompatibility;
249 d["num_small_cells"] = st.numSmall;
250 d["num_implicit_faces"] = st.numImplicitFaces;
251 d["num_flux_faces"] = st.numFluxFaces;
252 d["num_guarded_flux_faces"] = st.numGuardedFaces;
253 d["num_backflow_faces"] = st.numBackflowFaces;
254 d["bulk_courant"] = st.bulkCourant;
255 d["max_cell_peclet"] = st.maxCellPeclet;
256 return d;
257 },
258 nb::arg("name"),
259 "Census of the cut-cell scalar (collective under MPI, summed over ranks). The solve "
260 "part, of the last advance or steady solve: 'krylov_iterations', 'krylov_residual' "
261 "(the true max-norm residual over the reference max(max|b|, max|A c0|)), "
262 "'krylov_converged', 'num_mg_levels' (the ScalarMG levels the V-cycle used; 1: level 0 "
263 "alone), "
264 "'steady_incompatibility' (|sum b| / sum|b| of a singular steady problem before its "
265 "projection, else 0), 'num_solid_unknowns' (0: single phase; the solid unknowns of a "
266 "conjugate scalar, whose 'probe_rungs' then carries a 'solid' tuple too), 'solid_volume' "
267 "/ "
268 "'sealed_solid_volume' (physical: the conjugate solid kappa_s V, and its part in cells "
269 "that are not solid unknowns -- kappa_s > 0 with no open solid face and no conjugate "
270 "facet, ruling D-WO7-1). The advection part "
271 "(design §6.3, the last advance or steady solve): 'num_small_cells' (cut cells whose "
272 "explicit outflow would exceed the bulk's), 'num_implicit_faces' / 'num_flux_faces' "
273 "(faces carrying flux that took implicit upwind / all faces carrying flux; steady: all "
274 "implicit), 'bulk_courant' (C_bulk: max over full cells of dt Out/V; 0 steady), "
275 "'num_guarded_flux_faces' (faces with projection flux toward a cell that is not a fluid "
276 "unknown, whose flux the operator drops), 'num_backflow_faces' (rows of an 'outflow' "
277 "domain face whose flux enters the domain: their inflow takes the zero-gradient value; "
278 "a steady solve warns once), 'max_cell_peclet' (the largest "
279 "aperture-weighted face Peclet number |u_a| a h_a / D over the interior faces; the "
280 "steady envelope of the advective preconditioner is <= 10). The geometry "
281 "part: 'num_unknowns' (fluid unknowns), 'num_cut_cells' (cells carrying a facet), "
282 "'num_facets', 'num_two_sided' (cells with two facets), 'num_thin_solid' (two-facet "
283 "cells with solid between two fluids -- a resolution warning), 'num_sealed' / "
284 "'sealed_volume' (kappa > 0 behind closed faces; physical volume), 'probe_rungs' "
285 "({'fluid': (R0, R1a, R1b, R2)} facet counts of the probe ladder).");
286 cls.def(
287 "scalar_budget",
288 [](D& diag, const std::string& name) {
289 const auto b = diag.s->scalarBudget(name);
290 nb::dict d;
291 d["mass"] = b.mass;
292 d["mass_solid"] = b.massSolid;
293 d["d_mass"] = b.dMass;
294 d["wall_in"] = b.wallIn;
295 d["boundary_in"] = b.boundaryIn;
296 d["source_in"] = b.sourceIn;
297 d["defect"] = b.defect;
298 d["identity_error"] = b.identityError;
299 return d;
300 },
301 nb::arg("name"),
302 "Budget of a cut-cell scalar over the last advance (collective under MPI), physical: "
303 "'mass' = sum kappa V c, 'mass_solid' (= sum C_s kappa_s V c_s of a conjugate scalar; 0 "
304 "single phase), 'd_mass' = the change of mass + mass_solid over the advance, 'wall_in' / "
305 "'boundary_in' / 'source_in' = the rates INTO the fluid from the "
306 "immersed walls (the conjugate interfaces are internal: not in it), the domain faces "
307 "(the Dirichlet faces' diffusive flux plus the advective "
308 "flux through inflow/outflow faces) and the source, 'defect' = dt sum V r (r the "
309 "linear-solver residual), and 'identity_error' = d_mass - dt (wall_in + boundary_in + "
310 "source_in) + defect, which is round-off for a correct discretization. After a steady "
311 "solve it is the rate balance: d_mass = 0, defect = sum V r and identity_error = "
312 "defect - (wall_in + boundary_in + source_in). Computed on request from the stored "
313 "state.");
314 cls.def(
315 "scalar_facets",
316 [](D& diag, const std::string& name) {
317 auto f = diag.s->scalarFacets(name);
318 const std::size_t n = f.area.size();
319 nb::dict d;
320 d["centroid"] =
321 peclet::core::python::vector_to_ndarray(std::move(f.centroid), {n, 3}, {3, 1});
322 d["normal"] = peclet::core::python::vector_to_ndarray(std::move(f.normal), {n, 3}, {3, 1});
323 d["area"] = peclet::core::python::vector_to_ndarray(std::move(f.area), {n}, {1});
324 d["instance"] = peclet::core::python::vector_to_ndarray(std::move(f.instance), {n}, {1});
325 d["wall_value"] = peclet::core::python::vector_to_ndarray(std::move(f.wallValue), {n}, {1});
326 d["flux"] = peclet::core::python::vector_to_ndarray(std::move(f.flux), {n}, {1});
327 d["probe_rung"] = peclet::core::python::vector_to_ndarray(std::move(f.rung), {n}, {1});
328 return d;
329 },
330 nb::arg("name"),
331 "Per-facet arrays of a cut-cell scalar on this rank (facet order = x-fastest cell "
332 "order): 'centroid' (n, 3) physical coordinates, 'normal' (n, 3) into the fluid, 'area' "
333 "(physical), 'instance' (scene body; 0 for raw-SDF geometry), 'wall_value' (c at the "
334 "wall from the elimination: robin (D u_p + k s g)/(D + k s), dirichlet g, neumann "
335 "u_p + q s/D; NaN on a facet whose cell is not an unknown), 'flux' (into the fluid per "
336 "area, c L/T physical, after the last advance or steady solve; local Nu/Sh maps, first "
337 "order in the max norm) and 'probe_rung' (0..3 = R0, R1a, R1b, R2).");
338 cls.def(
339 "set_scalar_max_iterations",
340 [](D& diag, const std::string& name, int max_iter) {
341 diag.s->setScalarMaxIterations(name, max_iter);
342 },
343 nb::arg("name"), nb::arg("max_iter"),
344 "Cut-cell scalars: the BiCGStab iteration cap (default 200). On non-convergence the "
345 "iterate is kept, diagnostics.scalar_census reports it and a one-time warning is "
346 "printed.");
347}
348
349} // namespace peclet::flow::bindings
Shared helpers of the peclet.flow Python binding: array conversion, the string-enum tables,...
const std::vector< std::string > kScalarSchemes
int face_index(const std::string &f, const char *who)
int enum_index(const std::string &v, const std::vector< std::string > &names, const char *who, const char *what)
const std::vector< std::string > kScalarWallTypes
void bindDiagnosticsScalar(C &cls)
SolverDiagnostics (and its collocated twin): scalar geometry, census, budget and facets.
std::vector< double > grid_in(nb::ndarray< double, nb::f_contig > a)
nb::ndarray< nb::numpy, double > field_out(S &s, std::vector< double > &&v)
const std::vector< std::string > kScalarBcTypes
void bindSolverScalar(C &cls)
Solver (and its collocated twin): scalar transport.
Definition prof.py:1
The developer tier: a view onto one Solver<Grid> (no state of its own).
static double source(int gx, int gy, int gz)
static double value(int gx, int gy, int gz)