1use super::Matrix;
3use crate::{Result, grid::Grid, solver::Control};
4use serde::{Deserialize, Serialize};
5
6#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
9pub struct BlockSmootherStats {
10 pub level: usize,
12 pub axes: Vec<usize>,
14 pub block_unknowns: usize,
16 pub block_count: usize,
18 pub half_bandwidth: usize,
20 pub allocated_bytes: usize,
23}
24
25#[derive(Debug)]
26pub(super) struct BlockSmoother {
27 axes: Vec<usize>,
28 length: usize,
29 bandwidth: usize,
30 nodes: Vec<usize>,
31 outside_offsets: Vec<usize>,
32 outside_columns: Vec<usize>,
33 outside_values: Vec<f64>,
34 factor: Vec<f64>,
35 scratch: Vec<f64>,
36}
37impl BlockSmoother {
38 pub fn build(
39 matrix: &Matrix,
40 n: [usize; 3],
41 axes: &[usize],
42 periodic: [bool; 3],
43 control: &Control,
44 ) -> Result<Self> {
45 let count = matrix.diagonal.len();
46 let length = axes.iter().map(|a| n[*a]).product();
47 let mut nodes = Vec::with_capacity(count);
48 for i in 0..count {
49 let mut q = [i % n[0], i / n[0] % n[1], i / (n[0] * n[1])];
50 if axes.iter().any(|a| q[*a] != 0) {
51 continue;
52 }
53 for at in 0..length {
54 let mut remainder = at;
57 for &axis in axes {
58 let at = remainder % n[axis];
59 remainder /= n[axis];
60 q[axis] = if !periodic[axis] {
61 at
62 } else if at.is_multiple_of(2) {
63 at / 2
64 } else {
65 n[axis] - 1 - at / 2
66 };
67 }
68 nodes.push(Grid::index(n, q));
69 }
70 }
71 let mut position = vec![0; count];
72 for (at, &cell) in nodes.iter().enumerate() {
73 position[cell] = at;
74 }
75 let mut bandwidth = 0;
76 let mut outside_count = 0;
77 for i in 0..count {
78 let pi = position[i];
79 for at in matrix.offsets[i]..matrix.offsets[i + 1] {
80 let pj = position[matrix.columns[at]];
81 if pi / length == pj / length {
82 bandwidth = bandwidth.max(pi.abs_diff(pj));
83 } else {
84 outside_count += 1;
85 }
86 }
87 }
88 let stride = bandwidth + 1;
89 let mut outside_offsets = Vec::with_capacity(count + 1);
91 let mut outside_columns = Vec::with_capacity(outside_count);
92 let mut outside_values = Vec::with_capacity(outside_count);
93 outside_offsets.push(0);
94 for (at, &cell) in nodes.iter().enumerate() {
95 for entry in matrix.offsets[cell]..matrix.offsets[cell + 1] {
96 let col = matrix.columns[entry];
97 if position[col] / length != at / length {
98 outside_columns.push(col);
99 outside_values.push(matrix.values[entry]);
100 }
101 }
102 outside_offsets.push(outside_columns.len());
103 }
104
105 let mut factor = vec![0.0; count * stride];
106 for (at, &cell) in nodes.iter().enumerate() {
107 factor[at * stride] = matrix.diagonal[cell];
108 for entry in matrix.offsets[cell]..matrix.offsets[cell + 1] {
109 let col = position[matrix.columns[entry]];
110 if col / length == at / length && col < at {
111 factor[at * stride + at - col] += matrix.values[entry];
112 }
113 }
114 }
115 for line in 0..count / length {
116 if line.is_multiple_of(128) {
117 control.check()?;
118 }
119 let base = line * length * stride;
120 for i in 0..length {
121 for j in i.saturating_sub(bandwidth)..=i {
122 let row = base + i * stride;
123 let other = base + j * stride;
124 let mut value = factor[row + i - j];
125 for k in i.saturating_sub(bandwidth)..j {
126 value -= factor[row + i - k] * factor[other + j - k];
127 }
128 if i == j {
129 if !value.is_finite() || value <= 0.0 {
130 return Err("CFD-E036: numerics.pressure_preconditioner: multigrid line Cholesky lost positive definiteness".into());
131 }
132 factor[row] = value.sqrt();
133 } else {
134 factor[row + i - j] = value / factor[other];
135 }
136 }
137 }
138 }
139 for row in 0..count {
141 factor[row * stride] = 1.0 / factor[row * stride];
142 }
143 Ok(Self {
144 axes: axes.to_vec(),
145 length,
146 bandwidth,
147 nodes,
148 outside_offsets,
149 outside_columns,
150 outside_values,
151 factor,
152 scratch: vec![0.0; length],
153 })
154 }
155 pub fn sweep(&mut self, _matrix: &Matrix, rhs: &[f64], x: &mut [f64], backward: bool) -> u64 {
156 let count = self.nodes.len() / self.length;
157 let stride = self.bandwidth + 1;
158 for at in 0..count {
159 let line = if backward { count - 1 - at } else { at };
160 let start = line * self.length;
161 let base = start * stride;
162 for i in 0..self.length {
163 let cell = self.nodes[start + i];
164 let mut value = rhs[cell];
165 for entry in self.outside_offsets[start + i]..self.outside_offsets[start + i + 1] {
166 value -= self.outside_values[entry] * x[self.outside_columns[entry]];
167 }
168 self.scratch[i] = value;
169 }
170 for i in 0..self.length {
171 let row = base + i * stride;
172 let mut value = self.scratch[i];
173 for j in i.saturating_sub(self.bandwidth)..i {
174 value -= self.factor[row + i - j] * self.scratch[j];
175 }
176 self.scratch[i] = value * self.factor[row];
177 }
178 for i in (0..self.length).rev() {
179 let mut value = self.scratch[i];
180 for j in i + 1..self.length.min(i + self.bandwidth + 1) {
181 value -= self.factor[base + j * stride + j - i] * self.scratch[j];
182 }
183 self.scratch[i] = value * self.factor[base + i * stride];
184 }
185 for i in 0..self.length {
186 x[self.nodes[start + i]] = self.scratch[i];
187 }
188 }
189 count as u64
190 }
191 pub fn allocated_bytes(&self) -> usize {
192 8 * (self.nodes.capacity()
193 + self.axes.capacity()
194 + self.outside_offsets.capacity()
195 + self.outside_columns.capacity()
196 + self.outside_values.capacity()
197 + self.factor.capacity()
198 + self.scratch.capacity())
199 }
200 pub fn stats(&self, level: usize) -> BlockSmootherStats {
201 BlockSmootherStats {
202 level,
203 axes: self.axes.clone(),
204 block_unknowns: self.length,
205 block_count: self.nodes.len() / self.length,
206 half_bandwidth: self.bandwidth,
207 allocated_bytes: self.allocated_bytes(),
208 }
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::super::Hierarchy;
215 use super::*;
216 use crate::case::{Boundary, Case, Flow};
217 fn grid(n: [usize; 3], boundary: Boundary) -> Grid {
218 let mut c: Case = serde_json::from_str(include_str!(
219 "../../../../cases/verification/lid-cavity.json"
220 ))
221 .unwrap();
222 c.grid.cells = n;
223 c.moving_walls.clear();
224 c.boundaries.x = boundary;
225 c.flow = Flow::Laminar {
226 initial_velocity_m_s: [1., 0., 0.],
227 viscosity_m2_s: 0.01,
228 acceleration_m_s2: [0.; 3],
229 };
230 Grid::build(&c).unwrap()
231 }
232 fn dense(m: &Matrix) -> Vec<Vec<f64>> {
233 let n = m.diagonal.len();
234 let mut a = vec![vec![0.; n]; n];
235 for j in 0..n {
236 let mut x = vec![0.; n];
237 let mut y = x.clone();
238 x[j] = 1.;
239 m.product(&x, &mut y);
240 for (row, value) in a.iter_mut().zip(y) {
241 row[j] = value;
242 }
243 }
244 a
245 }
246 fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Vec<f64> {
248 let n = b.len();
249 for k in 0..n {
250 let pivot = (k..n)
251 .max_by(|i, j| a[*i][k].abs().total_cmp(&a[*j][k].abs()))
252 .unwrap();
253 a.swap(k, pivot);
254 b.swap(k, pivot);
255 assert!(a[k][k].abs() > 0.);
256 for i in k + 1..n {
257 let s = a[i][k] / a[k][k];
258 let (before, after) = a.split_at_mut(i);
259 for (entry, pivot) in after[0].iter_mut().zip(&before[k]).skip(k + 1) {
260 *entry -= s * pivot;
261 }
262 b[i] -= s * b[k];
263 }
264 }
265 for i in (0..n).rev() {
266 b[i] = (b[i] - (i + 1..n).map(|j| a[i][j] * b[j]).sum::<f64>()) / a[i][i];
267 }
268 b
269 }
270 fn reference(
271 a: &[Vec<f64>],
272 n: [usize; 3],
273 axes: &[usize],
274 rhs: &[f64],
275 x: &mut [f64],
276 back: bool,
277 ) {
278 let mut groups = vec![];
279 let length = axes.iter().map(|a| n[*a]).product();
280 for i in 0..x.len() {
281 let mut q = [i % n[0], i / n[0] % n[1], i / (n[0] * n[1])];
282 if axes.iter().any(|a| q[*a] != 0) {
283 continue;
284 }
285 let mut nodes = vec![];
286 for k in 0..length {
287 let mut at = k;
288 for &axis in axes {
289 q[axis] = at % n[axis];
290 at /= n[axis];
291 }
292 nodes.push(Grid::index(n, q));
293 }
294 groups.push(nodes);
295 }
296 if back {
297 groups.reverse();
298 }
299 for nodes in groups {
300 let b = nodes
301 .iter()
302 .map(|i| {
303 rhs[*i]
304 - (0..x.len())
305 .filter(|j| !nodes.contains(j))
306 .map(|j| a[*i][j] * x[j])
307 .sum::<f64>()
308 })
309 .collect();
310 let block = nodes
311 .iter()
312 .map(|i| nodes.iter().map(|j| a[*i][*j]).collect())
313 .collect();
314 for (i, value) in nodes.iter().zip(solve(block, b)) {
315 x[*i] = value;
316 }
317 }
318 }
319 #[test]
320 fn banded_lines_and_small_planes_match_independent_dense_sweeps() {
321 for boundary in [Boundary::Wall, Boundary::Periodic, Boundary::Open] {
322 for n in [[7, 3, 5], [2, 3, 5]] {
323 let g = grid(n, boundary);
324 let h = Hierarchy::build(&g, &Control::new(20.)).unwrap();
325 let mut dims = n;
326 for level in &h.levels {
327 let a = dense(&level.matrix);
328 for axes in [vec![0], vec![1], vec![2], vec![0, 2]] {
329 let periodic = [boundary == Boundary::Periodic, true, false];
330 let mut smoother = BlockSmoother::build(
331 &level.matrix,
332 dims,
333 &axes,
334 periodic,
335 &Control::new(20.),
336 )
337 .unwrap();
338 for backward in [false, true] {
339 let rhs: Vec<_> =
340 (0..a.len()).map(|i| (i as f64 * 0.31).sin()).collect();
341 let mut x: Vec<_> =
342 (0..a.len()).map(|i| (i as f64 * 0.19).cos()).collect();
343 let mut expected = x.clone();
344 reference(&a, dims, &axes, &rhs, &mut expected, backward);
345 smoother.sweep(&level.matrix, &rhs, &mut x, backward);
346 for (v, r) in x.iter().zip(expected) {
347 assert!((v - r).abs() < 1e-9 * r.abs().max(1.));
348 }
349 }
350 }
351 dims = dims.map(|n| if n <= 2 { n } else { n.div_ceil(2) });
352 }
353 }
354 }
355 }
356 #[test]
357 fn folded_periodic_lines_keep_a_narrow_band() {
358 let g = grid([17, 3, 3], Boundary::Periodic);
359 let h = Hierarchy::build(&g, &Control::new(20.)).unwrap();
360 let mut n = g.n;
361 for (level, l) in h.levels.iter().enumerate() {
362 let block =
363 BlockSmoother::build(&l.matrix, n, &[0], [true, true, false], &Control::new(20.))
364 .unwrap();
365 assert!(block.bandwidth <= if level == 0 { 2 } else { 4 });
366 n = n.map(|v| if v <= 2 { v } else { v.div_ceil(2) });
367 }
368 }
369 #[test]
370 fn invalid_block_pivot_fails_without_a_shift_or_fallback() {
371 let m = Matrix::build(&[], &[-1.; 8]);
372 assert!(
373 BlockSmoother::build(&m, [2, 2, 2], &[0], [false; 3], &Control::new(20.))
374 .unwrap_err()
375 .contains("CFD-E036: numerics.pressure_preconditioner")
376 );
377 }
378}