cfd-craft 0.2.0

Research solver for incompressible Cartesian flow and the dispersion of gases and particles around buildings, with bounded, independently checked runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! Fixed symmetric multigrid for the unchanged Cartesian pressure equation.
//! This is an original implementation; no external CFD implementation is used.
//!
//! Selected with `numerics.pressure_preconditioner = multigrid`, it
//! preconditions the same PCG solve as IC(0), with the same fine equation and
//! acceptance gates. Unmasked coarse levels are Galerkin products of linear
//! interpolation; masks use connected aggregates with one gauge per sealed
//! component and componentwise coarse solves. strongly anisotropic spacings select exact line or small
//! plane block smoothing and semicoarsening. The hierarchy is cached in the
//! grid and rebuilt when the face coefficients change. The public types
//! report its storage ([`MultigridStats`], from
//! [`pressure::multigrid_stats`](crate::pressure::multigrid_stats)) and its
//! work in a phase profile ([`MultigridWork`]). See the
//! [pressure multigrid guide](https://github.com/dietmarwo/CFD-craft/blob/main/docs/developer/pressure-multigrid.md).
use crate::{
    Result,
    grid::{FaceKind, Grid},
    solver::Control,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, sync::Mutex};

const COARSE_CELLS: usize = 32;
const SWEEPS: usize = 2;
mod line;
mod masked;
use line::BlockSmoother;
pub use line::BlockSmootherStats;

/// A weak invariant span is retained by interpolation, whereas a stiff short
/// axis still needs line relaxation. Selection is fixed for the whole solve.
pub(crate) fn line_axes(n: [usize; 3], dx: [f64; 3]) -> Vec<usize> {
    let weights = dx.map(|d| 1.0 / (d * d));
    if weights.iter().any(|w| !w.is_finite() || *w <= 0.0) {
        return vec![];
    }
    let minimum = (0..3)
        .filter(|a| n[*a] > 2)
        .map(|a| weights[a])
        .fold(f64::INFINITY, f64::min);
    let maximum = weights.into_iter().fold(0.0, f64::max);
    if maximum / minimum <= 25.0 {
        return vec![];
    }
    (0..3).filter(|a| weights[*a] >= maximum / 4.0).collect()
}
fn zero(value: &u64) -> bool {
    *value == 0
}

/// Retained hierarchy and scratch storage, excluding allocator overhead, the
/// grid, outer PCG vectors and temporary hierarchy-construction storage.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct MultigridStats {
    /// Unknowns per level, finest first; their sum relative to the first
    /// entry is the grid complexity.
    pub level_cells: Vec<usize>,
    /// Cell dimensions per level, finest first; shows semicoarsening.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub level_dimensions: Vec<[usize; 3]>,
    /// Stored matrix entries per level, including diagonals and duplicate
    /// fine entries; their sum relative to the first is the operator
    /// complexity.
    pub level_nonzeros: Vec<usize>,
    /// Retained numeric and index storage in bytes, excluding allocator
    /// overhead, the grid and the outer PCG vectors.
    pub allocated_bytes: usize,
    /// The block smoothers of anisotropic levels; empty for point smoothing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub block_smoothers: Vec<BlockSmootherStats>,
}

/// Attempted work, accumulated locally without timers or locks inside PCG.
/// Hierarchy dimensions/storage are maxima, not sums over repeated solves.
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MultigridWork {
    /// Hierarchy constructions (0 when a cached hierarchy was reused).
    pub hierarchy_builds: u64,
    /// Number of levels (maximum over the merged solves).
    pub hierarchy_levels: u64,
    /// Unknowns over all levels (maximum over the merged solves).
    pub hierarchy_cells: u64,
    /// Stored matrix entries over all levels (maximum over the merged
    /// solves).
    pub hierarchy_nonzeros: u64,
    /// Retained hierarchy storage in bytes (maximum over the merged solves).
    pub hierarchy_bytes: u64,
    /// V-cycles applied, one per preconditioner application.
    pub cycles: u64,
    /// Cell updates of all smoothing sweeps, point and block.
    pub smoothing_cell_updates: u64,
    /// Cell updates of residual evaluations, one per cell and nonterminal
    /// level visit.
    pub residual_cell_updates: u64,
    /// Cell updates of restrictions; equal to the residual updates.
    pub restriction_cell_updates: u64,
    /// Cell updates of prolongations; equal to the residual updates.
    pub prolongation_cell_updates: u64,
    /// Dense direct solves on the coarsest level, one per cycle.
    pub coarse_solves: u64,
    /// Cell updates of block sweeps; omitted when zero. Twice the block
    /// level visits.
    #[serde(default, skip_serializing_if = "zero")]
    pub block_smoothing_cell_updates: u64,
    /// Exact line or plane block solves; omitted when zero.
    #[serde(default, skip_serializing_if = "zero")]
    pub block_solves: u64,
    /// Cells of the block-smoothed levels per visit; omitted when zero. Then
    /// smoothing = 4 x residual - 2 x block visits.
    #[serde(default, skip_serializing_if = "zero")]
    pub block_level_cell_visits: u64,
}
impl MultigridWork {
    pub(crate) fn merge(&mut self, other: &Self) {
        self.hierarchy_builds += other.hierarchy_builds;
        self.hierarchy_levels = self.hierarchy_levels.max(other.hierarchy_levels);
        self.hierarchy_cells = self.hierarchy_cells.max(other.hierarchy_cells);
        self.hierarchy_nonzeros = self.hierarchy_nonzeros.max(other.hierarchy_nonzeros);
        self.hierarchy_bytes = self.hierarchy_bytes.max(other.hierarchy_bytes);
        self.cycles += other.cycles;
        self.smoothing_cell_updates += other.smoothing_cell_updates;
        self.residual_cell_updates += other.residual_cell_updates;
        self.restriction_cell_updates += other.restriction_cell_updates;
        self.prolongation_cell_updates += other.prolongation_cell_updates;
        self.coarse_solves += other.coarse_solves;
        self.block_smoothing_cell_updates += other.block_smoothing_cell_updates;
        self.block_solves += other.block_solves;
        self.block_level_cell_visits += other.block_level_cell_visits;
    }
}

