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
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
//! Interoperability between LAPACK triangular storage formats.

use crate::{
    PackedLower, PackedMatrixError, PackedUpper,
    backend::PackedFormatConversion,
    factorization::{check_info, checked_n},
    storage::{PackedStorage, PackedStorageMut},
};
use std::marker::PhantomData;

/// Selects the physically stored triangle of a triangular matrix.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Triangle {
    /// Store or interpret the lower triangle.
    Lower,
    /// Store or interpret the upper triangle.
    Upper,
}

impl Triangle {
    fn uplo(self) -> u8 {
        match self {
            Self::Lower => b'L',
            Self::Upper => b'U',
        }
    }

    fn name(self) -> &'static str {
        match self {
            Self::Lower => "lower",
            Self::Upper => "upper",
        }
    }
}

/// Selects the physical orientation of rectangular full packed (RFP) data.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RfpTranspose {
    /// LAPACK's normal RFP representation.
    Normal,
    /// The transpose for real scalars or conjugate transpose for complex scalars.
    Transposed,
}

/// A triangular matrix in column-major full (`TR`) storage.
///
/// `data` has exactly `dimension * dimension` entries. The triangle opposite
/// [`Self::triangle`] contains structural zeros and is not read when converting
/// back to traditional packed storage.
///
/// # Examples
///
/// ```
/// use matrixpacked::{FullTriangular, Triangle};
///
/// // Column-major lower triangle: [1, 2], [0, 3].
/// let full = FullTriangular::from_vec(
///     2,
///     Triangle::Lower,
///     vec![1.0_f64, 2.0, 0.0, 3.0],
/// )?;
/// assert_eq!(full.leading_dimension(), 2);
/// assert_eq!(full.triangle(), Triangle::Lower);
/// # Ok::<(), matrixpacked::PackedMatrixError>(())
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct FullTriangular<T> {
    data: Vec<T>,
    dimension: usize,
    triangle: Triangle,
}

impl<T> FullTriangular<T> {
    /// Creates owned full triangular storage from a column-major square buffer.
    ///
    /// Entries in the opposite triangle are retained but ignored by conversions.
    ///
    /// # Errors
    ///
    /// Returns [`PackedMatrixError::InvalidLength`] unless `data.len()` is
    /// `dimension * dimension`, or [`PackedMatrixError::DimensionOverflow`] if
    /// that product cannot be represented.
    pub fn from_vec(
        dimension: usize,
        triangle: Triangle,
        data: Vec<T>,
    ) -> Result<Self, PackedMatrixError> {
        let expected = full_len(dimension)?;
        if data.len() != expected {
            return Err(PackedMatrixError::InvalidLength {
                n: dimension,
                expected,
                actual: data.len(),
            });
        }
        Ok(Self {
            data,
            dimension,
            triangle,
        })
    }

    /// Borrows the full `dimension * dimension` column-major buffer.
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Consumes the wrapper and returns its column-major allocation.
    pub fn into_vec(self) -> Vec<T> {
        self.data
    }

    /// Returns the square matrix dimension.
    pub const fn dimension(&self) -> usize {
        self.dimension
    }

    /// Returns the triangle interpreted as meaningful during conversion.
    pub const fn triangle(&self) -> Triangle {
        self.triangle
    }

    /// Returns the column-major leading dimension (`max(1, dimension)`).
    pub fn leading_dimension(&self) -> usize {
        self.dimension.max(1)
    }
}

/// A triangular matrix in LAPACK rectangular full packed (`TF`/RFP) storage.
///
/// RFP is compact like traditional packed storage, but arranges the same
/// `n*(n+1)/2` values as a rectangular column-major array for different LAPACK
/// kernels. It is not directly usable by operations on [`PackedLower`] or
/// [`PackedUpper`]; convert it back first.
#[derive(Clone, Debug)]
pub struct RectangularFullPacked<T, S = Vec<T>> {
    data: S,
    dimension: usize,
    triangle: Triangle,
    transpose: RfpTranspose,
    marker: PhantomData<T>,
}

/// Immutable borrowed RFP storage.
pub type RectangularFullPackedView<'a, T> = RectangularFullPacked<T, &'a [T]>;
/// Mutable borrowed RFP storage.
pub type RectangularFullPackedViewMut<'a, T> = RectangularFullPacked<T, &'a mut [T]>;

