@@ -279,6 +279,43 @@ where
279
279
D : Dimension ,
280
280
{
281
281
/// Try to convert this array into a [`nalgebra::MatrixView`] using the given shape and strides.
282
+ ///
283
+ /// Note that nalgebra's types default to Fortan/column-major standard strides whereas NumPy creates C/row-major strides by default.
284
+ /// Furthermore, array views created by slicing into existing arrays will often have non-standard strides.
285
+ ///
286
+ /// If you do not fully control the memory layout of a given array, e.g. at your API entry points,
287
+ /// it can be useful to opt into nalgebra's support for [dynamic strides][nalgebra::Dyn], for example
288
+ ///
289
+ /// ```rust
290
+ /// # use pyo3::prelude::*;
291
+ /// use pyo3::py_run;
292
+ /// use numpy::{get_array_module, PyReadonlyArray2};
293
+ /// use nalgebra::{MatrixView, Const, Dyn};
294
+ ///
295
+ /// #[pyfunction]
296
+ /// fn sum_standard_layout<'py>(py: Python<'py>, array: PyReadonlyArray2<'py, f64>) -> Option<f64> {
297
+ /// let matrix: Option<MatrixView<f64, Const<2>, Const<2>>> = array.try_as_matrix();
298
+ /// matrix.map(|matrix| matrix.sum())
299
+ /// }
300
+ ///
301
+ /// #[pyfunction]
302
+ /// fn sum_dynamic_strides<'py>(py: Python<'py>, array: PyReadonlyArray2<'py, f64>) -> Option<f64> {
303
+ /// let matrix: Option<MatrixView<f64, Const<2>, Const<2>, Dyn, Dyn>> = array.try_as_matrix();
304
+ /// matrix.map(|matrix| matrix.sum())
305
+ /// }
306
+ ///
307
+ /// Python::with_gil(|py| {
308
+ /// let np = py.eval("__import__('numpy')", None, None).unwrap();
309
+ /// let sum_standard_layout = wrap_pyfunction!(sum_standard_layout)(py).unwrap();
310
+ /// let sum_dynamic_strides = wrap_pyfunction!(sum_dynamic_strides)(py).unwrap();
311
+ ///
312
+ /// py_run!(py, np sum_standard_layout, r"assert sum_standard_layout(np.ones((2, 2), order='F')) == 4.");
313
+ /// py_run!(py, np sum_standard_layout, r"assert sum_standard_layout(np.ones((2, 2, 2))[:,:,0]) is None");
314
+ ///
315
+ /// py_run!(py, np sum_dynamic_strides, r"assert sum_dynamic_strides(np.ones((2, 2), order='F')) == 4.");
316
+ /// py_run!(py, np sum_dynamic_strides, r"assert sum_dynamic_strides(np.ones((2, 2, 2))[:,:,0]) == 4.");
317
+ /// });
318
+ /// ```
282
319
#[ doc( alias = "nalgebra" ) ]
283
320
pub fn try_as_matrix < R , C , RStride , CStride > (
284
321
& self ,
@@ -466,6 +503,8 @@ where
466
503
D : Dimension ,
467
504
{
468
505
/// Try to convert this array into a [`nalgebra::MatrixViewMut`] using the given shape and strides.
506
+ ///
507
+ /// See [`PyReadonlyArray::try_as_matrix`] for a discussion of the memory layout requirements.
469
508
#[ doc( alias = "nalgebra" ) ]
470
509
pub fn try_as_matrix_mut < R , C , RStride , CStride > (
471
510
& self ,
0 commit comments