Debian Codegraph @

debian/missing-sources/nalgebra/src/sparse/cs_matrix_cholesky.rs

raw
1 use std::iter;
2 use std::mem;
3
4 use crate::allocator::Allocator;
5 use crate::sparse::{CsMatrix, CsStorage, CsStorageIter, CsStorageIterMut, CsVecStorage};
6 use crate::{Const, DefaultAllocator, Dim, Matrix, OVector, RealField};
7
8 /// The cholesky decomposition of a column compressed sparse matrix.
9 pub struct CsCholesky<T: RealField, D: Dim>
10 where
11 DefaultAllocator: Allocator<D>,
12 {
13 // Non-zero pattern of the original matrix upper-triangular part.
14 // Unlike the original matrix, the `original_p` array does contain the last sentinel value
15 // equal to `original_i.len()` at the end.
16 original_p: Vec<usize>,
17 original_i: Vec<usize>,
18 // Decomposition result.
19 l: CsMatrix<T, D, D>,
20 // Used only for the pattern.
21 // TODO: store only the nonzero pattern instead.
22 u: CsMatrix<T, D, D>,
23 ok: bool,
24 // Workspaces.
25 work_x: OVector<T, D>,
26 work_c: OVector<usize, D>,
27 }
28
29 impl<T: RealField, D: Dim> CsCholesky<T, D>
30 where
31 DefaultAllocator: Allocator<D> + Allocator<D>,
32 {
33 /// Computes the cholesky decomposition of the sparse matrix `m`.
34 pub fn new(m: &CsMatrix<T, D, D>) -> Self {
35 let mut me = Self::new_symbolic(m);
36 let _ = me.decompose_left_looking(&m.data.vals);
37 me
38 }
39 /// Perform symbolic analysis for the given matrix.
40 ///
41 /// This does not access the numerical values of `m`.
42 pub fn new_symbolic(m: &CsMatrix<T, D, D>) -> Self {
43 assert!(
44 m.is_square(),
45 "The matrix `m` must be square to compute its elimination tree."
46 );
47
48 let (l, u) = Self::nonzero_pattern(m);
49
50 // Workspaces.
51 let work_x = Matrix::zeros_generic(m.data.shape().0, Const::<1>);
52 let work_c = Matrix::zeros_generic(m.data.shape().1, Const::<1>);
53 let mut original_p = m.data.p.as_slice().to_vec();
54 original_p.push(m.data.i.len());
55
56 CsCholesky {
57 original_p,
58 original_i: m.data.i.clone(),
59 l,
60 u,
61 ok: false,
62 work_x,
63 work_c,
64 }
65 }
66
67 /// The lower-triangular matrix of the cholesky decomposition.
68 #[must_use]
69 pub fn l(&self) -> Option<&CsMatrix<T, D, D>> {
70 if self.ok { Some(&self.l) } else { None }
71 }
72
73 /// Extracts the lower-triangular matrix of the cholesky decomposition.
74 pub fn unwrap_l(self) -> Option<CsMatrix<T, D, D>> {
75 if self.ok { Some(self.l) } else { None }
76 }
77
78 /// Perform a numerical left-looking cholesky decomposition of a matrix with the same structure as the
79 /// one used to initialize `self`, but with different non-zero values provided by `values`.
80 pub fn decompose_left_looking(&mut self, values: &[T]) -> bool {
81 assert!(
82 values.len() >= self.original_i.len(),
83 "The set of values is too small."
84 );
85
86 let n = self.l.nrows();
87
88 // Reset `work_c` to the column pointers of `l`.
89 self.work_c.copy_from(&self.l.data.p);
90
91 unsafe {
92 for k in 0..n {
93 // Scatter the k-th column of the original matrix with the values provided.
94 let range_k =
95 *self.original_p.get_unchecked(k)..*self.original_p.get_unchecked(k + 1);
96
97 *self.work_x.vget_unchecked_mut(k) = T::zero();
98 for p in range_k.clone() {
99 let irow = *self.original_i.get_unchecked(p);
100
101 if irow >= k {
102 *self.work_x.vget_unchecked_mut(irow) = values.get_unchecked(p).clone();
103 }
104 }
105
106 for j in self.u.data.column_row_indices(k) {
107 let factor = -self
108 .l
109 .data
110 .vals
111 .get_unchecked(*self.work_c.vget_unchecked(j))
112 .clone();
113 *self.work_c.vget_unchecked_mut(j) += 1;
114
115 if j < k {
116 for (z, val) in self.l.data.column_entries(j) {
117 if z >= k {
118 *self.work_x.vget_unchecked_mut(z) += val * factor.clone();
119 }
120 }
121 }
122 }
123
124 let diag = self.work_x.vget_unchecked(k).clone();
125
126 if diag > T::zero() {
127 let denom = diag.sqrt();
128 *self
129 .l
130 .data
131 .vals
132 .get_unchecked_mut(*self.l.data.p.vget_unchecked(k)) = denom.clone();
133
134 for (p, val) in self.l.data.column_entries_mut(k) {
135 *val = self.work_x.vget_unchecked(p).clone() / denom.clone();
136 *self.work_x.vget_unchecked_mut(p) = T::zero();
137 }
138 } else {
139 self.ok = false;
140 return false;
141 }
142 }
143 }
144
145 self.ok = true;
146 true
147 }
148
149 /// Perform a numerical up-looking cholesky decomposition of a matrix with the same structure as the
150 /// one used to initialize `self`, but with different non-zero values provided by `values`.
151 pub fn decompose_up_looking(&mut self, values: &[T]) -> bool {
152 assert!(
153 values.len() >= self.original_i.len(),
154 "The set of values is too small."
155 );
156
157 // Reset `work_c` to the column pointers of `l`.
158 self.work_c.copy_from(&self.l.data.p);
159
160 // Perform the decomposition.
161 for k in 0..self.l.nrows() {
162 unsafe {
163 // Scatter the k-th column of the original matrix with the values provided.
164 let column_range =
165 *self.original_p.get_unchecked(k)..*self.original_p.get_unchecked(k + 1);
166
167 *self.work_x.vget_unchecked_mut(k) = T::zero();
168 for p in column_range.clone() {
169 let irow = *self.original_i.get_unchecked(p);
170
171 if irow <= k {
172 *self.work_x.vget_unchecked_mut(irow) = values.get_unchecked(p).clone();
173 }
174 }
175
176 let mut diag = self.work_x.vget_unchecked(k).clone();
177 *self.work_x.vget_unchecked_mut(k) = T::zero();
178
179 // Triangular solve.
180 for irow in self.u.data.column_row_indices(k) {
181 if irow >= k {
182 continue;
183 }
184
185 let lki = self.work_x.vget_unchecked(irow).clone()
186 / self
187 .l
188 .data
189 .vals
190 .get_unchecked(*self.l.data.p.vget_unchecked(irow))
191 .clone();
192 *self.work_x.vget_unchecked_mut(irow) = T::zero();
193
194 for p in
195 *self.l.data.p.vget_unchecked(irow) + 1..*self.work_c.vget_unchecked(irow)
196 {
197 *self
198 .work_x
199 .vget_unchecked_mut(*self.l.data.i.get_unchecked(p)) -=
200 self.l.data.vals.get_unchecked(p).clone() * lki.clone();
201 }
202
203 diag -= lki.clone() * lki.clone();
204 let p = *self.work_c.vget_unchecked(irow);
205 *self.work_c.vget_unchecked_mut(irow) += 1;
206 *self.l.data.i.get_unchecked_mut(p) = k;
207 *self.l.data.vals.get_unchecked_mut(p) = lki;
208 }
209
210 if diag <= T::zero() {
211 self.ok = false;
212 return false;
213 }
214
215 // Deal with the diagonal element.
216 let p = *self.work_c.vget_unchecked(k);
217 *self.work_c.vget_unchecked_mut(k) += 1;
218 *self.l.data.i.get_unchecked_mut(p) = k;
219 *self.l.data.vals.get_unchecked_mut(p) = diag.sqrt();
220 }
221 }
222
223 self.ok = true;
224 true
225 }
226
227 fn elimination_tree<S: CsStorage<T, D, D>>(m: &CsMatrix<T, D, D, S>) -> Vec<usize> {
228 let nrows = m.nrows();
229 let mut forest: Vec<_> = iter::repeat(usize::MAX).take(nrows).collect();
230 let mut ancestor: Vec<_> = iter::repeat(usize::MAX).take(nrows).collect();
231
232 for k in 0..nrows {
233 for irow in m.data.column_row_indices(k) {
234 let mut i = irow;
235
236 while i < k {
237 let i_ancestor = ancestor[i];
238 ancestor[i] = k;
239
240 if i_ancestor == usize::MAX {
241 forest[i] = k;
242 break;
243 }
244
245 i = i_ancestor;
246 }
247 }
248 }
249
250 forest
251 }
252
253 fn reach<S: CsStorage<T, D, D>>(
254 m: &CsMatrix<T, D, D, S>,
255 j: usize,
256 max_j: usize,
257 tree: &[usize],
258 marks: &mut Vec<bool>,
259 out: &mut Vec<usize>,
260 ) {
261 marks.clear();
262 marks.resize(tree.len(), false);
263
264 // TODO: avoid all those allocations.
265 let mut tmp = Vec::new();
266 let mut res = Vec::new();
267
268 for irow in m.data.column_row_indices(j) {
269 let mut curr = irow;
270 while curr != usize::MAX && curr <= max_j && !marks[curr] {
271 marks[curr] = true;
272 tmp.push(curr);
273 curr = tree[curr];
274 }
275
276 tmp.append(&mut res);
277 mem::swap(&mut tmp, &mut res);
278 }
279
280 out.append(&mut res);
281 }
282
283 fn nonzero_pattern<S: CsStorage<T, D, D>>(
284 m: &CsMatrix<T, D, D, S>,
285 ) -> (CsMatrix<T, D, D>, CsMatrix<T, D, D>) {
286 let etree = Self::elimination_tree(m);
287 let (nrows, ncols) = m.data.shape();
288 let mut rows = Vec::with_capacity(m.len());
289 let mut cols = Matrix::zeros_generic(m.data.shape().0, Const::<1>);
290 let mut marks = Vec::new();
291
292 // NOTE: the following will actually compute the non-zero pattern of
293 // the transpose of l.
294 for i in 0..nrows.value() {
295 cols[i] = rows.len();
296 Self::reach(m, i, i, &etree, &mut marks, &mut rows);
297 }
298
299 let mut vals = Vec::with_capacity(rows.len());
300 unsafe {
301 vals.set_len(rows.len());
302 }
303 vals.shrink_to_fit();
304
305 let data = CsVecStorage {
306 shape: (nrows, ncols),
307 p: cols,
308 i: rows,
309 vals,
310 };
311
312 let u = CsMatrix::from_data(data);
313 // XXX: avoid this transpose.
314 let l = u.transpose();
315
316 (l, u)
317 }
318
319 /*
320 *
321 * NOTE: All the following methods are untested and currently unused.
322 *
323 *
324 fn column_counts<S: CsStorage<T, D, D>>(
325 m: &CsMatrix<T, D, D, S>,
326 tree: &[usize],
327 ) -> Vec<usize> {
328 let len = m.data.shape().0.value();
329 let mut counts: Vec<_> = iter::repeat(0).take(len).collect();
330 let mut reach = Vec::new();
331 let mut marks = Vec::new();
332
333 for i in 0..len {
334 Self::reach(m, i, i, tree, &mut marks, &mut reach);
335
336 for j in reach.drain(..) {
337 counts[j] += 1;
338 }
339 }
340
341 counts
342 }
343
344 fn tree_postorder(tree: &[usize]) -> Vec<usize> {
345 // TODO: avoid all those allocations?
346 let mut first_child: Vec<_> = iter::repeat(usize::MAX).take(tree.len()).collect();
347 let mut other_children: Vec<_> =
348 iter::repeat(usize::MAX).take(tree.len()).collect();
349
350 // Build the children list from the parent list.
351 // The set of children of the node `i` is given by the linked list
352 // starting at `first_child[i]`. The nodes of this list are then:
353 // { first_child[i], other_children[first_child[i]], other_children[other_children[first_child[i]], ... }
354 for (i, parent) in tree.iter().enumerate() {
355 if *parent != usize::MAX {
356 let brother = first_child[*parent];
357 first_child[*parent] = i;
358 other_children[i] = brother;
359 }
360 }
361
362 let mut stack = Vec::with_capacity(tree.len());
363 let mut postorder = Vec::with_capacity(tree.len());
364
365 for (i, node) in tree.iter().enumerate() {
366 if *node == usize::MAX {
367 Self::dfs(
368 i,
369 &mut first_child,
370 &other_children,
371 &mut stack,
372 &mut postorder,
373 )
374 }
375 }
376
377 postorder
378 }
379
380 fn dfs(
381 i: usize,
382 first_child: &mut [usize],
383 other_children: &[usize],
384 stack: &mut Vec<usize>,
385 result: &mut Vec<usize>,
386 ) {
387 stack.clear();
388 stack.push(i);
389
390 while let Some(n) = stack.pop() {
391 let child = first_child[n];
392
393 if child == usize::MAX {
394 // No children left.
395 result.push(n);
396 } else {
397 stack.push(n);
398 stack.push(child);
399 first_child[n] = other_children[child];
400 }
401 }
402 }
403 */
404 }