matrixpacked 0.1.0

Packed structured matrices with BLAS and LAPACK integration
Documentation
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
//! Options and result types shared by packed triangular BLAS/LAPACK operations.
//!
//! [`Transpose`], [`Diagonal`], [`MatrixNorm`], and [`ConditionNorm`] configure
//! methods implemented on [`crate::PackedLower`] and [`crate::PackedUpper`]. A
//! typical workflow constructs one of those matrices, multiplies or solves a
//! vector, then optionally estimates a norm/condition or refines column-major
//! solutions. [`RefinementReport`] contains one forward/backward estimate per
//! RHS. The [crate guide](crate) compares the available solve levels.

/// Matrix operation applied by a triangular multiply or solve.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Transpose {
    /// Use `A` directly.
    #[default]
    None,
    /// Use the transpose `A^T`.
    Transpose,
    /// Use the conjugate transpose `A^H` (`A^T` for real scalars).
    ConjugateTranspose,
}

impl Transpose {
    pub(crate) const fn as_lapack(self) -> u8 {
        match self {
            Self::None => b'N',
            Self::Transpose => b'T',
            Self::ConjugateTranspose => b'C',
        }
    }
}

/// Whether diagonal entries are read from packed storage or treated as one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Diagonal {
    /// Read diagonal entries from packed storage.
    #[default]
    NonUnit,
    /// Treat every diagonal entry as one without reading stored diagonal values.
    Unit,
}

impl Diagonal {
    pub(crate) const fn as_lapack(self) -> u8 {
        match self {
            Self::NonUnit => b'N',
            Self::Unit => b'U',
        }
    }
}

/// Norms supported by LAPACK's `xLANTP` packed triangular norm routine.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatrixNorm {
    /// Maximum absolute matrix element.
    MaxAbs,
    /// Maximum absolute column sum.
    One,
    /// Maximum absolute row sum.
    Infinity,
    /// Frobenius norm, the square root of the sum of squared magnitudes.
    Frobenius,
}

impl MatrixNorm {
    pub(crate) const fn as_lapack(self) -> u8 {
        match self {
            Self::MaxAbs => b'M',
            Self::One => b'1',
            Self::Infinity => b'I',
            Self::Frobenius => b'F',
        }
    }
}

/// Norm used for a reciprocal condition-number estimate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConditionNorm {
    /// Estimate the reciprocal condition number in the one-norm.
    One,
    /// Estimate the reciprocal condition number in the infinity norm.
    Infinity,
}

impl ConditionNorm {
    pub(crate) const fn as_lapack(self) -> u8 {
        match self {
            Self::One => b'1',
            Self::Infinity => b'I',
        }
    }
}

/// Error estimates returned by LAPACK's `xTPRFS` iterative refinement.
#[derive(Clone, Debug, PartialEq)]
pub struct RefinementReport<R> {
    /// Estimated forward error bound for each right-hand side.
    pub forward_error: Vec<R>,
    /// Componentwise relative backward error for each right-hand side.
    pub backward_error: Vec<R>,
}

pub(crate) fn check_strided_vector(
    n: usize,
    len: usize,
    increment: i32,
) -> Result<(), crate::PackedMatrixError> {
    let stride = increment
        .checked_abs()
        .ok_or(crate::PackedMatrixError::InvalidIncrement { increment })? as usize;
    if stride == 0 {
        return Err(crate::PackedMatrixError::InvalidIncrement { increment });
    }
    let expected = if n == 0 {
        0
    } else {
        1 + (n - 1)
            .checked_mul(stride)
            .ok_or(crate::PackedMatrixError::DimensionOverflow { n })?
    };
    if len < expected {
        return Err(crate::PackedMatrixError::InvalidVectorLength {
            expected,
            actual: len,
        });
    }
    Ok(())
}