impl<T, S> RectangularFullPacked<T, S> {
    fn validate_len(dimension: usize, actual: usize) -> Result<(), PackedMatrixError> {
        let expected = packed_len(dimension)?;
        if actual == expected {
            Ok(())
        } else {
            Err(PackedMatrixError::InvalidLength {
                n: dimension,
                expected,
                actual,
            })
        }
    }

    /// Returns the logical square matrix dimension.
    pub const fn dimension(&self) -> usize {
        self.dimension
    }

    /// Returns the triangle represented by the RFP data.
    pub const fn triangle(&self) -> Triangle {
        self.triangle
    }

    /// Returns the physical RFP orientation.
    pub const fn transpose(&self) -> RfpTranspose {
        self.transpose
    }

    /// Returns the physical `(rows, columns)` of the column-major RFP rectangle.
    pub fn shape(&self) -> (usize, usize) {
        let normal = if self.dimension.is_multiple_of(2) {
            (self.dimension + 1, self.dimension / 2)
        } else {
            (self.dimension, self.dimension.div_ceil(2))
        };
        match self.transpose {
            RfpTranspose::Normal => normal,
            RfpTranspose::Transposed => (normal.1, normal.0),
        }
    }

    /// Returns the leading dimension of the physical column-major RFP rectangle.
    pub fn leading_dimension(&self) -> usize {
        self.shape().0.max(1)
    }
}

impl<T, S: PackedStorage<T>> RectangularFullPacked<T, S> {
    /// Borrows the physical RFP elements.
    pub fn as_slice(&self) -> &[T] {
        self.data.as_slice()
    }

    /// Creates an immutable view without copying the RFP elements.
    pub fn as_view(&self) -> RectangularFullPackedView<'_, T> {
        RectangularFullPacked {
            data: self.as_slice(),
            dimension: self.dimension,
            triangle: self.triangle,
            transpose: self.transpose,
            marker: PhantomData,
        }
    }
}

impl<T, S: PackedStorageMut<T>> RectangularFullPacked<T, S> {
    /// Mutably borrows the physical RFP elements.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        self.data.as_mut_slice()
    }

    /// Creates a mutable view without copying the RFP elements.
    pub fn as_view_mut(&mut self) -> RectangularFullPackedViewMut<'_, T> {
        let dimension = self.dimension;
        let triangle = self.triangle;
        let transpose = self.transpose;
        RectangularFullPacked {
            data: self.as_mut_slice(),
            dimension,
            triangle,
            transpose,
            marker: PhantomData,
        }
    }
}

impl<T> RectangularFullPacked<T> {
    /// Creates owned RFP storage from its physical rectangle buffer.
    ///
    /// # Errors
    ///
    /// Returns an error unless `data` contains exactly `n * (n + 1) / 2`
    /// elements, or when that packed length overflows.
    pub fn from_vec(
        dimension: usize,
        triangle: Triangle,
        transpose: RfpTranspose,
        data: Vec<T>,
    ) -> Result<Self, PackedMatrixError> {
        Self::validate_len(dimension, data.len())?;
        Ok(Self {
            data,
            dimension,
            triangle,
            transpose,
            marker: PhantomData,
        })
    }

    /// Consumes the wrapper and returns its RFP allocation.
    pub fn into_vec(self) -> Vec<T> {
        self.data
    }
}

impl<'a, T> RectangularFullPacked<T, &'a [T]> {
    /// Creates an immutable RFP view over an existing packed-length slice.
    ///
    /// # Errors
    ///
    /// Returns an error when the slice length does not match `dimension`.
    pub fn from_slice(
        dimension: usize,
        triangle: Triangle,
        transpose: RfpTranspose,
        data: &'a [T],
    ) -> Result<Self, PackedMatrixError> {
        Self::validate_len(dimension, data.len())?;
        Ok(Self {
            data,
            dimension,
            triangle,
            transpose,
            marker: PhantomData,
        })
    }
}

