use crate::{Result, case::*};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, VecDeque};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FaceKind {
Interior,
Wall,
Slip,
Inlet,
Outlet,
Blocked,
}
#[derive(Clone, Debug)]
pub struct Face {
pub axis: usize,
pub coord: [usize; 3],
pub center: [f64; 3],
pub lo: Option<usize>,
pub hi: Option<usize>,
pub kind: FaceKind,
pub area: f64,
pub distance: f64,
}
#[derive(Clone, Debug)]
pub struct Grid {
pub n: [usize; 3],
pub dx: [f64; 3],
pub volume: f64,
pub fluid: Vec<bool>,
pub faces: Vec<Face>,
pub cell_faces: Vec<[[usize; 2]; 3]>,
pub component: Vec<usize>,
pub components: Vec<Vec<usize>>,
pub anchored: Vec<bool>,
pub face_dims: [[usize; 3]; 3],
offsets: [usize; 3],
pub box_cells: BTreeMap<String, usize>,
pub shape_evidence: BTreeMap<String, ShapeEvidence>,
pub pressure_factor: std::sync::OnceLock<crate::pressure::Factor>,
pub pressure_preconditioner: PressurePreconditioner,
pub(crate) pressure_multigrid: std::sync::Arc<crate::multigrid::Cache>,
pub(crate) momentum_stencil: std::sync::OnceLock<crate::momentum_solve::Stencil>,
pub(crate) neighbor_faces: std::sync::OnceLock<Vec<[[Option<usize>; 2]; 3]>>,
pub(crate) edge_faces: std::sync::OnceLock<Vec<[[Option<usize>; 2]; 3]>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GeometryEvidence {
pub fluid_cells: usize,
pub solid_cells: usize,
pub fluid_components: usize,
pub solid_volume_m3: f64,
pub mask_sha256: String,
pub box_cells: BTreeMap<String, usize>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub shapes: BTreeMap<String, ShapeEvidence>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ShapeEvidence {
pub solid_cells: usize,
pub exact_volume_m3: f64,
pub represented_volume_m3: f64,
pub volume_error_m3: f64,
pub narrowest_fluid_passage_cells: Option<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MaskTopology {
pub fluid_components: usize,
pub solid_cells: usize,
pub solid_volume_m3: f64,
}
impl Grid {
pub fn count(&self) -> usize {
self.fluid.len()
}
pub fn index(n: [usize; 3], p: [usize; 3]) -> usize {
(p[2] * n[1] + p[1]) * n[0] + p[0]
}
pub fn coord(&self, i: usize) -> [usize; 3] {
[
i % self.n[0],
i / self.n[0] % self.n[1],
i / (self.n[0] * self.n[1]),
]
}
pub fn center(&self, i: usize) -> [f64; 3] {
let q = self.coord(i);
std::array::from_fn(|a| (q[a] as f64 + 0.5) * self.dx[a])
}
pub fn build(c: &Case) -> Result<Self> {
c.validate()?;
let n = c.grid.cells;
let dx = std::array::from_fn(|a| c.domain.size_m[a] / n[a] as f64);
let volume = dx.iter().product();
let count = n.iter().product();
let mut g = Self {
n,
dx,
volume,
fluid: vec![true; count],
faces: vec![],
cell_faces: vec![[[usize::MAX; 2]; 3]; count],
component: vec![usize::MAX; count],
components: vec![],
anchored: vec![],
face_dims: [n; 3],
offsets: [0; 3],
box_cells: BTreeMap::new(),
shape_evidence: BTreeMap::new(),
pressure_factor: std::sync::OnceLock::new(),
pressure_preconditioner: c.numerics.pressure_preconditioner,
pressure_multigrid: Default::default(),
momentum_stencil: std::sync::OnceLock::new(),
neighbor_faces: std::sync::OnceLock::new(),
edge_faces: std::sync::OnceLock::new(),
};
let raster = |b| crate::geometry::Raster::new(b, n, dx);
let mut box_cells = vec![0usize; c.geometry.len()];
for (b, cells) in c.geometry.iter().zip(box_cells.iter_mut()) {
let r = raster(b);
r.for_each(n, |_, i| g.fluid[i] = false);
*cells = r.count();
}
for (i, (b, n)) in c.geometry.iter().zip(&box_cells).enumerate() {
if *n == 0 {
let kind = if b.footprint_m.is_some() {
"prism"
} else {
"box"
};
return Err(format!(
"CFD-E028: geometry[{i}] ({kind} {}) contains no cell center, so the grid does not represent it; enlarge it or refine the grid",
b.id
));
}
}
g.box_cells = c
.geometry
.iter()
.map(|b| b.id.clone())
.zip(box_cells)
.collect();
for b in &c.geometry {
let mut passage: Option<usize> = None;
raster(b).for_each(n, |q, _| {
for axis in 0..2 {
for sign in [-1isize, 1] {
let mut next = q.map(|v| v as isize);
next[axis] += sign;
let mut width = 0;
while (0..n[axis] as isize).contains(&next[axis]) {
let j = Self::index(n, next.map(|v| v as usize));
if !g.fluid[j] {
if width > 0 {
passage = Some(passage.map_or(width, |old| old.min(width)));
}
break;
}
width += 1;
next[axis] += sign;
}
}
}
});
let cells = g.box_cells[&b.id];
let exact = b.volume();
let represented = cells as f64 * volume;
g.shape_evidence.insert(
b.id.clone(),
ShapeEvidence {
solid_cells: cells,
exact_volume_m3: exact,
represented_volume_m3: represented,
volume_error_m3: represented - exact,
narrowest_fluid_passage_cells: passage,
},
);
}
if !g.fluid.iter().any(|b| *b) {
return Err("CFD-E030: geometry contains no fluid cells".into());
}
for a in 0..3 {
g.offsets[a] = g.faces.len();
let periodic = c.boundaries.at(a) == Boundary::Periodic;
if !periodic {
g.face_dims[a][a] += 1;
}
let dims = g.face_dims[a];
for k in 0..dims[2] {
for j in 0..dims[1] {
for i in 0..dims[0] {
let q = [i, j, k];
let t = q[a];
let lo0 = if t > 0 {
let mut p = q;
p[a] -= 1;
Some(Self::index(n, p))
} else if periodic {
let mut p = q;
p[a] = n[a] - 1;
Some(Self::index(n, p))
} else {
None
};
let hi0 = if t < n[a] {
Some(Self::index(n, q))
} else {
None
};
let lo = lo0.filter(|x| g.fluid[*x]);
let hi = hi0.filter(|x| g.fluid[*x]);
let center = std::array::from_fn(|d| {
(q[d] as f64 + if d == a { 0.0 } else { 0.5 }) * dx[d]
});
let kind = if lo.is_some() && hi.is_some() {
FaceKind::Interior
} else if lo.is_none() && hi.is_none() {
FaceKind::Blocked
} else if lo0.is_some() && hi0.is_some() {
FaceKind::Wall
} else {
match c.boundaries.at(a) {
Boundary::Wall => FaceKind::Wall,
Boundary::Slip => FaceKind::Slip,
Boundary::GroundOpenTop => {
if t == 0 {
FaceKind::Wall
} else {
FaceKind::Slip
}
}
Boundary::Open => {
let normal = if t == 0 { -1.0 } else { 1.0 };
let v = c.flow.vector(center[2])[a] * normal;
if v < -1e-12 {
FaceKind::Inlet
} else if v > 1e-12 {
FaceKind::Outlet
} else {
FaceKind::Slip
}
}
Boundary::Periodic => unreachable!(),
}
};
let f = g.faces.len();
if let Some(x) = lo {
g.cell_faces[x][a][1] = f;
}
if let Some(x) = hi {
g.cell_faces[x][a][0] = f;
}
g.faces.push(Face {
axis: a,
coord: q,
center,
lo,
hi,
kind,
area: volume / dx[a],
distance: if kind == FaceKind::Interior {
dx[a]
} else {
0.5 * dx[a]
},
});
}
}
}
}
for start in 0..count {
if !g.fluid[start] || g.component[start] != usize::MAX {
continue;
}
let id = g.components.len();
let mut members = vec![];
let mut queue = VecDeque::from([start]);
g.component[start] = id;
let mut anchored = false;
while let Some(i) = queue.pop_front() {
members.push(i);
for pair in g.cell_faces[i] {
for fi in pair {
let f = &g.faces[fi];
anchored |= f.kind == FaceKind::Outlet;
if f.kind != FaceKind::Interior {
continue;
}
let j = if f.lo == Some(i) {
f.hi.unwrap()
} else {
f.lo.unwrap()
};
if g.component[j] == usize::MAX {
g.component[j] = id;
queue.push_back(j);
}
}
}
}
g.components.push(members);
g.anchored.push(anchored);
}
Ok(g)
}
pub fn mask_topology(c: &Case) -> Result<MaskTopology> {
let n = c.grid.cells;
let count = n.iter().try_fold(1usize, |p, v| p.checked_mul(*v));
let valid = (0..3).all(|a| {
let minimum = if c.boundaries.at(a) == Boundary::Periodic {
1
} else {
2
};
(minimum..=4096).contains(&n[a])
});
let count = match count {
Some(v) if valid && v <= 100_000_000 => v,
_ => {
return Err(
"the grid needs 2..4096 cells per axis (1..4096 on a periodic axis) and at most 1e8 cells"
.into(),
);
}
};
const SOLID: u32 = u32::MAX;
let dx: [f64; 3] = std::array::from_fn(|a| c.domain.size_m[a] / n[a] as f64);
let mut parent: Vec<u32> = (0..count as u32).collect();
let mut solid_cells = 0usize;
crate::geometry::for_each_solid(c, |i| {
if parent[i] != SOLID {
parent[i] = SOLID;
solid_cells += 1;
}
});
fn root(parent: &mut [u32], mut i: u32) -> u32 {
while parent[i as usize] != i {
let up = parent[parent[i as usize] as usize];
parent[i as usize] = up;
i = up;
}
i
}
for i in 0..count {
if parent[i] == SOLID {
continue;
}
let q = [i % n[0], i / n[0] % n[1], i / (n[0] * n[1])];
for a in 0..3 {
let lo = if q[a] > 0 {
q[a] - 1
} else if c.boundaries.at(a) == Boundary::Periodic {
n[a] - 1
} else {
continue;
};
let mut p = q;
p[a] = lo;
let j = Self::index(n, p);
if parent[j] == SOLID {
continue;
}
let (ri, rj) = (root(&mut parent, i as u32), root(&mut parent, j as u32));
if ri != rj {
parent[ri.max(rj) as usize] = ri.min(rj);
}
}
}
let fluid_components = (0..count)
.filter(|i| parent[*i] != SOLID && root(&mut parent, *i as u32) == *i as u32)
.count();
Ok(MaskTopology {
fluid_components,
solid_cells,
solid_volume_m3: solid_cells as f64 * dx.iter().product::<f64>(),
})
}
pub fn evidence(&self) -> GeometryEvidence {
let fluid_cells = self.fluid.iter().filter(|v| **v).count();
GeometryEvidence {
fluid_cells,
solid_cells: self.count() - fluid_cells,
fluid_components: self.components.len(),
solid_volume_m3: (self.count() - fluid_cells) as f64 * self.volume,
mask_sha256: hash_bytes(&self.fluid.iter().map(|v| u8::from(*v)).collect::<Vec<_>>()),
box_cells: self.box_cells.clone(),
shapes: self.shape_evidence.clone(),
}
}
pub(crate) fn neighbor_faces(&self, c: &Case) -> &[[[Option<usize>; 2]; 3]] {
self.neighbor_faces.get_or_init(|| {
self.faces
.iter()
.map(|f| {
std::array::from_fn(|d| {
std::array::from_fn(|side| {
let mut q = f.coord.map(|v| v as isize);
q[d] += if side == 0 { -1 } else { 1 };
self.face_at(c, f.axis, q)
})
})
})
.collect()
})
}
pub(crate) fn edge_faces(&self, c: &Case) -> &[[[Option<usize>; 2]; 3]] {
self.edge_faces.get_or_init(|| {
self.faces
.iter()
.map(|f| {
std::array::from_fn(|d| {
if d == f.axis {
return [None; 2];
}
let mut q = f.coord.map(|v| v as isize);
q[d] += 1;
let upper = self.face_at(c, d, q);
q[f.axis] -= 1;
[upper, self.face_at(c, d, q)]
})
})
.collect()
})
}
pub fn face_at(&self, c: &Case, a: usize, mut q: [isize; 3]) -> Option<usize> {
for (d, qd) in q.iter_mut().enumerate() {
if c.boundaries.at(d) == Boundary::Periodic {
*qd = qd.rem_euclid(self.n[d] as isize);
} else if *qd < 0 || *qd >= self.face_dims[a][d] as isize {
return None;
}
}
Some(self.offsets[a] + Self::index(self.face_dims[a], q.map(|v| v as usize)))
}
pub fn divergence(&self, u: &[f64]) -> Vec<f64> {
(0..self.count())
.map(|i| {
if self.fluid[i] {
(0..3)
.map(|a| {
let [lo, hi] = self.cell_faces[i][a];
(u[hi] - u[lo]) / self.dx[a]
})
.sum()
} else {
0.0
}
})
.collect()
}
pub fn cell_velocity(&self, u: &[f64]) -> Vec<[f64; 3]> {
(0..self.count())
.map(|i| {
if self.fluid[i] {
std::array::from_fn(|a| {
let [lo, hi] = self.cell_faces[i][a];
0.5 * (u[lo] + u[hi])
})
} else {
[0.0; 3]
}
})
.collect()
}
pub fn gradient(&self, p: &[f64]) -> Vec<f64> {
self.faces
.iter()
.map(|f| match f.kind {
FaceKind::Interior => (p[f.hi.unwrap()] - p[f.lo.unwrap()]) / f.distance,
FaceKind::Outlet => {
if let Some(i) = f.lo {
-p[i] / f.distance
} else {
p[f.hi.unwrap()] / f.distance
}
}
_ => 0.0,
})
.collect()
}
pub fn initial_velocity(&self, c: &Case) -> Vec<f64> {
self.faces
.iter()
.map(|f| {
if matches!(f.kind, FaceKind::Wall | FaceKind::Slip | FaceKind::Blocked) {
0.0
} else {
c.flow.vector(f.center[2])[f.axis]
}
})
.collect()
}
pub fn enforce_velocity(&self, c: &Case, u: &mut [f64]) {
for (v, f) in u.iter_mut().zip(&self.faces) {
match f.kind {
FaceKind::Wall | FaceKind::Slip | FaceKind::Blocked => *v = 0.0,
FaceKind::Inlet => *v = c.flow.vector(f.center[2])[f.axis],
_ => {}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::case::CONTAINS_CALLS;
fn calls() -> usize {
CONTAINS_CALLS.with(|c| c.replace(0))
}
fn case() -> Case {
let mut c: Case =
serde_json::from_str(include_str!("../../../cases/verification/lid-cavity.json"))
.unwrap();
c.moving_walls.clear();
c.grid.cells = [48, 40, 12];
c.domain.size_m = [14.4, 12.0, 3.6];
c.geometry_min_passage_cells = Some(2);
let dx = 0.3;
let at = |q: usize| (q as f64 + 0.5) * dx;
let mut seed = 12345u64;
let mut next = |m: usize| {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(seed >> 33) as usize % m
};
let mut k = 0;
while c.geometry.len() < 160 {
let (i, j) = (next(37), next(29));
let (w, h, top) = (1 + next(5), 1 + next(5), at(1 + next(8)));
let footprint = match k % 4 {
0 => None,
1 => Some(vec![[at(i), at(j)], [at(i + w), at(j)], [at(i), at(j + h)]]),
2 => Some(vec![
[at(i + w), at(j)],
[at(i + 2 * w), at(j + w)],
[at(i + w), at(j + 2 * w)],
[at(i), at(j + w)],
]),
_ => Some(vec![
[at(i), at(j + h)],
[at(i + 2 * w), at(j + h)],
[at(i + w), at(j)],
]),
};
let (lo, hi) = match &footprint {
None if k % 8 == 0 => ([at(i), at(j), 0.0], [at(i + w), at(j + h), top]),
None => (
[i as f64 * dx + 0.07, j as f64 * dx, 0.0],
[(i + w) as f64 * dx + 0.11, (j + h) as f64 * dx, top],
),
Some(p) => {
let lo = [0, 1].map(|d| p.iter().map(|v| v[d]).fold(f64::INFINITY, f64::min));
let hi =
[0, 1].map(|d| p.iter().map(|v| v[d]).fold(f64::NEG_INFINITY, f64::max));
([lo[0], lo[1], 0.0], [hi[0], hi[1], top])
}
};
let mut b = Block {
id: format!("s{k}"),
min_m: lo,
max_m: hi,
footprint_m: footprint,
};
if k % 3 == 0
&& let Some(p) = &mut b.footprint_m
{
p.reverse();
}
k += 1;
let represented = (0..48 * 40 * 12).any(|i| {
let p = [i % 48, i / 48 % 40, i / 1920].map(|v| (v as f64 + 0.5) * dx);
b.contains(p)
});
if represented {
c.geometry.push(b);
}
}
c
}
#[test]
fn shape_masks_and_evidence_cost_the_bounding_boxes_not_the_grid() {
let c = case();
calls();
let g = Grid::build(&c).unwrap();
let build_calls = calls();
let n = g.n;
let inside: Vec<Vec<bool>> = c
.geometry
.iter()
.map(|b| (0..g.count()).map(|i| b.contains(g.center(i))).collect())
.collect();
let brute_calls = calls();
let fluid: Vec<bool> = (0..g.count())
.map(|i| inside.iter().all(|s| !s[i]))
.collect();
assert_eq!(g.fluid, fluid);
assert!(fluid.iter().any(|v| *v) && fluid.iter().any(|v| !*v));
let mut polygon_cells = 0;
for (b, s) in c.geometry.iter().zip(&inside) {
let mut passage: Option<usize> = None;
for i in (0..g.count()).filter(|i| s[*i]) {
let q = g.coord(i).map(|v| v as isize);
for axis in 0..2 {
for sign in [-1, 1] {
let mut p = q;
p[axis] += sign;
let mut width = 0;
while (0..n[axis] as isize).contains(&p[axis]) {
if !fluid[Grid::index(n, p.map(|v| v as usize))] {
if width > 0 {
passage = Some(passage.map_or(width, |o| o.min(width)));
}
break;
}
width += 1;
p[axis] += sign;
}
}
}
}
let cells = s.iter().filter(|v| **v).count();
polygon_cells += cells * usize::from(b.footprint_m.is_some());
assert_eq!(g.box_cells[&b.id], cells, "{}", b.id);
let e = &g.shape_evidence[&b.id];
assert_eq!(
(e.solid_cells, e.narrowest_fluid_passage_cells),
(cells, passage)
);
}
assert!(polygon_cells > 100);
let mut minimum: Option<usize> = None;
for k in 0..n[2] {
for a in 0..2 {
for j in 0..n[1 - a] {
let (mut after_solid, mut width) = (false, 0);
for i in 0..n[a] {
let mut q = [0, 0, k];
(q[a], q[1 - a]) = (i, j);
if fluid[Grid::index(n, q)] {
width += 1;
} else {
if after_solid && width > 0 {
minimum = Some(minimum.map_or(width, |o| o.min(width)));
}
(after_solid, width) = (true, 0);
}
}
}
}
}
calls();
assert_eq!(crate::geometry::minimum_passage(&c), minimum);
let passage_calls = calls();
let topology = Grid::mask_topology(&c).unwrap();
let topology_calls = calls();
assert_eq!(
topology.solid_cells,
g.count() - fluid.iter().filter(|v| **v).count()
);
let dx = g.dx;
let columns: usize = c
.geometry
.iter()
.map(|b| {
(0..2)
.map(|a| ((b.max_m[a] - b.min_m[a]) / dx[a]).floor() as usize + 1)
.product::<usize>()
})
.sum();
assert_eq!(brute_calls, c.geometry.len() * g.count());
assert!(build_calls <= 3 * columns, "{build_calls} > 3 x {columns}");
assert!(
100 * build_calls < brute_calls,
"{build_calls} {brute_calls}"
);
assert!(passage_calls <= columns, "{passage_calls} > {columns}");
assert!(topology_calls <= columns, "{topology_calls} > {columns}");
}
#[test]
fn masks_of_an_invalid_domain_still_test_every_cell() {
let mut c = case();
c.domain.size_m[0] = -14.4;
for b in &mut c.geometry {
(b.min_m[0], b.max_m[0]) = (-b.max_m[0], -b.min_m[0]);
for v in b.footprint_m.iter_mut().flatten() {
v[0] = -v[0];
}
}
let n = c.grid.cells;
let dx: [f64; 3] = std::array::from_fn(|a| c.domain.size_m[a] / n[a] as f64);
let solid = |q: [usize; 3]| {
let p = std::array::from_fn(|d| (q[d] as f64 + 0.5) * dx[d]);
c.geometry.iter().any(|b| b.contains(p))
};
let mut minimum: Option<usize> = None;
for k in 0..n[2] {
for a in 0..2 {
for j in 0..n[1 - a] {
let (mut after_solid, mut width) = (false, 0);
for i in 0..n[a] {
let mut q = [0, 0, k];
(q[a], q[1 - a]) = (i, j);
if solid(q) {
if after_solid && width > 0 {
minimum = Some(minimum.map_or(width, |o| o.min(width)));
}
(after_solid, width) = (true, 0);
} else {
width += 1;
}
}
}
}
}
assert!(minimum.is_some());
assert_eq!(crate::geometry::minimum_passage(&c), minimum);
let solid_cells = (0..n.iter().product())
.filter(|i| solid([i % n[0], i / n[0] % n[1], i / (n[0] * n[1])]))
.count();
assert!(solid_cells > 1000);
assert_eq!(Grid::mask_topology(&c).unwrap().solid_cells, solid_cells);
assert!(c.check().diagnostics.iter().any(|d| d.code == "CFD-E003"));
}
}