/// The grid's multigrid state. Statistics have their own lock, so they can be
/// read (for example from a poll callback) while a solve holds the hierarchy.
#[derive(Debug, Default)]
pub(crate) struct Cache {
    pub hierarchy: Mutex<Option<Cached>>,
    pub stats: Mutex<Option<MultigridStats>>,
}

#[derive(Debug)]
pub(crate) struct Cached {
    pub signature: Signature,
    pub hierarchy: Hierarchy,
}

/// Reject an empty represented pressure space. Masks use connected aggregates.
pub(crate) fn validate(g: &Grid) -> Result<()> {
    if g.components.is_empty() {
        return Err(
            "CFD-E034: numerics.pressure_preconditioner: multigrid requires fluid cells".into(),
        );
    }
    Ok(())
}

fn face_entry(g: &Grid, f: &crate::grid::Face) -> Option<(u8, usize, usize, u64)> {
    let kind = match f.kind {
        FaceKind::Interior => 1,
        FaceKind::Outlet => 2,
        _ => return None,
    };
    let weight = f.area / (f.distance * g.volume);
    Some((
        kind,
        f.lo.unwrap_or(usize::MAX),
        f.hi.unwrap_or(usize::MAX),
        weight.to_bits(),
    ))
}

/// The topology and pressure face weights a hierarchy was built from. Public face
/// coefficients can change; each solve compares them exactly, without hashing or
/// allocating, and rebuilds on any difference. The fine PCG operator and final
/// residual are still built/evaluated independently.
#[derive(Debug)]
pub(crate) struct Signature {
    n: [usize; 3],
    anchored: Vec<bool>,
    fluid: Vec<bool>,
    spacing: [u64; 3],
    faces: Vec<(u8, usize, usize, u64)>,
}
impl Signature {
    pub(crate) fn of(g: &Grid) -> Result<Self> {
        validate(g)?;
        let mut faces = Vec::with_capacity(g.faces.len());
        for f in &g.faces {
            if let Some(entry) = face_entry(g, f) {
                let weight = f64::from_bits(entry.3);
                if !weight.is_finite() || weight <= 0.0 {
                    return Err("CFD-E034: numerics.pressure_preconditioner: multigrid requires finite positive pressure face weights".into());
                }
                faces.push(entry);
            }
        }
        Ok(Self {
            n: g.n,
            anchored: g.anchored.clone(),
            fluid: g.fluid.clone(),
            spacing: g.dx.map(f64::to_bits),
            faces,
        })
    }
    pub(crate) fn matches(&self, g: &Grid) -> bool {
        if self.n != g.n
            || self.anchored != g.anchored
            || self.fluid != g.fluid
            || self.spacing != g.dx.map(f64::to_bits)
        {
            return false;
        }
        let mut stored = self.faces.iter();
        for entry in g.faces.iter().filter_map(|f| face_entry(g, f)) {
            if stored.next() != Some(&entry) {
                return false;
            }
        }
        stored.next().is_none()
    }
}