impl<'a, T> RectangularFullPacked<T, &'a mut [T]> {
    /// Creates a mutable RFP view over an existing packed-length slice.
    ///
    /// # Errors
    ///
    /// Returns an error when the slice length does not match `dimension`.
    pub fn from_slice_mut(
        dimension: usize,
        triangle: Triangle,
        transpose: RfpTranspose,
        data: &'a mut [T],
    ) -> Result<Self, PackedMatrixError> {
        Self::validate_len(dimension, data.len())?;
        Ok(Self {
            data,
            dimension,
            triangle,
            transpose,
            marker: PhantomData,
        })
    }
}

fn packed_len(n: usize) -> Result<usize, PackedMatrixError> {
    n.checked_add(1)
        .and_then(|n1| n.checked_mul(n1))
        .map(|len| len / 2)
        .ok_or(PackedMatrixError::DimensionOverflow { n })
}

fn full_len(n: usize) -> Result<usize, PackedMatrixError> {
    n.checked_mul(n)
        .ok_or(PackedMatrixError::DimensionOverflow { n })
}

fn transr<T: PackedFormatConversion>(transpose: RfpTranspose) -> u8 {
    match transpose {
        RfpTranspose::Normal => b'N',
        RfpTranspose::Transposed => T::RFP_TRANSPOSE,
    }
}

fn packed_to_full<T: PackedFormatConversion>(
    n: usize,
    triangle: Triangle,
    packed: &[T],
) -> Result<FullTriangular<T>, PackedMatrixError> {
    let mut data = vec![T::zero(); full_len(n)?];
    let mut info = 0;
    unsafe {
        T::tpttr(
            triangle.uplo(),
            checked_n(n)?,
            packed,
            &mut data,
            checked_n(n.max(1))?,
            &mut info,
        )
    };
    check_info(
        info,
        "traditional packed to full triangular conversion failed",
    )?;
    FullTriangular::from_vec(n, triangle, data)
}

fn full_to_packed<T: PackedFormatConversion>(
    full: &FullTriangular<T>,
    expected: Triangle,
) -> Result<Vec<T>, PackedMatrixError> {
    check_triangle(expected, full.triangle)?;
    let n = full.dimension;
    let mut packed = vec![T::zero(); packed_len(n)?];
    let mut info = 0;
    unsafe {
        T::trttp(
            expected.uplo(),
            checked_n(n)?,
            &full.data,
            checked_n(n.max(1))?,
            &mut packed,
            &mut info,
        )
    };
    check_info(
        info,
        "full triangular to traditional packed conversion failed",
    )?;
    Ok(packed)
}

fn packed_to_rfp_into<T: PackedFormatConversion>(
    n: usize,
    triangle: Triangle,
    transpose: RfpTranspose,
    packed: &[T],
    rfp: &mut [T],
) -> Result<(), PackedMatrixError> {
    let mut info = 0;
    unsafe {
        T::tpttf(
            transr::<T>(transpose),
            triangle.uplo(),
            checked_n(n)?,
            packed,
            rfp,
            &mut info,
        )
    };
    check_info(info, "traditional packed to RFP conversion failed")
}

fn packed_to_rfp<T: PackedFormatConversion>(
    n: usize,
    triangle: Triangle,
    transpose: RfpTranspose,
    packed: &[T],
) -> Result<RectangularFullPacked<T>, PackedMatrixError> {
    let mut data = vec![T::zero(); packed_len(n)?];
    packed_to_rfp_into(n, triangle, transpose, packed, &mut data)?;
    RectangularFullPacked::from_vec(n, triangle, transpose, data)
}

fn rfp_to_packed<T: PackedFormatConversion, S: PackedStorage<T>>(
    rfp: &RectangularFullPacked<T, S>,
    expected: Triangle,
) -> Result<Vec<T>, PackedMatrixError> {
    check_triangle(expected, rfp.triangle)?;
    let mut packed = vec![T::zero(); packed_len(rfp.dimension)?];
    rfp_to_packed_into(
        rfp.dimension,
        expected,
        rfp.transpose,
        rfp.as_slice(),
        &mut packed,
    )?;
    Ok(packed)
}

