Debian Codegraph @

debian/missing-sources/nalgebra/tests/macros/stack.rs

raw
1 use crate::macros::assert_eq_and_type;
2 use cool_asserts::assert_panics;
3 use na::VecStorage;
4 use nalgebra::dimension::U1;
5 use nalgebra::{
6 DMatrix, DMatrixView, Dyn, Matrix, Matrix2, Matrix4, OMatrix, SMatrix, SMatrixView,
7 SMatrixViewMut, Scalar, U2,
8 };
9 use nalgebra::{dmatrix, matrix, stack};
10 use nalgebra_macros::vector;
11 use num_traits::Zero;
12
13 /// Simple implementation that stacks dynamic matrices.
14 ///
15 /// Used for verifying results of the stack! macro. `None` entries are considered to represent
16 /// a zero block.
17 fn stack_dyn<T: Scalar + Zero>(blocks: DMatrix<Option<DMatrix<T>>>) -> DMatrix<T> {
18 let row_counts: Vec<usize> = blocks
19 .row_iter()
20 .map(|block_row| {
21 block_row
22 .iter()
23 .map(|block_or_implicit_zero| {
24 block_or_implicit_zero.as_ref().map(|block| block.nrows())
25 })
26 .reduce(|nrows1, nrows2| match (nrows1, nrows2) {
27 (Some(_), None) => nrows1,
28 (None, Some(_)) => nrows2,
29 (None, None) => None,
30 (Some(nrows1), Some(nrows2)) if nrows1 == nrows2 => Some(nrows1),
31 _ => panic!("Number of rows must be consistent in each block row"),
32 })
33 .unwrap_or(Some(0))
34 .expect("Each block row must have at least one entry which is not a zero literal")
35 })
36 .collect();
37 let col_counts: Vec<usize> = blocks
38 .column_iter()
39 .map(|block_col| {
40 block_col
41 .iter()
42 .map(|block_or_implicit_zero| {
43 block_or_implicit_zero.as_ref().map(|block| block.ncols())
44 })
45 .reduce(|ncols1, ncols2| match (ncols1, ncols2) {
46 (Some(_), None) => ncols1,
47 (None, Some(_)) => ncols2,
48 (None, None) => None,
49 (Some(ncols1), Some(ncols2)) if ncols1 == ncols2 => Some(ncols1),
50 _ => panic!("Number of columns must be consistent in each block column"),
51 })
52 .unwrap_or(Some(0))
53 .expect(
54 "Each block column must have at least one entry which is not a zero literal",
55 )
56 })
57 .collect();
58
59 let nrows_total = row_counts.iter().sum();
60 let ncols_total = col_counts.iter().sum();
61 let mut output = DMatrix::zeros(nrows_total, ncols_total);
62
63 let mut col_offset = 0;
64 for j in 0..blocks.ncols() {
65 let mut row_offset = 0;
66 for i in 0..blocks.nrows() {
67 if let Some(input_ij) = &blocks[(i, j)] {
68 let (block_nrows, block_ncols) = input_ij.shape();
69 output
70 .view_mut((row_offset, col_offset), (block_nrows, block_ncols))
71 .copy_from(&input_ij);
72 }
73 row_offset += row_counts[i];
74 }
75 col_offset += col_counts[j];
76 }
77
78 output
79 }
80
81 macro_rules! stack_dyn_convert_to_dmatrix_option {
82 (0) => {
83 None
84 };
85 ($entry:expr) => {
86 Some($entry.as_view::<Dyn, Dyn, U1, Dyn>().clone_owned())
87 };
88 }
89
90 /// Helper macro that compares the result of stack! with a simplified implementation that
91 /// works only with heap-allocated data.
92 ///
93 /// This implementation is essentially radically different to the implementation in stack!,
94 /// so if they both match, then it's a good sign that the stack! impl is correct.
95 macro_rules! verify_stack {
96 ($matrix_type:ty ; [$($($entry:expr),*);*]) => {
97 {
98 // Our input has the same syntax as the stack! macro (and matrix! macro, for that matter)
99 let stack_result: $matrix_type = stack![$($($entry),*);*];
100 // Use the dmatrix! macro to nest matrices into each other
101 let dyn_result = stack_dyn(
102 dmatrix![$($(stack_dyn_convert_to_dmatrix_option!($entry)),*);*]
103 );
104 // println!("{}", stack_result);
105 // println!("{}", dyn_result);
106 assert_eq!(stack_result, dyn_result);
107 }
108 }
109 }
110
111 #[test]
112 fn stack_simple() {
113 let m = stack![
114 Matrix2::<usize>::identity(), 0;
115 0, &Matrix2::identity();
116 ];
117
118 assert_eq_and_type!(m, Matrix4::identity());
119 }
120
121 #[test]
122 fn stack_diag() {
123 let m = stack![
124 0, matrix![1, 2; 3, 4;];
125 matrix![5, 6; 7, 8;], 0;
126 ];
127
128 let res = matrix![
129 0, 0, 1, 2;
130 0, 0, 3, 4;
131 5, 6, 0, 0;
132 7, 8, 0, 0;
133 ];
134
135 assert_eq_and_type!(m, res);
136 }
137
138 #[test]
139 fn stack_dynamic() {
140 let m = stack![
141 matrix![ 1, 2; 3, 4; ], 0;
142 0, dmatrix![7, 8, 9; 10, 11, 12; ];
143 ];
144
145 let res = dmatrix![
146 1, 2, 0, 0, 0;
147 3, 4, 0, 0, 0;
148 0, 0, 7, 8, 9;
149 0, 0, 10, 11, 12;
150 ];
151
152 assert_eq_and_type!(m, res);
153 }
154
155 #[test]
156 fn stack_nested() {
157 let m = stack![
158 stack![ matrix![1, 2; 3, 4;]; matrix![5, 6;]],
159 stack![ matrix![7;9;10;], matrix![11; 12; 13;] ];
160 ];
161
162 let res = matrix![
163 1, 2, 7, 11;
164 3, 4, 9, 12;
165 5, 6, 10, 13;
166 ];
167
168 assert_eq_and_type!(m, res);
169 }
170
171 #[test]
172 fn stack_single() {
173 let a = matrix![1, 2; 3, 4];
174 let b = stack![a];
175
176 assert_eq_and_type!(a, b);
177 }
178
179 #[test]
180 fn stack_single_row() {
181 let a = matrix![1, 2; 3, 4];
182 let m = stack![a, a];
183
184 let res = matrix![
185 1, 2, 1, 2;
186 3, 4, 3, 4;
187 ];
188
189 assert_eq_and_type!(m, res);
190 }
191
192 #[test]
193 fn stack_single_col() {
194 let a = matrix![1, 2; 3, 4];
195 let m = stack![a; a];
196
197 let res = matrix![
198 1, 2;
199 3, 4;
200 1, 2;
201 3, 4;
202 ];
203
204 assert_eq_and_type!(m, res);
205 }
206
207 #[test]
208 #[rustfmt::skip]
209 fn stack_expr() {
210 let a = matrix![1, 2; 3, 4];
211 let b = matrix![5, 6; 7, 8];
212 let m = stack![a + b; 2i32 * b - a];
213
214 let res = matrix![
215 6, 8;
216 10, 12;
217 9, 10;
218 11, 12;
219 ];
220
221 assert_eq_and_type!(m, res);
222 }
223
224 #[test]
225 fn stack_edge_cases() {
226 {
227 // Empty stack should return zero matrix with specified type
228 let _: SMatrix<i32, 0, 0> = stack![];
229 let _: SMatrix<f64, 0, 0> = stack![];
230 }
231
232 {
233 // Case suggested by @tpdickso: https://github.com/dimforge/nalgebra/pull/1080#discussion_r1435871752
234 let a = matrix![1, 2;
235 3, 4];
236 let b = DMatrix::from_data(VecStorage::new(Dyn(2), Dyn(0), vec![]));
237 assert_eq!(
238 stack![a, 0;
239 0, b],
240 matrix![1, 2;
241 3, 4;
242 0, 0;
243 0, 0]
244 );
245 }
246 }
247
248 #[rustfmt::skip]
249 #[test]
250 fn stack_many_tests() {
251 // s prefix means static, d prefix means dynamic
252 // Static matrices
253 let s_0x0: SMatrix<i32, 0, 0> = matrix![];
254 let s_0x1: SMatrix<i32, 0, 1> = Matrix::default();
255 let s_1x0: SMatrix<i32, 1, 0> = Matrix::default();
256 let s_1x1: SMatrix<i32, 1, 1> = matrix![1];
257 let s_2x2: SMatrix<i32, 2, 2> = matrix![6, 7; 8, 9];
258 let s_2x3: SMatrix<i32, 2, 3> = matrix![16, 17, 18; 19, 20, 21];
259 let s_3x3: SMatrix<i32, 3, 3> = matrix![28, 29, 30; 31, 32, 33; 34, 35, 36];
260
261 // Dynamic matrices
262 let d_0x0: DMatrix<i32> = dmatrix![];
263 let d_1x2: DMatrix<i32> = dmatrix![9, 10];
264 let d_2x2: DMatrix<i32> = dmatrix![5, 6; 7, 8];
265 let d_4x4: DMatrix<i32> = dmatrix![10, 11, 12, 13; 14, 15, 16, 17; 18, 19, 20, 21; 22, 23, 24, 25];
266
267 // Check for weirdness with matrices that have zero row/cols
268 verify_stack!(SMatrix<_, 0, 0>; [s_0x0]);
269 verify_stack!(SMatrix<_, 0, 1>; [s_0x1]);
270 verify_stack!(SMatrix<_, 1, 0>; [s_1x0]);
271 verify_stack!(SMatrix<_, 0, 0>; [s_0x0; s_0x0]);
272 verify_stack!(SMatrix<_, 0, 0>; [s_0x0, s_0x0; s_0x0, s_0x0]);
273 verify_stack!(SMatrix<_, 0, 2>; [s_0x1, s_0x1]);
274 verify_stack!(SMatrix<_, 2, 0>; [s_1x0; s_1x0]);
275 verify_stack!(SMatrix<_, 1, 0>; [s_1x0, s_1x0]);
276 verify_stack!(DMatrix<_>; [d_0x0]);
277
278 // Horizontal stacking
279 verify_stack!(SMatrix<_, 1, 2>; [s_1x1, s_1x1]);
280 verify_stack!(SMatrix<_, 2, 4>; [s_2x2, s_2x2]);
281 verify_stack!(DMatrix<_>; [d_1x2, d_1x2]);
282
283 // Vertical stacking
284 verify_stack!(SMatrix<_, 2, 1>; [s_1x1; s_1x1]);
285 verify_stack!(SMatrix<_, 4, 2>; [s_2x2; s_2x2]);
286 verify_stack!(DMatrix<_>; [d_2x2; d_2x2]);
287
288 // Mix static and dynamic matrices
289 verify_stack!(OMatrix<_, U2, Dyn>; [s_2x2, d_2x2]);
290 verify_stack!(OMatrix<_, Dyn, U2>; [s_2x2; d_1x2]);
291
292 // Stack more than two matrices
293 verify_stack!(SMatrix<_, 1, 3>; [s_1x1, s_1x1, s_1x1]);
294 verify_stack!(DMatrix<_>; [d_1x2, d_1x2, d_1x2]);
295
296 // Slightly larger dims
297 verify_stack!(SMatrix<_, 3, 6>; [s_3x3, s_3x3]);
298 verify_stack!(DMatrix<_>; [d_4x4; d_4x4]);
299 verify_stack!(SMatrix<_, 4, 7>; [s_2x2, s_2x3, d_2x2;
300 d_2x2, s_2x3, s_2x2]);
301
302 // Mix of references and owned
303 verify_stack!(OMatrix<_, Dyn, U2>; [&s_2x2; &d_1x2]);
304 verify_stack!(SMatrix<_, 4, 7>; [ s_2x2, &s_2x3, d_2x2;
305 &d_2x2, s_2x3, &s_2x2]);
306
307 // Views
308 let s_2x2_v: SMatrixView<_, 2, 2> = s_2x2.as_view();
309 let s_2x3_v: SMatrixView<_, 2, 3> = s_2x3.as_view();
310 let d_2x2_v: DMatrixView<_> = d_2x2.as_view();
311 let mut s_2x2_vm = s_2x2.clone();
312 let s_2x2_vm: SMatrixViewMut<_, 2, 2> = s_2x2_vm.as_view_mut();
313 let mut s_2x3_vm = s_2x3.clone();
314 let s_2x3_vm: SMatrixViewMut<_, 2, 3> = s_2x3_vm.as_view_mut();
315 verify_stack!(SMatrix<_, 4, 7>; [ s_2x2_vm, &s_2x3_vm, d_2x2_v;
316 &d_2x2_v, s_2x3_v, &s_2x2_v]);
317
318 // Expressions
319 let matrix_fn = |matrix: &DMatrix<_>| matrix.map(|x_ij| x_ij * 3);
320 verify_stack!(SMatrix<_, 2, 5>; [ 2 * s_2x2 - 3 * &d_2x2, s_2x3 + 2 * s_2x3]);
321 verify_stack!(DMatrix<_>; [ 2 * matrix_fn(&d_2x2) ]);
322 verify_stack!(SMatrix<_, 2, 5>; [ (|matrix| 4 * matrix)(s_2x2), s_2x3 ]);
323 }
324
325 #[test]
326 fn stack_trybuild_tests() {
327 let t = trybuild::TestCases::new();
328
329 // Verify error message when a row or column only contains a zero entry
330 t.compile_fail("tests/macros/trybuild/stack_empty_row.rs");
331 t.compile_fail("tests/macros/trybuild/stack_empty_col.rs");
332 t.compile_fail("tests/macros/trybuild/stack_incompatible_block_dimensions.rs");
333 t.compile_fail("tests/macros/trybuild/stack_incompatible_block_dimensions2.rs");
334 }
335
336 #[test]
337 fn stack_mismatched_dimensions_runtime_panics() {
338 // s prefix denotes static, d dynamic
339 let s_2x2 = matrix![1, 2; 3, 4];
340 let d_2x3 = dmatrix![5, 6, 7; 8, 9, 10];
341 let d_1x2 = dmatrix![11, 12];
342 let d_1x3 = dmatrix![13, 14, 15];
343
344 assert_panics!(
345 stack![s_2x2, d_1x2],
346 includes("All blocks in block row 0 must have the same number of rows")
347 );
348
349 assert_panics!(
350 stack![s_2x2; d_2x3],
351 includes("All blocks in block column 0 must have the same number of columns")
352 );
353
354 assert_panics!(
355 stack![s_2x2, s_2x2; d_1x2, d_2x3],
356 includes("All blocks in block row 1 must have the same number of rows")
357 );
358
359 assert_panics!(
360 stack![s_2x2, s_2x2; d_1x2, d_1x3],
361 includes("All blocks in block column 1 must have the same number of columns")
362 );
363
364 assert_panics!(
365 {
366 // Edge case suggested by @tpdickso: https://github.com/dimforge/nalgebra/pull/1080#discussion_r1435871752
367 let d_3x0 = DMatrix::from_data(VecStorage::new(Dyn(3), Dyn(0), Vec::<i32>::new()));
368 stack![s_2x2, d_3x0]
369 },
370 includes("All blocks in block row 0 must have the same number of rows")
371 );
372 }
373
374 #[test]
375 fn stack_test_builtin_types() {
376 // Other than T: Zero, there's nothing type-specific in the logic for stack!
377 // These tests are just sanity tests, to make sure it works with the common built-in types
378 let a = matrix![1, 2; 3, 4];
379 let b = vector![5, 6];
380 let c = matrix![7, 8];
381
382 let expected = matrix![ 1, 2, 5;
383 3, 4, 6;
384 7, 8, 0 ];
385
386 macro_rules! check_builtin {
387 ($T:ty) => {{
388 // Cannot use .cast::<$T> because we cannot convert between unsigned and signed
389 let stacked = stack![a.map(|a_ij| a_ij as $T), b.map(|b_ij| b_ij as $T);
390 c.map(|c_ij| c_ij as $T), 0];
391 assert_eq!(stacked, expected.map(|e_ij| e_ij as $T));
392 }}
393 }
394
395 check_builtin!(i8);
396 check_builtin!(i16);
397 check_builtin!(i32);
398 check_builtin!(i64);
399 check_builtin!(i128);
400 check_builtin!(u8);
401 check_builtin!(u16);
402 check_builtin!(u32);
403 check_builtin!(u64);
404 check_builtin!(u128);
405 check_builtin!(f32);
406 check_builtin!(f64);
407 }
408
409 #[test]
410 fn stack_test_complex() {
411 use num_complex::Complex as C;
412 type C32 = C<f32>;
413 let a = matrix![C::new(1.0, 1.0), C::new(2.0, 2.0); C::new(3.0, 3.0), C::new(4.0, 4.0)];
414 let b = vector![C::new(5.0, 5.0), C::new(6.0, 6.0)];
415 let c = matrix![C::new(7.0, 7.0), C::new(8.0, 8.0)];
416
417 let expected = matrix![ 1, 2, 5;
418 3, 4, 6;
419 7, 8, 0 ]
420 .map(|x| C::new(x as f64, x as f64));
421
422 assert_eq!(stack![a, b; c, 0], expected);
423 assert_eq!(
424 stack![a.cast::<C32>(), b.cast::<C32>(); c.cast::<C32>(), 0],
425 expected.cast::<C32>()
426 );
427 }