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