#[derive(Debug)]
struct Matrix {
    offsets: Vec<usize>,
    columns: Vec<usize>,
    values: Vec<f64>,
    diagonal: Vec<f64>,
}
type Edge = (usize, usize, f64);
impl Matrix {
    fn build(edges: &[Edge], anchors: &[f64]) -> Self {
        let n = anchors.len();
        let mut offsets = vec![0; n + 1];
        for &(i, j, _) in edges {
            offsets[i + 1] += 1;
            offsets[j + 1] += 1;
        }
        for i in 0..n {
            offsets[i + 1] += offsets[i];
        }
        let mut columns = vec![0; offsets[n]];
        let mut values = vec![0.0; offsets[n]];
        let mut next = offsets[..n].to_vec();
        let mut diagonal = anchors.to_vec();
        for &(i, j, w) in edges {
            for (row, col) in [(i, j), (j, i)] {
                diagonal[row] += w;
                let at = next[row];
                columns[at] = col;
                values[at] = -w;
                next[row] += 1;
            }
        }
        Self {
            offsets,
            columns,
            values,
            diagonal,
        }
    }
    fn product(&self, x: &[f64], y: &mut [f64]) {
        for i in 0..x.len() {
            let mut value = self.diagonal[i] * x[i];
            for at in self.offsets[i]..self.offsets[i + 1] {
                value += self.values[at] * x[self.columns[at]];
            }
            y[i] = value;
        }
    }
    fn sweep(&self, rhs: &[f64], x: &mut [f64], backward: bool) {
        for at in 0..x.len() {
            let i = if backward { x.len() - 1 - at } else { at };
            let mut value = rhs[i];
            for entry in self.offsets[i]..self.offsets[i + 1] {
                value -= self.values[entry] * x[self.columns[entry]];
            }
            x[i] = value / self.diagonal[i];
        }
    }
    fn allocated_bytes(&self) -> usize {
        8 * (self.offsets.capacity()
            + self.columns.capacity()
            + self.values.capacity()
            + self.diagonal.capacity())
    }
}

