Debian Codegraph @

debian/missing-sources/nalgebra/src/proptest/mod.rs

raw
1 //! `proptest`-related features for `nalgebra` data structures.
2 //!
3 //! **This module is only available when the `proptest-support` feature is enabled in `nalgebra`**.
4 //!
5 //! `proptest` is a library for *property-based testing*. While similar to `QuickCheck`,
6 //! which may be more familiar to some users, it has a more sophisticated design that
7 //! provides users with automatic invariant-preserving shrinking. This means that when using
8 //! `proptest`, you rarely need to write your own shrinkers - which is usually very difficult -
9 //! and can instead get this "for free". Moreover, `proptest` does not rely on a canonical
10 //! `Arbitrary` trait implementation like `QuickCheck`, though it does also provide this. For
11 //! more information, check out the [proptest docs](https://docs.rs/proptest/0.10.1/proptest/)
12 //! and the [proptest book](https://altsysrq.github.io/proptest-book/intro.html).
13 //!
14 //! This module provides users of `nalgebra` with tools to work with `nalgebra` types in
15 //! `proptest` tests. At present, this integration is at an early stage, and only
16 //! provides tools for generating matrices and vectors, and not any of the geometry types.
17 //! There are essentially two ways of using this functionality:
18 //!
19 //! - Using the [`matrix()`] function to generate matrices with constraints
20 //! on dimensions and elements.
21 //! - Relying on the [`Arbitrary`] implementation of [`OMatrix`].
22 //!
23 //! The first variant is almost always preferred in practice. Read on to discover why.
24 //!
25 //! ### Using free function strategies
26 //!
27 //! In `proptest`, it is usually preferable to have free functions that generate *strategies*.
28 //! Currently, the [`matrix()`] function fills this role. The analogous function for
29 //! column vectors is [`vector()`]. Let's take a quick look at how it may be used:
30 //! ```
31 //! use nalgebra::proptest::matrix;
32 //! use proptest::prelude::*;
33 //!
34 //! proptest! {
35 //! # /*
36 //! #[test]
37 //! # */
38 //! fn my_test(a in matrix(-5 ..= 5, 2 ..= 4, 1..=4)) {
39 //! // Generates matrices with elements in the range -5 ..= 5, rows in 2..=4 and
40 //! // columns in 1..=4.
41 //! }
42 //! }
43 //!
44 //! # fn main() { my_test(); }
45 //! ```
46 //!
47 //! In the above example, we generate matrices with constraints on the elements, as well as the
48 //! on the allowed dimensions. When a failing example is found, the resulting shrinking process
49 //! will preserve these invariants. We can use this to compose more advanced strategies.
50 //! For example, let's consider a toy example where we need to generate pairs of matrices
51 //! with exactly 3 rows fixed at compile-time and the same number of columns, but we want the
52 //! number of columns to vary. One way to do this is to use `proptest` combinators in combination
53 //! with [`matrix()`] as follows:
54 //!
55 //! ```
56 //! use nalgebra::{Dyn, OMatrix, Const};
57 //! use nalgebra::proptest::matrix;
58 //! use proptest::prelude::*;
59 //!
60 //! type MyMatrix = OMatrix<i32, Const::<3>, Dyn>;
61 //!
62 //! /// Returns a strategy for pairs of matrices with `U3` rows and the same number of
63 //! /// columns.
64 //! fn matrix_pairs() -> impl Strategy<Value=(MyMatrix, MyMatrix)> {
65 //! matrix(-5 ..= 5, Const::<3>, 0 ..= 10)
66 //! // We first generate the initial matrix `a`, and then depending on the concrete
67 //! // instances of `a`, we pick a second matrix with the same number of columns
68 //! .prop_flat_map(|a| {
69 //! let b = matrix(-5 .. 5, Const::<3>, a.ncols());
70 //! // This returns a new tuple strategy where we keep `a` fixed while
71 //! // the second item is a strategy that generates instances with the same
72 //! // dimensions as `a`
73 //! (Just(a), b)
74 //! })
75 //! }
76 //!
77 //! proptest! {
78 //! # /*
79 //! #[test]
80 //! # */
81 //! fn my_test((a, b) in matrix_pairs()) {
82 //! // Let's double-check that the two matrices do indeed have the same number of
83 //! // columns
84 //! prop_assert_eq!(a.ncols(), b.ncols());
85 //! }
86 //! }
87 //!
88 //! # fn main() { my_test(); }
89 //! ```
90 //!
91 //! ### The `Arbitrary` implementation
92 //!
93 //! If you don't care about the dimensions of matrices, you can write tests like these:
94 //!
95 //! ```
96 //! use nalgebra::{DMatrix, DVector, Dyn, Matrix3, OMatrix, Vector3, U3};
97 //! use proptest::prelude::*;
98 //!
99 //! proptest! {
100 //! # /*
101 //! #[test]
102 //! # */
103 //! fn test_dynamic(matrix: DMatrix<i32>) {
104 //! // This will generate arbitrary instances of `DMatrix` and also attempt
105 //! // to shrink/simplify them when test failures are encountered.
106 //! }
107 //!
108 //! # /*
109 //! #[test]
110 //! # */
111 //! fn test_static_and_mixed(matrix: Matrix3<i32>, matrix2: OMatrix<i32, U3, Dyn>) {
112 //! // Test some property involving these matrices
113 //! }
114 //!
115 //! # /*
116 //! #[test]
117 //! # */
118 //! fn test_vectors(fixed_size_vector: Vector3<i32>, dyn_vector: DVector<i32>) {
119 //! // Test some property involving these vectors
120 //! }
121 //! }
122 //!
123 //! # fn main() { test_dynamic(); test_static_and_mixed(); test_vectors(); }
124 //! ```
125 //!
126 //! While this may be convenient, the default strategies for built-in types in `proptest` can
127 //! generate *any* number, including integers large enough to easily lead to overflow when used in
128 //! matrix operations, or even infinity or NaN values for floating-point types. Therefore
129 //! `Arbitrary` is rarely the method of choice for writing property-based tests.
130 //!
131 //! ### Notes on shrinking
132 //!
133 //! Due to some limitations of the current implementation, shrinking takes place by first
134 //! shrinking the matrix elements before trying to shrink the dimensions of the matrix.
135 //! This unfortunately often leads to the fact that a large number of shrinking iterations
136 //! are necessary to find a (nearly) minimal failing test case. As a workaround for this,
137 //! you can increase the maximum number of shrinking iterations when debugging. To do this,
138 //! simply set the `PROPTEST_MAX_SHRINK_ITERS` variable to a high number. For example:
139 //!
140 //! ```text
141 //! PROPTEST_MAX_SHRINK_ITERS=100000 cargo test my_failing_test
142 //! ```
143 use crate::allocator::Allocator;
144 use crate::{Const, DefaultAllocator, Dim, DimName, Dyn, OMatrix, Scalar, U1};
145 use proptest::arbitrary::Arbitrary;
146 use proptest::collection::vec;
147 use proptest::strategy::{BoxedStrategy, Just, NewTree, Strategy, ValueTree};
148 use proptest::test_runner::TestRunner;
149
150 use std::ops::RangeInclusive;
151
152 /// Parameters for arbitrary matrix generation.
153 #[derive(Debug, Clone)]
154 #[non_exhaustive]
155 pub struct MatrixParameters<NParameters, R, C> {
156 /// The range of rows that may be generated.
157 pub rows: DimRange<R>,
158 /// The range of columns that may be generated.
159 pub cols: DimRange<C>,
160 /// Parameters for the `Arbitrary` implementation of the scalar values.
161 pub value_parameters: NParameters,
162 }
163
164 /// A range of allowed dimensions for use in generation of matrices.
165 ///
166 /// The `DimRange` type is used to encode the range of dimensions that can be used for generation
167 /// of matrices with `proptest`. In most cases, you do not need to concern yourself with
168 /// `DimRange` directly, as it supports conversion from other types such as `U3` or inclusive
169 /// ranges such as `5 ..= 6`. The latter example corresponds to dimensions from (inclusive)
170 /// `Dyn(5)` to `Dyn(6)` (inclusive).
171 #[derive(Debug, Clone, PartialEq, Eq)]
172 pub struct DimRange<D = Dyn>(RangeInclusive<D>);
173
174 impl<D: Dim> DimRange<D> {
175 /// The lower bound for dimensions generated.
176 pub fn lower_bound(&self) -> D {
177 *self.0.start()
178 }
179
180 /// The upper bound for dimensions generated.
181 pub fn upper_bound(&self) -> D {
182 *self.0.end()
183 }
184 }
185
186 impl<D: Dim> From<D> for DimRange<D> {
187 fn from(dim: D) -> Self {
188 DimRange(dim..=dim)
189 }
190 }
191
192 impl<D: Dim> From<RangeInclusive<D>> for DimRange<D> {
193 fn from(range: RangeInclusive<D>) -> Self {
194 DimRange(range)
195 }
196 }
197
198 impl From<RangeInclusive<usize>> for DimRange<Dyn> {
199 fn from(range: RangeInclusive<usize>) -> Self {
200 DimRange::from(Dyn(*range.start())..=Dyn(*range.end()))
201 }
202 }
203
204 impl<D: Dim> DimRange<D> {
205 /// Converts the `DimRange` into an instance of `RangeInclusive`.
206 pub fn to_range_inclusive(&self) -> RangeInclusive<usize> {
207 self.lower_bound().value()..=self.upper_bound().value()
208 }
209 }
210
211 impl From<usize> for DimRange<Dyn> {
212 fn from(dim: usize) -> Self {
213 DimRange::from(Dyn(dim))
214 }
215 }
216
217 /// The default range used for Dyn dimensions when generating arbitrary matrices.
218 fn dynamic_dim_range() -> DimRange<Dyn> {
219 DimRange::from(0..=6)
220 }
221
222 /// Create a strategy to generate matrices containing values drawn from the given strategy,
223 /// with rows and columns in the provided ranges.
224 ///
225 /// ## Examples
226 /// ```
227 /// use nalgebra::proptest::matrix;
228 /// use nalgebra::{OMatrix, Const, Dyn};
229 /// use proptest::prelude::*;
230 ///
231 /// proptest! {
232 /// # /*
233 /// #[test]
234 /// # */
235 /// fn my_test(a in matrix(0 .. 5i32, Const::<3>, 0 ..= 5)) {
236 /// // Let's make sure we've got the correct type first
237 /// let a: OMatrix<_, Const::<3>, Dyn> = a;
238 /// prop_assert!(a.nrows() == 3);
239 /// prop_assert!(a.ncols() <= 5);
240 /// prop_assert!(a.iter().all(|x_ij| *x_ij >= 0 && *x_ij < 5));
241 /// }
242 /// }
243 ///
244 /// # fn main() { my_test(); }
245 /// ```
246 ///
247 /// ## Limitations
248 /// The current implementation has some limitations that lead to suboptimal shrinking behavior.
249 /// See the [module-level documentation](index.html) for more.
250 pub fn matrix<R, C, ScalarStrategy>(
251 value_strategy: ScalarStrategy,
252 rows: impl Into<DimRange<R>>,
253 cols: impl Into<DimRange<C>>,
254 ) -> MatrixStrategy<ScalarStrategy, R, C>
255 where
256 ScalarStrategy: Strategy + Clone + 'static,
257 ScalarStrategy::Value: Scalar,
258 R: Dim,
259 C: Dim,
260 DefaultAllocator: Allocator<R, C>,
261 {
262 matrix_(value_strategy, rows.into(), cols.into())
263 }
264
265 /// Same as `matrix`, but without the additional anonymous generic types
266 fn matrix_<R, C, ScalarStrategy>(
267 value_strategy: ScalarStrategy,
268 rows: DimRange<R>,
269 cols: DimRange<C>,
270 ) -> MatrixStrategy<ScalarStrategy, R, C>
271 where
272 ScalarStrategy: Strategy + Clone + 'static,
273 ScalarStrategy::Value: Scalar,
274 R: Dim,
275 C: Dim,
276 DefaultAllocator: Allocator<R, C>,
277 {
278 let nrows = rows.lower_bound().value()..=rows.upper_bound().value();
279 let ncols = cols.lower_bound().value()..=cols.upper_bound().value();
280
281 // Even though we can use this function to generate fixed-size matrices,
282 // we currently generate all matrices with heap allocated Vec data.
283 // TODO: Avoid heap allocation for fixed-size matrices.
284 // Doing this *properly* would probably require us to implement a custom
285 // strategy and valuetree with custom shrinking logic, which is not trivial
286
287 // Perhaps more problematic, however, is the poor shrinking behavior the current setup leads to.
288 // Shrinking in proptest basically happens in "reverse" of the combinators, so
289 // by first generating the dimensions and then the elements, we get shrinking that first
290 // tries to completely shrink the individual elements before trying to reduce the dimension.
291 // This is clearly the opposite of what we want. I can't find any good way around this
292 // short of writing our own custom value tree, which we should probably do at some point.
293 // TODO: Custom implementation of value tree for better shrinking behavior.
294
295 let strategy = nrows
296 .prop_flat_map(move |nrows| (Just(nrows), ncols.clone()))
297 .prop_flat_map(move |(nrows, ncols)| {
298 (
299 Just(nrows),
300 Just(ncols),
301 vec(value_strategy.clone(), nrows * ncols),
302 )
303 })
304 .prop_map(|(nrows, ncols, values)| {
305 // Note: R/C::from_usize will panic if nrows/ncols does not fit in the dimension type.
306 // However, this should never fail, because we should only be generating
307 // this stuff in the first place
308 OMatrix::from_iterator_generic(R::from_usize(nrows), C::from_usize(ncols), values)
309 })
310 .boxed();
311
312 MatrixStrategy { strategy }
313 }
314
315 /// Create a strategy to generate column vectors containing values drawn from the given strategy,
316 /// with length in the provided range.
317 ///
318 /// This is a convenience function for calling
319 /// [`matrix(value_strategy, length, U1)`](crate::matrix) and should
320 /// be used when you only want to generate column vectors, as it's simpler and makes the intent
321 /// clear.
322 pub fn vector<D, ScalarStrategy>(
323 value_strategy: ScalarStrategy,
324 length: impl Into<DimRange<D>>,
325 ) -> MatrixStrategy<ScalarStrategy, D, U1>
326 where
327 ScalarStrategy: Strategy + Clone + 'static,
328 ScalarStrategy::Value: Scalar,
329 D: Dim,
330 DefaultAllocator: Allocator<D>,
331 {
332 matrix_(value_strategy, length.into(), Const::<1>.into())
333 }
334
335 impl<NParameters, R, C> Default for MatrixParameters<NParameters, R, C>
336 where
337 NParameters: Default,
338 R: DimName,
339 C: DimName,
340 {
341 fn default() -> Self {
342 Self {
343 rows: DimRange::from(R::name()),
344 cols: DimRange::from(C::name()),
345 value_parameters: NParameters::default(),
346 }
347 }
348 }
349
350 impl<NParameters, R> Default for MatrixParameters<NParameters, R, Dyn>
351 where
352 NParameters: Default,
353 R: DimName,
354 {
355 fn default() -> Self {
356 Self {
357 rows: DimRange::from(R::name()),
358 cols: dynamic_dim_range(),
359 value_parameters: NParameters::default(),
360 }
361 }
362 }
363
364 impl<NParameters, C> Default for MatrixParameters<NParameters, Dyn, C>
365 where
366 NParameters: Default,
367 C: DimName,
368 {
369 fn default() -> Self {
370 Self {
371 rows: dynamic_dim_range(),
372 cols: DimRange::from(C::name()),
373 value_parameters: NParameters::default(),
374 }
375 }
376 }
377
378 impl<NParameters> Default for MatrixParameters<NParameters, Dyn, Dyn>
379 where
380 NParameters: Default,
381 {
382 fn default() -> Self {
383 Self {
384 rows: dynamic_dim_range(),
385 cols: dynamic_dim_range(),
386 value_parameters: NParameters::default(),
387 }
388 }
389 }
390
391 impl<T, R, C> Arbitrary for OMatrix<T, R, C>
392 where
393 T: Scalar + Arbitrary,
394 <T as Arbitrary>::Strategy: Clone,
395 R: Dim,
396 C: Dim,
397 MatrixParameters<T::Parameters, R, C>: Default,
398 DefaultAllocator: Allocator<R, C>,
399 {
400 type Parameters = MatrixParameters<T::Parameters, R, C>;
401
402 fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
403 let value_strategy = T::arbitrary_with(args.value_parameters);
404 matrix(value_strategy, args.rows, args.cols)
405 }
406
407 type Strategy = MatrixStrategy<T::Strategy, R, C>;
408 }
409
410 /// A strategy for generating matrices.
411 #[derive(Debug, Clone)]
412 pub struct MatrixStrategy<NStrategy, R: Dim, C: Dim>
413 where
414 NStrategy: Strategy,
415 NStrategy::Value: Scalar,
416 DefaultAllocator: Allocator<R, C>,
417 {
418 // For now we only internally hold a boxed strategy. The reason for introducing this
419 // separate wrapper struct is so that we can replace the strategy logic with custom logic
420 // later down the road without introducing significant breaking changes
421 strategy: BoxedStrategy<OMatrix<NStrategy::Value, R, C>>,
422 }
423
424 impl<NStrategy, R, C> Strategy for MatrixStrategy<NStrategy, R, C>
425 where
426 NStrategy: Strategy,
427 NStrategy::Value: Scalar,
428 R: Dim,
429 C: Dim,
430 DefaultAllocator: Allocator<R, C>,
431 {
432 type Tree = MatrixValueTree<NStrategy::Value, R, C>;
433 type Value = OMatrix<NStrategy::Value, R, C>;
434
435 fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> {
436 let underlying_tree = self.strategy.new_tree(runner)?;
437 Ok(MatrixValueTree {
438 value_tree: underlying_tree,
439 })
440 }
441 }
442
443 /// A value tree for matrices.
444 pub struct MatrixValueTree<T, R, C>
445 where
446 T: Scalar,
447 R: Dim,
448 C: Dim,
449 DefaultAllocator: Allocator<R, C>,
450 {
451 // For now we only wrap a boxed value tree. The reason for wrapping is that this allows us
452 // to swap out the value tree logic down the road without significant breaking changes.
453 value_tree: Box<dyn ValueTree<Value = OMatrix<T, R, C>>>,
454 }
455
456 impl<T, R, C> ValueTree for MatrixValueTree<T, R, C>
457 where
458 T: Scalar,
459 R: Dim,
460 C: Dim,
461 DefaultAllocator: Allocator<R, C>,
462 {
463 type Value = OMatrix<T, R, C>;
464
465 fn current(&self) -> Self::Value {
466 self.value_tree.current()
467 }
468
469 fn simplify(&mut self) -> bool {
470 self.value_tree.simplify()
471 }
472
473 fn complicate(&mut self) -> bool {
474 self.value_tree.complicate()
475 }
476 }