1use super::formats::CsrMatrix;
7use super::iterative::LinearOperator;
8use crate::error::{LinalgError, Result};
9use std::collections::BTreeMap;
10
11#[derive(Clone, Debug)]
13pub struct IncompleteCholesky {
14 n: usize,
15 rows: Vec<Vec<(usize, f64)>>,
17 diag: Vec<f64>,
19 shift: f64,
20 order: Option<Vec<usize>>,
23}
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum IcOrdering {
30 Natural,
32 ReverseCuthillMcKee,
34 MinimumDegree,
37}
38
39#[derive(Clone, Copy)]
40enum Mode {
41 Pattern,
43 Threshold { drop_tol: f64, max_fill: usize },
45}
46
47impl IncompleteCholesky {
48 pub fn ic0(a: &CsrMatrix) -> Result<IncompleteCholesky> {
54 Self::with_shifts(a, Mode::Pattern)
55 }
56 pub fn ic0_shifted(a: &CsrMatrix, shift: f64) -> Result<IncompleteCholesky> {
61 factor(a, Mode::Pattern, shift)
62 }
63
64 pub fn ic_k(a: &CsrMatrix, level: usize, modified: bool) -> Result<IncompleteCholesky> {
75 let pattern = level_pattern(a, level)?;
76 let mut shift = 0.0;
77 loop {
78 match factor_right_looking(a, &pattern, modified, shift) {
79 Err(LinalgError::NotPositiveDefinite(_)) if shift < 1e3 => shift = if shift == 0.0 { 1e-3 } else { shift * 2.0 },
80 other => return other,
81 }
82 }
83 }
84 pub fn ict(a: &CsrMatrix, drop_tol: f64, max_fill: usize) -> Result<IncompleteCholesky> {
90 Self::with_shifts(a, Mode::Threshold { drop_tol, max_fill })
91 }
92
93 fn with_shifts(a: &CsrMatrix, mode: Mode) -> Result<IncompleteCholesky> {
94 let mut shift = 0.0;
95 loop {
96 match factor(a, mode, shift) {
97 Err(LinalgError::NotPositiveDefinite(_)) if shift < 1e3 => shift = if shift == 0.0 { 1e-3 } else { shift * 2.0 },
98 other => return other,
99 }
100 }
101 }
102
103 pub fn ordered(a: &CsrMatrix, ordering: IcOrdering, factor: impl FnOnce(&CsrMatrix) -> Result<IncompleteCholesky>) -> Result<IncompleteCholesky> {
109 let order = match ordering {
110 IcOrdering::Natural => return factor(a),
111 IcOrdering::ReverseCuthillMcKee => super::direct::reverse_cuthill_mckee(a),
112 IcOrdering::MinimumDegree => super::amd::minimum_degree(a),
113 };
114 let n = a.nrows;
115 if a.ncols != n || order.len() != n {
116 return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
117 }
118 let mut position = vec![0usize; n];
119 for (k, &o) in order.iter().enumerate() {
120 position[o] = k;
121 }
122 let (mut rows, mut cols, mut vals) = (Vec::with_capacity(a.nnz()), Vec::with_capacity(a.nnz()), Vec::with_capacity(a.nnz()));
123 for i in 0..n {
124 for p in a.indptr[i]..a.indptr[i + 1] {
125 rows.push(position[i]);
126 cols.push(position[a.indices[p]]);
127 vals.push(a.data[p]);
128 }
129 }
130 let permuted = CsrMatrix::from_triplets(n, n, &rows, &cols, &vals)?;
131 let mut ic = factor(&permuted)?;
132 ic.order = Some(order);
133 Ok(ic)
134 }
135 pub fn solve(&self, b: &[f64]) -> Vec<f64> {
140 match &self.order {
141 None => self.solve_natural(b),
142 Some(order) => {
143 let permuted: Vec<f64> = order.iter().map(|&o| b[o]).collect();
144 let z = self.solve_natural(&permuted);
145 let mut x = vec![0.0; b.len()];
146 for (k, &o) in order.iter().enumerate() {
147 x[o] = z[k];
148 }
149 x
150 }
151 }
152 }
153
154 fn solve_natural(&self, b: &[f64]) -> Vec<f64> {
155 let mut x = b.to_vec();
156 for i in 0..self.n {
157 let s: f64 = self.rows[i].iter().map(|&(j, v)| v * x[j]).sum();
158 x[i] = (x[i] - s) / self.diag[i];
159 }
160 for i in (0..self.n).rev() {
161 x[i] /= self.diag[i];
162 let xi = x[i];
163 for &(j, v) in &self.rows[i] {
164 x[j] -= v * xi;
165 }
166 }
167 x
168 }
169
170 pub fn nnz(&self) -> usize {
172 self.n + self.rows.iter().map(Vec::len).sum::<usize>()
173 }
174
175 pub fn shift(&self) -> f64 {
177 self.shift
178 }
179}
180
181fn level_pattern(a: &CsrMatrix, level: usize) -> Result<Vec<Vec<usize>>> {
183 let n = a.nrows;
184 if a.ncols != n {
185 return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
186 }
187 let mut cols_lev: Vec<BTreeMap<usize, usize>> = vec![BTreeMap::new(); n];
190 for i in 0..n {
191 let mut r: BTreeMap<usize, usize> = (a.indptr[i]..a.indptr[i + 1]).map(|p| a.indices[p]).filter(|&j| j < i).map(|j| (j, 0)).collect();
192 let mut next = 0;
193 while let Some((&j, &lij)) = r.range(next..i).next() {
194 next = j + 1;
195 for (&m, &lmj) in &cols_lev[j] {
196 let lev = lij + lmj + 1;
197 if lev <= level {
198 let e = r.entry(m).or_insert(lev);
199 *e = (*e).min(lev);
200 }
201 }
202 }
203 for (&j, &lev) in &r {
204 cols_lev[j].insert(i, lev);
205 }
206 }
207 let cols: Vec<Vec<usize>> = cols_lev.into_iter().map(|c| c.into_keys().collect()).collect();
208 Ok(cols)
209}
210
211fn factor_right_looking(a: &CsrMatrix, pattern: &[Vec<usize>], modified: bool, shift: f64) -> Result<IncompleteCholesky> {
213 let n = a.nrows;
214 let mut diag = vec![0.0; n];
215 let mut cols: Vec<BTreeMap<usize, f64>> = pattern.iter().map(|rows| rows.iter().map(|&i| (i, 0.0)).collect()).collect();
216 for i in 0..n {
217 for p in a.indptr[i]..a.indptr[i + 1] {
218 let (j, v) = (a.indices[p], a.data[p]);
219 if j == i {
220 diag[i] += v;
221 } else if j < i {
222 *cols[j].get_mut(&i).expect("the pattern contains the pattern of A") += v;
223 }
224 }
225 diag[i] *= 1.0 + shift;
226 }
227 let mut factored: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
228 let mut l_diag = vec![0.0; n];
229 for k in 0..n {
230 let d = diag[k];
231 if d <= 0.0 || !d.is_finite() {
232 return Err(LinalgError::NotPositiveDefinite(k));
233 }
234 let dk = d.sqrt();
235 l_diag[k] = dk;
236 let col: Vec<(usize, f64)> = std::mem::take(&mut cols[k]).into_iter().map(|(i, v)| (i, v / dk)).collect();
237 for (x, &(i, lik)) in col.iter().enumerate() {
238 diag[i] -= lik * lik;
239 for &(j, ljk) in &col[..x] {
240 let upd = lik * ljk;
242 match cols[j].get_mut(&i) {
243 Some(v) => *v -= upd,
244 None if modified => {
245 diag[i] -= upd;
246 diag[j] -= upd;
247 }
248 None => {}
249 }
250 }
251 }
252 factored.push(col);
253 }
254 let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
255 for (j, col) in factored.iter().enumerate() {
256 for &(i, v) in col {
257 rows[i].push((j, v));
258 }
259 }
260 Ok(IncompleteCholesky { n, rows, diag: l_diag, shift, order: None })
261}
262
263fn factor(a: &CsrMatrix, mode: Mode, shift: f64) -> Result<IncompleteCholesky> {
269 let n = a.nrows;
270 if a.ncols != n {
271 return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
272 }
273 let mut rows: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
274 let mut diag: Vec<f64> = Vec::with_capacity(n);
275 let mut cols: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
277 for i in 0..n {
278 let mut w: BTreeMap<usize, f64> = BTreeMap::new();
279 let mut aii = 0.0;
280 let mut norm = 0.0;
281 for p in a.indptr[i]..a.indptr[i + 1] {
282 let (j, v) = (a.indices[p], a.data[p]);
283 norm += v * v;
284 if j < i {
285 *w.entry(j).or_insert(0.0) += v;
286 } else if j == i {
287 aii += v;
288 }
289 }
290 let (tau, max_fill) = match mode {
291 Mode::Pattern => (0.0, usize::MAX),
292 Mode::Threshold { drop_tol, max_fill } => (drop_tol * norm.sqrt(), max_fill),
293 };
294 let mut sum_sq = 0.0;
295 let mut kept: Vec<(usize, f64)> = Vec::new();
296 let mut next = 0;
297 while let Some((&j, &wj)) = w.range(next..i).next() {
298 next = j + 1;
299 let lij = wj / diag[j];
300 if matches!(mode, Mode::Threshold { .. }) && lij.abs() < tau {
301 w.remove(&j);
302 continue;
303 }
304 w.insert(j, lij);
305 for &(m, lmj) in &cols[j] {
306 match mode {
307 Mode::Pattern => {
308 if let Some(x) = w.get_mut(&m) {
309 *x -= lij * lmj;
310 }
311 }
312 Mode::Threshold { .. } => *w.entry(m).or_insert(0.0) -= lij * lmj,
313 }
314 }
315 }
316 let mut entries: Vec<(usize, f64)> = w.into_iter().filter(|&(_, v)| v != 0.0).collect();
317 if entries.len() > max_fill {
318 entries.sort_by(|x, y| y.1.abs().total_cmp(&x.1.abs()));
319 entries.truncate(max_fill);
320 entries.sort_by_key(|e| e.0);
321 }
322 for &(j, v) in &entries {
323 sum_sq += v * v;
324 kept.push((j, v));
325 }
326 let d = aii * (1.0 + shift) - sum_sq;
327 if d <= 1e-14 * aii.abs() || d <= 0.0 || !d.is_finite() {
328 return Err(LinalgError::NotPositiveDefinite(i));
329 }
330 let dii = d.sqrt();
331 for &(j, v) in &kept {
332 cols[j].push((i, v));
333 }
334 rows.push(kept);
335 diag.push(dii);
336 }
337 Ok(IncompleteCholesky { n, rows, diag, shift, order: None })
338}
339impl LinearOperator for IncompleteCholesky {
343 fn shape(&self) -> (usize, usize) {
344 (self.n, self.n)
345 }
346 fn matvec(&self, x: &[f64]) -> Vec<f64> {
347 self.solve(x)
348 }
349 fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
350 self.solve(x)
351 }
352}