#[derive(Debug, Default)]
struct Transfer {
    offsets: Vec<usize>,
    columns: Vec<usize>,
    weights: Vec<f64>,
}
fn axis_weights(x: f64, centers: &[f64], periodic: bool, extent: f64) -> Vec<(usize, f64)> {
    let n = centers.len();
    if n == 1 {
        return vec![(0, 1.0)];
    }
    let hi = centers.partition_point(|v| *v < x);
    let (lo, hi, left, right) = if hi == 0 {
        if !periodic {
            return vec![(0, 1.0)];
        }
        (n - 1, 0, centers[n - 1] - extent, centers[0])
    } else if hi == n {
        if !periodic {
            return vec![(n - 1, 1.0)];
        }
        (n - 1, 0, centers[n - 1], centers[0] + extent)
    } else {
        (hi - 1, hi, centers[hi - 1], centers[hi])
    };
    let t = (x - left) / (right - left);
    [(lo, 1.0 - t), (hi, t)]
        .into_iter()
        .filter(|(_, w)| *w != 0.0)
        .collect()
}
impl Transfer {
    fn build(
        n: [usize; 3],
        centers: &[Vec<f64>; 3],
        periodic: [bool; 3],
        extent: [f64; 3],
    ) -> (Self, [Vec<f64>; 3]) {
        Self::build_selected(n, centers, periodic, extent, n.map(|v| v > 2))
    }
    fn build_selected(
        n: [usize; 3],
        centers: &[Vec<f64>; 3],
        periodic: [bool; 3],
        extent: [f64; 3],
        coarsen: [bool; 3],
    ) -> (Self, [Vec<f64>; 3]) {
        let coarse: [Vec<f64>; 3] = std::array::from_fn(|a| {
            centers[a]
                .chunks(if coarsen[a] { 2 } else { 1 })
                .map(|s| s.iter().sum::<f64>() / s.len() as f64)
                .collect()
        });
        let nc = coarse.each_ref().map(|v| v.len());
        let weights: [Vec<_>; 3] = std::array::from_fn(|a| {
            centers[a]
                .iter()
                .map(|x| axis_weights(*x, &coarse[a], periodic[a], extent[a]))
                .collect()
        });
        let mut p = Self::default();
        let mut row = Vec::with_capacity(8);
        p.offsets.push(0);
        for i in 0..n.iter().product() {
            let q = [i % n[0], i / n[0] % n[1], i / (n[0] * n[1])];
            row.clear();
            for &(z, wz) in &weights[2][q[2]] {
                for &(y, wy) in &weights[1][q[1]] {
                    for &(x, wx) in &weights[0][q[0]] {
                        row.push((Grid::index(nc, [x, y, z]), wx * wy * wz));
                    }
                }
            }
            row.sort_unstable_by_key(|v| v.0);
            for &(j, w) in &row {
                p.columns.push(j);
                p.weights.push(w);
            }
            p.offsets.push(p.columns.len());
        }
        (p, coarse)
    }
    fn row(&self, i: usize) -> impl Iterator<Item = (usize, f64)> + '_ {
        let range = self.offsets[i]..self.offsets[i + 1];
        self.columns[range.clone()]
            .iter()
            .copied()
            .zip(self.weights[range].iter().copied())
    }
    fn galerkin(&self, edges: &[Edge], anchors: &[f64], nc: usize) -> (Vec<Edge>, Vec<f64>) {
        let mut off = BTreeMap::new();
        let mut delta = Vec::with_capacity(16);
        // Assemble symmetric off-diagonals from edge energies w(P_i-P_j)^2.
        // Row sums are transferred separately, preserving the constant mode.
        for &(i, j, w) in edges {
            delta.clear();
            let mut lo = self.row(i).peekable();
            let mut hi = self.row(j).peekable();
            while lo.peek().is_some() || hi.peek().is_some() {
                let a = lo.peek().map(|v| v.0).unwrap_or(usize::MAX);
                let b = hi.peek().map(|v| v.0).unwrap_or(usize::MAX);
                let (col, value) = if a == b {
                    (a, lo.next().unwrap().1 - hi.next().unwrap().1)
                } else if a < b {
                    lo.next().unwrap()
                } else {
                    let (c, v) = hi.next().unwrap();
                    (c, -v)
                };
                if value != 0.0 {
                    delta.push((col, value));
                }
            }
            for (at, &(a, u)) in delta.iter().enumerate() {
                for &(b, v) in &delta[at + 1..] {
                    *off.entry((a, b)).or_insert(0.0) += w * u * v;
                }
            }
        }
        let mut coarse_anchors = vec![0.0; nc];
        for (i, &w) in anchors.iter().enumerate() {
            if w == 0.0 {
                continue;
            }
            delta.clear();
            delta.extend(self.row(i));
            for (at, &(a, u)) in delta.iter().enumerate() {
                coarse_anchors[a] += w * u;
                for &(b, v) in &delta[at + 1..] {
                    *off.entry((a, b)).or_insert(0.0) += w * u * v;
                }
            }
        }
        (
            off.into_iter()
                .filter_map(|((i, j), v)| (v != 0.0).then_some((i, j, -v)))
                .collect(),
            coarse_anchors,
        )
    }
    fn allocated_bytes(&self) -> usize {
        8 * (self.offsets.capacity() + self.columns.capacity() + self.weights.capacity())
    }
}
#[derive(Debug)]
struct Level {
    matrix: Matrix,
    transfer: Transfer,
    rhs: Vec<f64>,
    x: Vec<f64>,
    residual: Vec<f64>,
    // Dense lower Cholesky at the terminal level, with one gauge removed if closed.
    cholesky: Vec<f64>,
    anchored: bool,
    lines: Vec<BlockSmoother>,
}
fn center(x: &mut [f64], anchored: bool) {
    if !anchored {
        let mean = x.iter().sum::<f64>() / x.len() as f64;
        for v in x {
            *v -= mean;
        }
    }
}
impl Level {
    fn new(matrix: Matrix, transfer: Transfer, anchored: bool) -> Self {
        let n = matrix.diagonal.len();
        Self {
            matrix,
            transfer,
            rhs: vec![0.0; n],
            x: vec![0.0; n],
            residual: vec![0.0; n],
            cholesky: vec![],
            anchored,
            lines: vec![],
        }
    }
    fn factor(&mut self) -> Result<()> {
        let skip = usize::from(!self.anchored);
        let n = self.x.len() - skip;
        let mut l = vec![0.0; n * n];
        for row in skip..self.x.len() {
            let i = row - skip;
            l[i * n + i] = self.matrix.diagonal[row];
            for at in self.matrix.offsets[row]..self.matrix.offsets[row + 1] {
                let col = self.matrix.columns[at];
                if col >= skip {
                    l[i * n + col - skip] += self.matrix.values[at];
                }
            }
        }
        for i in 0..n {
            for j in 0..=i {
                let mut value = l[i * n + j];
                for k in 0..j {
                    value -= l[i * n + k] * l[j * n + k];
                }
                if i == j {
                    if !value.is_finite() || value <= 0.0 {
                        return Err("CFD-E035: numerics.pressure_preconditioner: multigrid coarse Cholesky lost positive definiteness".into());
                    }
                    l[i * n + j] = value.sqrt();
                } else {
                    l[i * n + j] = value / l[j * n + j];
                }
            }
        }
        self.cholesky = l;
        Ok(())
    }
    fn direct(&mut self) {
        let skip = usize::from(!self.anchored);
        let n = self.x.len() - skip;
        self.x.fill(0.0);
        for i in 0..n {
            let mut value = self.rhs[i + skip];
            for j in 0..i {
                value -= self.cholesky[i * n + j] * self.x[j + skip];
            }
            self.x[i + skip] = value / self.cholesky[i * n + i];
        }
        for i in (0..n).rev() {
            let mut value = self.x[i + skip];
            for j in i + 1..n {
                value -= self.cholesky[j * n + i] * self.x[j + skip];
            }
            self.x[i + skip] = value / self.cholesky[i * n + i];
        }
        center(&mut self.x, self.anchored);
    }
}

