Skip to main content

cfd_craft/
multigrid.rs

1//! Fixed symmetric multigrid for the unchanged Cartesian pressure equation.
2//! This is an original implementation; no external CFD implementation is used.
3//!
4//! Selected with `numerics.pressure_preconditioner = multigrid`, it
5//! preconditions the same PCG solve as IC(0), with the same fine equation and
6//! acceptance gates. Unmasked coarse levels are Galerkin products of linear
7//! interpolation; masks use connected aggregates with one gauge per sealed
8//! component and componentwise coarse solves. strongly anisotropic spacings select exact line or small
9//! plane block smoothing and semicoarsening. The hierarchy is cached in the
10//! grid and rebuilt when the face coefficients change. The public types
11//! report its storage ([`MultigridStats`], from
12//! [`pressure::multigrid_stats`](crate::pressure::multigrid_stats)) and its
13//! work in a phase profile ([`MultigridWork`]). See the
14//! [pressure multigrid guide](https://github.com/dietmarwo/CFD-craft/blob/main/docs/developer/pressure-multigrid.md).
15use crate::{
16    Result,
17    grid::{FaceKind, Grid},
18    solver::Control,
19};
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22use std::{collections::BTreeMap, sync::Mutex};
23
24const COARSE_CELLS: usize = 32;
25const SWEEPS: usize = 2;
26mod line;
27mod masked;
28use line::BlockSmoother;
29pub use line::BlockSmootherStats;
30
31/// A weak invariant span is retained by interpolation, whereas a stiff short
32/// axis still needs line relaxation. Selection is fixed for the whole solve.
33pub(crate) fn line_axes(n: [usize; 3], dx: [f64; 3]) -> Vec<usize> {
34    let weights = dx.map(|d| 1.0 / (d * d));
35    if weights.iter().any(|w| !w.is_finite() || *w <= 0.0) {
36        return vec![];
37    }
38    let minimum = (0..3)
39        .filter(|a| n[*a] > 2)
40        .map(|a| weights[a])
41        .fold(f64::INFINITY, f64::min);
42    let maximum = weights.into_iter().fold(0.0, f64::max);
43    if maximum / minimum <= 25.0 {
44        return vec![];
45    }
46    (0..3).filter(|a| weights[*a] >= maximum / 4.0).collect()
47}
48fn zero(value: &u64) -> bool {
49    *value == 0
50}
51
52/// Retained hierarchy and scratch storage, excluding allocator overhead, the
53/// grid, outer PCG vectors and temporary hierarchy-construction storage.
54#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
55pub struct MultigridStats {
56    /// Unknowns per level, finest first; their sum relative to the first
57    /// entry is the grid complexity.
58    pub level_cells: Vec<usize>,
59    /// Cell dimensions per level, finest first; shows semicoarsening.
60    #[serde(default, skip_serializing_if = "Vec::is_empty")]
61    pub level_dimensions: Vec<[usize; 3]>,
62    /// Stored matrix entries per level, including diagonals and duplicate
63    /// fine entries; their sum relative to the first is the operator
64    /// complexity.
65    pub level_nonzeros: Vec<usize>,
66    /// Retained numeric and index storage in bytes, excluding allocator
67    /// overhead, the grid and the outer PCG vectors.
68    pub allocated_bytes: usize,
69    /// The block smoothers of anisotropic levels; empty for point smoothing.
70    #[serde(default, skip_serializing_if = "Vec::is_empty")]
71    pub block_smoothers: Vec<BlockSmootherStats>,
72}
73
74/// Attempted work, accumulated locally without timers or locks inside PCG.
75/// Hierarchy dimensions/storage are maxima, not sums over repeated solves.
76#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
77#[serde(deny_unknown_fields)]
78pub struct MultigridWork {
79    /// Hierarchy constructions (0 when a cached hierarchy was reused).
80    pub hierarchy_builds: u64,
81    /// Number of levels (maximum over the merged solves).
82    pub hierarchy_levels: u64,
83    /// Unknowns over all levels (maximum over the merged solves).
84    pub hierarchy_cells: u64,
85    /// Stored matrix entries over all levels (maximum over the merged
86    /// solves).
87    pub hierarchy_nonzeros: u64,
88    /// Retained hierarchy storage in bytes (maximum over the merged solves).
89    pub hierarchy_bytes: u64,
90    /// V-cycles applied, one per preconditioner application.
91    pub cycles: u64,
92    /// Cell updates of all smoothing sweeps, point and block.
93    pub smoothing_cell_updates: u64,
94    /// Cell updates of residual evaluations, one per cell and nonterminal
95    /// level visit.
96    pub residual_cell_updates: u64,
97    /// Cell updates of restrictions; equal to the residual updates.
98    pub restriction_cell_updates: u64,
99    /// Cell updates of prolongations; equal to the residual updates.
100    pub prolongation_cell_updates: u64,
101    /// Dense direct solves on the coarsest level, one per cycle.
102    pub coarse_solves: u64,
103    /// Cell updates of block sweeps; omitted when zero. Twice the block
104    /// level visits.
105    #[serde(default, skip_serializing_if = "zero")]
106    pub block_smoothing_cell_updates: u64,
107    /// Exact line or plane block solves; omitted when zero.
108    #[serde(default, skip_serializing_if = "zero")]
109    pub block_solves: u64,
110    /// Cells of the block-smoothed levels per visit; omitted when zero. Then
111    /// smoothing = 4 x residual - 2 x block visits.
112    #[serde(default, skip_serializing_if = "zero")]
113    pub block_level_cell_visits: u64,
114}
115impl MultigridWork {
116    pub(crate) fn merge(&mut self, other: &Self) {
117        self.hierarchy_builds += other.hierarchy_builds;
118        self.hierarchy_levels = self.hierarchy_levels.max(other.hierarchy_levels);
119        self.hierarchy_cells = self.hierarchy_cells.max(other.hierarchy_cells);
120        self.hierarchy_nonzeros = self.hierarchy_nonzeros.max(other.hierarchy_nonzeros);
121        self.hierarchy_bytes = self.hierarchy_bytes.max(other.hierarchy_bytes);
122        self.cycles += other.cycles;
123        self.smoothing_cell_updates += other.smoothing_cell_updates;
124        self.residual_cell_updates += other.residual_cell_updates;
125        self.restriction_cell_updates += other.restriction_cell_updates;
126        self.prolongation_cell_updates += other.prolongation_cell_updates;
127        self.coarse_solves += other.coarse_solves;
128        self.block_smoothing_cell_updates += other.block_smoothing_cell_updates;
129        self.block_solves += other.block_solves;
130        self.block_level_cell_visits += other.block_level_cell_visits;
131    }
132}
133
134/// The grid's multigrid state. Statistics have their own lock, so they can be
135/// read (for example from a poll callback) while a solve holds the hierarchy.
136#[derive(Debug, Default)]
137pub(crate) struct Cache {
138    pub hierarchy: Mutex<Option<Cached>>,
139    pub stats: Mutex<Option<MultigridStats>>,
140}
141
142#[derive(Debug)]
143pub(crate) struct Cached {
144    pub signature: Signature,
145    pub hierarchy: Hierarchy,
146}
147
148/// Reject an empty represented pressure space. Masks use connected aggregates.
149pub(crate) fn validate(g: &Grid) -> Result<()> {
150    if g.components.is_empty() {
151        return Err(
152            "CFD-E034: numerics.pressure_preconditioner: multigrid requires fluid cells".into(),
153        );
154    }
155    Ok(())
156}
157
158fn face_entry(g: &Grid, f: &crate::grid::Face) -> Option<(u8, usize, usize, u64)> {
159    let kind = match f.kind {
160        FaceKind::Interior => 1,
161        FaceKind::Outlet => 2,
162        _ => return None,
163    };
164    let weight = f.area / (f.distance * g.volume);
165    Some((
166        kind,
167        f.lo.unwrap_or(usize::MAX),
168        f.hi.unwrap_or(usize::MAX),
169        weight.to_bits(),
170    ))
171}
172
173/// The topology and pressure face weights a hierarchy was built from. Public face
174/// coefficients can change; each solve compares them exactly, without hashing or
175/// allocating, and rebuilds on any difference. The fine PCG operator and final
176/// residual are still built/evaluated independently.
177#[derive(Debug)]
178pub(crate) struct Signature {
179    n: [usize; 3],
180    anchored: Vec<bool>,
181    fluid: Vec<bool>,
182    spacing: [u64; 3],
183    faces: Vec<(u8, usize, usize, u64)>,
184}
185impl Signature {
186    pub(crate) fn of(g: &Grid) -> Result<Self> {
187        validate(g)?;
188        let mut faces = Vec::with_capacity(g.faces.len());
189        for f in &g.faces {
190            if let Some(entry) = face_entry(g, f) {
191                let weight = f64::from_bits(entry.3);
192                if !weight.is_finite() || weight <= 0.0 {
193                    return Err("CFD-E034: numerics.pressure_preconditioner: multigrid requires finite positive pressure face weights".into());
194                }
195                faces.push(entry);
196            }
197        }
198        Ok(Self {
199            n: g.n,
200            anchored: g.anchored.clone(),
201            fluid: g.fluid.clone(),
202            spacing: g.dx.map(f64::to_bits),
203            faces,
204        })
205    }
206    pub(crate) fn matches(&self, g: &Grid) -> bool {
207        if self.n != g.n
208            || self.anchored != g.anchored
209            || self.fluid != g.fluid
210            || self.spacing != g.dx.map(f64::to_bits)
211        {
212            return false;
213        }
214        let mut stored = self.faces.iter();
215        for entry in g.faces.iter().filter_map(|f| face_entry(g, f)) {
216            if stored.next() != Some(&entry) {
217                return false;
218            }
219        }
220        stored.next().is_none()
221    }
222}
223
224#[derive(Debug)]
225struct Matrix {
226    offsets: Vec<usize>,
227    columns: Vec<usize>,
228    values: Vec<f64>,
229    diagonal: Vec<f64>,
230}
231type Edge = (usize, usize, f64);
232impl Matrix {
233    fn build(edges: &[Edge], anchors: &[f64]) -> Self {
234        let n = anchors.len();
235        let mut offsets = vec![0; n + 1];
236        for &(i, j, _) in edges {
237            offsets[i + 1] += 1;
238            offsets[j + 1] += 1;
239        }
240        for i in 0..n {
241            offsets[i + 1] += offsets[i];
242        }
243        let mut columns = vec![0; offsets[n]];
244        let mut values = vec![0.0; offsets[n]];
245        let mut next = offsets[..n].to_vec();
246        let mut diagonal = anchors.to_vec();
247        for &(i, j, w) in edges {
248            for (row, col) in [(i, j), (j, i)] {
249                diagonal[row] += w;
250                let at = next[row];
251                columns[at] = col;
252                values[at] = -w;
253                next[row] += 1;
254            }
255        }
256        Self {
257            offsets,
258            columns,
259            values,
260            diagonal,
261        }
262    }
263    fn product(&self, x: &[f64], y: &mut [f64]) {
264        for i in 0..x.len() {
265            let mut value = self.diagonal[i] * x[i];
266            for at in self.offsets[i]..self.offsets[i + 1] {
267                value += self.values[at] * x[self.columns[at]];
268            }
269            y[i] = value;
270        }
271    }
272    fn sweep(&self, rhs: &[f64], x: &mut [f64], backward: bool) {
273        for at in 0..x.len() {
274            let i = if backward { x.len() - 1 - at } else { at };
275            let mut value = rhs[i];
276            for entry in self.offsets[i]..self.offsets[i + 1] {
277                value -= self.values[entry] * x[self.columns[entry]];
278            }
279            x[i] = value / self.diagonal[i];
280        }
281    }
282    fn allocated_bytes(&self) -> usize {
283        8 * (self.offsets.capacity()
284            + self.columns.capacity()
285            + self.values.capacity()
286            + self.diagonal.capacity())
287    }
288}
289
290#[derive(Debug, Default)]
291struct Transfer {
292    offsets: Vec<usize>,
293    columns: Vec<usize>,
294    weights: Vec<f64>,
295}
296fn axis_weights(x: f64, centers: &[f64], periodic: bool, extent: f64) -> Vec<(usize, f64)> {
297    let n = centers.len();
298    if n == 1 {
299        return vec![(0, 1.0)];
300    }
301    let hi = centers.partition_point(|v| *v < x);
302    let (lo, hi, left, right) = if hi == 0 {
303        if !periodic {
304            return vec![(0, 1.0)];
305        }
306        (n - 1, 0, centers[n - 1] - extent, centers[0])
307    } else if hi == n {
308        if !periodic {
309            return vec![(n - 1, 1.0)];
310        }
311        (n - 1, 0, centers[n - 1], centers[0] + extent)
312    } else {
313        (hi - 1, hi, centers[hi - 1], centers[hi])
314    };
315    let t = (x - left) / (right - left);
316    [(lo, 1.0 - t), (hi, t)]
317        .into_iter()
318        .filter(|(_, w)| *w != 0.0)
319        .collect()
320}
321impl Transfer {
322    fn build(
323        n: [usize; 3],
324        centers: &[Vec<f64>; 3],
325        periodic: [bool; 3],
326        extent: [f64; 3],
327    ) -> (Self, [Vec<f64>; 3]) {
328        Self::build_selected(n, centers, periodic, extent, n.map(|v| v > 2))
329    }
330    fn build_selected(
331        n: [usize; 3],
332        centers: &[Vec<f64>; 3],
333        periodic: [bool; 3],
334        extent: [f64; 3],
335        coarsen: [bool; 3],
336    ) -> (Self, [Vec<f64>; 3]) {
337        let coarse: [Vec<f64>; 3] = std::array::from_fn(|a| {
338            centers[a]
339                .chunks(if coarsen[a] { 2 } else { 1 })
340                .map(|s| s.iter().sum::<f64>() / s.len() as f64)
341                .collect()
342        });
343        let nc = coarse.each_ref().map(|v| v.len());
344        let weights: [Vec<_>; 3] = std::array::from_fn(|a| {
345            centers[a]
346                .iter()
347                .map(|x| axis_weights(*x, &coarse[a], periodic[a], extent[a]))
348                .collect()
349        });
350        let mut p = Self::default();
351        let mut row = Vec::with_capacity(8);
352        p.offsets.push(0);
353        for i in 0..n.iter().product() {
354            let q = [i % n[0], i / n[0] % n[1], i / (n[0] * n[1])];
355            row.clear();
356            for &(z, wz) in &weights[2][q[2]] {
357                for &(y, wy) in &weights[1][q[1]] {
358                    for &(x, wx) in &weights[0][q[0]] {
359                        row.push((Grid::index(nc, [x, y, z]), wx * wy * wz));
360                    }
361                }
362            }
363            row.sort_unstable_by_key(|v| v.0);
364            for &(j, w) in &row {
365                p.columns.push(j);
366                p.weights.push(w);
367            }
368            p.offsets.push(p.columns.len());
369        }
370        (p, coarse)
371    }
372    fn row(&self, i: usize) -> impl Iterator<Item = (usize, f64)> + '_ {
373        let range = self.offsets[i]..self.offsets[i + 1];
374        self.columns[range.clone()]
375            .iter()
376            .copied()
377            .zip(self.weights[range].iter().copied())
378    }
379    fn galerkin(&self, edges: &[Edge], anchors: &[f64], nc: usize) -> (Vec<Edge>, Vec<f64>) {
380        let mut off = BTreeMap::new();
381        let mut delta = Vec::with_capacity(16);
382        // Assemble symmetric off-diagonals from edge energies w(P_i-P_j)^2.
383        // Row sums are transferred separately, preserving the constant mode.
384        for &(i, j, w) in edges {
385            delta.clear();
386            let mut lo = self.row(i).peekable();
387            let mut hi = self.row(j).peekable();
388            while lo.peek().is_some() || hi.peek().is_some() {
389                let a = lo.peek().map(|v| v.0).unwrap_or(usize::MAX);
390                let b = hi.peek().map(|v| v.0).unwrap_or(usize::MAX);
391                let (col, value) = if a == b {
392                    (a, lo.next().unwrap().1 - hi.next().unwrap().1)
393                } else if a < b {
394                    lo.next().unwrap()
395                } else {
396                    let (c, v) = hi.next().unwrap();
397                    (c, -v)
398                };
399                if value != 0.0 {
400                    delta.push((col, value));
401                }
402            }
403            for (at, &(a, u)) in delta.iter().enumerate() {
404                for &(b, v) in &delta[at + 1..] {
405                    *off.entry((a, b)).or_insert(0.0) += w * u * v;
406                }
407            }
408        }
409        let mut coarse_anchors = vec![0.0; nc];
410        for (i, &w) in anchors.iter().enumerate() {
411            if w == 0.0 {
412                continue;
413            }
414            delta.clear();
415            delta.extend(self.row(i));
416            for (at, &(a, u)) in delta.iter().enumerate() {
417                coarse_anchors[a] += w * u;
418                for &(b, v) in &delta[at + 1..] {
419                    *off.entry((a, b)).or_insert(0.0) += w * u * v;
420                }
421            }
422        }
423        (
424            off.into_iter()
425                .filter_map(|((i, j), v)| (v != 0.0).then_some((i, j, -v)))
426                .collect(),
427            coarse_anchors,
428        )
429    }
430    fn allocated_bytes(&self) -> usize {
431        8 * (self.offsets.capacity() + self.columns.capacity() + self.weights.capacity())
432    }
433}
434#[derive(Debug)]
435struct Level {
436    matrix: Matrix,
437    transfer: Transfer,
438    rhs: Vec<f64>,
439    x: Vec<f64>,
440    residual: Vec<f64>,
441    // Dense lower Cholesky at the terminal level, with one gauge removed if closed.
442    cholesky: Vec<f64>,
443    anchored: bool,
444    lines: Vec<BlockSmoother>,
445}
446fn center(x: &mut [f64], anchored: bool) {
447    if !anchored {
448        let mean = x.iter().sum::<f64>() / x.len() as f64;
449        for v in x {
450            *v -= mean;
451        }
452    }
453}
454impl Level {
455    fn new(matrix: Matrix, transfer: Transfer, anchored: bool) -> Self {
456        let n = matrix.diagonal.len();
457        Self {
458            matrix,
459            transfer,
460            rhs: vec![0.0; n],
461            x: vec![0.0; n],
462            residual: vec![0.0; n],
463            cholesky: vec![],
464            anchored,
465            lines: vec![],
466        }
467    }
468    fn factor(&mut self) -> Result<()> {
469        let skip = usize::from(!self.anchored);
470        let n = self.x.len() - skip;
471        let mut l = vec![0.0; n * n];
472        for row in skip..self.x.len() {
473            let i = row - skip;
474            l[i * n + i] = self.matrix.diagonal[row];
475            for at in self.matrix.offsets[row]..self.matrix.offsets[row + 1] {
476                let col = self.matrix.columns[at];
477                if col >= skip {
478                    l[i * n + col - skip] += self.matrix.values[at];
479                }
480            }
481        }
482        for i in 0..n {
483            for j in 0..=i {
484                let mut value = l[i * n + j];
485                for k in 0..j {
486                    value -= l[i * n + k] * l[j * n + k];
487                }
488                if i == j {
489                    if !value.is_finite() || value <= 0.0 {
490                        return Err("CFD-E035: numerics.pressure_preconditioner: multigrid coarse Cholesky lost positive definiteness".into());
491                    }
492                    l[i * n + j] = value.sqrt();
493                } else {
494                    l[i * n + j] = value / l[j * n + j];
495                }
496            }
497        }
498        self.cholesky = l;
499        Ok(())
500    }
501    fn direct(&mut self) {
502        let skip = usize::from(!self.anchored);
503        let n = self.x.len() - skip;
504        self.x.fill(0.0);
505        for i in 0..n {
506            let mut value = self.rhs[i + skip];
507            for j in 0..i {
508                value -= self.cholesky[i * n + j] * self.x[j + skip];
509            }
510            self.x[i + skip] = value / self.cholesky[i * n + i];
511        }
512        for i in (0..n).rev() {
513            let mut value = self.x[i + skip];
514            for j in i + 1..n {
515                value -= self.cholesky[j * n + i] * self.x[j + skip];
516            }
517            self.x[i + skip] = value / self.cholesky[i * n + i];
518        }
519        center(&mut self.x, self.anchored);
520    }
521}
522
523#[derive(Debug)]
524pub(crate) struct Hierarchy {
525    levels: Vec<Level>,
526    masked: Option<masked::MaskedHierarchy>,
527    pub stats: MultigridStats,
528}
529impl Hierarchy {
530    pub fn build(g: &Grid, control: &Control) -> Result<Self> {
531        if g.fluid.iter().any(|v| !v) || g.components.len() != 1 {
532            let masked = masked::MaskedHierarchy::build(g, control)?;
533            return Ok(Self {
534                levels: vec![],
535                stats: masked.stats.clone(),
536                masked: Some(masked),
537            });
538        }
539        let mut n = g.n;
540        let axes = line_axes(g.n, g.dx);
541        let mut centers: [Vec<f64>; 3] =
542            std::array::from_fn(|a| (0..n[a]).map(|i| i as f64 + 0.5).collect());
543        let extent = n.map(|v| v as f64);
544        let periodic = std::array::from_fn(|a| {
545            g.faces
546                .iter()
547                .any(|f| f.axis == a && f.coord[a] == 0 && f.kind == FaceKind::Interior)
548        });
549        let anchored = g.anchored[0];
550        let mut anchors = vec![0.0; g.count()];
551        let mut edges = Vec::with_capacity(g.faces.len());
552        for f in &g.faces {
553            let w = f.area / (f.distance * g.volume);
554            match f.kind {
555                FaceKind::Interior => edges.push((f.lo.unwrap(), f.hi.unwrap(), w)),
556                FaceKind::Outlet => anchors[f.lo.or(f.hi).unwrap()] += w,
557                _ => {}
558            }
559        }
560        let mut levels = Vec::new();
561        let mut dimensions = Vec::new();
562        loop {
563            dimensions.push(n);
564            control.check()?;
565            let matrix = Matrix::build(&edges, &anchors);
566            let count = anchors.len();
567            if count <= COARSE_CELLS {
568                let mut last = Level::new(matrix, Transfer::default(), anchored);
569                last.factor()?;
570                levels.push(last);
571                break;
572            }
573            let (transfer, coarse) = if axes.is_empty() {
574                Transfer::build(n, &centers, periodic, extent)
575            } else {
576                // Preserve weak-axis modes until stiff directions have collapsed.
577                // Once they have only two cells, exact small line/plane blocks
578                // allow the remaining weak directions to coarsen safely.
579                let stiff_can_coarsen = axes.iter().any(|a| n[*a] > 2);
580                let coarsen =
581                    std::array::from_fn(|a| n[a] > 2 && (!stiff_can_coarsen || axes.contains(&a)));
582                Transfer::build_selected(n, &centers, periodic, extent, coarsen)
583            };
584            let groups = if axes.is_empty() {
585                vec![]
586            } else if axes.len() > 1 && axes.iter().map(|a| n[*a]).product::<usize>() <= 16 {
587                vec![axes.clone()]
588            } else {
589                vec![vec![
590                    *axes
591                        .iter()
592                        .min_by(|a, b| g.dx[**a].total_cmp(&g.dx[**b]))
593                        .unwrap(),
594                ]]
595            };
596            let lines = groups
597                .iter()
598                .map(|a| BlockSmoother::build(&matrix, n, a, periodic, control))
599                .collect::<Result<Vec<_>>>()?;
600            n = coarse.each_ref().map(|v| v.len());
601            let (coarse_edges, coarse_anchors) =
602                transfer.galerkin(&edges, &anchors, n.iter().product());
603            edges = coarse_edges;
604            centers = coarse;
605            let mut level = Level::new(matrix, transfer, anchored);
606            level.lines = lines;
607            levels.push(level);
608            anchors = coarse_anchors;
609        }
610        let stats = MultigridStats {
611            level_dimensions: dimensions,
612            block_smoothers: levels
613                .iter()
614                .enumerate()
615                .flat_map(|(i, l)| l.lines.iter().map(move |s| s.stats(i)))
616                .collect(),
617            level_cells: levels.iter().map(|l| l.x.len()).collect(),
618            level_nonzeros: levels
619                .iter()
620                .map(|l| l.matrix.values.len() + l.x.len())
621                .collect(),
622            allocated_bytes: levels.capacity() * std::mem::size_of::<Level>()
623                + levels
624                    .iter()
625                    .map(|l| {
626                        l.matrix.allocated_bytes()
627                            + l.lines.capacity() * std::mem::size_of::<BlockSmoother>()
628                            + l.lines
629                                .iter()
630                                .map(BlockSmoother::allocated_bytes)
631                                .sum::<usize>()
632                            + l.transfer.allocated_bytes()
633                            + 8 * (l.rhs.capacity()
634                                + l.x.capacity()
635                                + l.residual.capacity()
636                                + l.cholesky.capacity())
637                    })
638                    .sum::<usize>(),
639        };
640        Ok(Self {
641            levels,
642            stats,
643            masked: None,
644        })
645    }
646    pub fn work(&self, built: bool) -> MultigridWork {
647        MultigridWork {
648            hierarchy_builds: u64::from(built),
649            hierarchy_levels: self.stats.level_cells.len() as u64,
650            hierarchy_cells: self.stats.level_cells.iter().sum::<usize>() as u64,
651            hierarchy_nonzeros: self.stats.level_nonzeros.iter().sum::<usize>() as u64,
652            hierarchy_bytes: self.stats.allocated_bytes as u64,
653            ..MultigridWork::default()
654        }
655    }
656    pub fn apply(&mut self, rhs: &[f64], z: &mut [f64], work: &mut MultigridWork) {
657        if let Some(masked) = &mut self.masked {
658            masked.apply(rhs, z, work);
659            return;
660        }
661        self.levels[0].rhs.copy_from_slice(rhs);
662        cycle(&mut self.levels, work);
663        z.copy_from_slice(&self.levels[0].x);
664        work.cycles += 1;
665    }
666}
667fn cycle(levels: &mut [Level], work: &mut MultigridWork) {
668    let (level, rest) = levels.split_first_mut().expect("nonempty hierarchy");
669    center(&mut level.rhs, level.anchored);
670    if rest.is_empty() {
671        level.direct();
672        work.coarse_solves += 1;
673        return;
674    }
675    level.x.fill(0.0);
676    let sweeps = if level.lines.is_empty() { SWEEPS } else { 1 };
677    if !level.lines.is_empty() {
678        work.block_level_cell_visits += level.x.len() as u64;
679    }
680    for pass in 0..sweeps {
681        if level.lines.is_empty() {
682            level.matrix.sweep(&level.rhs, &mut level.x, false);
683        } else {
684            let i = pass % level.lines.len();
685            work.block_solves +=
686                level.lines[i].sweep(&level.matrix, &level.rhs, &mut level.x, false);
687            work.block_smoothing_cell_updates += level.x.len() as u64;
688        }
689    }
690    center(&mut level.x, level.anchored);
691    level.matrix.product(&level.x, &mut level.residual);
692    for (r, b) in level.residual.iter_mut().zip(&level.rhs) {
693        *r = b - *r;
694    }
695    center(&mut level.residual, level.anchored);
696    rest[0].rhs.fill(0.0);
697    for (i, &r) in level.residual.iter().enumerate() {
698        for (j, w) in level.transfer.row(i) {
699            rest[0].rhs[j] += w * r;
700        }
701    }
702    cycle(rest, work);
703    for (i, x) in level.x.iter_mut().enumerate() {
704        *x += level
705            .transfer
706            .row(i)
707            .map(|(j, w)| w * rest[0].x[j])
708            .sum::<f64>();
709    }
710    for pass in 0..sweeps {
711        if level.lines.is_empty() {
712            level.matrix.sweep(&level.rhs, &mut level.x, true);
713        } else {
714            let i = (sweeps - 1 - pass) % level.lines.len();
715            work.block_solves +=
716                level.lines[i].sweep(&level.matrix, &level.rhs, &mut level.x, true);
717            work.block_smoothing_cell_updates += level.x.len() as u64;
718        }
719    }
720    center(&mut level.x, level.anchored);
721    let cells = level.x.len() as u64;
722    work.smoothing_cell_updates += 2 * sweeps as u64 * cells;
723    work.residual_cell_updates += cells;
724    work.restriction_cell_updates += cells;
725    work.prolongation_cell_updates += cells;
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731    use crate::case::{Boundary, Case, Flow, PressurePreconditioner};
732
733    fn grid(n: [usize; 3], boundary: Boundary) -> Grid {
734        let mut c: Case =
735            serde_json::from_str(include_str!("../../../cases/verification/lid-cavity.json"))
736                .unwrap();
737        c.grid.cells = n;
738        c.domain.size_m = [2.7, 1.9, 3.1];
739        c.moving_walls.clear();
740        c.boundaries.x = boundary;
741        c.boundaries.y = Boundary::Periodic;
742        c.boundaries.z = Boundary::Wall;
743        c.flow = Flow::Laminar {
744            initial_velocity_m_s: [1.0, 0.0, 0.0],
745            viscosity_m2_s: 0.01,
746            acceleration_m_s2: [0.0; 3],
747        };
748        c.numerics.pressure_preconditioner = PressurePreconditioner::Multigrid;
749        Grid::build(&c).unwrap()
750    }
751    fn dense(g: &Grid) -> Vec<Vec<f64>> {
752        let n = g.count();
753        let mut a = vec![vec![0.0; n]; n];
754        for j in 0..n {
755            let mut e = vec![0.0; n];
756            e[j] = 1.0;
757            for (i, v) in g.divergence(&g.gradient(&e)).iter().enumerate() {
758                a[i][j] = -v;
759            }
760        }
761        a
762    }
763    fn close(a: f64, b: f64) {
764        assert!(
765            (a - b).abs() <= 2e-11 * a.abs().max(b.abs()).max(1.0),
766            "{a} != {b}"
767        );
768    }
769    #[test]
770    fn interpolation_preserves_constants_linear_interior_and_short_axes() {
771        for periodic in [false, true] {
772            for n in [3, 4, 7, 8, 17] {
773                let fine = (0..n).map(|i| i as f64 + 0.5).collect::<Vec<_>>();
774                let coarse = fine
775                    .chunks(2)
776                    .map(|c| c.iter().sum::<f64>() / c.len() as f64)
777                    .collect::<Vec<_>>();
778                for &x in &fine {
779                    let w = axis_weights(x, &coarse, periodic, n as f64);
780                    close(w.iter().map(|p| p.1).sum(), 1.0);
781                    assert!(w.iter().all(|p| p.1 > 0.0));
782                    if x >= coarse[0] && x <= coarse[coarse.len() - 1] {
783                        close(w.iter().map(|(j, w)| coarse[*j] * w).sum(), x);
784                    }
785                }
786            }
787        }
788        let n = [8, 2, 6];
789        let centers = std::array::from_fn(|a| (0..n[a]).map(|i| i as f64 + 0.5).collect());
790        let (p, coarse) = Transfer::build(n, &centers, [false, true, false], n.map(|v| v as f64));
791        assert_eq!(coarse[1], vec![0.5, 1.5]);
792        let nc = coarse.each_ref().map(|a| a.len());
793        for i in 0..n.iter().product() {
794            let span = i / n[0] % n[1];
795            assert!(p.row(i).all(|(j, _)| j / nc[0] % nc[1] == span));
796        }
797    }
798    #[test]
799    fn every_level_is_independent_galerkin_with_constants_and_outlet_anchors() {
800        // Odd aggregates, unequal spacings, periodic duplicates and multiple levels.
801        for n in [[9, 2, 7], [5, 3, 3], [2, 2, 9]] {
802            for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
803                let g = grid(n, boundary);
804                let h = Hierarchy::build(&g, &Control::new(20.0)).unwrap();
805                let mut a = dense(&g);
806                for l in &h.levels {
807                    for j in 0..a.len() {
808                        let mut e = vec![0.0; a.len()];
809                        let mut y = e.clone();
810                        e[j] = 1.0;
811                        l.matrix.product(&e, &mut y);
812                        for i in 0..a.len() {
813                            close(y[i], a[i][j]);
814                        }
815                    }
816                    let ones = vec![1.0; a.len()];
817                    let mut y = vec![0.0; a.len()];
818                    l.matrix.product(&ones, &mut y);
819                    if boundary == Boundary::Open {
820                        assert!(y.iter().sum::<f64>() > 0.0);
821                    } else {
822                        for v in y {
823                            close(v, 0.0);
824                        }
825                    }
826                    if !l.transfer.offsets.is_empty() {
827                        let nc = 1 + *l.transfer.columns.iter().max().unwrap();
828                        let mut ac = vec![vec![0.0; nc]; nc];
829                        for (i, row) in a.iter().enumerate() {
830                            for (j, &aij) in row.iter().enumerate() {
831                                for (ci, wi) in l.transfer.row(i) {
832                                    for (cj, wj) in l.transfer.row(j) {
833                                        ac[ci][cj] += wi * aij * wj;
834                                    }
835                                }
836                            }
837                        }
838                        a = ac;
839                    }
840                }
841            }
842        }
843    }
844    #[test]
845    fn the_fixed_cycle_is_linear_symmetric_and_positive_on_its_entire_subspace() {
846        for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
847            for (n, scales) in [
848                ([5, 3, 3], [1., 1., 1.]),
849                ([5, 3, 3], [0.02, 1., 1.]),
850                ([5, 3, 3], [0.02, 1., 0.02]),
851                // One cell on the periodic axis: a two-dimensional grid.
852                ([5, 1, 4], [1., 1., 1.]),
853            ] {
854                let mut g = grid(n, boundary);
855                for (d, s) in g.dx.iter_mut().zip(scales) {
856                    *d *= s;
857                }
858                g.volume = g.dx.iter().product();
859                for f in &mut g.faces {
860                    f.area = g.volume / g.dx[f.axis];
861                    f.distance = g.dx[f.axis]
862                        * if f.kind == FaceKind::Interior {
863                            1.
864                        } else {
865                            0.5
866                        };
867                }
868
869                let mut h = Hierarchy::build(&g, &Control::new(20.0)).unwrap();
870                let n = g.count();
871                let mut m = vec![vec![0.0; n]; n];
872                // Form the complete projected preconditioner, not just random probes.
873                for j in 0..n {
874                    let mut e = vec![0.0; n];
875                    let mut y = e.clone();
876                    e[j] = 1.0;
877                    center(&mut e, g.anchored[0]);
878                    h.apply(&e, &mut y, &mut MultigridWork::default());
879                    for i in 0..n {
880                        m[i][j] = y[i];
881                    }
882                }
883                for (i, row) in m.iter().enumerate() {
884                    for (j, &mij) in row.iter().enumerate() {
885                        close(mij, m[j][i]);
886                    }
887                }
888                let anchored = g.anchored[0];
889                let rank = n - usize::from(!anchored);
890                let mut a = vec![vec![0.0; rank]; rank];
891                for i in 0..rank {
892                    for j in 0..rank {
893                        // Basis e_i-e_last spans the closed compatible subspace.
894                        a[i][j] = if anchored {
895                            m[i][j]
896                        } else {
897                            m[i][j] - m[i][n - 1] - m[n - 1][j] + m[n - 1][n - 1]
898                        };
899                    }
900                }
901                for i in 0..rank {
902                    for j in 0..=i {
903                        let v = a[i][j] - (0..j).map(|k| a[i][k] * a[j][k]).sum::<f64>();
904                        if i == j {
905                            assert!(v > 0.0);
906                            a[i][j] = v.sqrt();
907                        } else {
908                            a[i][j] = v / a[j][j];
909                        }
910                    }
911                }
912                let r: Vec<_> = (0..n).map(|i| (0.73 * i as f64).sin()).collect();
913                let mut compatible = r.clone();
914                center(&mut compatible, anchored);
915                let mut y = vec![0.0; n];
916                h.apply(&compatible, &mut y, &mut MultigridWork::default());
917                for i in 0..n {
918                    close(y[i], (0..n).map(|j| m[i][j] * r[j]).sum());
919                }
920                assert!(compatible.iter().zip(y).map(|(a, b)| a * b).sum::<f64>() > 0.0);
921            }
922        }
923    }
924    #[test]
925    fn semicoarse_operators_match_dense_galerkin_and_preserve_weak_axis_modes() {
926        for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
927            for scales in [[1., 1., 0.02], [0.02, 1., 0.02]] {
928                let mut g = grid([9, 3, 7], boundary);
929                for (dx, scale) in g.dx.iter_mut().zip(scales) {
930                    *dx *= scale;
931                }
932                g.volume = g.dx.iter().product();
933                for f in &mut g.faces {
934                    f.area = g.volume / g.dx[f.axis];
935                    f.distance = g.dx[f.axis]
936                        * if f.kind == FaceKind::Interior {
937                            1.
938                        } else {
939                            0.5
940                        };
941                }
942                let h = Hierarchy::build(&g, &Control::new(20.)).unwrap();
943                let axes = line_axes(g.n, g.dx);
944                let mut a = dense(&g);
945                for (number, l) in h.levels.iter().enumerate() {
946                    let scale = a.iter().flatten().copied().map(f64::abs).fold(1., f64::max);
947                    for j in 0..a.len() {
948                        let mut x = vec![0.; a.len()];
949                        let mut y = x.clone();
950                        x[j] = 1.;
951                        l.matrix.product(&x, &mut y);
952                        for (row, value) in a.iter().zip(y) {
953                            assert!((row[j] - value).abs() <= 1e-12 * scale);
954                        }
955                    }
956                    if !l.transfer.offsets.is_empty() {
957                        let n = h.stats.level_dimensions[number];
958                        let next = h.stats.level_dimensions[number + 1];
959                        if axes.iter().any(|a| n[*a] > 2) {
960                            for a in 0..3 {
961                                if !axes.contains(&a) {
962                                    assert_eq!(n[a], next[a]);
963                                }
964                            }
965                        }
966                        let nc = next.iter().product();
967                        let mut coarse = vec![vec![0.; nc]; nc];
968                        for (i, row) in a.iter().enumerate() {
969                            for (j, &value) in row.iter().enumerate() {
970                                for (ci, wi) in l.transfer.row(i) {
971                                    for (cj, wj) in l.transfer.row(j) {
972                                        coarse[ci][cj] += wi * value * wj;
973                                    }
974                                }
975                            }
976                        }
977                        a = coarse;
978                    }
979                }
980                assert!(!h.stats.block_smoothers.is_empty());
981            }
982        }
983    }
984    #[test]
985    fn a_collapsed_closed_coarse_cell_has_no_pressure_unknown() {
986        let mut l = Level::new(Matrix::build(&[], &[0.0]), Transfer::default(), false);
987        l.factor().unwrap();
988        l.rhs[0] = 0.0;
989        l.direct();
990        assert!(l.cholesky.is_empty());
991        assert_eq!(l.x, vec![0.0]);
992    }
993    #[test]
994    fn an_invalid_coarse_factor_is_a_coded_error() {
995        let mut l = Level::new(Matrix::build(&[], &[-1.0]), Transfer::default(), true);
996        assert!(
997            l.factor()
998                .unwrap_err()
999                .contains("CFD-E035: numerics.pressure_preconditioner")
1000        );
1001    }
1002}