macro_rules! impl_triangular_packed_ops {
    ($name:ident, $uplo:expr, $label:literal) => {
        impl<T, S> $name<T, S>
        where
            T: crate::backend::TriangularPackedBackend,
            S: crate::storage::PackedStorage<T>,
        {
            /// Returns an owned packed inverse, leaving this matrix unchanged.
            ///
            /// The default treats the diagonal as non-unit. This allocates only packed storage.
            ///
            /// # Errors
            ///
            /// Returns an error for dimension overflow, an illegal LAPACK
            /// argument, or a zero diagonal entry.
            pub fn inverse(&self) -> Result<$name<T>, crate::PackedMatrixError> {
                self.inverse_with_diagonal(crate::Diagonal::NonUnit)
            }

            /// Returns an owned packed inverse with the requested diagonal convention.
            ///
            /// # Errors
            ///
            /// Returns an error for dimension overflow, an illegal LAPACK
            /// argument, or a zero diagonal in non-unit mode.
            pub fn inverse_with_diagonal(
                &self,
                diagonal: crate::Diagonal,
            ) -> Result<$name<T>, crate::PackedMatrixError> {
                let mut inverse = $name::from_vec(self.n, self.as_slice().to_vec())?;
                inverse.inverse_in_place_with_diagonal(diagonal)?;
                Ok(inverse)
            }
        }
        impl<T> $name<T, Vec<T>>
        where
            T: crate::backend::TriangularPackedBackend,
        {
            /// Consumes this matrix and returns its packed inverse without allocating new storage.
            ///
            /// # Errors
            ///
            /// Returns the same errors as [`Self::inverse_in_place`].
            pub fn into_inverse(mut self) -> Result<Self, crate::PackedMatrixError> {
                self.inverse_in_place()?;
                Ok(self)
            }

            /// Consumes this matrix and returns its packed inverse using the requested diagonal convention.
            ///
            /// # Errors
            ///
            /// Returns the same errors as [`Self::inverse_in_place_with_diagonal`].
            pub fn into_inverse_with_diagonal(
                mut self,
                diagonal: crate::Diagonal,
            ) -> Result<Self, crate::PackedMatrixError> {
                self.inverse_in_place_with_diagonal(diagonal)?;
                Ok(self)
            }
        }
        impl<T, S> $name<T, S>
        where
            T: crate::backend::TriangularPackedBackend,
            S: crate::storage::PackedStorage<T>,
        {
            /// Computes `x := op(A)*x` in place using BLAS `xTPMV` without copying `A` or `x`.
            ///
            /// Negative increments traverse the logical vector in reverse BLAS order.
            /// Unit diagonal mode ignores stored diagonal entries.
            ///
            /// # Errors
            ///
            /// Returns an error for a zero stride, insufficient strided storage,
            /// dimension overflow, or invalid backend dimension.
            pub fn mul_vector_strided_in_place(
                &self,
                x: &mut [T],
                increment: i32,
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<(), crate::PackedMatrixError> {
                crate::triangular::check_strided_vector(self.n, x.len(), increment)?;
                unsafe {
                    T::tpmv(
                        $uplo,
                        op.as_lapack(),
                        diagonal.as_lapack(),
                        crate::factorization::checked_n(self.n)?,
                        self.as_slice(),
                        x,
                        increment,
                    )
                };
                Ok(())
            }
            /// Computes contiguous `x := op(A) * x` in place.
            ///
            /// # Errors
            ///
            /// Returns an error unless `x.len() == n` or dimensions are invalid.
            pub fn mul_vector_op_in_place(
                &self,
                x: &mut [T],
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<(), crate::PackedMatrixError> {
                self.mul_vector_strided_in_place(x, 1, op, diagonal)
            }
            /// Computes `x := A * x` for a non-unit triangular matrix.
            ///
            /// # Errors
            ///
            /// Returns an error unless `x.len() == n` or dimensions are invalid.
            pub fn mul_vector_in_place(&self, x: &mut [T]) -> Result<(), crate::PackedMatrixError> {
                self.mul_vector_op_in_place(x, crate::Transpose::None, crate::Diagonal::NonUnit)
            }
            /// Allocates and returns `op(A) * x` with the requested diagonal convention.
            ///
            /// # Errors
            ///
            /// Returns an error unless `x.len() == n` or dimensions are invalid.
            pub fn mul_vector_op(
                &self,
                x: &[T],
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<Vec<T>, crate::PackedMatrixError> {
                let mut y = x.to_vec();
                self.mul_vector_op_in_place(&mut y, op, diagonal)?;
                Ok(y)
            }
            /// Allocates and returns `A * x` for a non-unit triangular matrix.
            ///
            /// # Errors
            ///
            /// Returns an error unless `x.len() == n` or dimensions are invalid.
            pub fn mul_vector(&self, x: &[T]) -> Result<Vec<T>, crate::PackedMatrixError> {
                self.mul_vector_op(x, crate::Transpose::None, crate::Diagonal::NonUnit)
            }

            /// Solves `op(A)*x=b` in place with the single-vector BLAS `xTPSV` routine.
            ///
            /// # Errors
            ///
            /// Returns an error for zero stride, insufficient strided storage,
            /// dimension overflow, or invalid backend dimension. BLAS `xTPSV`
            /// does not diagnose a singular diagonal.
            pub fn solve_vector_blas_strided_in_place(
                &self,
                x: &mut [T],
                increment: i32,
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<(), crate::PackedMatrixError> {
                crate::triangular::check_strided_vector(self.n, x.len(), increment)?;
                unsafe {
                    T::tpsv(
                        $uplo,
                        op.as_lapack(),
                        diagonal.as_lapack(),
                        crate::factorization::checked_n(self.n)?,
                        self.as_slice(),
                        x,
                        increment,
                    )
                };
                Ok(())
            }
            /// Solves contiguous `op(A) * x = b`, overwriting `x` with the solution.
            ///
            /// # Errors
            ///
            /// Returns an error unless the buffer has length `n` or dimensions are invalid.
            pub fn solve_vector_blas_in_place(
                &self,
                x: &mut [T],
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<(), crate::PackedMatrixError> {
                self.solve_vector_blas_strided_in_place(x, 1, op, diagonal)
            }
            /// Allocates a solution of `op(A) * x = b` using BLAS `xTPSV`.
            ///
            /// # Errors
            ///
            /// Returns an error unless `b.len() == n` or dimensions are invalid.
            pub fn solve_vector_blas(
                &self,
                b: &[T],
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<Vec<T>, crate::PackedMatrixError> {
                let mut x = b.to_vec();
                self.solve_vector_blas_in_place(&mut x, op, diagonal)?;
                Ok(x)
            }

            /// Solves one or more column-major right-hand sides with LAPACK `xTPTRS`.
            ///
            /// `b` contains `nrhs` consecutive columns, each of length `n`, and
            /// is overwritten with the corresponding solution.
            ///
            /// # Errors
            ///
            /// Returns an error for a wrong RHS length, dimension overflow, an
            /// illegal LAPACK argument, or a singular non-unit diagonal.
            pub fn solve_many_in_place(
                &self,
                b: &mut [T],
                nrhs: usize,
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<(), crate::PackedMatrixError> {
                crate::factorization::check_rhs_many(self.n, nrhs, b)?;
                let n = crate::factorization::checked_n(self.n)?;
                let mut info = 0;
                unsafe {
                    T::tptrs(
                        $uplo,
                        op.as_lapack(),
                        diagonal.as_lapack(),
                        n,
                        crate::factorization::checked_n(nrhs)?,
                        self.as_slice(),
                        b,
                        n.max(1),
                        &mut info,
                    )
                };
                crate::factorization::check_info(
                    info,
                    concat!($label, " packed triangular solve failed"),
                )
            }
            /// Solves `A x = b` for one non-unit, non-transposed RHS in place.
            ///
            /// # Errors
            ///
            /// Returns an error for a wrong RHS length, invalid dimensions, or
            /// a singular diagonal reported by LAPACK.
            pub fn solve_vector_in_place(
                &self,
                b: &mut [T],
            ) -> Result<(), crate::PackedMatrixError> {
                self.solve_many_in_place(b, 1, crate::Transpose::None, crate::Diagonal::NonUnit)
            }
            /// Allocates and returns the solution of `A x = b`.
            ///
            /// # Errors
            ///
            /// Returns an error for a wrong RHS length, invalid dimensions, or
            /// a singular diagonal reported by LAPACK.
            pub fn solve_vector(&self, b: &[T]) -> Result<Vec<T>, crate::PackedMatrixError> {
                let mut x = b.to_vec();
                self.solve_vector_in_place(&mut x)?;
                Ok(x)
            }

            /// Estimates `1 / cond(A)` with LAPACK `xTPCON` without forming `A^-1`.
            ///
            /// # Errors
            ///
            /// Returns an error for dimension/workspace overflow or an illegal
            /// LAPACK argument.
            pub fn rcond(
                &self,
                norm: crate::ConditionNorm,
                diagonal: crate::Diagonal,
            ) -> Result<T::Real, crate::PackedMatrixError> {
                let n = crate::factorization::checked_n(self.n)?;
                let mut r = <T::Real as num_traits::Zero>::zero();
                let mut work = vec![
                    T::zero();
                    crate::factorization::checked_workspace_len(
                        self.n,
                        if T::IS_COMPLEX { 2 } else { 3 }
                    )?
                ];
                let mut rw = vec![
                    <T::Real as num_traits::Zero>::zero();
                    if T::IS_COMPLEX { self.n } else { 0 }
                ];
                let mut iw = vec![0; if T::IS_COMPLEX { 0 } else { self.n }];
                let mut info = 0;
                unsafe {
                    T::tpcon(
                        norm.as_lapack(),
                        $uplo,
                        diagonal.as_lapack(),
                        n,
                        self.as_slice(),
                        &mut r,
                        &mut work,
                        &mut rw,
                        &mut iw,
                        &mut info,
                    )
                };
                crate::factorization::check_info(
                    info,
                    "packed triangular condition estimate failed",
                )?;
                Ok(r)
            }
            /// Long-form alias for [`Self::rcond`].
            ///
            /// # Errors
            ///
            /// Returns the same errors as [`Self::rcond`].
            pub fn reciprocal_condition_number(
                &self,
                norm: crate::ConditionNorm,
                diagonal: crate::Diagonal,
            ) -> Result<T::Real, crate::PackedMatrixError> {
                self.rcond(norm, diagonal)
            }

            /// Computes a packed triangular matrix norm with LAPACK `xLANTP`.
            ///
            /// # Errors
            ///
            /// Returns an error if the dimension does not fit the LAPACK integer type.
            pub fn matrix_norm(
                &self,
                norm: crate::MatrixNorm,
                diagonal: crate::Diagonal,
            ) -> Result<T::Real, crate::PackedMatrixError> {
                let mut work = vec![<T::Real as num_traits::Zero>::zero(); self.n];
                Ok(unsafe {
                    T::lantp(
                        norm.as_lapack(),
                        $uplo,
                        diagonal.as_lapack(),
                        crate::factorization::checked_n(self.n)?,
                        self.as_slice(),
                        &mut work,
                    )
                })
            }

            /// Refines column-major solutions in place and returns LAPACK forward/backward errors.
            ///
            /// `b` and `x` each contain `nrhs` consecutive columns of length
            /// `n`; the report contains one `ferr` and `berr` value per column.
            ///
            /// # Errors
            ///
            /// Returns an error for invalid RHS layouts, dimension/workspace
            /// overflow, or an illegal LAPACK argument.
            pub fn refine_many_in_place(
                &self,
                b: &[T],
                x: &mut [T],
                nrhs: usize,
                op: crate::Transpose,
                diagonal: crate::Diagonal,
            ) -> Result<crate::RefinementReport<T::Real>, crate::PackedMatrixError> {
                crate::factorization::check_rhs_many(self.n, nrhs, b)?;
                crate::factorization::check_rhs_many(self.n, nrhs, x)?;
                let n = crate::factorization::checked_n(self.n)?;
                let mut ferr = vec![<T::Real as num_traits::Zero>::zero(); nrhs];
                let mut berr = ferr.clone();
                let mut work = vec![
                    T::zero();
                    crate::factorization::checked_workspace_len(
                        self.n,
                        if T::IS_COMPLEX { 2 } else { 3 }
                    )?
                ];
                let mut rw = vec![
                    <T::Real as num_traits::Zero>::zero();
                    if T::IS_COMPLEX { self.n } else { 0 }
                ];
                let mut iw = vec![0; if T::IS_COMPLEX { 0 } else { self.n }];
                let mut info = 0;
                unsafe {
                    T::tprfs(
                        $uplo,
                        op.as_lapack(),
                        diagonal.as_lapack(),
                        n,
                        crate::factorization::checked_n(nrhs)?,
                        self.as_slice(),
                        b,
                        n.max(1),
                        x,
                        n.max(1),
                        &mut ferr,
                        &mut berr,
                        &mut work,
                        &mut rw,
                        &mut iw,
                        &mut info,
                    )
                };
                crate::factorization::check_info(
                    info,
                    "packed triangular iterative refinement failed",
                )?;
                Ok(crate::RefinementReport {
                    forward_error: ferr,
                    backward_error: berr,
                })
            }
        }
        impl<T, S> $name<T, S>
        where
            T: crate::backend::TriangularPackedBackend,
            S: crate::storage::PackedStorageMut<T>,
        {
            /// Inverts the packed triangular matrix in place using LAPACK `xTPTRI`.
            ///
            /// # Errors
            ///
            /// Returns an error for dimension overflow, an illegal LAPACK
            /// argument, or a zero diagonal in non-unit mode. On failure the
            /// packed buffer may be partially overwritten.
            pub fn inverse_in_place_with_diagonal(
                &mut self,
                diagonal: crate::Diagonal,
            ) -> Result<(), crate::PackedMatrixError> {
                let mut info = 0;
                unsafe {
                    T::tptri(
                        $uplo,
                        diagonal.as_lapack(),
                        crate::factorization::checked_n(self.n)?,
                        self.as_mut_slice(),
                        &mut info,
                    )
                };
                crate::factorization::check_info(
                    info,
                    concat!($label, " packed triangular inverse failed"),
                )
            }
            /// Inverts a non-unit triangular matrix in place.
            ///
            /// # Errors
            ///
            /// Returns the same errors as [`Self::inverse_in_place_with_diagonal`].
            pub fn inverse_in_place(&mut self) -> Result<(), crate::PackedMatrixError> {
                self.inverse_in_place_with_diagonal(crate::Diagonal::NonUnit)
            }
        }
    };
}
pub(crate) use impl_triangular_packed_ops;