Skip to main content

xingo_statla/
view.rs

1//! # Chapter 12.0.2 — Dense views
2//!
3//! ## Purpose
4//! The caller's data — an R matrix, a NumPy array in Fortran order, a
5//! block inside a larger array — is borrowed, not copied: [`MatRef`] and
6//! [`MatMut`] are column-major views with a leading dimension (decision S3
7//! of D-0127). The owned type of the crate's outputs is
8//! [`DenseBlock`] of `xingo-sparse` (`ld = rows`).
9//!
10//! ## Notation
11//! A view is `rows × cols` with leading dimension `ld ≥ rows`: `a_ij =
12//! data[i + j·ld]`. Column `j` is the contiguous slice `data[j·ld .. j·ld
13//! + rows]`. A C-order NumPy array is the view of its *transpose* (a rule
14//! for `xingo-ffi`).
15//!
16//! ## Algorithm V (checked construction)
17//! V1. \[Leading dimension.\] If `ld < rows`, `InvalidArgument`.
18//! V2. \[Extent.\] If `cols = 0` the extent is `0`; otherwise `need = ld·(cols
19//!     − 1) + rows`, computed with checked arithmetic (`InvalidArgument` on
20//!     `usize` overflow).
21//! V3. \[Length.\] If `data.len() < need`, `Dimension { what: "data",
22//!     expected: need, found: data.len() }`. Longer slices are accepted
23//!     (the tail is not part of the view).
24//!
25//! Finiteness is *not* checked here, but by the consumers (each reports
26//! the column-major position `i + j·rows`).
27//!
28//! ## Invariant
29//! (W1) `ld ≥ rows` and `data.len() ≥ need` for every live view, so every
30//!      accessor below indexes in bounds; the accessors that take indices
31//!      return `None` (or an error) out of range instead of panicking.
32
33use xingo_sparse::{DenseBlock, Real};
34
35use crate::StatlaError;
36
37/// A borrowed column-major `rows × cols` matrix with leading dimension
38/// `ld ≥ rows`: `a_ij = data[i + j·ld]` (the LAPACK/R layout; a C-order
39/// NumPy array is the view of its *transpose*, a rule for `xingo-ffi`).
40/// `data.len() ≥ ld·(cols − 1) + rows` when `cols > 0`.
41#[derive(Clone, Copy, Debug)]
42pub struct MatRef<'a, T: Real = f64> {
43    rows: usize,
44    cols: usize,
45    ld: usize,
46    data: &'a [T],
47}
48
49/// The mutable counterpart of [`MatRef`].
50#[derive(Debug)]
51pub struct MatMut<'a, T: Real = f64> {
52    rows: usize,
53    cols: usize,
54    ld: usize,
55    data: &'a mut [T],
56}
57
58/// Algorithm V: the extent `need` of a view, or the error.
59fn extent(rows: usize, cols: usize, ld: usize, len: usize) -> Result<usize, StatlaError> {
60    // V1.
61    if ld < rows {
62        return Err(StatlaError::InvalidArgument { what: "ld < rows" });
63    }
64    // V2.
65    let need = if cols == 0 {
66        0
67    } else {
68        ld.checked_mul(cols - 1)
69            .and_then(|v| v.checked_add(rows))
70            .ok_or(StatlaError::InvalidArgument {
71                what: "view extent overflows usize",
72            })?
73    };
74    // V3.
75    if len < need {
76        return Err(StatlaError::Dimension {
77            what: "data",
78            expected: need,
79            found: len,
80        });
81    }
82    Ok(need)
83}
84
85impl<'a, T: Real> MatRef<'a, T> {
86    /// A view of `data` (checked: `ld ≥ rows`, length, no `usize`
87    /// overflow; finiteness is *not* checked here, but by the consumers).
88    ///
89    /// # Errors
90    /// [`StatlaError::InvalidArgument`], [`StatlaError::Dimension`].
91    pub fn new(rows: usize, cols: usize, ld: usize, data: &'a [T]) -> Result<Self, StatlaError> {
92        extent(rows, cols, ld, data.len())?;
93        Ok(Self {
94            rows,
95            cols,
96            ld,
97            data,
98        })
99    }
100    /// The view of a whole block (`ld = rows`).
101    ///
102    /// A block whose `data` is shorter than `rows · cols` (its public
103    /// fields are inconsistent) gives a view with no columns: never a
104    /// panic.
105    #[must_use]
106    pub fn from_block(b: &'a DenseBlock<T>) -> Self {
107        let cols = if b.data.len() >= b.rows.saturating_mul(b.cols) {
108            b.cols
109        } else {
110            0
111        };
112        Self {
113            rows: b.rows,
114            cols,
115            ld: b.rows,
116            data: &b.data,
117        }
118    }
119    /// Number of rows.
120    #[must_use]
121    pub fn rows(&self) -> usize {
122        self.rows
123    }
124    /// Number of columns.
125    #[must_use]
126    pub fn cols(&self) -> usize {
127        self.cols
128    }
129    /// Leading dimension.
130    #[must_use]
131    pub fn ld(&self) -> usize {
132        self.ld
133    }
134    /// Entry `(i, j)`; `None` out of range.
135    #[must_use]
136    pub fn get(&self, i: usize, j: usize) -> Option<T> {
137        if i < self.rows && j < self.cols {
138            Some(self.data[i + j * self.ld])
139        } else {
140            None
141        }
142    }
143    /// Column `j` (contiguous, length `rows`); `None` out of range.
144    #[must_use]
145    pub fn col(&self, j: usize) -> Option<&'a [T]> {
146        if j < self.cols {
147            let s = j * self.ld;
148            Some(&self.data[s..s + self.rows])
149        } else {
150            None
151        }
152    }
153    /// The columns `j0..j1` as a view (no copy).
154    ///
155    /// # Errors
156    /// [`StatlaError::InvalidArgument`] if the range is not inside.
157    pub fn cols_range(&self, j0: usize, j1: usize) -> Result<Self, StatlaError> {
158        if j0 > j1 || j1 > self.cols {
159            return Err(StatlaError::InvalidArgument {
160                what: "column range outside the view",
161            });
162        }
163        let start = (j0 * self.ld).min(self.data.len());
164        Ok(Self {
165            rows: self.rows,
166            cols: j1 - j0,
167            ld: self.ld,
168            data: &self.data[start..],
169        })
170    }
171    /// The underlying slice (crate-internal: the operator loops of Chapter
172    /// 12.0.5 index it with `ld`; (W1) keeps every index in bounds).
173    pub(crate) fn raw(&self) -> &'a [T] {
174        self.data
175    }
176    /// An owned copy.
177    #[must_use]
178    pub fn to_block(&self) -> DenseBlock<T> {
179        let mut b = DenseBlock::zeros(self.rows, self.cols);
180        for j in 0..self.cols {
181            let s = j * self.ld;
182            b.data[j * self.rows..(j + 1) * self.rows]
183                .copy_from_slice(&self.data[s..s + self.rows]);
184        }
185        b
186    }
187}
188
189impl<'a, T: Real> MatMut<'a, T> {
190    /// A mutable view (same checks as [`MatRef::new`]).
191    ///
192    /// # Errors
193    /// [`StatlaError::InvalidArgument`], [`StatlaError::Dimension`].
194    pub fn new(
195        rows: usize,
196        cols: usize,
197        ld: usize,
198        data: &'a mut [T],
199    ) -> Result<Self, StatlaError> {
200        extent(rows, cols, ld, data.len())?;
201        Ok(Self {
202            rows,
203            cols,
204            ld,
205            data,
206        })
207    }
208    /// The mutable view of a whole block (an inconsistent block gives a
209    /// view with no columns, as [`MatRef::from_block`]).
210    pub fn from_block(b: &'a mut DenseBlock<T>) -> Self {
211        let cols = if b.data.len() >= b.rows.saturating_mul(b.cols) {
212            b.cols
213        } else {
214            0
215        };
216        Self {
217            rows: b.rows,
218            cols,
219            ld: b.rows,
220            data: &mut b.data,
221        }
222    }
223    /// Reborrow as a shared view.
224    #[must_use]
225    pub fn as_ref(&self) -> MatRef<'_, T> {
226        MatRef {
227            rows: self.rows,
228            cols: self.cols,
229            ld: self.ld,
230            data: self.data,
231        }
232    }
233    /// Number of rows.
234    #[must_use]
235    pub(crate) fn rows(&self) -> usize {
236        self.rows
237    }
238    /// Number of columns.
239    #[must_use]
240    pub(crate) fn cols(&self) -> usize {
241        self.cols
242    }
243    /// Column `j`, mutable; `None` out of range.
244    pub fn col_mut(&mut self, j: usize) -> Option<&mut [T]> {
245        if j < self.cols {
246            let s = j * self.ld;
247            Some(&mut self.data[s..s + self.rows])
248        } else {
249            None
250        }
251    }
252}
253
254#[cfg(test)]
255#[allow(clippy::float_cmp)] // the tests compare exact values
256mod tests {
257    use super::*;
258
259    #[test]
260    fn views_index_with_the_leading_dimension() {
261        // 2 × 3 inside a 3-row array: column j starts at 3j.
262        let data = [1.0, 2.0, 99.0, 3.0, 4.0, 99.0, 5.0, 6.0];
263        let a = MatRef::new(2, 3, 3, &data).unwrap();
264        assert_eq!((a.rows(), a.cols(), a.ld()), (2, 3, 3));
265        assert_eq!(a.get(1, 2), Some(6.0));
266        assert_eq!(a.get(2, 0), None);
267        assert_eq!(a.get(0, 3), None);
268        assert_eq!(a.col(1), Some(&[3.0, 4.0][..]));
269        assert_eq!(a.col(3), None);
270        let b = a.to_block();
271        assert_eq!(b.data, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
272        let c = a.cols_range(1, 3).unwrap();
273        assert_eq!(
274            (c.cols(), c.get(0, 0), c.get(1, 1)),
275            (2, Some(3.0), Some(6.0))
276        );
277        let e = a.cols_range(3, 3).unwrap();
278        assert_eq!((e.cols(), e.col(0)), (0, None));
279        assert!(a.cols_range(2, 1).is_err() && a.cols_range(0, 4).is_err());
280        assert_eq!(MatRef::from_block(&b).get(1, 2), Some(6.0));
281    }
282
283    #[test]
284    fn construction_is_checked() {
285        let data = [0.0; 5];
286        assert_eq!(
287            MatRef::new(3, 2, 2, &data).unwrap_err(),
288            StatlaError::InvalidArgument { what: "ld < rows" }
289        );
290        assert_eq!(
291            MatRef::new(3, 2, 3, &data).unwrap_err(),
292            StatlaError::Dimension {
293                what: "data",
294                expected: 6,
295                found: 5
296            }
297        );
298        assert!(MatRef::new(usize::MAX, 3, usize::MAX, &data).is_err());
299        assert!(MatRef::<f64>::new(0, 0, 0, &[]).is_ok());
300        assert!(MatRef::<f64>::new(4, 0, 4, &[]).is_ok());
301        let inconsistent = DenseBlock {
302            rows: 2,
303            cols: 2,
304            data: vec![1.0],
305        };
306        assert_eq!(MatRef::from_block(&inconsistent).cols(), 0);
307    }
308
309    #[test]
310    fn mutable_views_write_through() {
311        let mut data = vec![0.0; 8];
312        {
313            let mut m = MatMut::new(2, 3, 3, &mut data).unwrap();
314            m.col_mut(2).unwrap()[1] = 8.0;
315            assert!(m.col_mut(3).is_none());
316            assert_eq!(m.as_ref().get(1, 2), Some(8.0));
317        }
318        assert_eq!(data[7], 8.0);
319        let mut b = DenseBlock::<f64>::zeros(2, 2);
320        MatMut::from_block(&mut b).col_mut(1).unwrap()[0] = 3.0;
321        assert_eq!(b.get(0, 1), 3.0);
322        assert!(MatMut::new(3, 1, 2, &mut data).is_err());
323    }
324}