Skip to main content

cfd_craft/
pressure.rs

1//! The matrix-free pressure operator, its gauges, the PCG solve and the
2//! projection.
3//!
4//! The operator is the negated divergence of the face gradient on the fluid
5//! cells (`-div(grad p)` with [`Grid::divergence`] and [`Grid::gradient`]):
6//! symmetric positive semidefinite, with outlets as zero-pressure
7//! (Dirichlet) faces. A fluid component without an outlet has a constant
8//! nullspace; it is solved in the mean-zero subspace and needs a right-hand
9//! side with zero net flux (CFD-E031). [`project`] makes face velocities
10//! discretely divergence free with the same definitions.
11//!
12//! [`solve_scaled`] runs PCG with the grid's preconditioner (cached IC(0) by
13//! default, or [multigrid](crate::multigrid)) and accepts a solution only
14//! after recomputing its residual from the face definitions. Failures are
15//! `CFD-E031` (incompatible flux), `CFD-E032` (lost positive definiteness)
16//! and `CFD-E033` (iteration limit); multigrid adds `CFD-E034` (invalid topology or weights),
17//! `CFD-E035` and `CFD-E036`. A stop requested by the
18//! [`Control`] returns its `cancelled` or
19//! `wall_time_limit`.
20use crate::{
21    Result,
22    case::PressurePreconditioner,
23    grid::{FaceKind, Grid},
24    solver::Control,
25};
26use serde::{Deserialize, Serialize};
27use std::sync::MutexGuard;
28/// Work and accuracy of one linear solve.
29#[derive(Clone, Debug, Default, Serialize, Deserialize)]
30pub struct LinearInfo {
31    /// PCG iterations; 0 for a zero right-hand side.
32    pub iterations: usize,
33    /// Recomputed residual norm relative to the norm of the compatible
34    /// right-hand side.
35    pub relative_residual: f64,
36}
37
38enum Preconditioner<'a> {
39    Ic0(&'a Factor),
40    Multigrid(MutexGuard<'a, Option<crate::multigrid::Cached>>),
41}
42impl Preconditioner<'_> {
43    fn apply(&mut self, r: &[f64], z: &mut [f64], measured: &mut crate::profiling::Span) {
44        match self {
45            Self::Ic0(factor) => factor.apply(r, z),
46            Self::Multigrid(cache) => cache.as_mut().expect("built hierarchy").hierarchy.apply(
47                r,
48                z,
49                measured.multigrid.as_mut().expect("multigrid work"),
50            ),
51        }
52        measured.preconditioner_applications += 1;
53    }
54}
55fn preconditioner<'a>(
56    g: &'a Grid,
57    control: &Control,
58    measured: &mut crate::profiling::Span,
59) -> Result<Preconditioner<'a>> {
60    match g.pressure_preconditioner {
61        PressurePreconditioner::Ic0 => {
62            Ok(Preconditioner::Ic0(g.pressure_factor.get_or_init(|| {
63                let _setup = control.span(crate::profiling::Phase::PressureFactorSetup);
64                Factor::build(g)
65            })))
66        }
67        PressurePreconditioner::Multigrid => {
68            measured.multigrid = Some(Default::default());
69            control.check()?;
70            crate::multigrid::validate(g)?;
71            // One cache owns its reusable scratch vectors. Cloned grids can share
72            // it safely; a changed operator rebuilds it before the next application.
73            let mut cache = g
74                .pressure_multigrid
75                .hierarchy
76                .lock()
77                .unwrap_or_else(|e| e.into_inner());
78            let built = !cache.as_ref().is_some_and(|c| c.signature.matches(g));
79            if built {
80                let signature = crate::multigrid::Signature::of(g)?;
81                measured.multigrid.as_mut().unwrap().hierarchy_builds = 1;
82                let _setup = control.span(crate::profiling::Phase::PressureMultigridSetup);
83                let hierarchy = crate::multigrid::Hierarchy::build(g, control)?;
84                *g.pressure_multigrid
85                    .stats
86                    .lock()
87                    .unwrap_or_else(|e| e.into_inner()) = Some(hierarchy.stats.clone());
88                *cache = Some(crate::multigrid::Cached {
89                    signature,
90                    hierarchy,
91                });
92            }
93            measured.multigrid = Some(cache.as_ref().unwrap().hierarchy.work(built));
94            Ok(Preconditioner::Multigrid(cache))
95        }
96    }
97}
98/// Current allocated hierarchy dimensions/storage; absent before its first setup.
99/// It does not wait for a running solve, so a poll callback may call it.
100pub fn multigrid_stats(g: &Grid) -> Option<crate::multigrid::MultigridStats> {
101    g.pressure_multigrid
102        .stats
103        .lock()
104        .unwrap_or_else(|e| e.into_inner())
105        .clone()
106}
107
108/// IC(0) of a slightly shifted matrix, used only as a preconditioner.
109/// The solved operator and the recomputed residual remain unshifted.
110#[derive(Clone, Debug)]
111pub struct Factor {
112    row_offsets: Vec<usize>,
113    columns: Vec<usize>,
114    lower: Vec<f64>,
115    diagonal: Vec<f64>,
116}
117impl Factor {
118    fn build(g: &Grid) -> Self {
119        // Reserve row segments with two linear face passes. A short periodic
120        // direction can connect a pair twice, so capacity and live count differ.
121        // A one-cell periodic axis gives faces that join a cell to itself; they
122        // carry no pressure difference and are not part of the operator.
123        let mut row_offsets = vec![0; g.count() + 1];
124        for f in &g.faces {
125            if f.kind == FaceKind::Interior && f.lo != f.hi {
126                let row = f.lo.unwrap().max(f.hi.unwrap());
127                row_offsets[row + 1] += 1;
128            }
129        }
130        for row in 0..g.count() {
131            row_offsets[row + 1] += row_offsets[row];
132        }
133        let capacity = row_offsets[g.count()];
134        let mut columns = vec![0; capacity];
135        let mut lower = vec![0.0; capacity];
136        let mut counts = vec![0; g.count()];
137        let mut diag = vec![0.0; g.count()];
138        for f in &g.faces {
139            let w = f.area / (f.distance * g.volume);
140            match f.kind {
141                FaceKind::Interior if f.lo == f.hi => {}
142                FaceKind::Interior => {
143                    let i = f.lo.unwrap();
144                    let j = f.hi.unwrap();
145                    diag[i] += w;
146                    diag[j] += w;
147                    let (row, col) = if i > j { (i, j) } else { (j, i) };
148                    let start = row_offsets[row];
149                    let end = start + counts[row];
150                    if let Some(offset) = (start..end).find(|&k| columns[k] == col) {
151                        lower[offset] -= w;
152                    } else {
153                        columns[end] = col;
154                        lower[end] = -w;
155                        counts[row] += 1;
156                    }
157                }
158                FaceKind::Outlet => diag[f.lo.or(f.hi).unwrap()] += w,
159                _ => {}
160            }
161        }
162        // Sort each tiny row in place, then close duplicate-capacity gaps.
163        // Diagonal and duplicate accumulation above retain the original face order.
164        let mut write = 0;
165        let mut read = 0;
166        for row in 0..g.count() {
167            let next = row_offsets[row + 1];
168            let end = read + counts[row];
169            for offset in read + 1..end {
170                let (column, value) = (columns[offset], lower[offset]);
171                let mut at = offset;
172                while at > read && columns[at - 1] > column {
173                    columns[at] = columns[at - 1];
174                    lower[at] = lower[at - 1];
175                    at -= 1;
176                }
177                columns[at] = column;
178                lower[at] = value;
179            }
180            row_offsets[row] = write;
181            for offset in read..end {
182                columns[write] = columns[offset];
183                lower[write] = lower[offset];
184                write += 1;
185            }
186            read = next;
187        }
188        row_offsets[g.count()] = write;
189        columns.truncate(write);
190        lower.truncate(write);
191        let maxdiag = diag.iter().copied().fold(1.0, f64::max);
192        for row in 0..g.count() {
193            let start = row_offsets[row];
194            let end = row_offsets[row + 1];
195            for offset in start..end {
196                let col = columns[offset];
197                let mut dot = 0.0;
198                let mut other = row_offsets[col];
199                let other_end = row_offsets[col + 1];
200                for previous in start..offset {
201                    let k = columns[previous];
202                    while other < other_end && columns[other] < k {
203                        other += 1;
204                    }
205                    if other < other_end && columns[other] == k {
206                        dot += lower[previous] * lower[other];
207                    }
208                }
209                lower[offset] = (lower[offset] - dot) / diag[col];
210            }
211            let squared = lower[start..end].iter().map(|v| v * v).sum::<f64>();
212            diag[row] = (diag[row] + 1e-6 * maxdiag - squared)
213                .max(1e-12 * maxdiag)
214                .sqrt();
215        }
216        Self {
217            row_offsets,
218            columns,
219            lower,
220            diagonal: diag,
221        }
222    }
223    fn apply(&self, r: &[f64], z: &mut [f64]) {
224        assert_eq!(r.len(), z.len());
225        for i in 0..z.len() {
226            let range = self.row_offsets[i]..self.row_offsets[i + 1];
227            let mut value = r[i];
228            for (&column, &lower) in self.columns[range.clone()].iter().zip(&self.lower[range]) {
229                value -= lower * z[column];
230            }
231            z[i] = value / self.diagonal[i];
232        }
233        for i in (0..z.len()).rev() {
234            let value = z[i] / self.diagonal[i];
235            z[i] = value;
236            let range = self.row_offsets[i]..self.row_offsets[i + 1];
237            for (&column, &lower) in self.columns[range.clone()].iter().zip(&self.lower[range]) {
238                z[column] -= lower * value;
239            }
240        }
241    }
242}
243
244// Local to one solve: Grid's public face coefficients may be changed by callers.
245// Keep the original face order, including outlets interleaved with interiors.
246enum PressureEntry {
247    Interior { lo: usize, hi: usize, weight: f64 },
248    Outlet { cell: usize, weight: f64 },
249}
250struct Operator {
251    entries: Vec<PressureEntry>,
252}
253impl Operator {
254    fn build(g: &Grid) -> Self {
255        let mut entries = Vec::with_capacity(g.faces.len());
256        entries.extend(g.faces.iter().filter_map(|f| {
257            let weight = f.area / (f.distance * g.volume);
258            match f.kind {
259                FaceKind::Interior => Some(PressureEntry::Interior {
260                    lo: f.lo.unwrap(),
261                    hi: f.hi.unwrap(),
262                    weight,
263                }),
264                FaceKind::Outlet => Some(PressureEntry::Outlet {
265                    cell: f.lo.or(f.hi).unwrap(),
266                    weight,
267                }),
268                _ => None,
269            }
270        }));
271        Self { entries }
272    }
273    fn apply(&self, x: &[f64], y: &mut [f64]) {
274        y.fill(0.0);
275        for entry in &self.entries {
276            match *entry {
277                PressureEntry::Interior { lo, hi, weight } => {
278                    let d = weight * (x[lo] - x[hi]);
279                    y[lo] += d;
280                    y[hi] -= d;
281                }
282                PressureEntry::Outlet { cell, weight } => y[cell] += weight * x[cell],
283            }
284        }
285    }
286}
287
288/// `y = A x` for the pressure operator, assembled face by face from the
289/// current grid coefficients: interior faces couple their two cells with
290/// weight `area / (distance * volume)`, outlet faces add the same weight to
291/// their cell's diagonal. Solid cells get zero. This is the independent
292/// product the solve's final residual check uses.
293pub fn apply(g: &Grid, x: &[f64], y: &mut [f64]) {
294    y.fill(0.0);
295    for f in &g.faces {
296        let w = f.area / (f.distance * g.volume);
297        match f.kind {
298            FaceKind::Interior => {
299                let i = f.lo.unwrap();
300                let j = f.hi.unwrap();
301                let d = w * (x[i] - x[j]);
302                y[i] += d;
303                y[j] -= d;
304            }
305            FaceKind::Outlet => {
306                let i = f.lo.or(f.hi).unwrap();
307                y[i] += w * x[i];
308            }
309            _ => {}
310        }
311    }
312}
313/// Subtracts the mean of `x` over each fluid component without an outlet,
314/// in place: the gauge of the pressure field. Anchored components and solid
315/// cells are unchanged.
316pub fn center_nullspaces(g: &Grid, x: &mut [f64]) {
317    for (id, m) in g.components.iter().enumerate() {
318        if !g.anchored[id] {
319            let mean = m.iter().map(|i| x[*i]).sum::<f64>() / m.len() as f64;
320            for i in m {
321                x[*i] -= mean;
322            }
323        }
324    }
325}
326/// Solves `A x = b` to the relative tolerance `tol` within `max` PCG
327/// iterations: [`solve_scaled`] without a round-off scale, so a closed
328/// component's net flux is compared with `|b|`.
329pub fn solve(
330    g: &Grid,
331    b: &[f64],
332    tol: f64,
333    max: usize,
334    control: &Control,
335) -> Result<(Vec<f64>, LinearInfo)> {
336    solve_scaled(g, b, None, tol, max, control)
337}
338/// Solves the pressure equation. A closed fluid component must have a compatible
339/// right-hand side: its net flux must be round-off relative to `roundoff_scale` (per cell,
340/// the magnitude of the terms that formed `b`) or, without a scale, relative to `|b|`.
341/// There is no absolute floor, so a small but entirely incompatible system is rejected.
342pub fn solve_scaled(
343    g: &Grid,
344    b: &[f64],
345    roundoff_scale: Option<&[f64]>,
346    tol: f64,
347    max: usize,
348    control: &Control,
349) -> Result<(Vec<f64>, LinearInfo)> {
350    let mut measured = control.span(crate::profiling::Phase::PressureSolve);
351    for (id, m) in g.components.iter().enumerate() {
352        if !g.anchored[id] {
353            let sum = m.iter().map(|i| b[*i]).sum::<f64>();
354            let scale = m
355                .iter()
356                .map(|i| b[*i].abs().max(roundoff_scale.map_or(0.0, |s| s[*i])))
357                .sum::<f64>();
358            if sum.abs() > 1e-9 * scale {
359                return Err("CFD-E031: incompatible flux in a closed fluid component".into());
360            }
361        }
362    }
363    let mut preconditioner = preconditioner(g, control, &mut measured)?;
364    let dot = |x: &[f64], y: &[f64]| x.iter().zip(y).map(|(a, b)| a * b).sum::<f64>();
365    let mut x = vec![0.0; g.count()];
366    let mut r = b.to_vec();
367    center_nullspaces(g, &mut r);
368    // A closed component is solved in its compatible mean-zero subspace.
369    // Rechecking against the unprojected round-off mean can make convergence
370    // impossible even though the Poisson equation in that subspace is solved.
371    let compatible_b = r.clone();
372    let norm = dot(&r, &r).sqrt();
373    if norm < 1e-24 {
374        return Ok((x, LinearInfo::default()));
375    }
376    let mut z = vec![0.0; g.count()];
377    preconditioner.apply(&r, &mut z, &mut measured);
378    center_nullspaces(g, &mut z);
379    let mut p = z.clone();
380    let mut rz = dot(&r, &z);
381    let mut ap = vec![0.0; g.count()];
382    let operator = {
383        let _setup = control.span(crate::profiling::Phase::PressureOperatorSetup);
384        Operator::build(g)
385    };
386    for it in 0..max {
387        if it % 8 == 0 {
388            control.check()?;
389        }
390        measured.work_units += 1;
391        operator.apply(&p, &mut ap);
392        measured.operator_applications += 1;
393        let denom = dot(&p, &ap);
394        if denom <= 0.0 || !denom.is_finite() {
395            return Err("CFD-E032: pressure CG lost positive definiteness".into());
396        }
397        let alpha = rz / denom;
398        for i in 0..g.count() {
399            x[i] += alpha * p[i];
400            r[i] -= alpha * ap[i];
401        }
402        let rel = dot(&r, &r).sqrt() / norm;
403        if rel <= tol {
404            // Recompute, do not trust only the recurrent CG residual.
405            apply(g, &x, &mut ap);
406            measured.operator_applications += 1;
407            measured.true_residual_checks += 1;
408            let true_rel = ap
409                .iter()
410                .zip(&compatible_b)
411                .map(|(a, b)| (a - b).powi(2))
412                .sum::<f64>()
413                .sqrt()
414                / norm;
415            if true_rel <= tol * 10.0 + 1e-12 {
416                center_nullspaces(g, &mut x);
417                return Ok((
418                    x,
419                    LinearInfo {
420                        iterations: it + 1,
421                        relative_residual: true_rel,
422                    },
423                ));
424            }
425        }
426        preconditioner.apply(&r, &mut z, &mut measured);
427        center_nullspaces(g, &mut z);
428        let next = dot(&r, &z);
429        let beta = next / rz;
430        for i in 0..p.len() {
431            p[i] = z[i] + beta * p[i];
432        }
433        rz = next;
434    }
435    Err(format!("CFD-E033: pressure iteration limit {max}"))
436}
437/// The projection's right-hand side, -div(u)/dt, and the per-cell magnitude of the
438/// terms it differences, sum(|u_lo| + |u_hi|)/dx/dt, which scales its round-off.
439/// Both are formed in one cell pass with the axis order of `Grid::divergence`.
440fn projection_rhs(g: &Grid, u: &[f64], dt: f64) -> (Vec<f64>, Vec<f64>) {
441    let mut b = vec![-0.0; g.count()];
442    let mut terms = vec![0.0; g.count()];
443    for i in 0..g.count() {
444        if !g.fluid[i] {
445            continue;
446        }
447        let mut divergence = 0.0;
448        let mut scale = 0.0;
449        for a in 0..3 {
450            let [lo, hi] = g.cell_faces[i][a];
451            divergence += (u[hi] - u[lo]) / g.dx[a];
452            scale += (u[lo].abs() + u[hi].abs()) / g.dx[a];
453        }
454        b[i] = -divergence / dt;
455        // Round-off scales with the terms differenced, not with their small sum.
456        terms[i] = scale / dt;
457    }
458    (b, terms)
459}
460/// Projects the face velocities `u` onto the discretely divergence-free
461/// space at time step `dt`, in place, and adds the pressure correction to
462/// `p` (then re-centers its gauge).
463///
464/// It solves `A phi = -div(u) / dt`, subtracts `dt * grad(phi)` from `u` and
465/// adds `phi` to `p`. Only interior and outlet faces change; the caller
466/// reapplies fixed boundary velocities with
467/// [`Grid::enforce_velocity`](crate::grid::Grid::enforce_velocity). Errors
468/// are those of [`solve_scaled`]; `u` and `p` are unchanged on error.
469pub fn project(
470    g: &Grid,
471    u: &mut [f64],
472    p: &mut [f64],
473    dt: f64,
474    tol: f64,
475    max: usize,
476    control: &Control,
477) -> Result<LinearInfo> {
478    let _projection = control.span(crate::profiling::Phase::PressureProjection);
479    let (b, terms) = projection_rhs(g, u, dt);
480    let (correction, info) = solve_scaled(g, &b, Some(&terms), tol, max, control)?;
481    for (v, f) in u.iter_mut().zip(&g.faces) {
482        let d = match f.kind {
483            FaceKind::Interior => {
484                (correction[f.hi.unwrap()] - correction[f.lo.unwrap()]) / f.distance
485            }
486            FaceKind::Outlet => {
487                if let Some(i) = f.lo {
488                    -correction[i] / f.distance
489                } else {
490                    correction[f.hi.unwrap()] / f.distance
491                }
492            }
493            _ => 0.0,
494        };
495        *v -= dt * d;
496    }
497    for (p, q) in p.iter_mut().zip(correction) {
498        *p += q;
499    }
500    center_nullspaces(g, p);
501    Ok(info)
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507    use crate::case::{Block, Boundary, Case, Flow};
508
509    fn case(n: [usize; 3]) -> Case {
510        let mut c: Case = serde_json::from_str(include_str!(
511            "../../../cases/verification/periodic-tracer.json"
512        ))
513        .unwrap();
514        c.grid.cells = n;
515        c.domain.size_m = n.map(|v| v as f64);
516        c.flow = Flow::Laminar {
517            initial_velocity_m_s: [0.0; 3],
518            viscosity_m2_s: 0.01,
519            acceleration_m_s2: [0.0; 3],
520        };
521        c.constituents.clear();
522        c.initial_conditions.clear();
523        c.sources.clear();
524        c.receptors.clear();
525        c
526    }
527
528    // Assemble -D G from the grid's gradient/divergence, then form a dense IC(0)
529    // reference. This does not use the factor's sparse storage or face assembly.
530    fn dense_reference(g: &Grid, rhs: &[f64]) -> Vec<f64> {
531        let n = g.count();
532        let mut a = vec![vec![0.0; n]; n];
533        for j in 0..n {
534            let mut basis = vec![0.0; n];
535            basis[j] = 1.0;
536            for (i, v) in g.divergence(&g.gradient(&basis)).into_iter().enumerate() {
537                a[i][j] = -v;
538            }
539        }
540        let maximum = (0..n).map(|i| a[i][i]).fold(1.0, f64::max);
541        let mut l = vec![vec![0.0; n]; n];
542        for i in 0..n {
543            for j in 0..i {
544                if a[i][j] != 0.0 {
545                    let dot = (0..j).map(|k| l[i][k] * l[j][k]).sum::<f64>();
546                    l[i][j] = (a[i][j] - dot) / l[j][j];
547                }
548            }
549            let squared = (0..i).map(|j| l[i][j] * l[i][j]).sum::<f64>();
550            l[i][i] = (a[i][i] + 1e-6 * maximum - squared)
551                .max(1e-12 * maximum)
552                .sqrt();
553        }
554        let mut y = vec![0.0; n];
555        for i in 0..n {
556            y[i] = (rhs[i] - (0..i).map(|j| l[i][j] * y[j]).sum::<f64>()) / l[i][i];
557        }
558        let mut x = vec![0.0; n];
559        for i in (0..n).rev() {
560            x[i] = (y[i] - (i + 1..n).map(|j| l[j][i] * x[j]).sum::<f64>()) / l[i][i];
561        }
562        x
563    }
564
565    #[test]
566    fn compact_ic0_matches_dense_reference_with_periodic_duplicates_and_triangles() {
567        for n in [[2, 3, 2], [3, 3, 3], [4, 2, 3], [3, 1, 4], [1, 3, 1]] {
568            let c = case(n);
569            let g = Grid::build(&c).unwrap();
570            let r: Vec<_> = (0..g.count()).map(|i| (0.7 * i as f64).sin()).collect();
571            let expected = dense_reference(&g, &r);
572            let factor = Factor::build(&g);
573            for seed in [0.0, 42.0] {
574                let mut z = vec![seed; g.count()];
575                factor.apply(&r, &mut z);
576                for (a, b) in z.iter().zip(&expected) {
577                    assert!((a - b).abs() <= 1e-10 * b.abs().max(1.0));
578                }
579            }
580        }
581    }
582
583    #[test]
584    fn compact_ic0_matches_dense_reference_for_masked_closed_and_outlet_components() {
585        for open in [false, true] {
586            let mut c = case([6, 3, 2]);
587            c.boundaries.x = if open { Boundary::Open } else { Boundary::Wall };
588            if let Flow::Laminar {
589                initial_velocity_m_s,
590                ..
591            } = &mut c.flow
592                && open
593            {
594                *initial_velocity_m_s = [1.0, 0.0, 0.0];
595            }
596            c.geometry.push(Block {
597                footprint_m: None,
598                id: "barrier".into(),
599                min_m: [2.0, 0.0, 0.0],
600                max_m: [3.0, 3.0, 2.0],
601            });
602            let g = Grid::build(&c).unwrap();
603            let r: Vec<_> = (0..g.count())
604                .map(|i| {
605                    if g.fluid[i] {
606                        (i as f64 * 0.73).cos()
607                    } else {
608                        0.0
609                    }
610                })
611                .collect();
612            let expected = dense_reference(&g, &r);
613            let mut actual = vec![0.0; g.count()];
614            Factor::build(&g).apply(&r, &mut actual);
615            for (a, b) in actual.iter().zip(expected) {
616                assert!((a - b).abs() <= 1e-10 * b.abs().max(1.0));
617            }
618        }
619    }
620
621    #[test]
622    fn compact_operator_retains_face_order_on_periodic_masked_and_open_grids() {
623        for periodic in [false, true] {
624            let mut c = case([6, 3, 2]);
625            if !periodic {
626                c.boundaries.x = Boundary::Open;
627                if let Flow::Laminar {
628                    initial_velocity_m_s,
629                    ..
630                } = &mut c.flow
631                {
632                    *initial_velocity_m_s = [1.0, 0.0, 0.0];
633                }
634            }
635            c.geometry.push(Block {
636                footprint_m: None,
637                id: "barrier".into(),
638                min_m: [2.0, 0.0, 0.0],
639                max_m: [3.0, 3.0, 2.0],
640            });
641            let g = Grid::build(&c).unwrap();
642            let x: Vec<_> = (0..g.count()).map(|i| (0.73 * i as f64).sin()).collect();
643            let mut raw = vec![0.0; g.count()];
644            let mut compact = vec![42.0; g.count()];
645            apply(&g, &x, &mut raw);
646            Operator::build(&g).apply(&x, &mut compact);
647            assert_eq!(raw, compact);
648        }
649    }
650
651    #[test]
652    fn compact_operator_matches_the_public_operator_bitwise_on_unequal_spacing() {
653        // Unit spacing hides a reassociated weight; this grid has three spacings.
654        for open in [false, true] {
655            let mut c = case([18, 9, 33]);
656            c.domain.size_m = [7.15, 42.45, 38.31];
657            if open {
658                c.boundaries.x = Boundary::Open;
659                if let Flow::Laminar {
660                    initial_velocity_m_s,
661                    ..
662                } = &mut c.flow
663                {
664                    *initial_velocity_m_s = [1.0, 0.0, 0.0];
665                }
666            }
667            let g = Grid::build(&c).unwrap();
668            let x: Vec<_> = (0..g.count()).map(|i| (0.73 * i as f64).sin()).collect();
669            let mut raw = vec![0.0; g.count()];
670            let mut compact = vec![0.0; g.count()];
671            apply(&g, &x, &mut raw);
672            Operator::build(&g).apply(&x, &mut compact);
673            let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
674            assert_eq!(bits(&raw), bits(&compact));
675        }
676    }
677
678    #[test]
679    fn projection_rhs_and_roundoff_scale_match_their_definitions() {
680        let mut c = case([18, 9, 33]);
681        c.domain.size_m = [7.15, 42.45, 38.31];
682        c.geometry.push(Block {
683            footprint_m: None,
684            id: "barrier".into(),
685            min_m: [2.0, 0.0, 0.0],
686            max_m: [3.0, 20.0, 15.0],
687        });
688        let g = Grid::build(&c).unwrap();
689        // Mixed signs on opposite faces make |u_lo + u_hi| differ from |u_lo| + |u_hi|.
690        let u: Vec<_> = (0..g.faces.len())
691            .map(|i| 3.0 * (0.61 * i as f64).sin() - 0.4)
692            .collect();
693        let dt = 0.125;
694        let (b, terms) = projection_rhs(&g, &u, dt);
695        let divergence = g.divergence(&u);
696        for i in 0..g.count() {
697            assert_eq!(b[i], -divergence[i] / dt);
698            let expected = if g.fluid[i] {
699                (0..3)
700                    .map(|a| {
701                        let [lo, hi] = g.cell_faces[i][a];
702                        (u[lo].abs() + u[hi].abs()) / g.dx[a]
703                    })
704                    .sum::<f64>()
705                    / dt
706            } else {
707                0.0
708            };
709            assert_eq!(terms[i].to_bits(), expected.to_bits());
710        }
711        assert!(g.fluid.iter().any(|f| !f));
712    }
713
714    #[test]
715    fn a_second_solve_uses_changed_public_face_coefficients() {
716        let mut c = case([5, 4, 3]);
717        c.boundaries.x = Boundary::Open;
718        if let Flow::Laminar {
719            initial_velocity_m_s,
720            ..
721        } = &mut c.flow
722        {
723            *initial_velocity_m_s = [1.0, 0.0, 0.0];
724        }
725        let mut g = Grid::build(&c).unwrap();
726        let exact: Vec<_> = (0..g.count()).map(|i| (0.73 * i as f64).sin()).collect();
727        for changed in [false, true] {
728            if changed {
729                // The cached factor remains an approximate preconditioner. The
730                // solved operator and independent residual must use current faces.
731                for (i, f) in g.faces.iter_mut().enumerate() {
732                    f.area *= 1.0 + (i % 7) as f64 * 0.025;
733                }
734            }
735            let mut b = vec![0.0; g.count()];
736            apply(&g, &exact, &mut b);
737            let (solved, info) = solve(&g, &b, 1e-12, 2000, &Control::new(20.0)).unwrap();
738            assert!(info.relative_residual <= 1.1e-11);
739            for (a, b) in solved.iter().zip(&exact) {
740                assert!((a - b).abs() < 1e-10);
741            }
742        }
743    }
744
745    #[test]
746    fn fused_projection_matches_composed_divergence_and_gradient() {
747        for boundary in [Boundary::Periodic, Boundary::Wall, Boundary::Open] {
748            let mut c = case([6, 3, 2]);
749            c.boundaries.x = boundary;
750            if let Flow::Laminar {
751                initial_velocity_m_s,
752                ..
753            } = &mut c.flow
754            {
755                *initial_velocity_m_s = [1.0, 0.0, 0.0];
756            }
757            c.geometry.push(Block {
758                footprint_m: None,
759                id: "barrier".into(),
760                min_m: [2.0, 0.0, 0.0],
761                max_m: [3.0, 3.0, 2.0],
762            });
763            let g = Grid::build(&c).unwrap();
764            let potential: Vec<_> = (0..g.count()).map(|i| (i as f64 * 0.37).sin()).collect();
765            // A compatible gradient perturbation works for both closed components
766            // and pressure outlets without manufacturing net inlet flux.
767            let mut u = g.gradient(&potential);
768            let mut reference_u = u.clone();
769            let mut p = vec![0.0; g.count()];
770            let dt = 0.125;
771            let b: Vec<_> = g.divergence(&u).iter().map(|x| -x / dt).collect();
772            let terms: Vec<_> = (0..g.count())
773                .map(|i| {
774                    if !g.fluid[i] {
775                        return 0.0;
776                    }
777                    (0..3)
778                        .map(|a| {
779                            let [lo, hi] = g.cell_faces[i][a];
780                            (u[lo].abs() + u[hi].abs()) / g.dx[a]
781                        })
782                        .sum::<f64>()
783                        / dt
784                })
785                .collect();
786            let (mut reference_p, reference_info) =
787                solve_scaled(&g, &b, Some(&terms), 1e-12, 2000, &Control::new(20.0)).unwrap();
788            for (v, d) in reference_u.iter_mut().zip(g.gradient(&reference_p)) {
789                *v -= dt * d;
790            }
791            center_nullspaces(&g, &mut reference_p);
792            let info = project(&g, &mut u, &mut p, dt, 1e-12, 2000, &Control::new(20.0)).unwrap();
793            assert_eq!(info.iterations, reference_info.iterations);
794            assert_eq!(info.relative_residual, reference_info.relative_residual);
795            assert_eq!(u, reference_u);
796            assert_eq!(p, reference_p);
797        }
798    }
799}