cfd_craft/grid.rs
1//! The uniform staggered grid of a case: cells, faces, the solid mask and
2//! the fluid components.
3//!
4//! [`Grid::build`] turns a valid [`Case`] into the represented topology.
5//! Cells are uniform boxes of size `dx`; a cell is solid when its center lies
6//! inside a geometry box. Cell index `(k * ny + j) * nx + i` runs x fastest
7//! ([`Grid::index`]). Velocities live on faces: `faces` holds the x-faces,
8//! then the y-faces, then the z-faces, each block x fastest over its
9//! [`face_dims`](Grid::face_dims), with one extra face along a nonperiodic
10//! axis; a periodic axis wraps and has no duplicate end face. Every face has
11//! a [`FaceKind`] that fixes its role in the equations.
12//!
13//! Cells joined through interior faces form fluid components. A component
14//! touching an outlet is *anchored*; any other has a mean-zero pressure gauge
15//! and needs compatible net flux. [`GeometryEvidence`] summarizes the mask
16//! for geometry.json, and [`Grid::mask_topology`] counts components without
17//! building faces.
18//!
19//! The public fields are the representation the solver uses. Callers can
20//! read them freely; changing them breaks the invariants the operators rely
21//! on (rebuild the grid instead).
22//!
23//! ```
24//! # let json = r#"{"schema_version": "cfd-craft.case/0.1", "name": "tiny",
25//! # "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
26//! # "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
27//! # "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
28//! # "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
29//! # "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
30//! # "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
31//! # "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
32//! # "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 1000,
33//! # "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
34//! # "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}}"#;
35//! use cfd_craft::{case::Case, grid::{FaceKind, Grid}};
36//!
37//! let case: Case = serde_json::from_str(json).unwrap();
38//! let g = Grid::build(&case)?;
39//! assert_eq!((g.count(), g.dx), (32, [0.5, 0.5, 0.5]));
40//! // Open x: 9 x 2 x 2 x-faces; periodic y and z: 8 x 2 x 2 each.
41//! assert_eq!(g.faces.len(), 36 + 32 + 32);
42//! let i = Grid::index(g.n, [3, 1, 0]);
43//! assert_eq!(g.coord(i), [3, 1, 0]);
44//! assert_eq!(g.center(i), [1.75, 0.75, 0.25]);
45//! // The flow enters at x = 0 and leaves at x = 4 m, which anchors the
46//! // single fluid component.
47//! let [lower, upper] = g.cell_faces[Grid::index(g.n, [0, 0, 0])][0];
48//! assert_eq!(g.faces[lower].kind, FaceKind::Inlet);
49//! assert_eq!(g.faces[g.cell_faces[Grid::index(g.n, [7, 0, 0])][0][1]].kind, FaceKind::Outlet);
50//! assert_eq!(g.faces[upper].kind, FaceKind::Interior);
51//! assert_eq!((g.components.len(), g.anchored[0]), (1, true));
52//! # Ok::<(), String>(())
53//! ```
54use crate::{Result, case::*};
55use serde::{Deserialize, Serialize};
56use std::collections::{BTreeMap, VecDeque};
57
58/// The role of a face in the equations.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum FaceKind {
61 /// Fluid cells on both sides: carries a momentum equation and fluxes.
62 Interior,
63 /// Impermeable no-slip face: between a fluid and a solid cell, on a
64 /// `wall` boundary, or the ground of `ground_open_top`. Normal velocity
65 /// zero; the tangential condition enters through wall ghost values
66 /// (moving walls, wall functions with `neutral_rans`).
67 Wall,
68 /// Impermeable stress-free face: a `slip` boundary, the top of
69 /// `ground_open_top`, or an `open` boundary face without normal case flow.
70 Slip,
71 /// `open` boundary face where the case flow enters: the velocity is
72 /// prescribed from [`Flow::vector`] and the inflow concentration is zero.
73 Inlet,
74 /// `open` boundary face where the case flow leaves: carries a momentum
75 /// equation, fixes the pressure level (zero outside) and anchors its
76 /// fluid component.
77 Outlet,
78 /// No fluid on either side, for example inside a solid or on a domain
79 /// face of a solid cell. Velocity zero; no flux.
80 Blocked,
81}
82/// One staggered face. The face normal is `axis`; `lo` and `hi` are the fluid
83/// cells below and above it along that axis.
84#[derive(Clone, Debug)]
85pub struct Face {
86 /// Normal axis: 0 (x), 1 (y) or 2 (z).
87 pub axis: usize,
88 /// Integer position in this axis's face array, of dimensions
89 /// `Grid::face_dims[axis]`. It is the lower face of the cell with the
90 /// same coordinates; the last face of a nonperiodic axis is the upper face
91 /// of the last cell.
92 pub coord: [usize; 3],
93 /// Face center in meters.
94 pub center: [f64; 3],
95 /// Fluid cell below the face along `axis`; `None` for a solid cell or
96 /// outside the domain. Across a periodic boundary it is the wrapped cell.
97 pub lo: Option<usize>,
98 /// Fluid cell above the face along `axis`; `None` for a solid cell or
99 /// outside the domain.
100 pub hi: Option<usize>,
101 /// Role of the face.
102 pub kind: FaceKind,
103 /// Face area in m2.
104 pub area: f64,
105 /// Distance in meters over which the face gradient is taken: the cell
106 /// width for interior faces, half of it (cell center to face) otherwise.
107 pub distance: f64,
108}
109/// The represented topology of a case: uniform cells, the solid mask,
110/// staggered faces and the fluid components, plus lazily built caches of the
111/// pressure and implicit-momentum operators. Build it with
112/// [`build`](Self::build); see the [module docs](self) for the layout.
113#[derive(Clone, Debug)]
114pub struct Grid {
115 /// Cell counts along x, y and z.
116 pub n: [usize; 3],
117 /// Cell sizes in meters: domain length over cell count.
118 pub dx: [f64; 3],
119 /// Cell volume in m3.
120 pub volume: f64,
121 /// Per cell, true for fluid and false for solid.
122 pub fluid: Vec<bool>,
123 /// All faces: x-faces, then y-faces, then z-faces, each block x fastest.
124 pub faces: Vec<Face>,
125 /// Per cell and axis, the indices of its lower and upper faces in
126 /// `faces`. `usize::MAX` for solid cells. On a one-cell periodic axis
127 /// both entries are the same face.
128 pub cell_faces: Vec<[[usize; 2]; 3]>,
129 /// Per cell, the index of its fluid component; `usize::MAX` for solid
130 /// cells.
131 pub component: Vec<usize>,
132 /// The cells of each fluid component, in breadth-first order from its
133 /// lowest cell index.
134 pub components: Vec<Vec<usize>>,
135 /// Per component, whether it touches an outlet face, which fixes its
136 /// pressure level. Other components get a mean-zero pressure gauge and
137 /// must receive zero net flux (CFD-E031).
138 pub anchored: Vec<bool>,
139 /// Dimensions of the face array of each axis: `n`, plus one along that
140 /// axis when it is not periodic.
141 pub face_dims: [[usize; 3]; 3],
142 offsets: [usize; 3],
143 /// Per geometry box ID, the number of cells whose center lies inside it;
144 /// overlapping boxes share cells.
145 pub box_cells: BTreeMap<String, usize>,
146 /// Per-shape analytic and represented volumes and adjacent street resolution.
147 pub shape_evidence: BTreeMap<String, ShapeEvidence>,
148 /// IC(0) factor of the pressure operator, built by the first IC(0)
149 /// pressure solve and reused afterwards. It is only a preconditioner and
150 /// is not rebuilt if face coefficients change.
151 pub pressure_factor: std::sync::OnceLock<crate::pressure::Factor>,
152 /// Preconditioner of the pressure solves on this grid, copied from
153 /// `numerics.pressure_preconditioner`.
154 pub pressure_preconditioner: PressurePreconditioner,
155 pub(crate) pressure_multigrid: std::sync::Arc<crate::multigrid::Cache>,
156 /// Built on first use by the implicit pseudo-time algorithms.
157 pub(crate) momentum_stencil: std::sync::OnceLock<crate::momentum_solve::Stencil>,
158 /// Same-axis neighbor faces of every face, [direction][side], from `face_at`.
159 pub(crate) neighbor_faces: std::sync::OnceLock<Vec<[[Option<usize>; 2]; 3]>>,
160 /// For an a-face at q and d ≠ a, the d-faces at q + e_d and q + e_d − e_a.
161 pub(crate) edge_faces: std::sync::OnceLock<Vec<[[Option<usize>; 2]; 3]>>,
162}
163/// Summary of the represented mask, written as geometry.json. The mask
164/// itself is not archived; it is rebuilt from the case boxes and checked
165/// against `mask_sha256`.
166#[derive(Clone, Debug, Serialize, Deserialize)]
167pub struct GeometryEvidence {
168 /// Number of fluid cells.
169 pub fluid_cells: usize,
170 /// Number of solid cells.
171 pub solid_cells: usize,
172 /// Number of face-connected fluid regions.
173 pub fluid_components: usize,
174 /// Represented solid volume in m3: solid cells times the cell volume.
175 pub solid_volume_m3: f64,
176 /// SHA-256 of the mask as one byte per cell (1 fluid, 0 solid), in cell
177 /// order.
178 pub mask_sha256: String,
179 /// Cells whose center lies inside each box, by box ID; overlapping boxes share cells.
180 pub box_cells: BTreeMap<String, usize>,
181 /// Shape-local discretization evidence; overlaps are counted per shape.
182 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
183 pub shapes: BTreeMap<String, ShapeEvidence>,
184}
185/// Discretization of one box or polygon prism, independent of flow acceptance.
186#[derive(Clone, Debug, Serialize, Deserialize)]
187pub struct ShapeEvidence {
188 /// Number of contained solid cell centers.
189 pub solid_cells: usize,
190 /// Analytic shape volume in m3 (overlaps counted separately).
191 pub exact_volume_m3: f64,
192 /// Contained cell count times uniform cell volume.
193 pub represented_volume_m3: f64,
194 /// Represented minus exact volume in m3.
195 pub volume_error_m3: f64,
196 /// Narrowest horizontal fluid run from this shape to any other solid.
197 /// Null when no such bounded run is represented.
198 pub narrowest_fluid_passage_cells: Option<usize>,
199}
200/// Topology of a case's cell mask, from [`Grid::mask_topology`].
201#[derive(Clone, Copy, Debug, PartialEq)]
202pub struct MaskTopology {
203 /// Number of face-connected fluid regions, including periodic wraps.
204 pub fluid_components: usize,
205 /// Number of solid cells.
206 pub solid_cells: usize,
207 /// Solid cells times the cell volume, in m3.
208 pub solid_volume_m3: f64,
209}
210impl Grid {
211 /// Number of cells, fluid and solid.
212 pub fn count(&self) -> usize {
213 self.fluid.len()
214 }
215 /// Linear index of cell `p = [i, j, k]` in a grid of `n` cells:
216 /// `(k * n[1] + j) * n[0] + i`, x fastest. Also indexes a face array with
217 /// its `face_dims`.
218 pub fn index(n: [usize; 3], p: [usize; 3]) -> usize {
219 (p[2] * n[1] + p[1]) * n[0] + p[0]
220 }
221 /// The `[i, j, k]` coordinates of cell index `i`; the inverse of
222 /// [`index`](Self::index).
223 pub fn coord(&self, i: usize) -> [usize; 3] {
224 [
225 i % self.n[0],
226 i / self.n[0] % self.n[1],
227 i / (self.n[0] * self.n[1]),
228 ]
229 }
230 /// Center of cell `i` in meters.
231 pub fn center(&self, i: usize) -> [f64; 3] {
232 let q = self.coord(i);
233 std::array::from_fn(|a| (q[a] as f64 + 0.5) * self.dx[a])
234 }
235 /// Builds the grid of a case: validates it (an invalid case returns the
236 /// serialized check report), masks the cells whose centers lie in a box,
237 /// classifies every face and finds the fluid components.
238 ///
239 /// # Errors
240 ///
241 /// `CFD-E028` when a box or prism contains no cell center (the grid would not
242 /// represent it) and `CFD-E030` when no fluid cell remains. Source and
243 /// receptor support are checked separately, by
244 /// [`transport::source_fields`](crate::transport::source_fields) and
245 /// [`transport::receptor_weights`](crate::transport::receptor_weights).
246 pub fn build(c: &Case) -> Result<Self> {
247 c.validate()?;
248 let n = c.grid.cells;
249 let dx = std::array::from_fn(|a| c.domain.size_m[a] / n[a] as f64);
250 let volume = dx.iter().product();
251 let count = n.iter().product();
252 let mut g = Self {
253 n,
254 dx,
255 volume,
256 fluid: vec![true; count],
257 faces: vec![],
258 cell_faces: vec![[[usize::MAX; 2]; 3]; count],
259 component: vec![usize::MAX; count],
260 components: vec![],
261 anchored: vec![],
262 face_dims: [n; 3],
263 offsets: [0; 3],
264 box_cells: BTreeMap::new(),
265 shape_evidence: BTreeMap::new(),
266 pressure_factor: std::sync::OnceLock::new(),
267 pressure_preconditioner: c.numerics.pressure_preconditioner,
268 pressure_multigrid: Default::default(),
269 momentum_stencil: std::sync::OnceLock::new(),
270 neighbor_faces: std::sync::OnceLock::new(),
271 edge_faces: std::sync::OnceLock::new(),
272 };
273 // Each shape is rasterized over its bounding box only (validation
274 // guarantees finite positive cell widths); a raster is rebuilt for the
275 // evidence below rather than kept, so at most one is held at a time.
276 let raster = |b| crate::geometry::Raster::new(b, n, dx);
277 let mut box_cells = vec![0usize; c.geometry.len()];
278 for (b, cells) in c.geometry.iter().zip(box_cells.iter_mut()) {
279 let r = raster(b);
280 r.for_each(n, |_, i| g.fluid[i] = false);
281 *cells = r.count();
282 }
283 for (i, (b, n)) in c.geometry.iter().zip(&box_cells).enumerate() {
284 if *n == 0 {
285 let kind = if b.footprint_m.is_some() {
286 "prism"
287 } else {
288 "box"
289 };
290 return Err(format!(
291 "CFD-E028: geometry[{i}] ({kind} {}) contains no cell center, so the grid does not represent it; enlarge it or refine the grid",
292 b.id
293 ));
294 }
295 }
296 g.box_cells = c
297 .geometry
298 .iter()
299 .map(|b| b.id.clone())
300 .zip(box_cells)
301 .collect();
302 for b in &c.geometry {
303 let mut passage: Option<usize> = None;
304 raster(b).for_each(n, |q, _| {
305 for axis in 0..2 {
306 for sign in [-1isize, 1] {
307 let mut next = q.map(|v| v as isize);
308 next[axis] += sign;
309 let mut width = 0;
310 while (0..n[axis] as isize).contains(&next[axis]) {
311 let j = Self::index(n, next.map(|v| v as usize));
312 if !g.fluid[j] {
313 if width > 0 {
314 passage = Some(passage.map_or(width, |old| old.min(width)));
315 }
316 break;
317 }
318 width += 1;
319 next[axis] += sign;
320 }
321 }
322 }
323 });
324 let cells = g.box_cells[&b.id];
325 let exact = b.volume();
326 let represented = cells as f64 * volume;
327 g.shape_evidence.insert(
328 b.id.clone(),
329 ShapeEvidence {
330 solid_cells: cells,
331 exact_volume_m3: exact,
332 represented_volume_m3: represented,
333 volume_error_m3: represented - exact,
334 narrowest_fluid_passage_cells: passage,
335 },
336 );
337 }
338 if !g.fluid.iter().any(|b| *b) {
339 return Err("CFD-E030: geometry contains no fluid cells".into());
340 }
341 for a in 0..3 {
342 g.offsets[a] = g.faces.len();
343 let periodic = c.boundaries.at(a) == Boundary::Periodic;
344 if !periodic {
345 g.face_dims[a][a] += 1;
346 }
347 let dims = g.face_dims[a];
348 for k in 0..dims[2] {
349 for j in 0..dims[1] {
350 for i in 0..dims[0] {
351 let q = [i, j, k];
352 let t = q[a];
353 let lo0 = if t > 0 {
354 let mut p = q;
355 p[a] -= 1;
356 Some(Self::index(n, p))
357 } else if periodic {
358 let mut p = q;
359 p[a] = n[a] - 1;
360 Some(Self::index(n, p))
361 } else {
362 None
363 };
364 let hi0 = if t < n[a] {
365 Some(Self::index(n, q))
366 } else {
367 None
368 };
369 let lo = lo0.filter(|x| g.fluid[*x]);
370 let hi = hi0.filter(|x| g.fluid[*x]);
371 let center = std::array::from_fn(|d| {
372 (q[d] as f64 + if d == a { 0.0 } else { 0.5 }) * dx[d]
373 });
374 let kind = if lo.is_some() && hi.is_some() {
375 FaceKind::Interior
376 } else if lo.is_none() && hi.is_none() {
377 FaceKind::Blocked
378 } else if lo0.is_some() && hi0.is_some() {
379 FaceKind::Wall
380 } else {
381 match c.boundaries.at(a) {
382 Boundary::Wall => FaceKind::Wall,
383 Boundary::Slip => FaceKind::Slip,
384 Boundary::GroundOpenTop => {
385 if t == 0 {
386 FaceKind::Wall
387 } else {
388 FaceKind::Slip
389 }
390 }
391 Boundary::Open => {
392 let normal = if t == 0 { -1.0 } else { 1.0 };
393 let v = c.flow.vector(center[2])[a] * normal;
394 if v < -1e-12 {
395 FaceKind::Inlet
396 } else if v > 1e-12 {
397 FaceKind::Outlet
398 } else {
399 FaceKind::Slip
400 }
401 }
402 Boundary::Periodic => unreachable!(),
403 }
404 };
405 let f = g.faces.len();
406 if let Some(x) = lo {
407 g.cell_faces[x][a][1] = f;
408 }
409 if let Some(x) = hi {
410 g.cell_faces[x][a][0] = f;
411 }
412 g.faces.push(Face {
413 axis: a,
414 coord: q,
415 center,
416 lo,
417 hi,
418 kind,
419 area: volume / dx[a],
420 distance: if kind == FaceKind::Interior {
421 dx[a]
422 } else {
423 0.5 * dx[a]
424 },
425 });
426 }
427 }
428 }
429 }
430 for start in 0..count {
431 if !g.fluid[start] || g.component[start] != usize::MAX {
432 continue;
433 }
434 let id = g.components.len();
435 let mut members = vec![];
436 let mut queue = VecDeque::from([start]);
437 g.component[start] = id;
438 let mut anchored = false;
439 while let Some(i) = queue.pop_front() {
440 members.push(i);
441 for pair in g.cell_faces[i] {
442 for fi in pair {
443 let f = &g.faces[fi];
444 anchored |= f.kind == FaceKind::Outlet;
445 if f.kind != FaceKind::Interior {
446 continue;
447 }
448 let j = if f.lo == Some(i) {
449 f.hi.unwrap()
450 } else {
451 f.lo.unwrap()
452 };
453 if g.component[j] == usize::MAX {
454 g.component[j] = id;
455 queue.push_back(j);
456 }
457 }
458 }
459 }
460 g.components.push(members);
461 g.anchored.push(anchored);
462 }
463 Ok(g)
464 }
465 /// Fluid-component and solid-cell counts of the case's grid, computed from the cell
466 /// mask with a union-find over 4 bytes per cell, without building faces or the pressure
467 /// operator. Cells connect through shared faces, including periodic wraps, as in
468 /// [`Grid::build`]. Needs only valid axes (2..4096 cells, or 1..4096 on a
469 /// periodic axis, at most 1e8 in total).
470 pub fn mask_topology(c: &Case) -> Result<MaskTopology> {
471 let n = c.grid.cells;
472 let count = n.iter().try_fold(1usize, |p, v| p.checked_mul(*v));
473 let valid = (0..3).all(|a| {
474 let minimum = if c.boundaries.at(a) == Boundary::Periodic {
475 1
476 } else {
477 2
478 };
479 (minimum..=4096).contains(&n[a])
480 });
481 let count = match count {
482 Some(v) if valid && v <= 100_000_000 => v,
483 _ => {
484 return Err(
485 "the grid needs 2..4096 cells per axis (1..4096 on a periodic axis) and at most 1e8 cells"
486 .into(),
487 );
488 }
489 };
490 const SOLID: u32 = u32::MAX;
491 let dx: [f64; 3] = std::array::from_fn(|a| c.domain.size_m[a] / n[a] as f64);
492 let mut parent: Vec<u32> = (0..count as u32).collect();
493 let mut solid_cells = 0usize;
494 crate::geometry::for_each_solid(c, |i| {
495 if parent[i] != SOLID {
496 parent[i] = SOLID;
497 solid_cells += 1;
498 }
499 });
500 fn root(parent: &mut [u32], mut i: u32) -> u32 {
501 while parent[i as usize] != i {
502 let up = parent[parent[i as usize] as usize];
503 parent[i as usize] = up;
504 i = up;
505 }
506 i
507 }
508 for i in 0..count {
509 if parent[i] == SOLID {
510 continue;
511 }
512 let q = [i % n[0], i / n[0] % n[1], i / (n[0] * n[1])];
513 for a in 0..3 {
514 let lo = if q[a] > 0 {
515 q[a] - 1
516 } else if c.boundaries.at(a) == Boundary::Periodic {
517 n[a] - 1
518 } else {
519 continue;
520 };
521 let mut p = q;
522 p[a] = lo;
523 let j = Self::index(n, p);
524 if parent[j] == SOLID {
525 continue;
526 }
527 let (ri, rj) = (root(&mut parent, i as u32), root(&mut parent, j as u32));
528 if ri != rj {
529 parent[ri.max(rj) as usize] = ri.min(rj);
530 }
531 }
532 }
533 let fluid_components = (0..count)
534 .filter(|i| parent[*i] != SOLID && root(&mut parent, *i as u32) == *i as u32)
535 .count();
536 Ok(MaskTopology {
537 fluid_components,
538 solid_cells,
539 solid_volume_m3: solid_cells as f64 * dx.iter().product::<f64>(),
540 })
541 }
542 /// The geometry evidence of this grid, as written to geometry.json.
543 pub fn evidence(&self) -> GeometryEvidence {
544 let fluid_cells = self.fluid.iter().filter(|v| **v).count();
545 GeometryEvidence {
546 fluid_cells,
547 solid_cells: self.count() - fluid_cells,
548 fluid_components: self.components.len(),
549 solid_volume_m3: (self.count() - fluid_cells) as f64 * self.volume,
550 mask_sha256: hash_bytes(&self.fluid.iter().map(|v| u8::from(*v)).collect::<Vec<_>>()),
551 box_cells: self.box_cells.clone(),
552 shapes: self.shape_evidence.clone(),
553 }
554 }
555 /// The same-axis neighbors of every face in direction d and side (lower,
556 /// upper), as `face_at` finds them; built once per grid.
557 pub(crate) fn neighbor_faces(&self, c: &Case) -> &[[[Option<usize>; 2]; 3]] {
558 self.neighbor_faces.get_or_init(|| {
559 self.faces
560 .iter()
561 .map(|f| {
562 std::array::from_fn(|d| {
563 std::array::from_fn(|side| {
564 let mut q = f.coord.map(|v| v as isize);
565 q[d] += if side == 0 { -1 } else { 1 };
566 self.face_at(c, f.axis, q)
567 })
568 })
569 })
570 .collect()
571 })
572 }
573 /// For every a-face at q and direction d ≠ a, the two d-faces whose mean
574 /// advects through the momentum control-volume edge above it: the d-faces
575 /// at q + e_d and q + e_d − e_a, as `face_at` finds them; built once.
576 pub(crate) fn edge_faces(&self, c: &Case) -> &[[[Option<usize>; 2]; 3]] {
577 self.edge_faces.get_or_init(|| {
578 self.faces
579 .iter()
580 .map(|f| {
581 std::array::from_fn(|d| {
582 if d == f.axis {
583 return [None; 2];
584 }
585 let mut q = f.coord.map(|v| v as isize);
586 q[d] += 1;
587 let upper = self.face_at(c, d, q);
588 q[f.axis] -= 1;
589 [upper, self.face_at(c, d, q)]
590 })
591 })
592 .collect()
593 })
594 }
595 /// Index in `faces` of the axis-`a` face at integer position `q` of that
596 /// axis's face array. Periodic axes wrap; a position outside a
597 /// nonperiodic face array is `None`. `c` must be the case the grid was
598 /// built from.
599 pub fn face_at(&self, c: &Case, a: usize, mut q: [isize; 3]) -> Option<usize> {
600 for (d, qd) in q.iter_mut().enumerate() {
601 if c.boundaries.at(d) == Boundary::Periodic {
602 *qd = qd.rem_euclid(self.n[d] as isize);
603 } else if *qd < 0 || *qd >= self.face_dims[a][d] as isize {
604 return None;
605 }
606 }
607 Some(self.offsets[a] + Self::index(self.face_dims[a], q.map(|v| v as usize)))
608 }
609 /// Discrete divergence of the face velocities `u` (one per face) in 1/s,
610 /// per cell; zero for solid cells. The same definition is used by the
611 /// pressure operator and the continuity checks.
612 pub fn divergence(&self, u: &[f64]) -> Vec<f64> {
613 (0..self.count())
614 .map(|i| {
615 if self.fluid[i] {
616 (0..3)
617 .map(|a| {
618 let [lo, hi] = self.cell_faces[i][a];
619 (u[hi] - u[lo]) / self.dx[a]
620 })
621 .sum()
622 } else {
623 0.0
624 }
625 })
626 .collect()
627 }
628 /// Cell-centered velocity in m/s: per axis the mean of the cell's two
629 /// face velocities; zero for solid cells. Prefer it to reshaping the
630 /// face arrays by hand.
631 pub fn cell_velocity(&self, u: &[f64]) -> Vec<[f64; 3]> {
632 (0..self.count())
633 .map(|i| {
634 if self.fluid[i] {
635 std::array::from_fn(|a| {
636 let [lo, hi] = self.cell_faces[i][a];
637 0.5 * (u[lo] + u[hi])
638 })
639 } else {
640 [0.0; 3]
641 }
642 })
643 .collect()
644 }
645 /// Face-normal gradient of the cell field `p`, per face: the difference
646 /// across interior faces over `distance`, the difference to a zero value
647 /// outside an outlet, and zero on every other face. Its negated
648 /// [`divergence`](Self::divergence) is the operator of
649 /// [`pressure::apply`](crate::pressure::apply).
650 pub fn gradient(&self, p: &[f64]) -> Vec<f64> {
651 self.faces
652 .iter()
653 .map(|f| match f.kind {
654 FaceKind::Interior => (p[f.hi.unwrap()] - p[f.lo.unwrap()]) / f.distance,
655 FaceKind::Outlet => {
656 if let Some(i) = f.lo {
657 -p[i] / f.distance
658 } else {
659 p[f.hi.unwrap()] / f.distance
660 }
661 }
662 _ => 0.0,
663 })
664 .collect()
665 }
666 /// Initial face velocities from [`Flow::vector`] at each face center;
667 /// zero on wall, slip and blocked faces.
668 pub fn initial_velocity(&self, c: &Case) -> Vec<f64> {
669 self.faces
670 .iter()
671 .map(|f| {
672 if matches!(f.kind, FaceKind::Wall | FaceKind::Slip | FaceKind::Blocked) {
673 0.0
674 } else {
675 c.flow.vector(f.center[2])[f.axis]
676 }
677 })
678 .collect()
679 }
680 /// Reapplies the fixed face velocities in place: zero on wall, slip and
681 /// blocked faces and the case inflow on inlet faces. Interior and outlet
682 /// faces are left unchanged.
683 pub fn enforce_velocity(&self, c: &Case, u: &mut [f64]) {
684 for (v, f) in u.iter_mut().zip(&self.faces) {
685 match f.kind {
686 FaceKind::Wall | FaceKind::Slip | FaceKind::Blocked => *v = 0.0,
687 FaceKind::Inlet => *v = c.flow.vector(f.center[2])[f.axis],
688 _ => {}
689 }
690 }
691 }
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697 use crate::case::CONTAINS_CALLS;
698 fn calls() -> usize {
699 CONTAINS_CALLS.with(|c| c.replace(0))
700 }
701 /// Boxes and polygon prisms with bounds and edges on cell centers, in
702 /// both windings and overlapping, on a grid of cell width 0.3 m.
703 fn case() -> Case {
704 let mut c: Case =
705 serde_json::from_str(include_str!("../../../cases/verification/lid-cavity.json"))
706 .unwrap();
707 c.moving_walls.clear();
708 c.grid.cells = [48, 40, 12];
709 c.domain.size_m = [14.4, 12.0, 3.6];
710 c.geometry_min_passage_cells = Some(2);
711 let dx = 0.3;
712 let at = |q: usize| (q as f64 + 0.5) * dx;
713 let mut seed = 12345u64;
714 let mut next = |m: usize| {
715 seed = seed
716 .wrapping_mul(6364136223846793005)
717 .wrapping_add(1442695040888963407);
718 (seed >> 33) as usize % m
719 };
720 let mut k = 0;
721 while c.geometry.len() < 160 {
722 let (i, j) = (next(37), next(29));
723 let (w, h, top) = (1 + next(5), 1 + next(5), at(1 + next(8)));
724 let footprint = match k % 4 {
725 0 => None,
726 1 => Some(vec![[at(i), at(j)], [at(i + w), at(j)], [at(i), at(j + h)]]),
727 2 => Some(vec![
728 [at(i + w), at(j)],
729 [at(i + 2 * w), at(j + w)],
730 [at(i + w), at(j + 2 * w)],
731 [at(i), at(j + w)],
732 ]),
733 _ => Some(vec![
734 [at(i), at(j + h)],
735 [at(i + 2 * w), at(j + h)],
736 [at(i + w), at(j)],
737 ]),
738 };
739 let (lo, hi) = match &footprint {
740 None if k % 8 == 0 => ([at(i), at(j), 0.0], [at(i + w), at(j + h), top]),
741 None => (
742 [i as f64 * dx + 0.07, j as f64 * dx, 0.0],
743 [(i + w) as f64 * dx + 0.11, (j + h) as f64 * dx, top],
744 ),
745 Some(p) => {
746 let lo = [0, 1].map(|d| p.iter().map(|v| v[d]).fold(f64::INFINITY, f64::min));
747 let hi =
748 [0, 1].map(|d| p.iter().map(|v| v[d]).fold(f64::NEG_INFINITY, f64::max));
749 ([lo[0], lo[1], 0.0], [hi[0], hi[1], top])
750 }
751 };
752 let mut b = Block {
753 id: format!("s{k}"),
754 min_m: lo,
755 max_m: hi,
756 footprint_m: footprint,
757 };
758 if k % 3 == 0
759 && let Some(p) = &mut b.footprint_m
760 {
761 p.reverse();
762 }
763 k += 1;
764 // Every shape must contain a cell center (CFD-E028).
765 let represented = (0..48 * 40 * 12).any(|i| {
766 let p = [i % 48, i / 48 % 40, i / 1920].map(|v| (v as f64 + 0.5) * dx);
767 b.contains(p)
768 });
769 if represented {
770 c.geometry.push(b);
771 }
772 }
773 c
774 }
775 #[test]
776 fn shape_masks_and_evidence_cost_the_bounding_boxes_not_the_grid() {
777 let c = case();
778 calls();
779 let g = Grid::build(&c).unwrap();
780 let build_calls = calls();
781 // Reference: every shape against every cell center, as before the
782 // rasterization, with the per-shape passage walk.
783 let n = g.n;
784 let inside: Vec<Vec<bool>> = c
785 .geometry
786 .iter()
787 .map(|b| (0..g.count()).map(|i| b.contains(g.center(i))).collect())
788 .collect();
789 let brute_calls = calls();
790 let fluid: Vec<bool> = (0..g.count())
791 .map(|i| inside.iter().all(|s| !s[i]))
792 .collect();
793 assert_eq!(g.fluid, fluid);
794 assert!(fluid.iter().any(|v| *v) && fluid.iter().any(|v| !*v));
795 let mut polygon_cells = 0;
796 for (b, s) in c.geometry.iter().zip(&inside) {
797 let mut passage: Option<usize> = None;
798 for i in (0..g.count()).filter(|i| s[*i]) {
799 let q = g.coord(i).map(|v| v as isize);
800 for axis in 0..2 {
801 for sign in [-1, 1] {
802 let mut p = q;
803 p[axis] += sign;
804 let mut width = 0;
805 while (0..n[axis] as isize).contains(&p[axis]) {
806 if !fluid[Grid::index(n, p.map(|v| v as usize))] {
807 if width > 0 {
808 passage = Some(passage.map_or(width, |o| o.min(width)));
809 }
810 break;
811 }
812 width += 1;
813 p[axis] += sign;
814 }
815 }
816 }
817 }
818 let cells = s.iter().filter(|v| **v).count();
819 polygon_cells += cells * usize::from(b.footprint_m.is_some());
820 assert_eq!(g.box_cells[&b.id], cells, "{}", b.id);
821 let e = &g.shape_evidence[&b.id];
822 assert_eq!(
823 (e.solid_cells, e.narrowest_fluid_passage_cells),
824 (cells, passage)
825 );
826 }
827 assert!(polygon_cells > 100);
828 let mut minimum: Option<usize> = None;
829 for k in 0..n[2] {
830 for a in 0..2 {
831 for j in 0..n[1 - a] {
832 let (mut after_solid, mut width) = (false, 0);
833 for i in 0..n[a] {
834 let mut q = [0, 0, k];
835 (q[a], q[1 - a]) = (i, j);
836 if fluid[Grid::index(n, q)] {
837 width += 1;
838 } else {
839 if after_solid && width > 0 {
840 minimum = Some(minimum.map_or(width, |o| o.min(width)));
841 }
842 (after_solid, width) = (true, 0);
843 }
844 }
845 }
846 }
847 }
848 calls();
849 assert_eq!(crate::geometry::minimum_passage(&c), minimum);
850 let passage_calls = calls();
851 let topology = Grid::mask_topology(&c).unwrap();
852 let topology_calls = calls();
853 assert_eq!(
854 topology.solid_cells,
855 g.count() - fluid.iter().filter(|v| **v).count()
856 );
857 // Point-in-shape tests: one per column of each shape's bounding box,
858 // not one per cell and shape. `build` rasterizes twice (mask and
859 // evidence) after validation ran minimum_passage once.
860 let dx = g.dx;
861 let columns: usize = c
862 .geometry
863 .iter()
864 .map(|b| {
865 (0..2)
866 .map(|a| ((b.max_m[a] - b.min_m[a]) / dx[a]).floor() as usize + 1)
867 .product::<usize>()
868 })
869 .sum();
870 assert_eq!(brute_calls, c.geometry.len() * g.count());
871 assert!(build_calls <= 3 * columns, "{build_calls} > 3 x {columns}");
872 assert!(
873 100 * build_calls < brute_calls,
874 "{build_calls} {brute_calls}"
875 );
876 assert!(passage_calls <= columns, "{passage_calls} > {columns}");
877 assert!(topology_calls <= columns, "{topology_calls} > {columns}");
878 }
879 #[test]
880 fn masks_of_an_invalid_domain_still_test_every_cell() {
881 // Negative cell widths make centers decrease with the index, so no
882 // index range selects a shape. The case check still evaluates the
883 // passage, so the mask falls back to testing all cells.
884 let mut c = case();
885 c.domain.size_m[0] = -14.4;
886 for b in &mut c.geometry {
887 (b.min_m[0], b.max_m[0]) = (-b.max_m[0], -b.min_m[0]);
888 for v in b.footprint_m.iter_mut().flatten() {
889 v[0] = -v[0];
890 }
891 }
892 let n = c.grid.cells;
893 let dx: [f64; 3] = std::array::from_fn(|a| c.domain.size_m[a] / n[a] as f64);
894 let solid = |q: [usize; 3]| {
895 let p = std::array::from_fn(|d| (q[d] as f64 + 0.5) * dx[d]);
896 c.geometry.iter().any(|b| b.contains(p))
897 };
898 let mut minimum: Option<usize> = None;
899 for k in 0..n[2] {
900 for a in 0..2 {
901 for j in 0..n[1 - a] {
902 let (mut after_solid, mut width) = (false, 0);
903 for i in 0..n[a] {
904 let mut q = [0, 0, k];
905 (q[a], q[1 - a]) = (i, j);
906 if solid(q) {
907 if after_solid && width > 0 {
908 minimum = Some(minimum.map_or(width, |o| o.min(width)));
909 }
910 (after_solid, width) = (true, 0);
911 } else {
912 width += 1;
913 }
914 }
915 }
916 }
917 }
918 assert!(minimum.is_some());
919 assert_eq!(crate::geometry::minimum_passage(&c), minimum);
920 let solid_cells = (0..n.iter().product())
921 .filter(|i| solid([i % n[0], i / n[0] % n[1], i / (n[0] * n[1])]))
922 .count();
923 assert!(solid_cells > 1000);
924 assert_eq!(Grid::mask_topology(&c).unwrap().solid_cells, solid_cells);
925 assert!(c.check().diagnostics.iter().any(|d| d.code == "CFD-E003"));
926 }
927}