fn rfp_to_packed_into<T: PackedFormatConversion>(
    n: usize,
    triangle: Triangle,
    transpose: RfpTranspose,
    rfp: &[T],
    packed: &mut [T],
) -> Result<(), PackedMatrixError> {
    let mut info = 0;
    unsafe {
        T::tfttp(
            transr::<T>(transpose),
            triangle.uplo(),
            checked_n(n)?,
            rfp,
            packed,
            &mut info,
        )
    };
    check_info(info, "RFP to traditional packed conversion failed")
}

fn check_triangle(expected: Triangle, actual: Triangle) -> Result<(), PackedMatrixError> {
    if expected == actual {
        Ok(())
    } else {
        Err(PackedMatrixError::TriangleMismatch {
            expected: expected.name(),
            actual: actual.name(),
        })
    }
}

macro_rules! impl_packed_conversions {
    ($packed:ident, $triangle:ident) => {
        impl<T, S> $packed<T, S>
        where
            T: PackedFormatConversion,
            S: PackedStorage<T>,
        {
            /// Copies traditional packed (`TP`) storage to column-major full triangular (`TR`) storage.
            pub fn to_full_triangular(&self) -> Result<FullTriangular<T>, PackedMatrixError> {
                packed_to_full(self.dimension(), Triangle::$triangle, self.as_slice())
            }

            /// Copies traditional packed (`TP`) storage to rectangular full packed (`TF`/RFP) storage.
            pub fn to_rectangular_full_packed(
                &self,
                transpose: RfpTranspose,
            ) -> Result<RectangularFullPacked<T>, PackedMatrixError> {
                packed_to_rfp(
                    self.dimension(),
                    Triangle::$triangle,
                    transpose,
                    self.as_slice(),
                )
            }
        }

        impl<T> $packed<T>
        where
            T: PackedFormatConversion,
        {
            /// Converts full triangular (`TR`) storage back to traditional packed (`TP`) storage.
            pub fn from_full_triangular(
                full: &FullTriangular<T>,
            ) -> Result<Self, PackedMatrixError> {
                Self::from_vec(full.dimension(), full_to_packed(full, Triangle::$triangle)?)
            }

            /// Converts rectangular full packed (`TF`/RFP) storage back to traditional packed (`TP`) storage.
            pub fn from_rectangular_full_packed<S: PackedStorage<T>>(
                rfp: &RectangularFullPacked<T, S>,
            ) -> Result<Self, PackedMatrixError> {
                Self::from_vec(rfp.dimension(), rfp_to_packed(rfp, Triangle::$triangle)?)
            }

            /// Consumes traditional packed storage, reusing its allocation for the RFP result.
            pub fn into_rectangular_full_packed(
                self,
                transpose: RfpTranspose,
            ) -> Result<RectangularFullPacked<T>, PackedMatrixError> {
                let n = self.dimension();
                let mut data = self.into_vec();
                let packed = data.clone();
                packed_to_rfp_into(n, Triangle::$triangle, transpose, &packed, &mut data)?;
                RectangularFullPacked::from_vec(n, Triangle::$triangle, transpose, data)
            }
        }
    };
}

impl_packed_conversions!(PackedLower, Lower);
impl_packed_conversions!(PackedUpper, Upper);

impl<T, S> RectangularFullPacked<T, S>
where
    T: PackedFormatConversion,
    S: PackedStorage<T>,
{
    /// Copies lower-triangle RFP data into traditional packed-lower storage.
    ///
    /// # Errors
    ///
    /// Returns an error if this value represents the upper triangle, dimensions
    /// overflow LAPACK integers, or the linked `xTFTTP` routine fails.
    pub fn to_packed_lower(&self) -> Result<PackedLower<T>, PackedMatrixError> {
        PackedLower::from_rectangular_full_packed(self)
    }

    /// Copies upper-triangle RFP data into traditional packed-upper storage.
    ///
    /// # Errors
    ///
    /// Returns an error if this value represents the lower triangle, dimensions
    /// overflow LAPACK integers, or the linked `xTFTTP` routine fails.
    pub fn to_packed_upper(&self) -> Result<PackedUpper<T>, PackedMatrixError> {
        PackedUpper::from_rectangular_full_packed(self)
    }
}

