### Array Examples Source: https://docs.rs/ndarray/latest/ndarray/struct.RawRef.html Examples demonstrating the usage of array properties and methods. ```APIDOC ## Array Examples ### Square Array Check This example shows how to check if an array is square. ```rust use ndarray::array; let array = array![[1., 2.], [3., 4.]]; assert!(array.is_square()); ``` ### Non-Square Array Check This example shows how to check if an array is not square. ```rust use ndarray::array; let array = array![[1., 2., 5.], [3., 4., 6.]]; assert!(!array.is_square()); ``` ``` -------------------------------- ### azip Example 3: Elementwise Multiplication with References Source: https://docs.rs/ndarray/latest/ndarray/prelude/macro.azip.html Calculates the elementwise product of arrays b and c, storing the result in array a. This example demonstrates using azip with borrowed inputs within a function. ```rust // Example 3: azip!() on references // See the definition of the function below borrow_multiply(&mut a, &b, &c); assert_eq!(a, &b * &c); // Since this function borrows its inputs, the `IntoNdProducer` // expressions don't need to explicitly include `&mut` or `&`. fn borrow_multiply(a: &mut M, b: &M, c: &M) { azip!((a in a, &b in b, &c in c) *a = b * c); } ``` -------------------------------- ### azip Example 4: Row Summation Source: https://docs.rs/ndarray/latest/ndarray/prelude/macro.azip.html Calculates the sum of each row in a 2D array and stores the results in a 1D array. This example shows iterating over rows and using azip without explicit dereferencing for array views. ```rust // Example 4: using azip!() without dereference in pattern. // // Create a new array `totals` with one entry per row of `a`. // Use azip to traverse the rows of `a` and assign to the corresponding // entry in `totals` with the sum across each row. // // The row is an array view; it doesn't need to be dereferenced. let mut totals = Array1::zeros(a.nrows()); azip!((totals in &mut totals, row in a.rows()) *totals = row.sum()); // Check the result against the built in `.sum_axis()` along axis 1. assert_eq!(totals, a.sum_axis(Axis(1))); ``` -------------------------------- ### Test Predicates with Zip Source: https://docs.rs/ndarray/latest/ndarray/struct.Zip.html Examples of using all and any to evaluate conditions across multiple arrays in lock-step. ```rust use ndarray::{array, Zip}; let a = array![1, 2, 3]; let b = array![1, 4, 9]; assert!(Zip::from(&a).and(&b).all(|&a, &b| a * a == b)); ``` ```rust use ndarray::{array, Zip}; let a = array![1, 2, 3]; let b = array![1, 4, 9]; assert!(Zip::from(&a).and(&b).any(|&a, &b| a == b)); assert!(!Zip::from(&a).and(&b).any(|&a, &b| a - 1 == b)); ``` -------------------------------- ### Define Shape and Order for into_shape_with_order Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayViewMut.html Examples of valid shape and order configurations for the into_shape_with_order method. ```rust (3, 4) // Shape 3 x 4 with default order (RowMajor) ((3, 4), Order::RowMajor)) // use specific order ((3, 4), Order::ColumnMajor)) // use specific order ((3, 4), Order::C)) // use shorthand for order - shorthands C and F ``` -------------------------------- ### Initialize multi-dimensional arrays Source: https://docs.rs/ndarray/latest/ndarray/prelude/macro.array.html Examples of creating arrays with one to six dimensions using the array! macro. ```rust use ndarray::array; let a1 = array![1, 2, 3, 4]; let a2 = array![[1, 2], [3, 4]]; let a3 = array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]]; let a4 = array![[[[1, 2, 3, 4]]]]; let a5 = array![[[[[1, 2, 3, 4, 5]]]]]; let a6 = array![[[[[[1, 2, 3, 4, 5, 6]]]]]]; assert_eq!(a1.shape(), &[4]); assert_eq!(a2.shape(), &[2, 2]); assert_eq!(a3.shape(), &[2, 2, 2]); assert_eq!(a4.shape(), &[1, 1, 1, 4]); assert_eq!(a5.shape(), &[1, 1, 1, 1, 5]); assert_eq!(a6.shape(), &[1, 1, 1, 1, 1, 6]); ``` -------------------------------- ### starts_with Source: https://docs.rs/ndarray/latest/ndarray/struct.IxDynImpl.html Checks if the slice starts with the given needle. ```APIDOC ## starts_with ### Description Returns true if `needle` is a prefix of the slice or equal to the slice. ### Parameters - **needle** (&[T]) - Required - The prefix to check for. ``` -------------------------------- ### Basic azip usage and equivalence Source: https://docs.rs/ndarray/latest/ndarray/macro.azip.html Demonstrates the shorthand syntax of azip! compared to the explicit Zip API. ```Rust azip!((a in &mut a, &b in &b, &c in &c) *a = b + c); ``` ```Rust Zip::from(&mut a).and(&b).and(&c).for_each(|a, &b, &c| { *a = b + c }); ``` -------------------------------- ### Slice a 3D Array along an Axis Source: https://docs.rs/ndarray/latest/ndarray/doc/ndarray_for_numpy_users/index.html Use `a.slice(s![index, .., ..])` or `a.index_axis(Axis(axis_num), index)` to get a subview of a multi-dimensional array. This example gets the slice at index 1 of axis 0. ```rust a.slice(s![1, .., ..]) ``` ```rust a.index_axis(Axis(0), 1) ``` -------------------------------- ### ArrayBase Raw Data Access Source: https://docs.rs/ndarray/latest/ndarray/type.CowArray.html Provides methods for raw data access to array elements, including getting pointers to elements and the start of the array. ```APIDOC ## ArrayBase Raw Data Access ### impl, D: Dimension> ArrayBase #### pub fn get_ptr(&self, index: I) -> Option<*const A> where I: NdIndex, Return a raw pointer to the element at `index`, or return `None` if the index is out of bounds. ```rust use ndarray::arr2; let a = arr2(&[[1., 2.], [3., 4.]]); let v = a.raw_view(); let p = a.get_ptr((0, 1)).unwrap(); assert_eq!(unsafe { *p }, 2.); ``` #### pub fn get_mut_ptr(&mut self, index: I) -> Option<*mut A> where S: RawDataMut, I: NdIndex, Return a raw pointer to the element at `index`, or return `None` if the index is out of bounds. ```rust use ndarray::arr2; let mut a = arr2(&[[1., 2.], [3., 4.]]); let v = a.raw_view_mut(); let p = a.get_mut_ptr((0, 1)).unwrap(); unsafe { *p = 5.; } assert_eq!(a.get((0, 1)), Some(&5.)); ``` #### pub fn as_ptr(&self) -> *const A Return a pointer to the first element in the array. Raw access to array elements needs to follow the strided indexing scheme: an element at multi-index _I_ in an array with strides _S_ is located at offset _Σ 0 ≤ k < d Ik × Sk_ where _d_ is `self.ndim()`. #### pub fn raw_view(&self) -> RawArrayView Return a raw view of the array. ``` -------------------------------- ### Remove a prefix from a slice Source: https://docs.rs/ndarray/latest/ndarray/struct.IxDynImpl.html Use `strip_prefix` to get a subslice with the specified prefix removed. Returns `None` if the slice does not start with the prefix. An empty prefix returns the original slice. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### Comprehensive azip examples Source: https://docs.rs/ndarray/latest/ndarray/macro.azip.html Various usage patterns for azip!, including indexed access, borrowing, and row-wise operations. ```Rust use ndarray::{azip, Array1, Array2, Axis}; type M = Array2; // Setup example arrays let mut a = M::zeros((16, 16)); let mut b = M::zeros(a.dim()); let mut c = M::zeros(a.dim()); // assign values b.fill(1.); for ((i, j), elt) in c.indexed_iter_mut() { *elt = (i + 10 * j) as f32; } // Example 1: Compute a simple ternary operation: // elementwise addition of b and c, stored in a azip!((a in &mut a, &b in &b, &c in &c) *a = b + c); assert_eq!(a, &b + &c); // Example 2: azip!() with index azip!((index (i, j), &b in &b, &c in &c) { a[[i, j]] = b - c; }); assert_eq!(a, &b - &c); // Example 3: azip!() on references // See the definition of the function below borrow_multiply(&mut a, &b, &c); assert_eq!(a, &b * &c); // Since this function borrows its inputs, the `IntoNdProducer` // expressions don't need to explicitly include `&mut` or `&`. fn borrow_multiply(a: &mut M, b: &M, c: &M) { azip!((a in a, &b in b, &c in c) *a = b * c); } // Example 4: using azip!() without dereference in pattern. // // Create a new array `totals` with one entry per row of `a`. // Use azip to traverse the rows of `a` and assign to the corresponding // entry in `totals` with the sum across each row. // // The row is an array view; it doesn't need to be dereferenced. let mut totals = Array1::zeros(a.nrows()); azip!((totals in &mut totals, row in a.rows()) *totals = row.sum()); // Check the result against the built in `.sum_axis()` along axis 1. assert_eq!(totals, a.sum_axis(Axis(1))); ``` -------------------------------- ### Stacking arrays example Source: https://docs.rs/ndarray/latest/ndarray/fn.stack.html Demonstrates stacking two 2D arrays along a new axis to create a 3D array. ```rust extern crate ndarray; use ndarray::{arr2, arr3, stack, Axis}; let a = arr2(&[[2., 2.], [3., 3.]]); assert!( stack(Axis(0), &[a.view(), a.view()]) == Ok(arr3(&[[[2., 2.], [3., 3.]], [[2., 2.], [3., 3.]]])) ); ``` -------------------------------- ### Creating Arrays with ndarray Macro Source: https://docs.rs/ndarray/latest/ndarray/macro.array.html Examples demonstrating the creation of 1D to 6D arrays using the `array!` macro and asserting their shapes. ```rust use ndarray::array; let a1 = array![1, 2, 3, 4]; let a2 = array![[1, 2], [3, 4]]; let a3 = array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]]; let a4 = array![[[[[1, 2, 3, 4]]]]]; let a5 = array![[[[[[1, 2, 3, 4, 5]]]]]; let a6 = array![[[[[[[1, 2, 3, 4, 5, 6]]]]]]]; assert_eq!(a1.shape(), &[4]); assert_eq!(a2.shape(), &[2, 2]); assert_eq!(a3.shape(), &[2, 2, 2]); assert_eq!(a4.shape(), &[1, 1, 1, 4]); assert_eq!(a5.shape(), &[1, 1, 1, 1, 5]); assert_eq!(a6.shape(), &[1, 1, 1, 1, 1, 6]); ``` -------------------------------- ### Get Mutable Reference to First Element Source: https://docs.rs/ndarray/latest/ndarray/struct.ArrayRef.html Use `first_mut` to get a mutable reference to the first element. Returns `None` if the array is empty. ```rust use ndarray::Array3; let mut a = Array3::::zeros([3, 4, 2]); *a.first_mut().unwrap() = 42.; assert_eq!(a[[0, 0, 0]], 42.); let mut b = Array3::::zeros([3, 0, 5]); assert_eq!(b.first_mut(), None); ``` -------------------------------- ### Get Mutable Reference to Last Element Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef6.html Use `last_mut` to get a mutable reference to the last element. Returns `None` if the array is empty. ```rust use ndarray::Array3; let mut a = Array3::::zeros([3, 4, 2]); *a.last_mut().unwrap() = 42.; assert_eq!(a[[2, 3, 1]], 42.); let mut b = Array3::::zeros([3, 0, 5]); assert_eq!(b.last_mut(), None); ``` -------------------------------- ### Create a New Slice Source: https://docs.rs/ndarray/latest/ndarray/struct.Slice.html Constructs a new Slice with specified start, end, and step. The step must be non-zero. Equivalent to Python's `[start:end:step]`. ```rust pub fn new(start: isize, end: Option, step: isize) -> Slice ``` -------------------------------- ### Split Off Slice Starting with Third Element Source: https://docs.rs/ndarray/latest/ndarray/struct.IxDynImpl.html Use `split_off` with a range like `2..` to remove and return a subslice starting from a specific index. The original slice is modified. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### azip Example 1: Elementwise Addition Source: https://docs.rs/ndarray/latest/ndarray/prelude/macro.azip.html Computes the elementwise addition of two arrays (b and c) and stores the result in a third array (a). Requires arrays to be of the same shape. ```rust use ndarray::{azip, Array1, Array2, Axis}; type M = Array2; // Setup example arrays let mut a = M::zeros((16, 16)); let mut b = M::zeros(a.dim()); let mut c = M::zeros(a.dim()); // assign values b.fill(1.); for ((i, j), elt) in c.indexed_iter_mut() { *elt = (i + 10 * j) as f32; } // Example 1: Compute a simple ternary operation: // elementwise addition of b and c, stored in a azip!((a in &mut a, &b in &b, &c in &c) *a = b + c); assert_eq!(a, &b + &c); ``` -------------------------------- ### fn try_into Source: https://docs.rs/ndarray/latest/ndarray/struct.OwnedArcRepr.html Documentation for the try_into conversion method. ```APIDOC ## fn try_into ### Description Performs the conversion from the current type to the target type U. ### Method Rust Function ### Parameters - **self** - Required - The instance to be converted. ### Response - **Result>::Error>** - Returns the converted type U or an error if the conversion fails. ``` -------------------------------- ### Geometrically Spaced Array Creation Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayView.html Creates a one-dimensional array with a specified number of geometrically spaced elements between a start and end value. Returns None if start and end have different signs or if either is zero. ```APIDOC ## pub fn geomspace(start: A, end: A, n: usize) -> Option ### Description Create a one-dimensional array with `n` geometrically spaced elements from `start` to `end` (inclusive). `A` must be a floating point type. Returns `None` if `start` and `end` have different signs or if either one is zero. Conceptually, this means that in order to obtain a `Some` result, `end / start` must be positive. **Panics** if `n` is greater than `isize::MAX` or if converting `n - 1` to type `A` fails. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use approx::assert_abs_diff_eq; use ndarray::{Array, arr1}; let array = Array::geomspace(1e0, 1e3, 4)?; assert_abs_diff_eq!(array, arr1(&[1e0, 1e1, 1e2, 1e3]), epsilon = 1e-11); let array = Array::geomspace(-1e3, -1e0, 4)?; assert_abs_diff_eq!(array, arr1(&[-1e3, -1e2, -1e1, -1e0]), epsilon = 1e-11); ``` ### Response #### Success Response (200) - **Option** (Option): An optional array with geometrically spaced elements. Returns `None` if input conditions are not met. #### Response Example ```json { "example": "[1.0, 10.0, 100.0, 1000.0]" } ``` ``` -------------------------------- ### Create and initialize an uninitialized array Source: https://docs.rs/ndarray/latest/ndarray/type.ArcArray.html Demonstrates creating an uninitialized Array2, performing slice-based assignments, and safely converting it to an initialized array. ```rust use ndarray::{s, Array2}; // Example Task: Let's create a column shifted copy of the input fn shift_by_two(a: &Array2) -> Array2 { // create an uninitialized array let mut b = Array2::uninit(a.dim()); // two first columns in b are two last in a // rest of columns in b are the initial columns in a a.slice(s![.., -2..]).assign_to(b.slice_mut(s![.., ..2])); a.slice(s![.., 2..]).assign_to(b.slice_mut(s![.., ..-2])); // Now we can promise that `b` is safe to use with all operations unsafe { b.assume_init() } } ``` -------------------------------- ### Get Element by Index with Bounds Checking Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef6.html Use `get` to safely access an element by its index, returning `None` if the index is out of bounds. Direct indexing `array[index]` is also supported but panics on out-of-bounds access. ```rust use ndarray::arr2; let a = arr2(&[[1., 2.], [3., 4.]]); assert!( a.get((0, 1)) == Some(&2.) && a.get((0, 2)) == None && a[(0, 1)] == 2. && a[[0, 1]] == 2. ); ``` -------------------------------- ### GET /is_square Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Checks if the array is square. ```APIDOC ## GET /is_square ### Description Return true if the array is square, false otherwise. ### Method GET ### Response - **is_square** (bool) - True if square, false otherwise. ``` -------------------------------- ### TryInto Implementation Source: https://docs.rs/ndarray/latest/ndarray/struct.ShapeError.html Provides a convenient way to attempt conversion into another type, leveraging TryFrom. ```APIDOC ## impl TryInto for T ### Description Provides a convenient way to attempt conversion from type `T` into type `U`. ### Method `try_into` ### Endpoint N/A (Trait implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **U** (type) - The converted value of type `U`. #### Error Response - **Error** (type) - The error type returned if conversion fails. ``` -------------------------------- ### get Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef6.html Access an element at a specific index. ```APIDOC ## pub fn get(&self, index: I) -> Option<&A> ### Description Return a reference to the element at `index`, or return `None` if the index is out of bounds. ### Parameters #### Request Body - **index** (I: NdIndex) - Required - The index to access. ### Response - **Option<&A>** - The element reference or None. ``` -------------------------------- ### Zip::and Source: https://docs.rs/ndarray/latest/ndarray/struct.Zip.html Include a new producer in the Zip iteration. ```APIDOC ## pub fn and

