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
//! LU decomposition and solves.
use core::hint::cold_path;
use crate::matrix::{FiniteMatrix, Matrix};
use crate::vector::{FiniteVector, Vector};
use crate::{LaError, Tolerance};
/// LU decomposition (PA = LU) with partial pivoting.
#[must_use]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Lu<const D: usize> {
factors: LuFactors<D>,
piv: [usize; D],
piv_sign: f64,
}
/// In-place LU factor storage whose `U` diagonal is finite and usable.
///
/// Construction through [`Lu::factor_finite`] proves every stored entry is
/// finite and every `U[i,i]` satisfies the factorization tolerance.
#[derive(Clone, Copy, Debug, PartialEq)]
struct LuFactors<const D: usize> {
storage: Matrix<D>,
}
impl<const D: usize> LuFactors<D> {
/// Construct factors after LU factorization has proven the storage invariant.
#[inline]
const fn new_unchecked(storage: Matrix<D>) -> Self {
Self { storage }
}
/// Borrow a factor row.
#[inline]
#[must_use]
const fn row(&self, index: usize) -> &[f64; D] {
&self.storage.rows[index]
}
/// Return a diagonal entry of `U`.
#[inline]
#[must_use]
const fn diag(&self, index: usize) -> f64 {
self.storage.rows[index][index]
}
}
impl<const D: usize> Lu<D> {
/// Factor a finite square matrix into in-place LU storage for
/// `FiniteMatrix::lu`.
///
/// The input has already proven finite entries, so LU construction rejects
/// numerically singular pivots and non-finite elimination intermediates
/// before callers can observe a [`Lu`] value. Completed factor storage is
/// checked before return so successful factors do not contain a non-finite
/// value produced during elimination.
#[inline]
pub(crate) fn factor_finite(a: FiniteMatrix<D>, tol: Tolerance) -> Result<Self, LaError> {
let mut lu = a.into_matrix();
let tol = tol.get();
let mut piv = [0usize; D];
for (i, p) in piv.iter_mut().enumerate() {
*p = i;
}
let mut piv_sign = 1.0;
for k in 0..D {
// Choose pivot row.
let mut pivot_row = k;
let mut pivot_abs = lu.rows[k][k].abs();
for r in (k + 1)..D {
let v = lu.rows[r][k].abs();
if v > pivot_abs {
pivot_abs = v;
pivot_row = r;
}
}
if pivot_abs <= tol {
cold_path();
return Err(LaError::Singular { pivot_col: k });
}
if pivot_row != k {
lu.rows.swap(k, pivot_row);
piv.swap(k, pivot_row);
piv_sign = -piv_sign;
}
let pivot = lu.rows[k][k];
// Eliminate below pivot.
for r in (k + 1)..D {
let mult = lu.rows[r][k] / pivot;
lu.rows[r][k] = mult;
for c in (k + 1)..D {
let updated = (-mult).mul_add(lu.rows[k][c], lu.rows[r][c]);
lu.rows[r][c] = updated;
}
}
}
let lu = FiniteMatrix::new(lu)?.into_matrix();
Ok(Self {
factors: LuFactors::new_unchecked(lu),
piv,
piv_sign,
})
}
/// Solve `A x = b` using this LU factorization.
///
/// `solve_vec` performs floating-point forward/back substitution and does
/// not provide a certified absolute rounding-error bound for the returned
/// solution. Callers should not expect an absolute error bound like
/// [`Matrix::det_errbound`](crate::Matrix::det_errbound) or the
/// `ERR_COEFF_*` determinant constants provide.
///
/// # Examples
/// ```
/// use la_stack::prelude::*;
///
/// # fn main() -> Result<(), LaError> {
/// let a = Matrix::<2>::try_from_rows([[1.0, 2.0], [3.0, 4.0]])?;
/// let lu = a.lu(DEFAULT_PIVOT_TOL)?;
///
/// let b = Vector::<2>::try_new([5.0, 11.0])?;
/// let x = lu.solve_vec(b)?.into_array();
///
/// assert!((x[0] - 1.0).abs() <= 1e-12);
/// assert!((x[1] - 2.0).abs() <= 1e-12);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns [`LaError::NonFinite`] if the right-hand side contains
/// NaN/infinity or a computed substitution intermediate overflows to NaN or
/// infinity. The right-hand side is revalidated at this boundary before
/// entering substitution; public callers normally encounter the same
/// rejection earlier through [`Vector::try_new`](crate::Vector::try_new).
#[inline]
pub const fn solve_vec(&self, b: Vector<D>) -> Result<Vector<D>, LaError> {
let b = match FiniteVector::new(b) {
Ok(b) => b,
Err(err) => return Err(err),
};
match self.solve_finite_vec(b) {
Ok(x) => Ok(x.into_vector()),
Err(err) => Err(err),
}
}
/// Solve `A x = b` using this LU factorization and a finite right-hand side.
///
/// The right-hand side entries and stored factors are known finite, so this
/// path only checks computed substitution overflows.
///
/// # Errors
/// Returns [`LaError::NonFinite`] if a computed substitution intermediate
/// overflows to NaN or infinity.
#[inline]
pub(crate) const fn solve_finite_vec(
&self,
b: FiniteVector<D>,
) -> Result<FiniteVector<D>, LaError> {
let mut x = [0.0; D];
let mut i = 0;
let b = b.as_array();
while i < D {
x[i] = b[self.piv[i]];
i += 1;
}
// Forward substitution for L (unit diagonal).
let mut i = 0;
while i < D {
let mut sum = x[i];
let row = self.factors.row(i);
let mut j = 0;
while j < i {
sum = (-row[j]).mul_add(x[j], sum);
j += 1;
}
if !sum.is_finite() {
cold_path();
return Err(LaError::non_finite_at(i));
}
x[i] = sum;
i += 1;
}
// Back substitution for U.
let mut ii = 0;
while ii < D {
let i = D - 1 - ii;
let mut sum = x[i];
let row = self.factors.row(i);
let mut j = i + 1;
while j < D {
sum = (-row[j]).mul_add(x[j], sum);
j += 1;
}
let diag = row[i];
if !sum.is_finite() {
cold_path();
return Err(LaError::non_finite_at(i));
}
let quotient = sum / diag;
if !quotient.is_finite() {
cold_path();
return Err(LaError::non_finite_at(i));
}
x[i] = quotient;
ii += 1;
}
Ok(FiniteVector::new_unchecked(Vector::new_unchecked(x)))
}
/// Determinant of the original matrix.
///
/// # Examples
/// ```
/// use la_stack::prelude::*;
///
/// # fn main() -> Result<(), LaError> {
/// let a = Matrix::<2>::try_from_rows([[1.0, 2.0], [3.0, 4.0]])?;
/// let lu = a.lu(DEFAULT_PIVOT_TOL)?;
///
/// let det = lu.det()?;
/// assert!((det - (-2.0)).abs() <= 1e-12);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns [`LaError::NonFinite`] if the determinant product overflows to
/// NaN or infinity.
#[inline]
pub const fn det(&self) -> Result<f64, LaError> {
let mut det = self.piv_sign;
let mut i = 0;
while i < D {
det *= self.factors.diag(i);
if !det.is_finite() {
cold_path();
return Err(LaError::non_finite_at(i));
}
i += 1;
}
Ok(det)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DEFAULT_PIVOT_TOL;
use core::assert_matches;
use core::hint::black_box;
use approx::assert_abs_diff_eq;
use pastey::paste;
macro_rules! gen_public_api_pivoting_solve_vec_and_det_tests {
($d:literal) => {
paste! {
#[test]
fn [<public_api_lu_solve_vec_pivoting_ $d d>]() {
// Public API path under test:
// Matrix::lu (pub) -> Lu::solve_vec (pub).
// Permutation matrix that swaps the first two basis vectors.
// This forces pivoting in column 0 for any D >= 2.
let mut rows = [[0.0f64; $d]; $d];
for i in 0..$d {
rows[i][i] = 1.0;
}
rows.swap(0, 1);
let a = Matrix::<$d>::from_rows(black_box(rows));
let lu_fn: fn(Matrix<$d>, Tolerance) -> Result<Lu<$d>, LaError> =
black_box(Matrix::<$d>::lu);
let lu = lu_fn(a, DEFAULT_PIVOT_TOL).unwrap();
// Pick a simple RHS with unique entries, so the expected swap is obvious.
let b_arr = {
let mut arr = [0.0f64; $d];
let mut val = 1.0f64;
for dst in arr.iter_mut() {
*dst = val;
val += 1.0;
}
arr
};
let mut expected = b_arr;
expected.swap(0, 1);
let b = Vector::<$d>::new(black_box(b_arr));
let solve_fn: fn(&Lu<$d>, Vector<$d>) -> Result<Vector<$d>, LaError> =
black_box(Lu::<$d>::solve_vec);
let x = solve_fn(&lu, b).unwrap().into_array();
for i in 0..$d {
assert_abs_diff_eq!(x[i], expected[i], epsilon = 1e-12);
}
}
#[test]
fn [<public_api_lu_det_pivoting_ $d d>]() {
// Public API path under test:
// Matrix::lu (pub) -> Lu::det (pub).
// Permutation matrix that swaps the first two basis vectors.
let mut rows = [[0.0f64; $d]; $d];
for i in 0..$d {
rows[i][i] = 1.0;
}
rows.swap(0, 1);
let a = Matrix::<$d>::from_rows(black_box(rows));
let lu_fn: fn(Matrix<$d>, Tolerance) -> Result<Lu<$d>, LaError> =
black_box(Matrix::<$d>::lu);
let lu = lu_fn(a, DEFAULT_PIVOT_TOL).unwrap();
// Row swap ⇒ determinant sign flip.
let det_fn: fn(&Lu<$d>) -> Result<f64, LaError> =
black_box(Lu::<$d>::det);
assert_abs_diff_eq!(det_fn(&lu).unwrap(), -1.0, epsilon = 1e-12);
}
}
};
}
gen_public_api_pivoting_solve_vec_and_det_tests!(2);
gen_public_api_pivoting_solve_vec_and_det_tests!(3);
gen_public_api_pivoting_solve_vec_and_det_tests!(4);
gen_public_api_pivoting_solve_vec_and_det_tests!(5);
macro_rules! gen_public_api_tridiagonal_smoke_solve_vec_and_det_tests {
($d:literal) => {
paste! {
#[test]
fn [<public_api_lu_solve_vec_tridiagonal_smoke_ $d d>]() {
// Public API path under test:
// Matrix::lu (pub) -> Lu::solve_vec (pub).
// Classic SPD tridiagonal: 2 on diagonal, -1 on sub/super-diagonals.
#[allow(clippy::large_stack_arrays)]
let mut rows = [[0.0f64; $d]; $d];
for i in 0..$d {
rows[i][i] = 2.0;
if i > 0 {
rows[i][i - 1] = -1.0;
}
if i + 1 < $d {
rows[i][i + 1] = -1.0;
}
}
let a = Matrix::<$d>::from_rows(black_box(rows));
let lu_fn: fn(Matrix<$d>, Tolerance) -> Result<Lu<$d>, LaError> =
black_box(Matrix::<$d>::lu);
let lu = lu_fn(a, DEFAULT_PIVOT_TOL).unwrap();
// Choose x = 1, so b = A x is simple: [1, 0, 0, ..., 0, 1].
let mut b_arr = [0.0f64; $d];
b_arr[0] = 1.0;
b_arr[$d - 1] = 1.0;
let b = Vector::<$d>::new(black_box(b_arr));
let solve_fn: fn(&Lu<$d>, Vector<$d>) -> Result<Vector<$d>, LaError> =
black_box(Lu::<$d>::solve_vec);
let x = solve_fn(&lu, b).unwrap().into_array();
for &x_i in &x {
assert_abs_diff_eq!(x_i, 1.0, epsilon = 1e-9);
}
}
#[test]
fn [<public_api_lu_det_tridiagonal_smoke_ $d d>]() {
// Public API path under test:
// Matrix::lu (pub) -> Lu::det (pub).
// Classic SPD tridiagonal: 2 on diagonal, -1 on sub/super-diagonals.
// Determinant is known exactly: det = D + 1.
#[allow(clippy::large_stack_arrays)]
let mut rows = [[0.0f64; $d]; $d];
for i in 0..$d {
rows[i][i] = 2.0;
if i > 0 {
rows[i][i - 1] = -1.0;
}
if i + 1 < $d {
rows[i][i + 1] = -1.0;
}
}
let a = Matrix::<$d>::from_rows(black_box(rows));
let lu_fn: fn(Matrix<$d>, Tolerance) -> Result<Lu<$d>, LaError> =
black_box(Matrix::<$d>::lu);
let lu = lu_fn(a, DEFAULT_PIVOT_TOL).unwrap();
let det_fn: fn(&Lu<$d>) -> Result<f64, LaError> =
black_box(Lu::<$d>::det);
assert_abs_diff_eq!(det_fn(&lu).unwrap(), f64::from($d) + 1.0, epsilon = 1e-8);
}
}
};
}
gen_public_api_tridiagonal_smoke_solve_vec_and_det_tests!(16);
gen_public_api_tridiagonal_smoke_solve_vec_and_det_tests!(32);
gen_public_api_tridiagonal_smoke_solve_vec_and_det_tests!(64);
#[test]
fn solve_1x1() {
let a = Matrix::<1>::from_rows(black_box([[2.0]]));
let lu = FiniteMatrix::new(a).unwrap().lu(DEFAULT_PIVOT_TOL).unwrap();
let b = Vector::<1>::new(black_box([6.0]));
let solve_fn: fn(&Lu<1>, Vector<1>) -> Result<Vector<1>, LaError> =
black_box(Lu::<1>::solve_vec);
let x = solve_fn(&lu, b).unwrap().into_array();
assert_abs_diff_eq!(x[0], 3.0, epsilon = 1e-12);
let det_fn: fn(&Lu<1>) -> Result<f64, LaError> = black_box(Lu::<1>::det);
assert_abs_diff_eq!(det_fn(&lu).unwrap(), 2.0, epsilon = 0.0);
}
#[test]
fn solve_2x2_basic() {
let a = Matrix::<2>::from_rows(black_box([[1.0, 2.0], [3.0, 4.0]]));
let lu = FiniteMatrix::new(a).unwrap().lu(DEFAULT_PIVOT_TOL).unwrap();
let b = Vector::<2>::new(black_box([5.0, 11.0]));
let solve_fn: fn(&Lu<2>, Vector<2>) -> Result<Vector<2>, LaError> =
black_box(Lu::<2>::solve_vec);
let x = solve_fn(&lu, b).unwrap().into_array();
assert_abs_diff_eq!(x[0], 1.0, epsilon = 1e-12);
assert_abs_diff_eq!(x[1], 2.0, epsilon = 1e-12);
}
#[test]
fn det_2x2_basic() {
let a = Matrix::<2>::from_rows(black_box([[1.0, 2.0], [3.0, 4.0]]));
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
let det_fn: fn(&Lu<2>) -> Result<f64, LaError> = black_box(Lu::<2>::det);
assert_abs_diff_eq!(det_fn(&lu).unwrap(), -2.0, epsilon = 1e-12);
}
#[test]
fn det_requires_pivot_sign() {
// Row swap ⇒ determinant sign flip.
let a = Matrix::<2>::from_rows(black_box([[0.0, 1.0], [1.0, 0.0]]));
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
let det_fn: fn(&Lu<2>) -> Result<f64, LaError> = black_box(Lu::<2>::det);
assert_abs_diff_eq!(det_fn(&lu).unwrap(), -1.0, epsilon = 0.0);
}
#[test]
fn solve_requires_pivoting() {
let a = Matrix::<2>::from_rows(black_box([[0.0, 1.0], [1.0, 0.0]]));
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
let b = Vector::<2>::new(black_box([1.0, 2.0]));
let solve_fn: fn(&Lu<2>, Vector<2>) -> Result<Vector<2>, LaError> =
black_box(Lu::<2>::solve_vec);
let x = solve_fn(&lu, b).unwrap().into_array();
assert_abs_diff_eq!(x[0], 2.0, epsilon = 1e-12);
assert_abs_diff_eq!(x[1], 1.0, epsilon = 1e-12);
}
#[test]
fn singular_detected() {
let a = Matrix::<2>::from_rows(black_box([[1.0, 2.0], [2.0, 4.0]]));
let err = a.lu(DEFAULT_PIVOT_TOL).unwrap_err();
assert_eq!(err, LaError::Singular { pivot_col: 1 });
}
#[test]
fn singular_due_to_tolerance_at_first_pivot() {
// Not exactly singular, but below DEFAULT_PIVOT_TOL.
let a = Matrix::<2>::from_rows(black_box([[1e-13, 0.0], [0.0, 1.0]]));
let err = a.lu(DEFAULT_PIVOT_TOL).unwrap_err();
assert_eq!(err, LaError::Singular { pivot_col: 0 });
}
#[test]
fn invalid_tolerance_rejected() {
assert_eq!(
Tolerance::new(-1.0),
Err(LaError::InvalidTolerance { value: -1.0 })
);
assert_matches!(
Tolerance::new(f64::NAN),
Err(LaError::InvalidTolerance { value }) if value.is_nan()
);
assert_eq!(
Tolerance::new(f64::INFINITY),
Err(LaError::InvalidTolerance {
value: f64::INFINITY,
})
);
}
#[test]
fn matrix_constructor_rejects_nonfinite_pivot_entry() {
let err = Matrix::<2>::try_from_rows([[f64::NAN, 0.0], [0.0, 1.0]]).unwrap_err();
assert_eq!(
err,
LaError::NonFinite {
row: Some(0),
col: 0
}
);
}
#[test]
fn matrix_constructor_rejects_nonfinite_pivot_column_entry() {
let err = Matrix::<2>::try_from_rows([[1.0, 0.0], [f64::INFINITY, 1.0]]).unwrap_err();
assert_eq!(
err,
LaError::NonFinite {
row: Some(1),
col: 0
}
);
}
#[test]
fn nonfinite_detected_in_trailing_update() {
let a =
Matrix::<3>::from_rows([[1.0, f64::MAX, 0.0], [-1.0, f64::MAX, 0.0], [0.0, 0.0, 1.0]]);
let err = a.lu(DEFAULT_PIVOT_TOL).unwrap_err();
assert_eq!(
err,
LaError::NonFinite {
row: Some(1),
col: 1,
}
);
}
#[test]
fn solve_vec_nonfinite_forward_substitution_overflow() {
// L has a -1 multiplier, and a large RHS makes forward substitution overflow.
let a = Matrix::<3>::from_rows([[1.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
let b = Vector::<3>::new([1.0e308, 1.0e308, 0.0]);
let err = lu.solve_vec(b).unwrap_err();
assert_eq!(err, LaError::NonFinite { row: None, col: 1 });
}
#[test]
fn solve_vec_nonfinite_back_substitution_overflow() {
// Make x[1] overflow during back substitution, then ensure it is detected on the next row.
let a = Matrix::<2>::from_rows([[1.0, 1.0], [0.0, 2.0e-12]]);
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
let b = Vector::<2>::new([0.0, 1.0e300]);
let err = lu.solve_vec(b).unwrap_err();
assert_eq!(err, LaError::NonFinite { row: None, col: 1 });
}
#[test]
fn solve_vec_nonfinite_back_substitution_sum_overflow() {
// Upper-triangular U with a very large off-diagonal in row 1 and a
// very large x[2] produced by the RHS. The back-substitution
// accumulator `sum = (-row[j]).mul_add(x[j], sum)` overflows while
// reducing row 1, so the failure is detected via the `!sum.is_finite()`
// branch of the combined diag/sum check (distinct from the
// `q = sum / diag` overflow path covered above).
let a = Matrix::<3>::from_rows([[1.0, 0.0, 0.0], [0.0, 1.0, 1.0e200], [0.0, 0.0, 1.0]]);
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
let b = Vector::<3>::new([0.0, 0.0, 1.0e200]);
let err = lu.solve_vec(b).unwrap_err();
assert_eq!(err, LaError::NonFinite { row: None, col: 1 });
}
#[test]
fn det_rejects_product_overflow() {
let a = Matrix::<5>::from_rows([
[1.0e100, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0e100, 0.0, 0.0, 0.0],
[0.0, 0.0, 1.0e100, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0e100, 0.0],
[0.0, 0.0, 0.0, 0.0, 1.0e100],
]);
let lu = a.lu(DEFAULT_PIVOT_TOL).unwrap();
assert_eq!(lu.det(), Err(LaError::NonFinite { row: None, col: 3 }));
}
macro_rules! gen_solve_vec_boundary_tests {
($d:literal) => {
paste! {
/// Raw non-finite right-hand sides are rejected before a
/// public caller can construct a `Vector`.
#[test]
fn [<solve_vec_rhs_boundary_rejects_non_finite_ $d d>]() {
let mut rhs = [1.0; $d];
rhs[$d - 1] = f64::NAN;
assert_eq!(
Vector::<$d>::try_new(rhs),
Err(LaError::NonFinite {
row: None,
col: $d - 1,
})
);
}
#[test]
fn [<solve_vec_revalidates_unchecked_rhs_storage_ $d d>]() {
let lu = Matrix::<$d>::identity().lu(DEFAULT_PIVOT_TOL).unwrap();
let mut rhs = [1.0; $d];
rhs[$d - 1] = f64::NAN;
let rhs = Vector::<$d>::new_unchecked(rhs);
assert_eq!(
lu.solve_vec(rhs),
Err(LaError::NonFinite {
row: None,
col: $d - 1,
})
);
}
}
};
}
gen_solve_vec_boundary_tests!(2);
gen_solve_vec_boundary_tests!(3);
gen_solve_vec_boundary_tests!(4);
gen_solve_vec_boundary_tests!(5);
// -----------------------------------------------------------------------
// Const-evaluability tests.
//
// These prove that `Lu::det` and `Lu::solve_vec` are truly `const fn` by
// forcing the compiler to evaluate them inside a `const` initializer.
// `Lu::factor` is not (yet) `const fn` because it relies on `<[T]>::swap`,
// which is not const-stable; we therefore construct `Lu<D>` directly.
// -----------------------------------------------------------------------
#[test]
fn lu_det_const_eval_d2() {
const DET: Result<f64, LaError> = {
// Triangular factors with diag [2.0, 3.0] and no row swaps.
let mut factors = Matrix::<2>::identity();
factors.rows[0][0] = 2.0;
factors.rows[1][1] = 3.0;
let lu = Lu::<2> {
factors: LuFactors::new_unchecked(factors),
piv: [0, 1],
piv_sign: 1.0,
};
lu.det()
};
assert_eq!(DET, Ok(6.0));
}
#[test]
fn lu_det_const_eval_d3_row_swap() {
const DET: Result<f64, LaError> = {
// Identity factors but `piv_sign = -1.0` encoding a single row swap;
// the determinant magnitude is 1 but the sign flips.
let lu = Lu::<3> {
factors: LuFactors::new_unchecked(Matrix::<3>::identity()),
piv: [1, 0, 2],
piv_sign: -1.0,
};
lu.det()
};
assert_eq!(DET, Ok(-1.0));
}
#[test]
fn lu_solve_vec_const_eval_d2() {
// Identity LU ⇒ solve_vec returns the permuted RHS untouched.
const X: [f64; 2] = {
let lu = Lu::<2> {
factors: LuFactors::new_unchecked(Matrix::<2>::identity()),
piv: [0, 1],
piv_sign: 1.0,
};
let b = Vector::<2>::new([1.0, 2.0]);
match lu.solve_vec(b) {
Ok(v) => v.into_array(),
Err(_) => [0.0, 0.0],
}
};
assert!((X[0] - 1.0).abs() <= 1e-12);
assert!((X[1] - 2.0).abs() <= 1e-12);
}
}