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
//! Incomplete Cholesky factorization preconditioner
use crate::csr::CsrMatrix;
use crate::error::{SparseError, SparseResult};
use crate::linalg::interface::LinearOperator;
use scirs2_core::numeric::{Float, NumAssign, SparseElement};
use std::fmt::Debug;
use std::iter::Sum;
/// Incomplete Cholesky factorization preconditioner (IC(0))
///
/// This preconditioner computes an incomplete Cholesky factorization L*L^T ≈ A
/// where L is a lower triangular matrix with the same sparsity pattern as the
/// lower triangular part of A.
pub struct IC0Preconditioner<F> {
/// Lower triangular factor L in CSR format
l_factor: CsrMatrix<F>,
}
impl<F: Float + SparseElement + NumAssign + Sum + Debug + 'static> IC0Preconditioner<F> {
/// Create a new IC(0) preconditioner from a symmetric positive definite matrix
pub fn new(matrix: &CsrMatrix<F>) -> SparseResult<Self> {
let n = matrix.rows();
if n != matrix.cols() {
return Err(SparseError::DimensionMismatch {
expected: n,
found: matrix.cols(),
});
}
// Initialize L with the lower triangular part of A
let mut l_data = Vec::new();
let mut l_indices = Vec::new();
let mut l_indptr = vec![0];
for i in 0..n {
let row_start = matrix.indptr[i];
let row_end = matrix.indptr[i + 1];
// Copy lower triangular entries
for k in row_start..row_end {
let j = matrix.indices[k];
if j <= i {
l_indices.push(j);
l_data.push(matrix.data[k]);
}
}
l_indptr.push(l_indices.len());
}
// Perform incomplete Cholesky factorization
for i in 0..n {
let row_start = l_indptr[i];
let row_end = l_indptr[i + 1];
// Find diagonal element
let mut diag_idx = None;
for (idx, &col) in l_indices[row_start..row_end].iter().enumerate() {
if col == i {
diag_idx = Some(row_start + idx);
break;
}
}
let diag_idx = match diag_idx {
Some(idx) => idx,
None => {
return Err(SparseError::ValueError(format!(
"Missing diagonal element at position {i}"
)));
}
};
// Update diagonal element
let mut diag_val = l_data[diag_idx];
// Subtract contributions from previous columns
for k in row_start..diag_idx {
let j = l_indices[k];
// Find L[j,j]
let j_row_start = l_indptr[j];
let j_row_end = l_indptr[j + 1];
let mut l_jj = F::sparse_zero();
for idx in j_row_start..j_row_end {
if l_indices[idx] == j {
l_jj = l_data[idx];
break;
}
}
diag_val -= l_data[k] * l_data[k] / l_jj;
}
// Check if factorization is possible
if diag_val <= F::sparse_zero() {
return Err(SparseError::ValueError(
"Matrix is not positive definite or factorization broke down".to_string(),
));
}
l_data[diag_idx] = diag_val.sqrt();
// Update off-diagonal elements
for k in (diag_idx + 1)..row_end {
let j = l_indices[k];
let mut sum = F::sparse_zero();
// Compute dot product of row i and row j up to column j
for p in row_start..diag_idx {
let col_p = l_indices[p];
// Find corresponding element in row j
let j_row_start = l_indptr[j];
let j_row_end = l_indptr[j + 1];
for q in j_row_start..j_row_end {
if l_indices[q] == col_p {
sum += l_data[p] * l_data[q];
break;
}
}
}
l_data[k] = (l_data[k] - sum) / l_data[diag_idx];
}
}
// Create the L factor as a CSR _matrix
let l_factor = CsrMatrix::from_raw_csr(l_data, l_indptr, l_indices, (n, n))?;
Ok(Self { l_factor })
}
}
impl<F: Float + SparseElement + NumAssign + Sum + Debug + 'static> LinearOperator<F>
for IC0Preconditioner<F>
{
fn shape(&self) -> (usize, usize) {
self.l_factor.shape()
}
fn matvec(&self, x: &[F]) -> SparseResult<Vec<F>> {
let n = self.l_factor.rows();
if x.len() != n {
return Err(SparseError::DimensionMismatch {
expected: n,
found: x.len(),
});
}
// Solve L * L^T * y = x
// First solve L * z = x (forward substitution)
let mut z = vec![F::sparse_zero(); n];
for i in 0..n {
let row_start = self.l_factor.indptr[i];
let row_end = self.l_factor.indptr[i + 1];
let mut sum = x[i];
let mut diag_val = F::sparse_one();
for k in row_start..row_end {
let j = self.l_factor.indices[k];
let val = self.l_factor.data[k];
match j.cmp(&i) {
std::cmp::Ordering::Less => sum -= val * z[j],
std::cmp::Ordering::Equal => diag_val = val,
std::cmp::Ordering::Greater => {}
}
}
z[i] = sum / diag_val;
}
// Then solve L^T * y = z (backward substitution)
let mut y = vec![F::sparse_zero(); n];
for i in (0..n).rev() {
let mut sum = z[i];
// Find diagonal element
let row_start = self.l_factor.indptr[i];
let row_end = self.l_factor.indptr[i + 1];
let mut diag_val = F::sparse_one();
for k in row_start..row_end {
let j = self.l_factor.indices[k];
if j == i {
diag_val = self.l_factor.data[k];
break;
}
}
// Subtract contributions from already computed y values
// Iterate over y values for indices greater than i
// We need to use y as a lookup so we keep the index-based loop
// and add a comment explaining why we're not using an iterator pattern
#[allow(clippy::needless_range_loop)]
for j in (i + 1)..n {
// Find L[j,i] (which is L^T[i,j])
let j_row_start = self.l_factor.indptr[j];
let j_row_end = self.l_factor.indptr[j + 1];
// Use zip instead of index-based loop for indices and data
for (&col, &val) in self.l_factor.indices[j_row_start..j_row_end]
.iter()
.zip(self.l_factor.data[j_row_start..j_row_end].iter())
{
if col == i {
sum -= val * y[j];
break;
}
}
}
y[i] = sum / diag_val;
}
Ok(y)
}
fn has_adjoint(&self) -> bool {
true
}
fn rmatvec(&self, x: &[F]) -> SparseResult<Vec<F>> {
// For symmetric preconditioner, adjoint is the same as forward operation
self.matvec(x)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::csr::CsrMatrix;
#[test]
fn test_ic0_simple() {
// Test with a simple SPD matrix
// A = [4 -1 0]
// [-1 4 -1]
// [0 -1 4]
let data = vec![4.0, -1.0, -1.0, 4.0, -1.0, -1.0, 4.0];
let indptr = vec![0, 2, 5, 7];
let indices = vec![0, 1, 0, 1, 2, 1, 2];
let matrix =
CsrMatrix::from_raw_csr(data, indptr, indices, (3, 3)).expect("Operation failed");
let preconditioner = IC0Preconditioner::new(&matrix).expect("Operation failed");
// Test by applying preconditioner to a vector
let b = vec![1.0, 2.0, 3.0];
let x = preconditioner.matvec(&b).expect("Operation failed");
// The result should be approximately the solution to Ax = b
// For this simple case, we can verify the result is reasonable
assert!(x.iter().all(|&xi| xi.is_finite()));
}
#[test]
fn test_ic0_not_spd() {
// Test with a non-SPD matrix (should fail)
// A = [1 2]
// [3 4]
let data = vec![1.0, 2.0, 3.0, 4.0];
let indptr = vec![0, 2, 4];
let indices = vec![0, 1, 0, 1];
let matrix =
CsrMatrix::from_raw_csr(data, indptr, indices, (2, 2)).expect("Operation failed");
let result = IC0Preconditioner::new(&matrix);
assert!(result.is_err());
}
}