(self, p: P) -> Zip<(P1, P2, P::Output), D> ### Description Include the producer p in the Zip. Panics if p’s shape doesn’t match the Zip’s exactly. ### Parameters #### Request Body - **p** (IntoNdProducer) - Required - The producer to include in the Zip. ``` -------------------------------- ### Cloning and Default Initialization Source: https://docs.rs/ndarray/latest/ndarray/type.CowArray.html Methods for cloning arrays and creating default instances. ```APIDOC ## Clone and Default ### Description Provides methods for cloning arrays efficiently and creating default owned arrays. ### Methods - **clone_from**: Reuses an array's existing allocation. - **clone**: Returns a duplicate of the value. - **default**: Returns the default value for the array type. ``` -------------------------------- ### GET /len_of Source: https://docs.rs/ndarray/latest/ndarray/type.RawArrayViewMut.html Returns the length of a specific axis. ```APIDOC ## GET /len_of ### Description Return the length of the specified axis. ### Parameters #### Query Parameters - **axis** (Axis) - Required - The axis to query. ``` -------------------------------- ### Stacking Arrays with stack Macro Source: https://docs.rs/ndarray/latest/ndarray/macro.stack.html Examples of stacking 2D arrays along different axes to produce 3D arrays. ```rust extern crate ndarray; use ndarray::{arr2, arr3, stack, Axis}; let a = arr2(&[[1., 2.], [3., 4.]]); assert_eq!( stack![Axis(0), a, a], arr3(&[[[1., 2.], [3., 4.]], [[1., 2.], [3., 4.]]]), ); assert_eq!( stack![Axis(1), a, a,], arr3(&[[[1., 2.], [1., 2.]], [[3., 4.], [3., 4.]]]), ); assert_eq!( stack![Axis(2), a, a], arr3(&[[[1., 1.], [2., 2.]], [[3., 3.], [4., 4.]]]), ); ``` -------------------------------- ### GET /stride_of Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Returns the stride of a specific axis. ```APIDOC ## GET /stride_of ### Description Return the stride of the specified axis. ### Method GET ### Parameters #### Query Parameters - **axis** (Axis) - Required - The axis to query. ### Response - **stride** (isize) - The stride value for the given axis. ``` -------------------------------- ### GET /strides Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Returns the strides of the array as a slice. ```APIDOC ## GET /strides ### Description Return the strides of the array as a slice. ### Method GET ### Response - **strides** (&[isize]) - The strides of the array. ``` -------------------------------- ### Constructor: Slice::new Source: https://docs.rs/ndarray/latest/ndarray/struct.Slice.html Creates a new Slice instance with specified start, end, and step parameters. ```APIDOC ## POST /Slice/new ### Description Creates a new `Slice` with the given extents. The `step` parameter must be nonzero. ### Parameters #### Request Body - **start** (isize) - Required - Start index; negative values are counted from the back of the axis. - **end** (Option) - Required - End index (exclusive); negative values are counted from the back of the axis. If None, the slice extends to the end of the axis. - **step** (isize) - Required - Step size in elements. ### Response #### Success Response (200) - **Slice** (object) - The newly created Slice instance. ``` -------------------------------- ### Dim Cloning and Copying Source: https://docs.rs/ndarray/latest/ndarray/type.IxDyn.html Information on how to clone and copy `Dim` instances. ```APIDOC ## Dim Cloning and Copying ### Description This section details the cloning and copying capabilities of the `Dim` struct. ### Methods #### `clone(&self) -> Dim` Returns a duplicate of the value. #### `clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. ### Traits #### `impl Copy for Dim` Indicates that `Dim` implements the `Copy` trait. ``` -------------------------------- ### GET /nrows Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Returns the number of rows in a 2D array. ```APIDOC ## GET /nrows ### Description Return the number of rows (length of Axis(0)) in the two-dimensional array. ### Method GET ### Response - **nrows** (usize) - The number of rows. ``` -------------------------------- ### POST /build_uninit Source: https://docs.rs/ndarray/latest/ndarray/type.Array.html Creates an array with uninitialized elements and initializes it using a builder closure. ```APIDOC ## POST /build_uninit ### Description Create an array with uninitialized elements and provide a builder closure to modify the array before returning it. ### Method POST ### Endpoint /build_uninit ### Parameters #### Request Body - **shape** (ShapeBuilder) - Required - The shape of the array. - **builder** (FnOnce) - Required - A closure that receives a mutable view of the uninitialized array. ``` -------------------------------- ### GET /ncols Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Returns the number of columns in a 2D array. ```APIDOC ## GET /ncols ### Description Return the number of columns (length of Axis(1)) in the two-dimensional array. ### Method GET ### Response - **ncols** (usize) - The number of columns. ``` -------------------------------- ### Initialization and Dereferencing Source: https://docs.rs/ndarray/latest/ndarray/iter/struct.IntoIter.html Provides functions for initializing, dereferencing, and mutably dereferencing pointers, as well as dropping objects. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Method unsafe fn ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## unsafe fn deref<'a>(ptr: usize) -> &'a T ### Description Dereferences the given pointer. ### Method unsafe fn ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ### Description Mutably dereferences the given pointer. ### Method unsafe fn ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## unsafe fn drop(ptr: usize) ### Description Drops the object pointed to by the given pointer. ### Method unsafe fn ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Dim Indexing Source: https://docs.rs/ndarray/latest/ndarray/type.IxDyn.html Details on how to index `Dim` instances. ```APIDOC ## Dim Indexing ### Description This section explains how to access elements within a `Dim` instance using indexing. ### Methods #### `index(&self, index: usize) -> &Self::Output` Performs the indexing (`container[index]`) operation. #### `index_mut(&mut self, index: usize) -> &mut Self::Output` Performs the mutable indexing (`container[index]`) operation. ``` -------------------------------- ### GET /shape Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Returns the shape of the array as a slice of usize. ```APIDOC ## GET /shape ### Description Returns the shape of the array as a slice. Note that using this to create new arrays results in dynamic-dimensional arrays; use .raw_dim() for preserving dimensionality. ### Method GET ### Response - **shape** (&[usize]) - The dimensions of the array. ``` -------------------------------- ### GET /into_diag Source: https://docs.rs/ndarray/latest/ndarray/type.Array.html Returns the diagonal of the array as a one-dimensional array. ```APIDOC ## GET /into_diag ### Description Return the diagonal as a one-dimensional array. ### Method GET ### Endpoint /into_diag ``` -------------------------------- ### Create and Access Array Subviews Source: https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html Demonstrates creating subviews of a 3D array using `index_axis` to select slices along different axes. Also shows slicing with `s_` to select multiple subviews simultaneously. ```rust use ndarray::{arr3, aview1, aview2, s, Axis}; // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`. let a = arr3(&[[[ 1, 2, 3], // \ axis 0, submatrix 0 [ 4, 5, 6]], // / [[ 7, 8, 9], // \ axis 0, submatrix 1 [10, 11, 12]]]); // / // \ // axis 2, column 0 assert_eq!(a.shape(), &[2, 2, 3]); // Let’s take a subview along the greatest dimension (axis 0), // taking submatrix 0, then submatrix 1 let sub_0 = a.index_axis(Axis(0), 0); let sub_1 = a.index_axis(Axis(0), 1); assert_eq!(sub_0, aview2(&[[ 1, 2, 3], [ 4, 5, 6]])); assert_eq!(sub_1, aview2(&[[ 7, 8, 9], [10, 11, 12]])); assert_eq!(sub_0.shape(), &[2, 3]); // This is the subview picking only axis 2, column 0 let sub_col = a.index_axis(Axis(2), 0); assert_eq!(sub_col, aview2(&[[ 1, 4], [ 7, 10]])); // You can take multiple subviews at once (and slice at the same time) let double_sub = a.slice(s![1, .., 0]); assert_eq!(double_sub, aview1(&[7, 10])); ``` -------------------------------- ### GET /get_mut_ptr Source: https://docs.rs/ndarray/latest/ndarray/type.RawArrayViewMut.html Returns a raw pointer to the element at the specified index. ```APIDOC ## GET /get_mut_ptr ### Description Returns a raw pointer to the element at `index`, or returns `None` if the index is out of bounds. ### Parameters #### Path Parameters - **index** (I) - Required - The index to access, must implement NdIndex. ### Response #### Success Response (200) - **pointer** (*mut A) - A raw pointer to the element. ``` -------------------------------- ### Zip::from() Source: https://docs.rs/ndarray/latest/ndarray/struct.Zip.html Creates a new Zip instance from an initial producer. All subsequent producers added must have the same dimensions as the first one. ```APIDOC ## POST /api/users ### Description Creates a new `Zip` from the input array or other producer `p`. The Zip will take the exact dimension of `p` and all inputs must have the same dimensions (or be broadcast to them). ``` -------------------------------- ### Get Array Strides Source: https://docs.rs/ndarray/latest/ndarray/type.LayoutRef2.html Returns the strides of the array as a slice of isize. ```rust let a = Array2::::zeros((3, 4)); let strides = a.strides(); assert_eq!(strides, &[4, 1]); ``` -------------------------------- ### As Standard Layout Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef1.html Returns a standard-layout array, cloning the data if necessary. If the array is already in standard layout, a view is returned. ```APIDOC ## POST /api/as_standard_layout ### Description Returns a standard-layout array, cloning the data if necessary. If the array is already in standard layout, a view is returned. ### Method POST ### Endpoint /api/as_standard_layout ### Parameters (No parameters specified) ### Request Body (No request body specified) ### Response #### Success Response (200) - **CowArray** (CowArray<'_, A, D>) - A standard-layout array, potentially a view or owned data. #### Response Example (No response example specified) ``` -------------------------------- ### Get Mutable Array View Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef2.html Returns a read-write view of the array. ```rust pub fn view_mut(&mut self) -> ArrayViewMut<'_, A, D> ``` -------------------------------- ### Row-wise Summation with Zip Source: https://docs.rs/ndarray/latest/ndarray/struct.Zip.html Process arrays row by row using Zip. This example demonstrates summing elements across each row of a 2D array and storing the result in a 1D array. The producer for the output array and the row producer for the input array must have compatible shapes. ```rust use ndarray::Zip; use ndarray::{Array1, Axis}; let mut totals = Array1::zeros(a.nrows()); Zip::from(&mut totals) .and(a.rows()) .for_each(|totals, row| *totals = row.sum()); // Check the result against the built in `.sum_axis()` along axis 1. assert_eq!(totals, a.sum_axis(Axis(1))); ``` -------------------------------- ### Get Read-Only Array View Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef2.html Returns a read-only view of the array. ```rust pub fn view(&self) -> ArrayView<'_, A, D> ``` -------------------------------- ### ndarray Prelude Macros Source: https://docs.rs/ndarray/latest/ndarray/prelude/index.html This section details the macros available in the ndarray prelude for creating and manipulating arrays. ```APIDOC ## Macros ### `array` Create an **`Array`** with one, two, three, four, five, or six dimensions. ### `azip` Array zip macro: lock step function application across several arrays and producers. ### `s` Slice argument constructor. ``` -------------------------------- ### Get Axis Information Source: https://docs.rs/ndarray/latest/ndarray/type.CowArray.html Returns an iterator over the length and stride of each axis in the array. ```rust pub fn axes(&self) -> Axes<'_, D>; ``` -------------------------------- ### par_azip Usage and Equivalent Zip Source: https://docs.rs/ndarray/latest/ndarray/parallel/macro.par_azip.html Comparison between the par_azip macro syntax and the equivalent Zip method chain. ```rust par_azip!((a in &mut a, &b in &b, &c in &c) { *a = b + c }) ``` ```rust Zip::from(&mut a).and(&b).and(&c).par_for_each(|a, &b, &c| { *a = b + c; }); ``` -------------------------------- ### ArrayBase Get Pointer Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayViewMut.html Retrieves a raw pointer to an element at a given index. ```APIDOC ## `get_ptr()` for ArrayBase ### Description Return a raw pointer to the element at `index`, or return `None` if the index is out of bounds. ### Method `get_ptr(&self, index: I) -> Option<*const A>` ### Parameters #### Path Parameters - `index` (I): An index conforming to `NdIndex`. ### Request Example ```rust use ndarray::arr2; let a = arr2(&[[1., 2.], [3., 4.]]); let v = a.raw_view(); let p = a.get_ptr((0, 1)).unwrap(); assert_eq!(unsafe { *p }, 2.); ``` ``` -------------------------------- ### Get IxDyn as ArrayView1 Source: https://docs.rs/ndarray/latest/ndarray/type.IxDyn.html Borrows the IxDyn dimension as a read-only array view. ```rust fn as_array_view(&self) -> ArrayView1<'_, Ix> ``` -------------------------------- ### AsRef Implementation for RawRef Source: https://docs.rs/ndarray/latest/ndarray/struct.LayoutRef.html Shows how `RawRef` can be converted into a shared reference of `LayoutRef`. ```APIDOC ## impl AsRef> for RawRef ### fn as_ref(&self) -> &LayoutRef Converts this type into a shared reference of the (usually inferred) input type. ``` -------------------------------- ### Get Diagonal as 1D Array Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayView.html Returns the diagonal of an array as a one-dimensional array. ```rust pub fn into_diag(self) -> ArrayBase ``` -------------------------------- ### Create and Use Dynamic Dimension Arrays Source: https://docs.rs/ndarray/latest/ndarray/type.IxDyn.html Use IxDyn to create arrays with a dynamic number of dimensions. This example demonstrates creating, broadcasting, and indexing into arrays with dynamic shapes. Indexing panics if the number of indices does not match the array's dimensions. ```rust use ndarray::ArrayD; use ndarray::IxDyn; // Create a 5 × 6 × 3 × 4 array using the dynamic dimension type let mut a = ArrayD::::zeros(IxDyn(&[5, 6, 3, 4])); // Create a 1 × 3 × 4 array using the dynamic dimension type let mut b = ArrayD::::zeros(IxDyn(&[1, 3, 4])); // We can use broadcasting to add arrays of compatible shapes together: a += &b; // We can index into a, b using fixed size arrays: a[[0, 0, 0, 0]] = 0.; b[[0, 2, 3]] = a[[0, 0, 2, 3]]; // Note: indexing will panic at runtime if the number of indices given does // not match the array. // We can keep them in the same vector because both the arrays have // the same type `Array` a.k.a `ArrayD`: let arrays = vec![a, b]; ``` -------------------------------- ### TryFrom Implementation Source: https://docs.rs/ndarray/latest/ndarray/struct.IxDynImpl.html Provides a fallible conversion from one type to another. ```APIDOC ### impl TryFrom for T #### type Error = Infallible ### Description The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ``` -------------------------------- ### Get Last Element Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef4.html Retrieves an optional reference to the last element of the array. ```APIDOC ## pub fn last(&self) -> Option<&A> ### Description Returns a reference to the last element of the array, or `None` if it is empty. ### Example ```rust use ndarray::Array3; let mut a = Array3::::zeros([3, 4, 2]); a[[2, 3, 1]] = 42.; assert_eq!(a.last(), Some(&42.)); let b = Array3::::zeros([3, 0, 5]); assert_eq!(b.last(), None); ``` ``` -------------------------------- ### TryInto Implementation Source: https://docs.rs/ndarray/latest/ndarray/struct.IxDynImpl.html Provides a fallible conversion into another type. ```APIDOC ### impl TryInto for T #### type Error = >::Error ### Description The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> ### Description Performs the conversion. ``` -------------------------------- ### Get First Element Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef4.html Retrieves an optional reference to the first element of the array. ```APIDOC ## pub fn first(&self) -> Option<&A> ### Description Returns a reference to the first element of the array, or `None` if it is empty. ### Example ```rust use ndarray::Array3; let mut a = Array3::::zeros([3, 4, 2]); a[[0, 0, 0]] = 42.; assert_eq!(a.first(), Some(&42.)); let b = Array3::::zeros([3, 0, 5]); assert_eq!(b.first(), None); ``` ``` -------------------------------- ### AsRef Implementation for LayoutRef Source: https://docs.rs/ndarray/latest/ndarray/struct.LayoutRef.html Demonstrates how `LayoutRef` can be converted into a shared reference of itself. ```APIDOC ## impl AsRef> for LayoutRef ### fn as_ref(&self) -> &LayoutRef Converts this type into a shared reference of the (usually inferred) input type. ``` -------------------------------- ### Get Shared Reference to RawRef Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef3.html Converts `self` into a shared reference to `RawRef`. ```rust fn as_ref(&self) -> &RawRef ``` -------------------------------- ### Index a 2D array Source: https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html Demonstrates initializing a 2D array and modifying a specific element using the array[[i, j]] syntax. ```rust use ndarray::Array2; let mut array = Array2::zeros((4, 3)); array[[1, 1]] = 7; ``` -------------------------------- ### Get Shared Reference to LayoutRef Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef3.html Converts `self` into a shared reference to `LayoutRef`. ```rust fn as_ref(&self) -> &LayoutRef ``` -------------------------------- ### Optimized coordinate transformation with azip Source: https://docs.rs/ndarray/latest/ndarray/doc/ndarray_for_numpy_users/coord_transform/index.html Improved implementation using the azip macro to avoid manual indexing and reduce temporary memory allocations. ```rust use ndarray::prelude::*; let nelems = 4; let bunge = Array2::::ones((3, nelems)); let mut rmat = Array::zeros((3, 3, nelems).f()); azip!((mut rmat in rmat.axis_iter_mut(Axis(2)), bunge in bunge.axis_iter(Axis(1))) { let s1 = bunge[0].sin(); let c1 = bunge[0].cos(); let s2 = bunge[1].sin(); let c2 = bunge[1].cos(); let s3 = bunge[2].sin(); let c3 = bunge[2].cos(); rmat[[0, 0]] = c1 * c3 - s1 * s3 * c2; rmat[[0, 1]] = -c1 * s3 - s1 * c2 * c3; rmat[[0, 2]] = s1 * s2; rmat[[1, 0]] = s1 * c3 + c1 * c2 * s3; rmat[[1, 1]] = -s1 * s3 + c1 * c2 * c3; rmat[[1, 2]] = -c1 * s2; rmat[[2, 0]] = s2 * s3; rmat[[2, 1]] = s2 * c3; rmat[[2, 2]] = c2; }); let eye2d = Array2::::eye(3); let mut rotated = Array3::::zeros((3, 3, nelems).f()); azip!((mut rotated in rotated.axis_iter_mut(Axis(2)), rmat in rmat.axis_iter(Axis(2))) { rotated.assign(&rmat.dot(&eye2d)); }); ``` -------------------------------- ### Get Mutable Reference to RawRef Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef3.html Converts `self` into a mutable reference to `RawRef`. ```rust fn as_mut(&mut self) -> &mut RawRef ``` -------------------------------- ### Get Mutable Reference to LayoutRef Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef3.html Converts `self` into a mutable reference to `LayoutRef`. ```rust fn as_mut(&mut self) -> &mut LayoutRef ``` -------------------------------- ### Serialize Implementation Source: https://docs.rs/ndarray/latest/ndarray/type.Array.html Provides serialization support for ArrayBase via the serde crate. ```APIDOC ## Serialize ### Description Serialize this value into the given Serde serializer. Requires the `serde` crate feature. ### Methods - `serialize(&self, serializer: Se) -> Result` ``` -------------------------------- ### Indexing Arrays with NdIndex Source: https://docs.rs/ndarray/latest/ndarray/trait.NdIndex.html Demonstrates using tuples and arrays to index into a 2D array. ```rust use ndarray::arr2; let mut a = arr2(&[[0, 1], [2, 3]]); assert_eq!(a[[0, 1]], 1); assert_eq!(a[[1, 1]], 3); a[[1, 1]] += 1; assert_eq!(a[(1, 1)], 4); ``` -------------------------------- ### Get Read-Only Array View Source: https://docs.rs/ndarray/latest/ndarray/type.ArrayRef4.html Returns a read-only view of the entire array. ```rust use ndarray::Array2; let arr = Array2::from_shape_fn((2, 3), |(i, j)| i + j); let view = arr.view(); assert_eq!(view.shape(), &[2, 3]); assert_eq!(view[[0, 1]], 1); ```