#[derive(Debug)]
pub(crate) struct Hierarchy {
    levels: Vec<Level>,
    masked: Option<masked::MaskedHierarchy>,
    pub stats: MultigridStats,
}
impl Hierarchy {
    pub fn build(g: &Grid, control: &Control) -> Result<Self> {
        if g.fluid.iter().any(|v| !v) || g.components.len() != 1 {
            let masked = masked::MaskedHierarchy::build(g, control)?;
            return Ok(Self {
                levels: vec![],
                stats: masked.stats.clone(),
                masked: Some(masked),
            });
        }
        let mut n = g.n;
        let axes = line_axes(g.n, g.dx);
        let mut centers: [Vec<f64>; 3] =
            std::array::from_fn(|a| (0..n[a]).map(|i| i as f64 + 0.5).collect());
        let extent = n.map(|v| v as f64);
        let periodic = std::array::from_fn(|a| {
            g.faces
                .iter()
                .any(|f| f.axis == a && f.coord[a] == 0 && f.kind == FaceKind::Interior)
        });
        let anchored = g.anchored[0];
        let mut anchors = vec![0.0; g.count()];
        let mut edges = Vec::with_capacity(g.faces.len());
        for f in &g.faces {
            let w = f.area / (f.distance * g.volume);
            match f.kind {
                FaceKind::Interior => edges.push((f.lo.unwrap(), f.hi.unwrap(), w)),
                FaceKind::Outlet => anchors[f.lo.or(f.hi).unwrap()] += w,
                _ => {}
            }
        }
        let mut levels = Vec::new();
        let mut dimensions = Vec::new();
        loop {
            dimensions.push(n);
            control.check()?;
            let matrix = Matrix::build(&edges, &anchors);
            let count = anchors.len();
            if count <= COARSE_CELLS {
                let mut last = Level::new(matrix, Transfer::default(), anchored);
                last.factor()?;
                levels.push(last);
                break;
            }
            let (transfer, coarse) = if axes.is_empty() {
                Transfer::build(n, &centers, periodic, extent)
            } else {
                // Preserve weak-axis modes until stiff directions have collapsed.
                // Once they have only two cells, exact small line/plane blocks
                // allow the remaining weak directions to coarsen safely.
                let stiff_can_coarsen = axes.iter().any(|a| n[*a] > 2);
                let coarsen =
                    std::array::from_fn(|a| n[a] > 2 && (!stiff_can_coarsen || axes.contains(&a)));
                Transfer::build_selected(n, &centers, periodic, extent, coarsen)
            };
            let groups = if axes.is_empty() {
                vec![]
            } else if axes.len() > 1 && axes.iter().map(|a| n[*a]).product::<usize>() <= 16 {
                vec![axes.clone()]
            } else {
                vec![vec![
                    *axes
                        .iter()
                        .min_by(|a, b| g.dx[**a].total_cmp(&g.dx[**b]))
                        .unwrap(),
                ]]
            };
            let lines = groups
                .iter()
                .map(|a| BlockSmoother::build(&matrix, n, a, periodic, control))
                .collect::<Result<Vec<_>>>()?;
            n = coarse.each_ref().map(|v| v.len());
            let (coarse_edges, coarse_anchors) =
                transfer.galerkin(&edges, &anchors, n.iter().product());
            edges = coarse_edges;
            centers = coarse;
            let mut level = Level::new(matrix, transfer, anchored);
            level.lines = lines;
            levels.push(level);
            anchors = coarse_anchors;
        }
        let stats = MultigridStats {
            level_dimensions: dimensions,
            block_smoothers: levels
                .iter()
                .enumerate()
                .flat_map(|(i, l)| l.lines.iter().map(move |s| s.stats(i)))
                .collect(),
            level_cells: levels.iter().map(|l| l.x.len()).collect(),
            level_nonzeros: levels
                .iter()
                .map(|l| l.matrix.values.len() + l.x.len())
                .collect(),
            allocated_bytes: levels.capacity() * std::mem::size_of::<Level>()
                + levels
                    .iter()
                    .map(|l| {
                        l.matrix.allocated_bytes()
                            + l.lines.capacity() * std::mem::size_of::<BlockSmoother>()
                            + l.lines
                                .iter()
                                .map(BlockSmoother::allocated_bytes)
                                .sum::<usize>()
                            + l.transfer.allocated_bytes()
                            + 8 * (l.rhs.capacity()
                                + l.x.capacity()
                                + l.residual.capacity()
                                + l.cholesky.capacity())
                    })
                    .sum::<usize>(),
        };
        Ok(Self {
            levels,
            stats,
            masked: None,
        })
    }
    pub fn work(&self, built: bool) -> MultigridWork {
        MultigridWork {
            hierarchy_builds: u64::from(built),
            hierarchy_levels: self.stats.level_cells.len() as u64,
            hierarchy_cells: self.stats.level_cells.iter().sum::<usize>() as u64,
            hierarchy_nonzeros: self.stats.level_nonzeros.iter().sum::<usize>() as u64,
            hierarchy_bytes: self.stats.allocated_bytes as u64,
            ..MultigridWork::default()
        }
    }
    pub fn apply(&mut self, rhs: &[f64], z: &mut [f64], work: &mut MultigridWork) {
        if let Some(masked) = &mut self.masked {
            masked.apply(rhs, z, work);
            return;
        }
        self.levels[0].rhs.copy_from_slice(rhs);
        cycle(&mut self.levels, work);
        z.copy_from_slice(&self.levels[0].x);
        work.cycles += 1;
    }
}
fn cycle(levels: &mut [Level], work: &mut MultigridWork) {
    let (level, rest) = levels.split_first_mut().expect("nonempty hierarchy");
    center(&mut level.rhs, level.anchored);
    if rest.is_empty() {
        level.direct();
        work.coarse_solves += 1;
        return;
    }
    level.x.fill(0.0);
    let sweeps = if level.lines.is_empty() { SWEEPS } else { 1 };
    if !level.lines.is_empty() {
        work.block_level_cell_visits += level.x.len() as u64;
    }
    for pass in 0..sweeps {
        if level.lines.is_empty() {
            level.matrix.sweep(&level.rhs, &mut level.x, false);
        } else {
            let i = pass % level.lines.len();
            work.block_solves +=
                level.lines[i].sweep(&level.matrix, &level.rhs, &mut level.x, false);
            work.block_smoothing_cell_updates += level.x.len() as u64;
        }
    }
    center(&mut level.x, level.anchored);
    level.matrix.product(&level.x, &mut level.residual);
    for (r, b) in level.residual.iter_mut().zip(&level.rhs) {
        *r = b - *r;
    }
    center(&mut level.residual, level.anchored);
    rest[0].rhs.fill(0.0);
    for (i, &r) in level.residual.iter().enumerate() {
        for (j, w) in level.transfer.row(i) {
            rest[0].rhs[j] += w * r;
        }
    }
    cycle(rest, work);
    for (i, x) in level.x.iter_mut().enumerate() {
        *x += level
            .transfer
            .row(i)
            .map(|(j, w)| w * rest[0].x[j])
            .sum::<f64>();
    }
    for pass in 0..sweeps {
        if level.lines.is_empty() {
            level.matrix.sweep(&level.rhs, &mut level.x, true);
        } else {
            let i = (sweeps - 1 - pass) % level.lines.len();
            work.block_solves +=
                level.lines[i].sweep(&level.matrix, &level.rhs, &mut level.x, true);
            work.block_smoothing_cell_updates += level.x.len() as u64;
        }
    }
    center(&mut level.x, level.anchored);
    let cells = level.x.len() as u64;
    work.smoothing_cell_updates += 2 * sweeps as u64 * cells;
    work.residual_cell_updates += cells;
    work.restriction_cell_updates += cells;
    work.prolongation_cell_updates += cells;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::case::{Boundary, Case, Flow, PressurePreconditioner};

    fn grid(n: [usize; 3], boundary: Boundary) -> Grid {
        let mut c: Case =
            serde_json::from_str(include_str!("../../../cases/verification/lid-cavity.json"))
                .unwrap();
        c.grid.cells = n;
        c.domain.size_m = [2.7, 1.9, 3.1];
        c.moving_walls.clear();
        c.boundaries.x = boundary;
        c.boundaries.y = Boundary::Periodic;
        c.boundaries.z = Boundary::Wall;
        c.flow = Flow::Laminar {
            initial_velocity_m_s: [1.0, 0.0, 0.0],
            viscosity_m2_s: 0.01,
            acceleration_m_s2: [0.0; 3],
        };
        c.numerics.pressure_preconditioner = PressurePreconditioner::Multigrid;
        Grid::build(&c).unwrap()
    }
    fn dense(g: &Grid) -> Vec<Vec<f64>> {
        let n = g.count();
        let mut a = vec![vec![0.0; n]; n];
        for j in 0..n {
            let mut e = vec![0.0; n];
            e[j] = 1.0;
            for (i, v) in g.divergence(&g.gradient(&e)).iter().enumerate() {
                a[i][j] = -v;
            }
        }
        a
    }
    fn close(a: f64, b: f64) {
        assert!(
            (a - b).abs() <= 2e-11 * a.abs().max(b.abs()).max(1.0),
            "{a} != {b}"
        );
    }
    #[test]
    fn interpolation_preserves_constants_linear_interior_and_short_axes() {
        for periodic in [false, true] {
            for n in [3, 4, 7, 8, 17] {
                let fine = (0..n).map(|i| i as f64 + 0.5).collect::<Vec<_>>();
                let coarse = fine
                    .chunks(2)
                    .map(|c| c.iter().sum::<f64>() / c.len() as f64)
                    .collect::<Vec<_>>();
                for &x in &fine {
                    let w = axis_weights(x, &coarse, periodic, n as f64);
                    close(w.iter().map(|p| p.1).sum(), 1.0);
                    assert!(w.iter().all(|p| p.1 > 0.0));
                    if x >= coarse[0] && x <= coarse[coarse.len() - 1] {
                        close(w.iter().map(|(j, w)| coarse[*j] * w).sum(), x);
                    }
                }
            }
        }
        let n = [8, 2, 6];
        let centers = std::array::from_fn(|a| (0..n[a]).map(|i| i as f64 + 0.5).collect());
        let (p, coarse) = Transfer::build(n, &centers, [false, true, false], n.map(|v| v as f64));
        assert_eq!(coarse[1], vec![0.5, 1.5]);
        let nc = coarse.each_ref().map(|a| a.len());
        for i in 0..n.iter().product() {
            let span = i / n[0] % n[1];
            assert!(p.row(i).all(|(j, _)| j / nc[0] % nc[1] == span));
        }
    }
    #[test]
    fn every_level_is_independent_galerkin_with_constants_and_outlet_anchors() {
        // Odd aggregates, unequal spacings, periodic duplicates and multiple levels.
        for n in [[9, 2, 7], [5, 3, 3], [2, 2, 9]] {
            for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
                let g = grid(n, boundary);
                let h = Hierarchy::build(&g, &Control::new(20.0)).unwrap();
                let mut a = dense(&g);
                for l in &h.levels {
                    for j in 0..a.len() {
                        let mut e = vec![0.0; a.len()];
                        let mut y = e.clone();
                        e[j] = 1.0;
                        l.matrix.product(&e, &mut y);
                        for i in 0..a.len() {
                            close(y[i], a[i][j]);
                        }
                    }
                    let ones = vec![1.0; a.len()];
                    let mut y = vec![0.0; a.len()];
                    l.matrix.product(&ones, &mut y);
                    if boundary == Boundary::Open {
                        assert!(y.iter().sum::<f64>() > 0.0);
                    } else {
                        for v in y {
                            close(v, 0.0);
                        }
                    }
                    if !l.transfer.offsets.is_empty() {
                        let nc = 1 + *l.transfer.columns.iter().max().unwrap();
                        let mut ac = vec![vec![0.0; nc]; nc];
                        for (i, row) in a.iter().enumerate() {
                            for (j, &aij) in row.iter().enumerate() {
                                for (ci, wi) in l.transfer.row(i) {
                                    for (cj, wj) in l.transfer.row(j) {
                                        ac[ci][cj] += wi * aij * wj;
                                    }
                                }
                            }
                        }
                        a = ac;
                    }
                }
            }
        }
    }
    #[test]
    fn the_fixed_cycle_is_linear_symmetric_and_positive_on_its_entire_subspace() {
        for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
            for (n, scales) in [
                ([5, 3, 3], [1., 1., 1.]),
                ([5, 3, 3], [0.02, 1., 1.]),
                ([5, 3, 3], [0.02, 1., 0.02]),
                // One cell on the periodic axis: a two-dimensional grid.
                ([5, 1, 4], [1., 1., 1.]),
            ] {
                let mut g = grid(n, boundary);
                for (d, s) in g.dx.iter_mut().zip(scales) {
                    *d *= s;
                }
                g.volume = g.dx.iter().product();
                for f in &mut g.faces {
                    f.area = g.volume / g.dx[f.axis];
                    f.distance = g.dx[f.axis]
                        * if f.kind == FaceKind::Interior {
                            1.
                        } else {
                            0.5
                        };
                }

                let mut h = Hierarchy::build(&g, &Control::new(20.0)).unwrap();
                let n = g.count();
                let mut m = vec![vec![0.0; n]; n];
                // Form the complete projected preconditioner, not just random probes.
                for j in 0..n {
                    let mut e = vec![0.0; n];
                    let mut y = e.clone();
                    e[j] = 1.0;
                    center(&mut e, g.anchored[0]);
                    h.apply(&e, &mut y, &mut MultigridWork::default());
                    for i in 0..n {
                        m[i][j] = y[i];
                    }
                }
                for (i, row) in m.iter().enumerate() {
                    for (j, &mij) in row.iter().enumerate() {
                        close(mij, m[j][i]);
                    }
                }
                let anchored = g.anchored[0];
                let rank = n - usize::from(!anchored);
                let mut a = vec![vec![0.0; rank]; rank];
                for i in 0..rank {
                    for j in 0..rank {
                        // Basis e_i-e_last spans the closed compatible subspace.
                        a[i][j] = if anchored {
                            m[i][j]
                        } else {
                            m[i][j] - m[i][n - 1] - m[n - 1][j] + m[n - 1][n - 1]
                        };
                    }
                }
                for i in 0..rank {
                    for j in 0..=i {
                        let v = a[i][j] - (0..j).map(|k| a[i][k] * a[j][k]).sum::<f64>();
                        if i == j {
                            assert!(v > 0.0);
                            a[i][j] = v.sqrt();
                        } else {
                            a[i][j] = v / a[j][j];
                        }
                    }
                }
                let r: Vec<_> = (0..n).map(|i| (0.73 * i as f64).sin()).collect();
                let mut compatible = r.clone();
                center(&mut compatible, anchored);
                let mut y = vec![0.0; n];
                h.apply(&compatible, &mut y, &mut MultigridWork::default());
                for i in 0..n {
                    close(y[i], (0..n).map(|j| m[i][j] * r[j]).sum());
                }
                assert!(compatible.iter().zip(y).map(|(a, b)| a * b).sum::<f64>() > 0.0);
            }
        }
    }
    #[test]
    fn semicoarse_operators_match_dense_galerkin_and_preserve_weak_axis_modes() {
        for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
            for scales in [[1., 1., 0.02], [0.02, 1., 0.02]] {
                let mut g = grid([9, 3, 7], boundary);
                for (dx, scale) in g.dx.iter_mut().zip(scales) {
                    *dx *= scale;
                }
                g.volume = g.dx.iter().product();
                for f in &mut g.faces {
                    f.area = g.volume / g.dx[f.axis];
                    f.distance = g.dx[f.axis]
                        * if f.kind == FaceKind::Interior {
                            1.
                        } else {
                            0.5
                        };
                }
                let h = Hierarchy::build(&g, &Control::new(20.)).unwrap();
                let axes = line_axes(g.n, g.dx);
                let mut a = dense(&g);
                for (number, l) in h.levels.iter().enumerate() {
                    let scale = a.iter().flatten().copied().map(f64::abs).fold(1., f64::max);
                    for j in 0..a.len() {
                        let mut x = vec![0.; a.len()];
                        let mut y = x.clone();
                        x[j] = 1.;
                        l.matrix.product(&x, &mut y);
                        for (row, value) in a.iter().zip(y) {
                            assert!((row[j] - value).abs() <= 1e-12 * scale);
                        }
                    }
                    if !l.transfer.offsets.is_empty() {
                        let n = h.stats.level_dimensions[number];
                        let next = h.stats.level_dimensions[number + 1];
                        if axes.iter().any(|a| n[*a] > 2) {
                            for a in 0..3 {
                                if !axes.contains(&a) {
                                    assert_eq!(n[a], next[a]);
                                }
                            }
                        }
                        let nc = next.iter().product();
                        let mut coarse = vec![vec![0.; nc]; nc];
                        for (i, row) in a.iter().enumerate() {
                            for (j, &value) in row.iter().enumerate() {
                                for (ci, wi) in l.transfer.row(i) {
                                    for (cj, wj) in l.transfer.row(j) {
                                        coarse[ci][cj] += wi * value * wj;
                                    }
                                }
                            }
                        }
                        a = coarse;
                    }
                }
                assert!(!h.stats.block_smoothers.is_empty());
            }
        }
    }
    #[test]
    fn a_collapsed_closed_coarse_cell_has_no_pressure_unknown() {
        let mut l = Level::new(Matrix::build(&[], &[0.0]), Transfer::default(), false);
        l.factor().unwrap();
        l.rhs[0] = 0.0;
        l.direct();
        assert!(l.cholesky.is_empty());
        assert_eq!(l.x, vec![0.0]);
    }
    #[test]
    fn an_invalid_coarse_factor_is_a_coded_error() {
        let mut l = Level::new(Matrix::build(&[], &[-1.0]), Transfer::default(), true);
        assert!(
            l.factor()
                .unwrap_err()
                .contains("CFD-E035: numerics.pressure_preconditioner")
        );
    }
}