nalgebra-lapack 0.27.0

Matrix decompositions using nalgebra matrices and Lapack bindings.
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
use crate::{DiagonalKind, LapackErrorCode, Side, Transposition, TriangularStructure, qr::QrReal};
use na::{
    Dim, DimMin, DimMinimum, IsContiguous, Matrix, RawStorage, RawStorageMut, RealField, Vector,
};
use num::{ConstOne, Zero};

/// Error type for QR decomposition operations.
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum Error {
    /// Incorrect matrix dimensions.
    #[error("incorrect matrix dimensions")]
    Dimensions,
    /// LAPACK backend returned error.
    #[error("Lapack returned with error: {0}")]
    Lapack(#[from] LapackErrorCode),
    /// QR decomposition for underdetermined systems not supported.
    #[error("QR decomposition for underdetermined systems not supported")]
    Underdetermined,
    /// Matrix has rank zero.
    #[error("Matrix has rank zero")]
    ZeroRank,
}

/// Thin wrapper around certain invocation of `multiply_q_mut`, where:
/// * `qr`: contains the LAPACK-style QR decomposition of a matrix A
/// * `tau`: scalar factors of the elementary reflectors
/// * `b`: matrix B described below
///
/// Efficiently calculate the matrix product `Q B` of the factor `Q` with a
/// given matrix `B`. `Q` acts as if it is a matrix of dimension `m ⨯ m`, so
/// we require `B ∈ R^(m ⨯ k)`. The product is calculated in place and
/// must only be considered valid when the function returns without error.
pub(crate) fn q_mul_mut<T, R1, C1, S1, C2, S2, S3>(
    qr: &Matrix<T, R1, C1, S1>,
    tau: &Vector<T, DimMinimum<R1, C1>, S3>,
    b: &mut Matrix<T, R1, C2, S2>,
) -> Result<(), Error>
where
    T: QrReal + Zero + RealField,
    R1: DimMin<C1>,
    C1: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    C2: Dim,
    S2: RawStorageMut<T, R1, C2> + IsContiguous,
    S3: RawStorage<T, <R1 as DimMin<C1>>::Output> + IsContiguous,
{
    if b.nrows() != qr.nrows() {
        return Err(Error::Dimensions);
    }
    if qr.ncols().min(qr.nrows()) != tau.len() {
        return Err(Error::Dimensions);
    }
    // SAFETY: matrix has the correct dimensions for operation Q*B
    unsafe { multiply_q_mut(qr, tau, b, Side::Left, Transposition::No)? };
    Ok(())
}

/// Thin wrapper around certain invokation of `multiply_q_mut`, where:
/// * `qr`: contains the lapack-style qr decomposition of a matrix A
/// * `tau`: scalar factors of the elementary reflectors
/// * `b`: matrix B described below
///
/// Efficiently calculate the matrix product `Q^T B` of the factor `Q` with a
/// given matrix `B`. `Q` acts as if it is a matrix of dimension `m ⨯ m`, so
/// we require `B ∈ R^(m ⨯ k)`. The product is calculated in place and
/// must only be considered valid when the function returns without error.
pub(crate) fn q_tr_mul_mut<T, R1, C1, S1, C2, S2, S3>(
    qr: &Matrix<T, R1, C1, S1>,
    tau: &Vector<T, DimMinimum<R1, C1>, S3>,
    b: &mut Matrix<T, R1, C2, S2>,
) -> Result<(), Error>
where
    T: QrReal + Zero + RealField,
    R1: DimMin<C1>,
    C1: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    C2: Dim,
    C2: Dim,
    S2: RawStorageMut<T, R1, C2> + IsContiguous,
    S3: RawStorage<T, <R1 as DimMin<C1>>::Output> + IsContiguous,
{
    if b.nrows() != qr.nrows() {
        return Err(Error::Dimensions);
    }
    if qr.ncols().min(qr.nrows()) != tau.len() {
        return Err(Error::Dimensions);
    }
    // SAFETY: matrix has the correct dimensions for operation Q^T*B
    unsafe { multiply_q_mut(qr, tau, b, Side::Left, Transposition::Transpose)? };
    Ok(())
}

/// Thin wrapper around certain invokation of `multiply_q_mut`, where:
/// * `qr`: contains the lapack-style qr decomposition of a matrix A
/// * `tau`: scalar factors of the elementary reflectors
/// * `b`: matrix B described below
///
/// Efficiently calculate the matrix product `B Q` of the factor `Q` with a
/// given matrix `B`. `Q` acts as if it is a matrix of dimension `m ⨯ m`, so
/// we require `B ∈ R^(k ⨯ m)`. The product is calculated in place and
/// must only be considered valid when the function returns without error.
pub(crate) fn mul_q_mut<T, R1, C1, S1, R2, S2, S3>(
    qr: &Matrix<T, R1, C1, S1>,
    tau: &Vector<T, DimMinimum<R1, C1>, S3>,
    b: &mut Matrix<T, R2, R1, S2>,
) -> Result<(), Error>
where
    T: QrReal + Zero + RealField,
    R1: DimMin<C1>,
    C1: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    R2: Dim,
    S2: RawStorageMut<T, R2, R1> + IsContiguous,
    S3: RawStorage<T, <R1 as DimMin<C1>>::Output> + IsContiguous,
{
    if b.ncols() != qr.nrows() {
        return Err(Error::Dimensions);
    }
    if qr.ncols().min(qr.nrows()) != tau.len() {
        return Err(Error::Dimensions);
    }
    // SAFETY: matrix has the correct dimensions for operation B*Q
    unsafe { multiply_q_mut(qr, tau, b, Side::Right, Transposition::No)? };
    Ok(())
}

/// Thin wrapper around certain invokation of `multiply_q_mut`, where:
/// * `qr`: contains the lapack-style qr decomposition of a matrix A
/// * `tau`: scalar factors of the elementary reflectors
/// * `b`: matrix B described below
///
/// Efficiently calculate the matrix product `B Q^T` of the factor `Q` with a
/// given matrix `B`. `Q` acts as if it is a matrix of dimension `m ⨯ m`, so
/// we require `B ∈ R^(k ⨯ m)`. The product is calculated in place and
/// must only be considered valid when the function returns without error.
pub(crate) fn mul_q_tr_mut<T, R1, C1, S1, R2, S2, S3>(
    qr: &Matrix<T, R1, C1, S1>,
    tau: &Vector<T, DimMinimum<R1, C1>, S3>,
    b: &mut Matrix<T, R2, R1, S2>,
) -> Result<(), Error>
where
    T: QrReal + Zero + RealField,
    R1: DimMin<C1>,
    C1: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    R2: Dim,
    S2: RawStorageMut<T, R2, R1> + IsContiguous,
    S3: RawStorage<T, <R1 as DimMin<C1>>::Output> + IsContiguous,
{
    if b.ncols() != qr.nrows() {
        return Err(Error::Dimensions);
    }
    if qr.ncols().min(qr.nrows()) != tau.len() {
        return Err(Error::Dimensions);
    }
    // SAFETY: matrix has the correct dimensions for operation B Q^T
    unsafe { multiply_q_mut(qr, tau, b, Side::Right, Transposition::Transpose)? }
    Ok(())
}

/// this factors out solving a the A X = B in a least squares sense, given a
/// lapack qr decomposition of matrix A (in qr, tau). This also needs an explicit
/// rank for the matrix, which should be set to full rank for unpivoted QR.
///
/// This solver does not do the final row permutation necessary for col-pivoted
/// qr. For unpivoted QR, no extra permutation is necessary anyways.
pub(crate) fn qr_solve_mut_with_rank_unpermuted<T, R1, C1, S1, C2: Dim, S3, S2, S4>(
    qr: &Matrix<T, R1, C1, S1>,
    tau: &Vector<T, DimMinimum<R1, C1>, S4>,
    rank: u16,
    x: &mut Matrix<T, C1, C2, S2>,
    mut b: Matrix<T, R1, C2, S3>,
) -> Result<(), Error>
where
    T: QrReal + Zero + RealField,
    R1: DimMin<C1>,
    C1: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    S3: RawStorageMut<T, R1, C2> + IsContiguous,
    S2: RawStorageMut<T, C1, C2> + IsContiguous,
    S4: RawStorage<T, <R1 as DimMin<C1>>::Output> + IsContiguous,
{
    if b.nrows() != qr.nrows() {
        return Err(Error::Dimensions);
    }

    if qr.nrows() < qr.ncols() || qr.nrows() == 0 || qr.ncols() == 0 {
        return Err(Error::Underdetermined);
    }

    if x.ncols() != b.ncols() || x.nrows() != qr.ncols() {
        return Err(Error::Dimensions);
    }

    q_tr_mul_mut(qr, tau, &mut b)?;

    if rank == 0 {
        return Err(Error::ZeroRank);
    }

    debug_assert!(rank as usize <= qr.ncols().min(qr.nrows()));

    if (rank as usize) < qr.ncols() {
        x.view_mut((rank as usize, 0), (x.nrows() - rank as usize, x.ncols()))
            .iter_mut()
            .for_each(|val| val.set_zero());
    }

    let x_cols = x.ncols();
    x.view_mut((0, 0), (rank as usize, x_cols))
        .copy_from(&b.view((0, 0), (rank as usize, x_cols)));

    let ldb: i32 = x
        .nrows()
        .try_into()
        .expect("integer dimensions out of bounds");

    // SAFETY: input and dimensions according to lapack spec, see
    // https://www.netlib.org/lapack/explore-html/d4/dc1/group__trtrs_gab0b6a7438a7eb98fe2ab28e6c4d84b21.html#gab0b6a7438a7eb98fe2ab28e6c4d84b21
    unsafe {
        T::xtrtrs(
            TriangularStructure::Upper,
            Transposition::No,
            DiagonalKind::NonUnit,
            rank.try_into().expect("rank out of bounds"),
            x.ncols()
                .try_into()
                .expect("integer dimensions out of bounds"),
            qr.as_slice(),
            qr.nrows()
                .try_into()
                .expect("integer dimensions out of bounds"),
            x.as_mut_slice(),
            ldb,
        )?;
    }

    Ok(())
}

/// Thin-ish wrapper around the LAPACK function
/// [?ormqr](https://www.netlib.org/lapack/explore-html/d7/d50/group__unmqr.html),
/// which allows us to calculate either Q*B, Q^T*B, B*Q, B*Q^T for appropriately
/// shaped matrices B, without having to explicitly form Q. In this calculation
/// Q is constructed as if it were a square matrix of appropriate dimension.
///
/// # Safety
///
/// The dimensions of the matrices must be correct such that the multiplication
/// can be performed.
#[inline]
unsafe fn multiply_q_mut<T, R1, C1, S1, R2, C2, S2, S3>(
    qr: &Matrix<T, R1, C1, S1>,
    tau: &Vector<T, DimMinimum<R1, C1>, S3>,
    mat: &mut Matrix<T, R2, C2, S2>,
    side: Side,
    transpose: Transposition,
) -> Result<(), Error>
where
    T: QrReal,
    R1: DimMin<C1>,
    C1: Dim,
    S2: RawStorageMut<T, R2, C2> + IsContiguous,
    R2: Dim,
    C2: Dim,
    S1: IsContiguous + RawStorage<T, R1, C1>,
    S3: RawStorage<T, <R1 as DimMin<C1>>::Output> + IsContiguous,
{
    let a = qr.as_slice();
    let lda = qr
        .nrows()
        .try_into()
        .expect("integer dimension out of range");
    let m = mat
        .nrows()
        .try_into()
        .expect("integer dimension out of range");
    let n = mat
        .ncols()
        .try_into()
        .expect("integer dimension out of range");
    let k = tau
        .len()
        .try_into()
        .expect("integer dimension out of range");
    let ldc = mat
        .nrows()
        .try_into()
        .expect("integer dimension out of range");
    let c = mat.as_mut_slice();
    let trans = transpose;
    let tau = tau.as_slice();

    if k as usize != qr.ncols() {
        return Err(Error::Dimensions);
    }

    // dimensions checks from the lapack documentation
    // see e.g. https://www.netlib.org/lapack/explore-html/d7/d50/group__unmqr_ga768bd221f959be1b3d15bd177bb5c1b3.html#ga768bd221f959be1b3d15bd177bb5c1b3
    match side {
        Side::Left => {
            if m < k {
                return Err(Error::Dimensions);
            }

            if lda < m {
                return Err(Error::Dimensions);
            }
        }
        Side::Right => {
            if n < k {
                return Err(Error::Dimensions);
            }

            if lda < n {
                return Err(Error::Dimensions);
            }
        }
    }

    if ldc < m {
        return Err(Error::Dimensions);
    }

    // SAFETY: the dimensions are checked as above, but the user has to make
    // sure that qr indeed contains the contents of a qr decomposition returned
    // by lapack and tau must contain the scalar factors of the reflectors as
    // returned by lapack.
    let lwork = unsafe { T::xormqr_work_size(side, transpose, m, n, k, a, lda, tau, c, ldc)? };
    let mut work = vec![T::zero(); lwork as usize];

    // SAFETY: the containing function is unsafe and requires the correct
    // matrix dimensions as input
    unsafe {
        T::xormqr(side, trans, m, n, k, a, lda, tau, c, ldc, &mut work, lwork)?;
    }
    Ok(())
}

/// multiply R*B or R^T *B and place the result in B, where R is the upper triangular matrix
/// in a qr decomposition as computed by lapack.
pub fn r_xx_mul_mut<T, R1, C1, S1, C2, S2>(
    qr: &Matrix<T, R1, C1, S1>,
    transpose: Transposition,
    b: &mut Matrix<T, C1, C2, S2>,
) -> Result<(), Error>
where
    T: QrReal + ConstOne,
    R1: Dim,
    C1: Dim,
    C2: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    S2: RawStorageMut<T, C1, C2> + IsContiguous,
{
    // looking carefully at the lapack docs, the xTRMM requires
    // an overdetermined matrix (m>=n), because otherwise R will
    // be upper trapezoidal and the logic will be different and it
    // might not actually be useful to multiply the square part.
    if qr.nrows() < qr.ncols() {
        return Err(Error::Underdetermined);
    }

    if qr.ncols() != b.nrows() {
        return Err(Error::Dimensions);
    }

    multiply_r_mut(qr, transpose, Side::Left, b)?;
    Ok(())
}

/// multiply B*R or B * R^T and place the result in B, where R is the upper triangular matrix
/// in a qr decomposition as computed by lapack.
pub fn mul_r_xx_mut<T, R1, C1, S1, R2, S2>(
    qr: &Matrix<T, R1, C1, S1>,
    transpose: Transposition,
    b: &mut Matrix<T, R2, C1, S2>,
) -> Result<(), Error>
where
    T: QrReal + ConstOne,
    R1: Dim,
    C1: Dim,
    R2: Dim,
    S1: RawStorage<T, R1, C1> + IsContiguous,
    S2: RawStorageMut<T, R2, C1> + IsContiguous,
{
    // looking carefully at the lapack docs, the xTRMM requires
    // an overdetermined matrix (m>=n), because otherwise R will
    // be upper trapezoidal and the logic will be different and it
    // might not actually be useful to multiply the square part.
    if qr.nrows() < qr.ncols() {
        return Err(Error::Underdetermined);
    }

    if b.ncols() != qr.ncols() {
        return Err(Error::Dimensions);
    }

    multiply_r_mut(qr, transpose, Side::Right, b)?;
    Ok(())
}
/// thin-ish wrapper around the lapack function [?TRMM](https://www.netlib.org/lapack/explore-html/dd/dab/group__trmm.html)
/// for multiplying the upper triangular part R or a QR decomposition with another
/// matrix.
///
/// The way the ?TRMM logic works is that A is a kxk matrix, and B is m x n.
/// When multiplying from the left, then k = m and when multiplying from the
/// right, k = n. The matrix A can be stored in the QR decomposition as the
/// upper triangular part, so LDA is the number of rows for the QR decomp.
///
/// The ?TRMM functions also allow scaling with a factor alpha, which
/// we always set to 1 and they allow the matrix to be upper or lower triangular,
/// we always use upper triangular. They also allow to multiply from right or
/// left, but the dimension of R in a QR decomposition only allows multiplication
/// from the left, I think.
#[inline]
fn multiply_r_mut<T, R1, C1, S1, R2, C2, S2>(
    qr: &Matrix<T, R1, C1, S1>,
    transpose: Transposition,
    side: Side,
    mat: &mut Matrix<T, R2, C2, S2>,
) -> Result<(), Error>
where
    T: QrReal + ConstOne,
    R1: Dim,
    C1: Dim,
    S2: RawStorageMut<T, R2, C2> + IsContiguous,
    R2: Dim,
    C2: Dim,
    S1: IsContiguous + RawStorage<T, R1, C1>,
{
    let m: i32 = mat
        .nrows()
        .try_into()
        .expect("integer dimensions out of bounds");
    let n: i32 = mat
        .ncols()
        .try_into()
        .expect("integer dimensions out of bounds");
    let lda: i32 = qr
        .nrows()
        .try_into()
        .expect("integer dimensions out of bounds");
    let ldb: i32 = mat
        .nrows()
        .try_into()
        .expect("integer dimensions out of bounds");

    // these bounds are from the lapack documentation
    // see e.g. https://www.netlib.org/lapack/explore-html/dd/dab/group__trmm_ga4d2f76d6726f53c69031a2fe7f999add.html#ga4d2f76d6726f53c69031a2fe7f999add
    match side {
        Side::Left => {
            if lda == 0 || lda < m {
                return Err(Error::Dimensions);
            }
            if qr.ncols() != m as usize {
                return Err(Error::Dimensions);
            }
        }
        Side::Right => {
            if lda == 0 || lda < n {
                return Err(Error::Dimensions);
            }
            if qr.ncols() != n as usize {
                return Err(Error::Dimensions);
            }
        }
    }

    // SAFETY: we're using the correct types and we are giving the
    // correct matrix dimensions as per lapack docs
    unsafe {
        T::xtrmm(
            side,
            TriangularStructure::Upper,
            transpose,
            DiagonalKind::NonUnit,
            m,
            n,
            T::ONE,
            qr.as_slice(),
            lda,
            mat.as_mut_slice(),
            ldb,
        );
    }
    Ok(())
}