1use std::ops::{Index, IndexMut};
12
13use num_traits::Zero;
14
15#[derive(Clone, Debug, PartialEq)]
17pub struct Mat<T> {
18 data: Vec<T>,
19 shape: (usize, usize),
20}
21
22impl<T> Mat<T> {
23 pub fn from_vec_col_major(shape: [usize; 2], data: Vec<T>) -> Self {
29 assert_eq!(
30 data.len(),
31 shape[0] * shape[1],
32 "Mat::from_vec_col_major: buffer length does not match shape"
33 );
34 Self {
35 data,
36 shape: (shape[0], shape[1]),
37 }
38 }
39
40 pub fn from_fn<F: FnMut(&[usize]) -> T>(shape: [usize; 2], mut f: F) -> Self {
42 let (m, n) = (shape[0], shape[1]);
43 let mut data = Vec::with_capacity(m * n);
44 for j in 0..n {
45 for i in 0..m {
46 data.push(f(&[i, j]));
47 }
48 }
49 Self {
50 data,
51 shape: (m, n),
52 }
53 }
54
55 #[inline]
57 pub fn shape(&self) -> &(usize, usize) {
58 &self.shape
59 }
60
61 #[inline]
63 pub fn dims(&self) -> [usize; 2] {
64 [self.shape.0, self.shape.1]
65 }
66
67 #[inline]
69 pub fn dim(&self, axis: usize) -> usize {
70 match axis {
71 0 => self.shape.0,
72 1 => self.shape.1,
73 _ => panic!("Mat::dim: axis {axis} out of range for a matrix"),
74 }
75 }
76
77 #[inline]
78 pub fn nrows(&self) -> usize {
79 self.shape.0
80 }
81
82 #[inline]
83 pub fn ncols(&self) -> usize {
84 self.shape.1
85 }
86
87 #[inline]
88 pub fn len(&self) -> usize {
89 self.data.len()
90 }
91
92 #[inline]
93 pub fn is_empty(&self) -> bool {
94 self.data.is_empty()
95 }
96
97 #[inline]
99 pub fn as_slice(&self) -> &[T] {
100 &self.data
101 }
102
103 #[inline]
105 pub fn as_mut_slice(&mut self) -> &mut [T] {
106 &mut self.data
107 }
108
109 pub fn into_vec(self) -> Vec<T> {
111 self.data
112 }
113
114 #[inline]
116 pub fn col(&self, j: usize) -> &[T] {
117 let m = self.shape.0;
118 &self.data[j * m..(j + 1) * m]
119 }
120
121 #[inline]
123 pub fn col_mut(&mut self, j: usize) -> &mut [T] {
124 let m = self.shape.0;
125 &mut self.data[j * m..(j + 1) * m]
126 }
127
128 pub fn iter(&self) -> std::slice::Iter<'_, T> {
130 self.data.iter()
131 }
132
133 pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
135 self.data.iter_mut()
136 }
137
138 pub fn map<U, F: FnMut(&T) -> U>(&self, f: F) -> Mat<U> {
140 Mat {
141 data: self.data.iter().map(f).collect(),
142 shape: self.shape,
143 }
144 }
145}
146
147impl<T: Clone> Mat<T> {
148 pub fn from_elem(shape: [usize; 2], elem: T) -> Self {
150 Self {
151 data: vec![elem; shape[0] * shape[1]],
152 shape: (shape[0], shape[1]),
153 }
154 }
155
156 pub fn transpose(&self) -> Self {
158 let (m, n) = self.shape;
159 Self::from_fn([n, m], |idx| self.data[idx[1] + m * idx[0]].clone())
160 }
161
162 pub fn leading_cols(&self, ncols: usize) -> Self {
164 assert!(ncols <= self.shape.1, "Mat::leading_cols: too many columns");
165 Self {
166 data: self.data[..self.shape.0 * ncols].to_vec(),
167 shape: (self.shape.0, ncols),
168 }
169 }
170}
171
172impl<T: Clone> Mat<T> {
173 pub fn from_rows(rows: Vec<Vec<T>>) -> Self {
178 let m = rows.len();
179 let n = rows.first().map_or(0, Vec::len);
180 assert!(
181 rows.iter().all(|r| r.len() == n),
182 "Mat::from_rows: ragged rows"
183 );
184 Self::from_fn([m, n], |idx| rows[idx[0]][idx[1]].clone())
185 }
186}
187
188#[allow(unused_macros)]
190#[doc(hidden)]
191#[macro_export]
192macro_rules! mat {
193 ($([$($x:expr),* $(,)?]),+ $(,)?) => {
194 $crate::matrix::Mat::from_rows(vec![$(vec![$($x),*]),+])
195 };
196}
197#[allow(unused_imports)]
198#[doc(hidden)]
199pub use crate::mat;
200
201impl<T: Clone + Zero> Mat<T> {
202 pub fn zeros(shape: [usize; 2]) -> Self {
204 Self::from_elem(shape, T::zero())
205 }
206}
207
208impl<T> Index<[usize; 2]> for Mat<T> {
209 type Output = T;
210 #[inline(always)]
211 fn index(&self, idx: [usize; 2]) -> &T {
212 debug_assert!(idx[0] < self.shape.0 && idx[1] < self.shape.1);
213 &self.data[idx[0] + self.shape.0 * idx[1]]
214 }
215}
216
217impl<T> IndexMut<[usize; 2]> for Mat<T> {
218 #[inline(always)]
219 fn index_mut(&mut self, idx: [usize; 2]) -> &mut T {
220 debug_assert!(idx[0] < self.shape.0 && idx[1] < self.shape.1);
221 &mut self.data[idx[0] + self.shape.0 * idx[1]]
222 }
223}
224
225impl<T> Index<&[usize]> for Mat<T> {
226 type Output = T;
227 #[inline(always)]
228 fn index(&self, idx: &[usize]) -> &T {
229 &self[[idx[0], idx[1]]]
230 }
231}
232
233#[derive(Clone, Debug, PartialEq)]
235pub struct Mat3<T> {
236 data: Vec<T>,
237 shape: (usize, usize, usize),
238}
239
240impl<T> Mat3<T> {
241 #[inline]
243 pub fn shape(&self) -> &(usize, usize, usize) {
244 &self.shape
245 }
246
247 #[inline]
249 pub fn as_slice(&self) -> &[T] {
250 &self.data
251 }
252
253 pub fn into_vec(self) -> Vec<T> {
255 self.data
256 }
257
258 pub fn from_vec_col_major(shape: [usize; 3], data: Vec<T>) -> Self {
263 assert_eq!(
264 data.len(),
265 shape[0] * shape[1] * shape[2],
266 "Mat3::from_vec_col_major: buffer length does not match shape"
267 );
268 Self {
269 data,
270 shape: (shape[0], shape[1], shape[2]),
271 }
272 }
273}
274
275impl<T: Clone> Mat3<T> {
276 pub fn from_elem(shape: [usize; 3], elem: T) -> Self {
278 Self {
279 data: vec![elem; shape[0] * shape[1] * shape[2]],
280 shape: (shape[0], shape[1], shape[2]),
281 }
282 }
283}
284
285impl<T: Clone + Zero> Mat3<T> {
286 pub fn zeros(shape: [usize; 3]) -> Self {
288 Self::from_elem(shape, T::zero())
289 }
290}
291
292impl<T> Index<[usize; 3]> for Mat3<T> {
293 type Output = T;
294 #[inline(always)]
295 fn index(&self, idx: [usize; 3]) -> &T {
296 let (a, b, _) = self.shape;
297 &self.data[idx[0] + a * (idx[1] + b * idx[2])]
298 }
299}
300
301impl<T> IndexMut<[usize; 3]> for Mat3<T> {
302 #[inline(always)]
303 fn index_mut(&mut self, idx: [usize; 3]) -> &mut T {
304 let (a, b, _) = self.shape;
305 &mut self.data[idx[0] + a * (idx[1] + b * idx[2])]
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 #[test]
314 fn col_major_layout_and_transpose() {
315 let a = Mat::from_fn([2, 3], |idx| (10 * idx[0] + idx[1]) as f64);
316 assert_eq!(a.as_slice(), &[0.0, 10.0, 1.0, 11.0, 2.0, 12.0]);
317 assert_eq!(a[[1, 2]], 12.0);
318 assert_eq!(a.col(1), &[1.0, 11.0]);
319 let t = a.transpose();
320 assert_eq!(*t.shape(), (3, 2));
321 assert_eq!(t[[2, 1]], 12.0);
322 }
323
324 #[test]
325 fn rank3_indexing() {
326 let mut a = Mat3::<f64>::zeros([2, 3, 4]);
327 a[[1, 2, 3]] = 5.0;
328 assert_eq!(a.as_slice()[1 + 2 * (2 + 3 * 3)], 5.0);
329 }
330}