impl<T> RectangularFullPacked<T>
where
    T: PackedFormatConversion,
{
    /// Consumes lower RFP storage, reusing its allocation for traditional packed storage.
    pub fn into_packed_lower(self) -> Result<PackedLower<T>, PackedMatrixError> {
        check_triangle(Triangle::Lower, self.triangle)?;
        let n = self.dimension;
        let transpose = self.transpose;
        let mut data = self.data;
        let rfp = data.clone();
        rfp_to_packed_into(n, Triangle::Lower, transpose, &rfp, &mut data)?;
        PackedLower::from_vec(n, data)
    }

    /// Consumes upper RFP storage, reusing its allocation for traditional packed storage.
    pub fn into_packed_upper(self) -> Result<PackedUpper<T>, PackedMatrixError> {
        check_triangle(Triangle::Upper, self.triangle)?;
        let n = self.dimension;
        let transpose = self.transpose;
        let mut data = self.data;
        let rfp = data.clone();
        rfp_to_packed_into(n, Triangle::Upper, transpose, &rfp, &mut data)?;
        PackedUpper::from_vec(n, data)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use num_complex::{Complex32, Complex64};

    macro_rules! round_trips {
        ($scalar:ty, $value:expr) => {{
            for n in [0usize, 1, 4, 5] {
                let len = packed_len(n).unwrap();
                let data: Vec<$scalar> = (0..len).map($value).collect();
                for transpose in [RfpTranspose::Normal, RfpTranspose::Transposed] {
                    let lower = PackedLower::from_vec(n, data.clone()).unwrap();
                    let full = lower.to_full_triangular().unwrap();
                    assert_eq!(
                        PackedLower::from_full_triangular(&full).unwrap().as_slice(),
                        data
                    );
                    let rfp = lower.to_rectangular_full_packed(transpose).unwrap();
                    assert_eq!(rfp.to_packed_lower().unwrap().as_slice(), data);

                    let upper = PackedUpper::from_vec(n, data.clone()).unwrap();
                    let full = upper.to_full_triangular().unwrap();
                    assert_eq!(
                        PackedUpper::from_full_triangular(&full).unwrap().as_slice(),
                        data
                    );
                    let pointer = upper.as_slice().as_ptr();
                    let rfp = upper.into_rectangular_full_packed(transpose).unwrap();
                    assert_eq!(rfp.as_slice().as_ptr(), pointer);
                    let pointer = rfp.as_slice().as_ptr();
                    let packed = rfp.into_packed_upper().unwrap();
                    assert_eq!(packed.as_slice().as_ptr(), pointer);
                    assert_eq!(packed.as_slice(), data);
                }
            }
        }};
    }

    #[test]
    fn every_scalar_odd_even_orientation_and_transform() {
        round_trips!(f32, |i| i as f32 + 1.0);
        round_trips!(f64, |i| i as f64 + 1.0);
        round_trips!(Complex32, |i| Complex32::new(i as f32 + 1.0, i as f32));
        round_trips!(Complex64, |i| Complex64::new(i as f64 + 1.0, i as f64));
    }

    #[test]
    fn metadata_views_structural_zeros_and_validation() {
        let lower = PackedLower::from_vec(2, vec![1f64, 2., 3.]).unwrap();
        let full = lower.to_full_triangular().unwrap();
        assert_eq!(full.as_slice(), &[1., 2., 0., 3.]);
        assert_eq!(full.leading_dimension(), 2);
        assert!(PackedUpper::from_full_triangular(&full).is_err());

        let mut data = vec![1f64, 2., 3., 4., 5., 6.];
        let mut view = RectangularFullPackedViewMut::from_slice_mut(
            3,
            Triangle::Lower,
            RfpTranspose::Transposed,
            &mut data,
        )
        .unwrap();
        assert_eq!(view.shape(), (2, 3));
        assert_eq!(view.leading_dimension(), 2);
        assert_eq!(view.as_view().triangle(), Triangle::Lower);
        assert_eq!(view.as_mut_slice().len(), 6);
        assert!(view.to_packed_upper().is_err());

        assert!(FullTriangular::<f32>::from_vec(2, Triangle::Lower, vec![0.; 3]).is_err());
        assert!(
            RectangularFullPacked::<f32>::from_vec(
                2,
                Triangle::Lower,
                RfpTranspose::Normal,
                vec![0.; 2],
            )
            .is_err()
        );
    }
}