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
//! LL^T Cholesky decomposition.
//!
//! Standard Cholesky factorization for symmetric positive definite matrices.
//! For large matrices, uses blocked algorithm with GEMM/TRSM for cache efficiency.
use num_traits::{FromPrimitive, One};
use oxiblas_blas::level3::gemm::gemm;
#[cfg(feature = "parallel")]
use oxiblas_blas::level3::gemm::gemm_with_par;
use oxiblas_blas::level3::gemm_kernel::GemmKernel;
use oxiblas_blas::level3::trsm::{Diag, Side, Trans, Uplo, trsm_in_place};
#[cfg(feature = "parallel")]
use oxiblas_core::parallel::Par;
use oxiblas_core::scalar::{Field, Real, Scalar};
use oxiblas_matrix::{Mat, MatRef};
/// Error returned when Cholesky decomposition fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CholeskyError {
/// The matrix is not positive definite.
NotPositiveDefinite {
/// The row/column index where failure was detected.
index: usize,
},
/// The matrix is not square.
NotSquare {
/// Number of rows.
nrows: usize,
/// Number of columns.
ncols: usize,
},
/// Dimension mismatch in solve operation.
DimensionMismatch {
/// Expected dimension.
expected: usize,
/// Actual dimension.
actual: usize,
},
}
impl core::fmt::Display for CholeskyError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
CholeskyError::NotPositiveDefinite { index } => {
write!(
f,
"Matrix is not positive definite (detected at index {index})"
)
}
CholeskyError::NotSquare { nrows, ncols } => {
write!(f, "Matrix is not square: {nrows}×{ncols}")
}
CholeskyError::DimensionMismatch { expected, actual } => {
write!(f, "Dimension mismatch: expected {expected}, got {actual}")
}
}
}
}
impl std::error::Error for CholeskyError {}
/// Cholesky decomposition (LL^T factorization).
///
/// For a symmetric positive definite matrix A, computes L such that A = LL^T,
/// where L is lower triangular with positive diagonal entries.
#[derive(Clone, Debug)]
pub struct Cholesky<T: Scalar> {
/// The L factor (lower triangular).
l: Mat<T>,
}
impl<T: Field + Real + bytemuck::Zeroable> Cholesky<T> {
/// Computes the Cholesky decomposition of a symmetric positive definite matrix.
///
/// # Arguments
///
/// * `a` - A symmetric positive definite matrix
///
/// # Example
///
/// ```
/// use oxiblas_lapack::cholesky::Cholesky;
/// use oxiblas_matrix::Mat;
///
/// let a: Mat<f64> = Mat::from_rows(&[
/// &[4.0, 2.0],
/// &[2.0, 5.0],
/// ]);
///
/// let chol = Cholesky::compute(a.as_ref()).expect("Matrix is SPD");
///
/// // Get L factor
/// let l = chol.l_factor();
///
/// // Compute determinant: det(A) = (det(L))^2
/// let det = chol.determinant();
/// assert!((det - 16.0).abs() < 1e-10); // 4*5 - 2*2 = 16
///
/// // Solve Ax = b
/// let b: Mat<f64> = Mat::from_rows(&[&[8.0], &[11.0]]);
/// let x = chol.solve(b.as_ref()).expect("Should solve");
/// ```
///
/// # Errors
///
/// Returns `CholeskyError::NotSquare` if the matrix is not square.
/// Returns `CholeskyError::NotPositiveDefinite` if the matrix is not positive definite.
///
/// # Note
///
/// Only the lower triangular part of `a` is used. The matrix is assumed
/// to be symmetric.
pub fn compute(a: MatRef<'_, T>) -> Result<Self, CholeskyError> {
let n = a.nrows();
if n != a.ncols() {
return Err(CholeskyError::NotSquare {
nrows: n,
ncols: a.ncols(),
});
}
if n == 0 {
return Ok(Cholesky {
l: Mat::zeros(0, 0),
});
}
let mut l = Mat::zeros(n, n);
// Cholesky-Banachiewicz algorithm
for i in 0..n {
for j in 0..=i {
let mut sum = T::zero();
if j == i {
// Diagonal element
for k in 0..j {
sum = sum + l[(j, k)] * l[(j, k)];
}
let diag = a[(i, i)] - sum;
// Check for positive definiteness
let tol = <T as Scalar>::epsilon()
* <T as FromPrimitive>::from_usize(n).unwrap_or(<T as One>::one());
if diag <= tol {
return Err(CholeskyError::NotPositiveDefinite { index: i });
}
l[(i, j)] = Real::sqrt(diag);
} else {
// Off-diagonal element
for k in 0..j {
sum = sum + l[(i, k)] * l[(j, k)];
}
l[(i, j)] = (a[(i, j)] - sum) / l[(j, j)];
}
}
}
Ok(Cholesky { l })
}
/// Returns the size of the matrix (n for an n×n matrix).
#[inline]
pub fn size(&self) -> usize {
self.l.nrows()
}
/// Returns the L factor (lower triangular).
pub fn l_factor(&self) -> Mat<T> {
self.l.clone()
}
/// Computes the determinant of the original matrix.
///
/// For A = LL^T, det(A) = det(L)^2 = (∏ L\[i,i\])^2
pub fn determinant(&self) -> T {
let n = self.size();
if n == 0 {
return T::one();
}
let mut det_l = T::one();
for i in 0..n {
det_l = det_l * self.l[(i, i)];
}
det_l * det_l
}
/// Solves the system Ax = b for symmetric positive definite A.
///
/// Given A = LL^T, solves:
/// 1. Forward substitution: Ly = b
/// 2. Back substitution: L^T x = y
///
/// # Arguments
///
/// * `b` - The right-hand side matrix (n × m for multiple RHS)
///
/// # Errors
///
/// Returns `CholeskyError::DimensionMismatch` if b has wrong number of rows.
pub fn solve(&self, b: MatRef<'_, T>) -> Result<Mat<T>, CholeskyError> {
let n = self.size();
if b.nrows() != n {
return Err(CholeskyError::DimensionMismatch {
expected: n,
actual: b.nrows(),
});
}
let m = b.ncols();
let mut x = Mat::zeros(n, m);
// Copy b to x
for j in 0..m {
for i in 0..n {
x[(i, j)] = b[(i, j)];
}
}
// Forward substitution: Ly = b
for k in 0..n {
for j in 0..m {
x[(k, j)] = x[(k, j)] / self.l[(k, k)];
}
for i in (k + 1)..n {
let mult = self.l[(i, k)];
for j in 0..m {
let val = x[(i, j)] - mult * x[(k, j)];
x[(i, j)] = val;
}
}
}
// Back substitution: L^T x = y
for k in (0..n).rev() {
for j in 0..m {
x[(k, j)] = x[(k, j)] / self.l[(k, k)];
}
for i in 0..k {
let mult = self.l[(k, i)];
for j in 0..m {
let val = x[(i, j)] - mult * x[(k, j)];
x[(i, j)] = val;
}
}
}
Ok(x)
}
/// Computes the inverse of the original matrix.
///
/// Solves AX = I to find A^(-1).
pub fn inverse(&self) -> Result<Mat<T>, CholeskyError> {
let n = self.size();
let identity = Mat::<T>::eye(n);
self.solve(identity.as_ref())
}
/// Returns the log-determinant of the original matrix.
///
/// This is useful for numerical stability when det(A) is very large or small.
/// log(det(A)) = 2 * sum(log(L\[i,i\]))
pub fn log_determinant(&self) -> T {
let n = self.size();
if n == 0 {
return T::zero();
}
let mut log_det = T::zero();
let two = T::one() + T::one();
for i in 0..n {
log_det = log_det + Real::ln(self.l[(i, i)]);
}
two * log_det
}
}
// Optimized blocked Cholesky factorization for types that support GEMM
impl<T: Field + Real + GemmKernel + bytemuck::Zeroable> Cholesky<T> {
/// Computes the Cholesky decomposition using blocked algorithm for large matrices.
///
/// Uses GEMM and TRSM for cache-efficient computation on large matrices.
/// For matrices smaller than the block size, falls back to unblocked algorithm.
///
/// # Arguments
///
/// * `a` - A symmetric positive definite matrix
///
/// # Returns
///
/// The Cholesky decomposition on success.
///
/// # Errors
///
/// Returns `CholeskyError::NotSquare` if the matrix is not square.
/// Returns `CholeskyError::NotPositiveDefinite` if the matrix is not positive definite.
#[inline]
pub fn compute_blocked(a: MatRef<'_, T>) -> Result<Self, CholeskyError> {
let nb = crate::workspace::optimal_block_size_cholesky(a.nrows());
Self::compute_with_block_size(a, nb)
}
/// Computes Cholesky decomposition with a specified block size.
pub fn compute_with_block_size(a: MatRef<'_, T>, nb: usize) -> Result<Self, CholeskyError> {
let n = a.nrows();
if n != a.ncols() {
return Err(CholeskyError::NotSquare {
nrows: n,
ncols: a.ncols(),
});
}
if n == 0 {
return Ok(Cholesky {
l: Mat::zeros(0, 0),
});
}
// Copy lower triangular part of A
let mut l = Mat::zeros(n, n);
for j in 0..n {
for i in j..n {
l[(i, j)] = a[(i, j)];
}
}
// Use blocked algorithm for larger matrices
if n >= nb {
Self::blocked_factor(&mut l, n, nb)?;
} else {
Self::unblocked_factor(&mut l, n, 0)?;
}
Ok(Cholesky { l })
}
/// Blocked Cholesky factorization using GEMM for symmetric updates.
fn blocked_factor(l: &mut Mat<T>, n: usize, nb: usize) -> Result<(), CholeskyError> {
let mut jb = 0;
while jb < n {
// Current block size (may be smaller for last block)
let jb_size = nb.min(n - jb);
// Factor diagonal block A11 using unblocked Cholesky
Self::unblocked_factor_block(l, n, jb, jb_size)?;
// If there are more rows below this block
if jb + jb_size < n {
let rows_remaining = n - jb - jb_size;
// Extract L11 (the diagonal block we just factored)
let mut l11: Mat<T> = Mat::zeros(jb_size, jb_size);
for i in 0..jb_size {
for j in 0..=i {
l11[(i, j)] = l[(jb + i, jb + j)];
}
}
// Extract A21 block (will become L21)
let mut l21: Mat<T> = Mat::zeros(rows_remaining, jb_size);
for j in 0..jb_size {
for i in 0..rows_remaining {
l21[(i, j)] = l[(jb + jb_size + i, jb + j)];
}
}
// Solve L21 = A21 * L11^(-T) using TRSM: L11 * L21^T = A21^T
// Equivalently: L21 = A21 * inv(L11^T)
// TRSM: Right, Lower, Trans => B = B * inv(L^T)
let _ = trsm_in_place(
Side::Right,
Uplo::Lower,
Trans::Trans,
Diag::NonUnit,
l11.as_ref(),
l21.as_mut(),
);
// Copy L21 back
for j in 0..jb_size {
for i in 0..rows_remaining {
l[(jb + jb_size + i, jb + j)] = l21[(i, j)];
}
}
// Update A22 -= L21 * L21^T using GEMM (symmetric rank-k update)
// A22 is the trailing (rows_remaining x rows_remaining) block
let l21_t = l21.transpose();
let mut update: Mat<T> = Mat::zeros(rows_remaining, rows_remaining);
gemm(
T::one(),
l21.as_ref(),
l21_t.as_ref(),
T::zero(),
update.as_mut(),
);
// Subtract update from lower triangular part of A22
for j in 0..rows_remaining {
for i in j..rows_remaining {
l[(jb + jb_size + i, jb + jb_size + j)] =
l[(jb + jb_size + i, jb + jb_size + j)] - update[(i, j)];
}
}
}
jb += jb_size;
}
Ok(())
}
/// Unblocked Cholesky for a diagonal block only (rows/cols jb to jb+jb_size).
fn unblocked_factor_block(
l: &mut Mat<T>,
n: usize,
jb: usize,
jb_size: usize,
) -> Result<(), CholeskyError> {
for i in 0..jb_size {
let gi = jb + i; // Global index
// Compute diagonal element
let mut sum = T::zero();
for k in jb..gi {
sum = sum + l[(gi, k)] * l[(gi, k)];
}
let diag = l[(gi, gi)] - sum;
// Check for positive definiteness
let tol = <T as Scalar>::epsilon()
* <T as FromPrimitive>::from_usize(n).unwrap_or(<T as One>::one());
if diag <= tol {
return Err(CholeskyError::NotPositiveDefinite { index: gi });
}
l[(gi, gi)] = Real::sqrt(diag);
// Compute off-diagonal elements in this column (within the block only)
for j in (i + 1)..jb_size {
let gj = jb + j;
let mut sum = T::zero();
for k in jb..gi {
sum = sum + l[(gj, k)] * l[(gi, k)];
}
l[(gj, gi)] = (l[(gj, gi)] - sum) / l[(gi, gi)];
}
// Note: Elements below the block (L21) are computed via TRSM, not here
}
Ok(())
}
/// Unblocked Cholesky factorization (for small matrices).
fn unblocked_factor(l: &mut Mat<T>, n: usize, start: usize) -> Result<(), CholeskyError> {
for i in start..n {
for j in start..=i {
let mut sum = T::zero();
if j == i {
// Diagonal element
for k in start..j {
sum = sum + l[(j, k)] * l[(j, k)];
}
let diag = l[(i, i)] - sum;
let tol = <T as Scalar>::epsilon()
* <T as FromPrimitive>::from_usize(n).unwrap_or(<T as One>::one());
if diag <= tol {
return Err(CholeskyError::NotPositiveDefinite { index: i });
}
l[(i, j)] = Real::sqrt(diag);
} else {
// Off-diagonal element
for k in start..j {
sum = sum + l[(i, k)] * l[(j, k)];
}
l[(i, j)] = (l[(i, j)] - sum) / l[(j, j)];
}
}
}
Ok(())
}
}
// Recursive cache-oblivious Cholesky factorization
impl<T: Field + Real + GemmKernel + bytemuck::Zeroable> Cholesky<T> {
/// Recursion threshold: matrices at or below this size use the unblocked algorithm.
const RECURSIVE_THRESHOLD: usize = 64;
/// Computes the Cholesky decomposition using a recursive cache-oblivious algorithm.
///
/// This divide-and-conquer approach automatically adapts to the cache hierarchy
/// by recursively splitting the matrix into quadrants. At each level:
///
/// 1. Factor the top-left quadrant A11 recursively to get L11
/// 2. Solve L21 = A21 * L11^{-T} via TRSM
/// 3. Update A22 -= L21 * L21^T via SYRK (symmetric rank-k update)
/// 4. Factor the updated A22 recursively to get L22
///
/// For matrices smaller than the recursion threshold (64), falls back to the
/// unblocked algorithm which is more efficient at that scale.
///
/// # Arguments
///
/// * `a` - A symmetric positive definite matrix (only lower triangle is read)
///
/// # Example
///
/// ```
/// use oxiblas_lapack::cholesky::Cholesky;
/// use oxiblas_matrix::Mat;
///
/// let n = 200;
/// let mut a = Mat::zeros(n, n);
/// for i in 0..n {
/// a[(i, i)] = 2.0;
/// if i > 0 {
/// a[(i, i - 1)] = -1.0;
/// a[(i - 1, i)] = -1.0;
/// }
/// }
///
/// let chol = Cholesky::compute_recursive(a.as_ref()).expect("Matrix is SPD");
/// let det = chol.determinant();
/// ```
///
/// # Errors
///
/// Returns `CholeskyError::NotSquare` if the matrix is not square.
/// Returns `CholeskyError::NotPositiveDefinite` if the matrix is not positive definite.
pub fn compute_recursive(a: MatRef<'_, T>) -> Result<Self, CholeskyError> {
let n = a.nrows();
if n != a.ncols() {
return Err(CholeskyError::NotSquare {
nrows: n,
ncols: a.ncols(),
});
}
if n == 0 {
return Ok(Cholesky {
l: Mat::zeros(0, 0),
});
}
// Copy lower triangular part of A into L
let mut l = Mat::zeros(n, n);
for j in 0..n {
for i in j..n {
l[(i, j)] = a[(i, j)];
}
}
Self::recursive_factor(&mut l, n, 0)?;
Ok(Cholesky { l })
}
/// Recursive Cholesky factorization on a submatrix starting at (offset, offset).
///
/// Operates in-place on the lower triangular part of `l`.
/// The submatrix from (offset, offset) to (offset+size-1, offset+size-1) is factored.
fn recursive_factor(l: &mut Mat<T>, size: usize, offset: usize) -> Result<(), CholeskyError> {
// Base case: use unblocked algorithm for small matrices
if size <= Self::RECURSIVE_THRESHOLD {
let full_n = l.nrows();
Self::unblocked_factor_block(l, full_n, offset, size)?;
return Ok(());
}
// Split: n1 = size/2 (upper half), n2 = size - n1 (lower half)
let n1 = size / 2;
let n2 = size - n1;
// Step 1: Recursively factor A11 (top-left n1 x n1 block)
Self::recursive_factor(l, n1, offset)?;
// Step 2: Solve L21 = A21 * L11^{-T} via TRSM
// Extract L11 (lower triangular, already factored)
let mut l11 = Mat::zeros(n1, n1);
for i in 0..n1 {
for j in 0..=i {
l11[(i, j)] = l[(offset + i, offset + j)];
}
}
// Extract A21 (the block that will become L21)
let mut l21 = Mat::zeros(n2, n1);
for j in 0..n1 {
for i in 0..n2 {
l21[(i, j)] = l[(offset + n1 + i, offset + j)];
}
}
// TRSM: B = B * inv(L11^T), where B = L21
// Side::Right, Uplo::Lower, Trans::Trans, Diag::NonUnit
let _ = trsm_in_place(
Side::Right,
Uplo::Lower,
Trans::Trans,
Diag::NonUnit,
l11.as_ref(),
l21.as_mut(),
);
// Copy L21 back into l
for j in 0..n1 {
for i in 0..n2 {
l[(offset + n1 + i, offset + j)] = l21[(i, j)];
}
}
// Step 3: Symmetric rank-k update on A22
// A22 -= L21 * L21^T (only lower triangle)
let mut a22 = Mat::zeros(n2, n2);
for j in 0..n2 {
for i in j..n2 {
a22[(i, j)] = l[(offset + n1 + i, offset + n1 + j)];
}
}
use oxiblas_blas::level3::syrk::syrk;
// SYRK: C = alpha*A*A^T + beta*C => A22 = -1*L21*L21^T + 1*A22
let _ = syrk(
Uplo::Lower,
Trans::NoTrans,
-T::one(),
l21.as_ref(),
T::one(),
a22.as_mut(),
);
// Copy updated A22 back into l (lower triangle only)
for j in 0..n2 {
for i in j..n2 {
l[(offset + n1 + i, offset + n1 + j)] = a22[(i, j)];
}
}
// Step 4: Recursively factor updated A22
Self::recursive_factor(l, n2, offset + n1)?;
Ok(())
}
}
// Optimized automatic algorithm selection for f64 and f32
impl<T: Field + Real + GemmKernel + bytemuck::Zeroable> Cholesky<T> {
/// Computes the Cholesky decomposition with automatic algorithm selection.
///
/// For matrices with size >= 128, automatically uses the blocked algorithm
/// for better cache efficiency and performance. Otherwise uses the unblocked
/// algorithm which has less overhead for small matrices.
///
/// This method is available for f32 and f64 types which have optimized GEMM kernels.
///
/// # Example
///
/// ```
/// use oxiblas_lapack::cholesky::Cholesky;
/// use oxiblas_matrix::Mat;
///
/// let n = 256;
/// let mut a = Mat::zeros(n, n);
/// for i in 0..n {
/// a[(i, i)] = 2.0;
/// if i > 0 {
/// a[(i, i - 1)] = -1.0;
/// a[(i - 1, i)] = -1.0;
/// }
/// }
///
/// // Automatically uses blocked algorithm for n >= 128
/// let chol = Cholesky::compute_auto(a.as_ref()).unwrap();
/// ```
pub fn compute_auto(a: MatRef<'_, T>) -> Result<Self, CholeskyError> {
const AUTO_BLOCK_THRESHOLD: usize = 128;
let n = a.nrows();
// For large matrices, use blocked algorithm automatically
if n >= AUTO_BLOCK_THRESHOLD {
Self::compute_blocked(a)
} else {
// Use unblocked for small matrices
Self::compute(a)
}
}
}
// Parallel blocked Cholesky factorization
#[cfg(feature = "parallel")]
impl<T: Field + Real + GemmKernel + bytemuck::Zeroable + Send + Sync> Cholesky<T> {
/// Computes the Cholesky decomposition using a parallel blocked algorithm.
///
/// Parallelizes the GEMM (symmetric rank-k) updates within the blocked
/// factorization using Rayon. For matrices smaller than the block size,
/// falls back to the sequential unblocked algorithm.
///
/// # Arguments
///
/// * `a` - A symmetric positive definite matrix
///
/// # Returns
///
/// The Cholesky decomposition on success.
///
/// # Errors
///
/// Returns `CholeskyError::NotSquare` if the matrix is not square.
/// Returns `CholeskyError::NotPositiveDefinite` if the matrix is not positive definite.
#[inline]
pub fn compute_blocked_par(a: MatRef<'_, T>) -> Result<Self, CholeskyError> {
let nb = crate::workspace::optimal_block_size_cholesky(a.nrows());
Self::compute_blocked_par_with_block_size(a, nb)
}
/// Computes parallel blocked Cholesky decomposition with a specified block size.
pub fn compute_blocked_par_with_block_size(
a: MatRef<'_, T>,
nb: usize,
) -> Result<Self, CholeskyError> {
let n = a.nrows();
if n != a.ncols() {
return Err(CholeskyError::NotSquare {
nrows: n,
ncols: a.ncols(),
});
}
if n == 0 {
return Ok(Cholesky {
l: Mat::zeros(0, 0),
});
}
// Copy lower triangular part of A
let mut l = Mat::zeros(n, n);
for j in 0..n {
for i in j..n {
l[(i, j)] = a[(i, j)];
}
}
// Use blocked parallel algorithm for larger matrices
if n >= nb {
Self::blocked_factor_par(&mut l, n, nb)?;
} else {
Self::unblocked_factor(&mut l, n, 0)?;
}
Ok(Cholesky { l })
}
/// Blocked Cholesky factorization with parallel GEMM for symmetric updates.
fn blocked_factor_par(l: &mut Mat<T>, n: usize, nb: usize) -> Result<(), CholeskyError> {
let mut jb = 0;
while jb < n {
// Current block size (may be smaller for last block)
let jb_size = nb.min(n - jb);
// Factor diagonal block A11 using unblocked Cholesky (sequential -- panel is small)
Self::unblocked_factor_block(l, n, jb, jb_size)?;
// If there are more rows below this block
if jb + jb_size < n {
let rows_remaining = n - jb - jb_size;
// Extract L11 (the diagonal block we just factored)
let mut l11: Mat<T> = Mat::zeros(jb_size, jb_size);
for i in 0..jb_size {
for j in 0..=i {
l11[(i, j)] = l[(jb + i, jb + j)];
}
}
// Extract A21 block (will become L21)
let mut l21: Mat<T> = Mat::zeros(rows_remaining, jb_size);
for j in 0..jb_size {
for i in 0..rows_remaining {
l21[(i, j)] = l[(jb + jb_size + i, jb + j)];
}
}
// Solve L21 = A21 * L11^(-T) using TRSM
// TRSM internally uses parallel GEMM when the "parallel" feature is active
let _ = trsm_in_place(
Side::Right,
Uplo::Lower,
Trans::Trans,
Diag::NonUnit,
l11.as_ref(),
l21.as_mut(),
);
// Copy L21 back
for j in 0..jb_size {
for i in 0..rows_remaining {
l[(jb + jb_size + i, jb + j)] = l21[(i, j)];
}
}
// Update A22 -= L21 * L21^T using parallel GEMM (symmetric rank-k update)
let l21_t = l21.transpose();
let mut update: Mat<T> = Mat::zeros(rows_remaining, rows_remaining);
gemm_with_par(
T::one(),
l21.as_ref(),
l21_t.as_ref(),
T::zero(),
update.as_mut(),
Par::Rayon,
);
// Subtract update from lower triangular part of A22
for j in 0..rows_remaining {
for i in j..rows_remaining {
l[(jb + jb_size + i, jb + jb_size + j)] =
l[(jb + jb_size + i, jb + jb_size + j)] - update[(i, j)];
}
}
}
jb += jb_size;
}
Ok(())
}
}