[]Struct lumol::Array2

pub struct Array2<T>(_);

Two dimensional tensors, based on ndarray.

Most of the methods are simply forwarded to ndarray, so also look the doc for this crate. This array type mainly supports indexing using tuples as indices and is though as storage backend for multi-dimensional data.

let mut a = Array2::zeros((3, 5));

assert_eq!(a[(0, 4)], 0.0);

a[(0, 4)] = 7.0;
assert_eq!(a[(0, 4)], 7.0);

Implementations

impl<T> Array2<T> where
    T: Clone + Zero

pub fn zeros(size: (usize, usize)) -> Array2<T>

Create a new Array2 of the specified size filled with the Zero::zero return value.

Examples

let a: Array2<f64> = Array2::zeros((8, 5));
assert_eq!(a[(6, 2)], 0.0);

pub fn resize_if_different(&mut self, size: (usize, usize))

Resize the array if the current size is not size, and fill the new array with zeros.

Examples

let mut a = Array2::zeros((8, 5));

a[(3, 3)] = 42.0;

// This does nothing
a.resize_if_different((8, 5));
assert_eq!(a[(3, 3)], 42.0);

// This allocates a new array
a.resize_if_different((8, 9));
assert_eq!(a[(3, 3)], 0.0);

impl<T> Array2<T> where
    T: Default

pub fn default(size: (usize, usize)) -> Array2<T>

Create a new Array2 of the specified size filled with the Default::default return value.

Examples

let a: Array2<f64> = Array2::zeros((8, 5));
let b: Array2<f64> = Array2::default((8, 5));

assert_eq!(a, b);

Methods from Deref<Target = ArrayBase<OwnedRepr<T>, Dim<[usize; 2]>>>

pub fn len(&self) -> usize[src]

Return the total number of elements in the array.

pub fn len_of(&self, axis: Axis) -> usize[src]

Return the length of axis.

The axis should be in the range Axis( 0 .. n ) where n is the number of dimensions (axes) of the array.

Panics if the axis is out of bounds.

pub fn is_empty(&self) -> bool[src]

Return whether the array has any elements

pub fn ndim(&self) -> usize[src]

Return the number of dimensions (axes) in the array

pub fn dim(&self) -> <D as Dimension>::Pattern[src]

Return the shape of the array in its “pattern” form, an integer in the one-dimensional case, tuple in the n-dimensional cases and so on.

pub fn raw_dim(&self) -> D[src]

Return the shape of the array as it stored in the array.

pub fn shape(&self) -> &[usize][src]

Return the shape of the array as a slice.

pub fn strides(&self) -> &[isize][src]

Return the strides of the array as a slice

pub fn stride_of(&self, axis: Axis) -> isize[src]

Return the stride of axis.

The axis should be in the range Axis( 0 .. n ) where n is the number of dimensions (axes) of the array.

Panics if the axis is out of bounds.

pub fn view(&self) -> ArrayBase<ViewRepr<&A>, D>[src]

Return a read-only view of the array

pub fn view_mut(&mut self) -> ArrayBase<ViewRepr<&mut A>, D> where
    S: DataMut
[src]

Return a read-write view of the array

pub fn to_owned(&self) -> ArrayBase<OwnedRepr<A>, D> where
    A: Clone
[src]

Return an uniquely owned copy of the array.

If the input array is contiguous and its strides are positive, then the output array will have the same memory layout. Otherwise, the layout of the output array is unspecified. If you need a particular layout, you can allocate a new array with the desired memory layout and .assign() the data. Alternatively, you can collect an iterator, like this for a result in standard layout:

Array::from_shape_vec(arr.raw_dim(), arr.iter().cloned().collect()).unwrap()

or this for a result in column-major (Fortran) layout:

Array::from_shape_vec(arr.raw_dim().f(), arr.t().iter().cloned().collect()).unwrap()

pub fn to_shared(&self) -> ArrayBase<OwnedArcRepr<A>, D> where
    A: Clone
[src]

Return a shared ownership (copy on write) array.

pub fn first(&self) -> Option<&A>[src]

Returns a reference to the first element of the array, or None if it is empty.

pub fn first_mut(&mut self) -> Option<&mut A> where
    S: DataMut
[src]

Returns a mutable reference to the first element of the array, or None if it is empty.

pub fn iter(&self) -> Iter<'_, A, D>[src]

Return an iterator of references to the elements of the array.

Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.

Iterator element type is &A.

pub fn iter_mut(&mut self) -> IterMut<'_, A, D> where
    S: DataMut
[src]

Return an iterator of mutable references to the elements of the array.

Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.

Iterator element type is &mut A.

pub fn indexed_iter(&self) -> IndexedIter<'_, A, D>[src]

Return an iterator of indexes and references to the elements of the array.

Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.

Iterator element type is (D::Pattern, &A).

See also Zip::indexed

pub fn indexed_iter_mut(&mut self) -> IndexedIterMut<'_, A, D> where
    S: DataMut
[src]

Return an iterator of indexes and mutable references to the elements of the array.

Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.

Iterator element type is (D::Pattern, &mut A).

pub fn slice<Do>(
    &self,
    info: &SliceInfo<<D as Dimension>::SliceArg, Do>
) -> ArrayBase<ViewRepr<&A>, Do> where
    Do: Dimension
[src]

Return a sliced view of the array.

See Slicing for full documentation. See also SliceInfo and D::SliceArg.

Panics if an index is out of bounds or step size is zero.
(Panics if D is IxDyn and info does not match the number of array axes.)

pub fn slice_mut<Do>(
    &mut self,
    info: &SliceInfo<<D as Dimension>::SliceArg, Do>
) -> ArrayBase<ViewRepr<&mut A>, Do> where
    Do: Dimension,
    S: DataMut
[src]

Return a sliced read-write view of the array.

See Slicing for full documentation. See also SliceInfo and D::SliceArg.

Panics if an index is out of bounds or step size is zero.
(Panics if D is IxDyn and info does not match the number of array axes.)

pub fn slice_collapse(&mut self, indices: &<D as Dimension>::SliceArg)[src]

Slice the array in place without changing the number of dimensions.

Note that &SliceInfo (produced by the s![] macro) will usually coerce into &D::SliceArg automatically, but in some cases (e.g. if D is IxDyn), you may need to call .as_ref().

See Slicing for full documentation. See also D::SliceArg.

Panics if an index is out of bounds or step size is zero.
(Panics if D is IxDyn and indices does not match the number of array axes.)

pub fn slice_inplace(&mut self, indices: &<D as Dimension>::SliceArg)[src]

👎 Deprecated since 0.12.1:

renamed to slice_collapse

Slice the array in place without changing the number of dimensions.

Panics if an index is out of bounds or step size is zero.
(Panics if D is IxDyn and indices does not match the number of array axes.)

pub fn slice_axis(
    &self,
    axis: Axis,
    indices: Slice
) -> ArrayBase<ViewRepr<&A>, D>
[src]

Return a view of the array, sliced along the specified axis.

Panics if an index is out of bounds or step size is zero.
Panics if axis is out of bounds.

pub fn slice_axis_mut(
    &mut self,
    axis: Axis,
    indices: Slice
) -> ArrayBase<ViewRepr<&mut A>, D> where
    S: DataMut
[src]

Return a mutable view of the array, sliced along the specified axis.

Panics if an index is out of bounds or step size is zero.
Panics if axis is out of bounds.

pub fn slice_axis_inplace(&mut self, axis: Axis, indices: Slice)[src]

Slice the array in place along the specified axis.

Panics if an index is out of bounds or step size is zero.
Panics if axis is out of bounds.

pub fn get<I>(&self, index: I) -> Option<&A> where
    I: NdIndex<D>, 
[src]

Return a reference to the element at index, or return None if the index is out of bounds.

Arrays also support indexing syntax: array[index].

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.
);

pub fn get_mut<I>(&mut self, index: I) -> Option<&mut A> where
    I: NdIndex<D>,
    S: DataMut
[src]

Return a mutable reference to the element at index, or return None if the index is out of bounds.

pub unsafe fn uget<I>(&self, index: I) -> &A where
    I: NdIndex<D>, 
[src]

Perform unchecked array indexing.

Return a reference to the element at index.

Note: only unchecked for non-debug builds of ndarray.

pub unsafe fn uget_mut<I>(&mut self, index: I) -> &mut A where
    I: NdIndex<D>,
    S: DataMut
[src]

Perform unchecked array indexing.

Return a mutable reference to the element at index.

Note: Only unchecked for non-debug builds of ndarray.
Note: (For ArcArray) The array must be uniquely held when mutating it.

pub fn swap<I>(&mut self, index1: I, index2: I) where
    I: NdIndex<D>,
    S: DataMut
[src]

Swap elements at indices index1 and index2.

Indices may be equal.

Panics if an index is out of bounds.

pub unsafe fn uswap<I>(&mut self, index1: I, index2: I) where
    I: NdIndex<D>,
    S: DataMut
[src]

Swap elements unchecked at indices index1 and index2.

Indices may be equal.

Note: only unchecked for non-debug builds of ndarray.
Note: (For ArcArray) The array must be uniquely held.

pub fn index_axis(
    &self,
    axis: Axis,
    index: usize
) -> ArrayBase<ViewRepr<&A>, <D as Dimension>::Smaller> where
    D: RemoveAxis
[src]

Returns a view restricted to index along the axis, with the axis removed.

See Subviews for full documentation.

Panics if axis or index is out of bounds.

use ndarray::{arr2, ArrayView, Axis};

let a = arr2(&[[1., 2. ],    // ... axis 0, row 0
               [3., 4. ],    // --- axis 0, row 1
               [5., 6. ]]);  // ... axis 0, row 2
//               .   \
//                .   axis 1, column 1
//                 axis 1, column 0
assert!(
    a.index_axis(Axis(0), 1) == ArrayView::from(&[3., 4.]) &&
    a.index_axis(Axis(1), 1) == ArrayView::from(&[2., 4., 6.])
);

pub fn index_axis_mut(
    &mut self,
    axis: Axis,
    index: usize
) -> ArrayBase<ViewRepr<&mut A>, <D as Dimension>::Smaller> where
    D: RemoveAxis,
    S: DataMut
[src]

Returns a mutable view restricted to index along the axis, with the axis removed.

Panics if axis or index is out of bounds.

use ndarray::{arr2, aview2, Axis};

let mut a = arr2(&[[1., 2. ],
                   [3., 4. ]]);
//                   .   \
//                    .   axis 1, column 1
//                     axis 1, column 0

{
    let mut column1 = a.index_axis_mut(Axis(1), 1);
    column1 += 10.;
}

assert!(
    a == aview2(&[[1., 12.],
                  [3., 14.]])
);

pub fn collapse_axis(&mut self, axis: Axis, index: usize)[src]

Selects index along the axis, collapsing the axis into length one.

Panics if axis or index is out of bounds.

pub fn subview(
    &self,
    axis: Axis,
    index: usize
) -> ArrayBase<ViewRepr<&A>, <D as Dimension>::Smaller> where
    D: RemoveAxis
[src]

👎 Deprecated since 0.12.1:

renamed to index_axis

Along axis, select the subview index and return a view with that axis removed.

Panics if axis or index is out of bounds.

pub fn subview_mut(
    &mut self,
    axis: Axis,
    index: usize
) -> ArrayBase<ViewRepr<&mut A>, <D as Dimension>::Smaller> where
    D: RemoveAxis,
    S: DataMut
[src]

👎 Deprecated since 0.12.1:

renamed to index_axis_mut

Along axis, select the subview index and return a read-write view with the axis removed.

Panics if axis or index is out of bounds.

pub fn subview_inplace(&mut self, axis: Axis, index: usize)[src]

👎 Deprecated since 0.12.1:

renamed to collapse_axis

Collapse dimension axis into length one, and select the subview of index along that axis.

Panics if index is past the length of the axis.

pub fn select(
    &self,
    axis: Axis,
    indices: &[usize]
) -> ArrayBase<OwnedRepr<A>, D> where
    A: Copy,
    D: RemoveAxis
[src]

Along axis, select arbitrary subviews corresponding to indices and and copy them into a new array.

Panics if axis or an element of indices is out of bounds.

use ndarray::{arr2, Axis};

let x = arr2(&[[0., 1.],
               [2., 3.],
               [4., 5.],
               [6., 7.],
               [8., 9.]]);

let r = x.select(Axis(0), &[0, 4, 3]);
assert!(
        r == arr2(&[[0., 1.],
                    [8., 9.],
                    [6., 7.]])
);

pub fn genrows(&self) -> Lanes<'_, A, <D as Dimension>::Smaller>[src]

Return a producer and iterable that traverses over the generalized rows of the array. For a 2D array these are the regular rows.

This is equivalent to .lanes(Axis(n - 1)) where n is self.ndim().

For an array of dimensions a × b × c × ... × l × m it has a × b × c × ... × l rows each of length m.

For example, in a 2 × 2 × 3 array, each row is 3 elements long and there are 2 × 2 = 4 rows in total.

Iterator element is ArrayView1<A> (1D array view).

use ndarray::{arr3, Axis, arr1};

let a = arr3(&[[[ 0,  1,  2],    // -- row 0, 0
                [ 3,  4,  5]],   // -- row 0, 1
               [[ 6,  7,  8],    // -- row 1, 0
                [ 9, 10, 11]]]); // -- row 1, 1

// `genrows` will yield the four generalized rows of the array.
for row in a.genrows() {
    /* loop body */
}

pub fn genrows_mut(&mut self) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
    S: DataMut
[src]

Return a producer and iterable that traverses over the generalized rows of the array and yields mutable array views.

Iterator element is ArrayView1<A> (1D read-write array view).

pub fn gencolumns(&self) -> Lanes<'_, A, <D as Dimension>::Smaller>[src]

Return a producer and iterable that traverses over the generalized columns of the array. For a 2D array these are the regular columns.

This is equivalent to .lanes(Axis(0)).

For an array of dimensions a × b × c × ... × l × m it has b × c × ... × l × m columns each of length a.

For example, in a 2 × 2 × 3 array, each column is 2 elements long and there are 2 × 3 = 6 columns in total.

Iterator element is ArrayView1<A> (1D array view).

use ndarray::{arr3, Axis, arr1};

// The generalized columns of a 3D array:
// are directed along the 0th axis: 0 and 6, 1 and 7 and so on...
let a = arr3(&[[[ 0,  1,  2], [ 3,  4,  5]],
               [[ 6,  7,  8], [ 9, 10, 11]]]);

// Here `gencolumns` will yield the six generalized columns of the array.
for row in a.gencolumns() {
    /* loop body */
}

pub fn gencolumns_mut(&mut self) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
    S: DataMut
[src]

Return a producer and iterable that traverses over the generalized columns of the array and yields mutable array views.

Iterator element is ArrayView1<A> (1D read-write array view).

pub fn lanes(&self, axis: Axis) -> Lanes<'_, A, <D as Dimension>::Smaller>[src]

Return a producer and iterable that traverses over all 1D lanes pointing in the direction of axis.

When the pointing in the direction of the first axis, they are columns, in the direction of the last axis rows; in general they are all lanes and are one dimensional.

Iterator element is ArrayView1<A> (1D array view).

use ndarray::{arr3, aview1, Axis};

let a = arr3(&[[[ 0,  1,  2],
                [ 3,  4,  5]],
               [[ 6,  7,  8],
                [ 9, 10, 11]]]);

let inner0 = a.lanes(Axis(0));
let inner1 = a.lanes(Axis(1));
let inner2 = a.lanes(Axis(2));

// The first lane for axis 0 is [0, 6]
assert_eq!(inner0.into_iter().next().unwrap(), aview1(&[0, 6]));
// The first lane for axis 1 is [0, 3]
assert_eq!(inner1.into_iter().next().unwrap(), aview1(&[0, 3]));
// The first lane for axis 2 is [0, 1, 2]
assert_eq!(inner2.into_iter().next().unwrap(), aview1(&[0, 1, 2]));

pub fn lanes_mut(
    &mut self,
    axis: Axis
) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
    S: DataMut
[src]

Return a producer and iterable that traverses over all 1D lanes pointing in the direction of axis.

Iterator element is ArrayViewMut1<A> (1D read-write array view).

pub fn outer_iter(&self) -> AxisIter<'_, A, <D as Dimension>::Smaller> where
    D: RemoveAxis
[src]

Return an iterator that traverses over the outermost dimension and yields each subview.

This is equivalent to .axis_iter(Axis(0)).

Iterator element is ArrayView<A, D::Smaller> (read-only array view).

pub fn outer_iter_mut(
    &mut self
) -> AxisIterMut<'_, A, <D as Dimension>::Smaller> where
    D: RemoveAxis,
    S: DataMut
[src]

Return an iterator that traverses over the outermost dimension and yields each subview.

This is equivalent to .axis_iter_mut(Axis(0)).

Iterator element is ArrayViewMut<A, D::Smaller> (read-write array view).

pub fn axis_iter(
    &self,
    axis: Axis
) -> AxisIter<'_, A, <D as Dimension>::Smaller> where
    D: RemoveAxis
[src]

Return an iterator that traverses over axis and yields each subview along it.

For example, in a 3 × 4 × 5 array, with axis equal to Axis(2), the iterator element is a 3 × 4 subview (and there are 5 in total), as shown in the picture below.

Iterator element is ArrayView<A, D::Smaller> (read-only array view).

See Subviews for full documentation.

Panics if axis is out of bounds.

pub fn axis_iter_mut(
    &mut self,
    axis: Axis
) -> AxisIterMut<'_, A, <D as Dimension>::Smaller> where
    D: RemoveAxis,
    S: DataMut
[src]

Return an iterator that traverses over axis and yields each mutable subview along it.

Iterator element is ArrayViewMut<A, D::Smaller> (read-write array view).

Panics if axis is out of bounds.

pub fn axis_chunks_iter(
    &self,
    axis: Axis,
    size: usize
) -> AxisChunksIter<'_, A, D>
[src]

Return an iterator that traverses over axis by chunks of size, yielding non-overlapping views along that axis.

Iterator element is ArrayView<A, D>

The last view may have less elements if size does not divide the axis' dimension.

Panics if axis is out of bounds.

use ndarray::Array;
use ndarray::{arr3, Axis};

let a = Array::from_iter(0..28).into_shape((2, 7, 2)).unwrap();
let mut iter = a.axis_chunks_iter(Axis(1), 2);

// first iteration yields a 2 × 2 × 2 view
assert_eq!(iter.next().unwrap(),
           arr3(&[[[ 0,  1], [ 2, 3]],
                  [[14, 15], [16, 17]]]));

// however the last element is a 2 × 1 × 2 view since 7 % 2 == 1
assert_eq!(iter.next_back().unwrap(), arr3(&[[[12, 13]],
                                             [[26, 27]]]));

pub fn axis_chunks_iter_mut(
    &mut self,
    axis: Axis,
    size: usize
) -> AxisChunksIterMut<'_, A, D> where
    S: DataMut
[src]

Return an iterator that traverses over axis by chunks of size, yielding non-overlapping read-write views along that axis.

Iterator element is ArrayViewMut<A, D>

Panics if axis is out of bounds.

pub fn exact_chunks<E>(&self, chunk_size: E) -> ExactChunks<'_, A, D> where
    E: IntoDimension<Dim = D>, 
[src]

Return an exact chunks producer (and iterable).

It produces the whole chunks of a given n-dimensional chunk size, skipping the remainder along each dimension that doesn't fit evenly.

The produced element is a ArrayView<A, D> with exactly the dimension chunk_size.

Panics if any dimension of chunk_size is zero
(Panics if D is IxDyn and chunk_size does not match the number of array axes.)

pub fn exact_chunks_mut<E>(&mut self, chunk_size: E) -> ExactChunksMut<'_, A, D> where
    E: IntoDimension<Dim = D>,
    S: DataMut
[src]

Return an exact chunks producer (and iterable).

It produces the whole chunks of a given n-dimensional chunk size, skipping the remainder along each dimension that doesn't fit evenly.

The produced element is a ArrayViewMut<A, D> with exactly the dimension chunk_size.

Panics if any dimension of chunk_size is zero
(Panics if D is IxDyn and chunk_size does not match the number of array axes.)

use ndarray::Array;
use ndarray::arr2;
let mut a = Array::zeros((6, 7));

// Fill each 2 × 2 chunk with the index of where it appeared in iteration
for (i, mut chunk) in a.exact_chunks_mut((2, 2)).into_iter().enumerate() {
    chunk.fill(i);
}

// The resulting array is:
assert_eq!(
  a,
  arr2(&[[0, 0, 1, 1, 2, 2, 0],
         [0, 0, 1, 1, 2, 2, 0],
         [3, 3, 4, 4, 5, 5, 0],
         [3, 3, 4, 4, 5, 5, 0],
         [6, 6, 7, 7, 8, 8, 0],
         [6, 6, 7, 7, 8, 8, 0]]));

pub fn windows<E>(&self, window_size: E) -> Windows<'_, A, D> where
    E: IntoDimension<Dim = D>, 
[src]

Return a window producer and iterable.

The windows are all distinct overlapping views of size window_size that fit into the array's shape.

Will yield over no elements if window size is larger than the actual array size of any dimension.

The produced element is an ArrayView<A, D> with exactly the dimension window_size.

Panics if any dimension of window_size is zero.
(Panics if D is IxDyn and window_size does not match the number of array axes.)

pub fn diag(&self) -> ArrayBase<ViewRepr<&A>, Dim<[usize; 1]>>[src]

Return an view of the diagonal elements of the array.

The diagonal is simply the sequence indexed by (0, 0, .., 0), (1, 1, ..., 1) etc as long as all axes have elements.

pub fn diag_mut(&mut self) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
    S: DataMut
[src]

Return a read-write view over the diagonal elements of the array.

pub fn is_standard_layout(&self) -> bool[src]

Return true if the array data is laid out in contiguous “C order” in memory (where the last index is the most rapidly varying).

Return false otherwise, i.e the array is possibly not contiguous in memory, it has custom strides, etc.

pub fn as_ptr(&self) -> *const A[src]

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 as_mut_ptr(&mut self) -> *mut A where
    S: DataMut
[src]

Return a mutable pointer to the first element in the array.

pub fn as_slice(&self) -> Option<&[A]>[src]

Return the array’s data as a slice, if it is contiguous and in standard order. Return None otherwise.

If this function returns Some(_), then the element order in the slice corresponds to the logical order of the array’s elements.

pub fn as_slice_mut(&mut self) -> Option<&mut [A]> where
    S: DataMut
[src]

Return the array’s data as a slice, if it is contiguous and in standard order. Return None otherwise.

pub fn as_slice_memory_order(&self) -> Option<&[A]>[src]

Return the array’s data as a slice if it is contiguous, return None otherwise.

If this function returns Some(_), then the elements in the slice have whatever order the elements have in memory.

Implementation notes: Does not yet support negatively strided arrays.

pub fn as_slice_memory_order_mut(&mut self) -> Option<&mut [A]> where
    S: DataMut
[src]

Return the array’s data as a slice if it is contiguous, return None otherwise.

pub fn reshape<E>(&self, shape: E) -> ArrayBase<S, <E as IntoDimension>::Dim> where
    A: Clone,
    E: IntoDimension,
    S: DataShared + DataOwned
[src]

Note: Reshape is for ArcArray only. Use .into_shape() for other arrays and array views.

Transform the array into shape; any shape with the same number of elements is accepted.

May clone all elements if needed to arrange elements in standard layout (and break sharing).

Panics if shapes are incompatible.

use ndarray::{rcarr1, rcarr2};

assert!(
    rcarr1(&[1., 2., 3., 4.]).reshape((2, 2))
    == rcarr2(&[[1., 2.],
                [3., 4.]])
);

pub fn broadcast<E>(
    &self,
    dim: E
) -> Option<ArrayBase<ViewRepr<&A>, <E as IntoDimension>::Dim>> where
    E: IntoDimension
[src]

Act like a larger size and/or shape array by broadcasting into a larger shape, if possible.

Return None if shapes can not be broadcast together.

Background

  • Two axes are compatible if they are equal, or one of them is 1.
  • In this instance, only the axes of the smaller side (self) can be 1.

Compare axes beginning with the last axis of each shape.

For example (1, 2, 4) can be broadcast into (7, 6, 2, 4) because its axes are either equal or 1 (or missing); while (2, 2) can not be broadcast into (2, 4).

The implementation creates a view with strides set to zero for the axes that are to be repeated.

The broadcasting documentation for Numpy has more information.

use ndarray::{aview1, aview2};

assert!(
    aview1(&[1., 0.]).broadcast((10, 2)).unwrap()
    == aview2(&[[1., 0.]; 10])
);

pub fn swap_axes(&mut self, ax: usize, bx: usize)[src]

Swap axes ax and bx.

This does not move any data, it just adjusts the array’s dimensions and strides.

Panics if the axes are out of bounds.

use ndarray::arr2;

let mut a = arr2(&[[1., 2., 3.]]);
a.swap_axes(0, 1);
assert!(
    a == arr2(&[[1.], [2.], [3.]])
);

pub fn t(&self) -> ArrayBase<ViewRepr<&A>, D>[src]

Return a transposed view of the array.

This is a shorthand for self.view().reversed_axes().

See also the more general methods .reversed_axes() and .swap_axes().

pub fn axes(&self) -> Axes<'_, D>[src]

Return an iterator over the length and stride of each axis.

pub fn max_stride_axis(&self) -> Axis[src]

Return the axis with the greatest stride (by absolute value), preferring axes with len > 1.

pub fn invert_axis(&mut self, axis: Axis)[src]

Reverse the stride of axis.

Panics if the axis is out of bounds.

pub fn merge_axes(&mut self, take: Axis, into: Axis) -> bool[src]

If possible, merge in the axis take to into.

Returns true iff the axes are now merged.

This method merges the axes if movement along the two original axes (moving fastest along the into axis) can be equivalently represented as movement along one (merged) axis. Merging the axes preserves this order in the merged axis. If take and into are the same axis, then the axis is "merged" if its length is ≤ 1.

If the return value is true, then the following hold:

  • The new length of the into axis is the product of the original lengths of the two axes.

  • The new length of the take axis is 0 if the product of the original lengths of the two axes is 0, and 1 otherwise.

If the return value is false, then merging is not possible, and the original shape and strides have been preserved.

Note that the ordering constraint means that if it's possible to merge take into into, it's usually not possible to merge into into take, and vice versa.

use ndarray::Array3;
use ndarray::Axis;

let mut a = Array3::<f64>::zeros((2, 3, 4));
assert!(a.merge_axes(Axis(1), Axis(2)));
assert_eq!(a.shape(), &[2, 1, 12]);

Panics if an axis is out of bounds.

pub fn assign<E, S2>(&mut self, rhs: &ArrayBase<S2, E>) where
    A: Clone,
    E: Dimension,
    S: DataMut,
    S2: Data<Elem = A>, 
[src]

Perform an elementwise assigment to self from rhs.

If their shapes disagree, rhs is broadcast to the shape of self.

Panics if broadcasting isn’t possible.

pub fn fill(&mut self, x: A) where
    A: Clone,
    S: DataMut
[src]

Perform an elementwise assigment to self from element x.

pub fn zip_mut_with<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, f: F) where
    E: Dimension,
    F: FnMut(&mut A, &B),
    S: DataMut,
    S2: Data<Elem = B>, 
[src]

Traverse two arrays in unspecified order, in lock step, calling the closure f on each element pair.

If their shapes disagree, rhs is broadcast to the shape of self.

Panics if broadcasting isn’t possible.

pub fn fold<'a, F, B>(&'a self, init: B, f: F) -> B where
    A: 'a,
    F: FnMut(B, &'a A) -> B, 
[src]

Traverse the array elements and apply a fold, returning the resulting value.

Elements are visited in arbitrary order.

pub fn map<'a, B, F>(&'a self, f: F) -> ArrayBase<OwnedRepr<B>, D> where
    A: 'a,
    F: FnMut(&'a A) -> B, 
[src]

Call f by reference on each element and create a new array with the new values.

Elements are visited in arbitrary order.

Return an array with the same shape as self.

use ndarray::arr2;

let a = arr2(&[[ 0., 1.],
               [-1., 2.]]);
assert!(
    a.map(|x| *x >= 1.0)
    == arr2(&[[false, true],
              [false, true]])
);

pub fn map_mut<'a, B, F>(&'a mut self, f: F) -> ArrayBase<OwnedRepr<B>, D> where
    A: 'a,
    F: FnMut(&'a mut A) -> B,
    S: DataMut
[src]

Call f on a mutable reference of each element and create a new array with the new values.

Elements are visited in arbitrary order.

Return an array with the same shape as self.

pub fn mapv<B, F>(&self, f: F) -> ArrayBase<OwnedRepr<B>, D> where
    A: Clone,
    F: FnMut(A) -> B, 
[src]

Call f by value on each element and create a new array with the new values.

Elements are visited in arbitrary order.

Return an array with the same shape as self.

use ndarray::arr2;

let a = arr2(&[[ 0., 1.],
               [-1., 2.]]);
assert!(
    a.mapv(f32::abs) == arr2(&[[0., 1.],
                               [1., 2.]])
);

pub fn map_inplace<F>(&mut self, f: F) where
    F: FnMut(&mut A),
    S: DataMut
[src]

Modify the array in place by calling f by mutable reference on each element.

Elements are visited in arbitrary order.

pub fn mapv_inplace<F>(&mut self, f: F) where
    A: Clone,
    F: FnMut(A) -> A,
    S: DataMut
[src]

Modify the array in place by calling f by value on each element. The array is updated with the new values.

Elements are visited in arbitrary order.

use ndarray::arr2;

let mut a = arr2(&[[ 0., 1.],
                   [-1., 2.]]);
a.mapv_inplace(f32::exp);
assert!(
    a.all_close(&arr2(&[[1.00000, 2.71828],
                        [0.36788, 7.38906]]), 1e-5)
);

pub fn visit<'a, F>(&'a self, f: F) where
    A: 'a,
    F: FnMut(&'a A), 
[src]

Visit each element in the array by calling f by reference on each element.

Elements are visited in arbitrary order.

pub fn fold_axis<B, F>(
    &self,
    axis: Axis,
    init: B,
    fold: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
    B: Clone,
    D: RemoveAxis,
    F: FnMut(&B, &A) -> B, 
[src]

Fold along an axis.

Combine the elements of each subview with the previous using the fold function and initial value init.

Return the result as an Array.

Panics if axis is out of bounds.

pub fn map_axis<'a, B, F>(
    &'a self,
    axis: Axis,
    mapping: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
    A: 'a,
    D: RemoveAxis,
    F: FnMut(ArrayBase<ViewRepr<&'a A>, Dim<[usize; 1]>>) -> B, 
[src]

Reduce the values along an axis into just one value, producing a new array with one less dimension.

Elements are visited in arbitrary order.

Return the result as an Array.

Panics if axis is out of bounds.

pub fn map_axis_mut<'a, B, F>(
    &'a mut self,
    axis: Axis,
    mapping: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
    A: 'a,
    D: RemoveAxis,
    F: FnMut(ArrayBase<ViewRepr<&'a mut A>, Dim<[usize; 1]>>) -> B,
    S: DataMut
[src]

Reduce the values along an axis into just one value, producing a new array with one less dimension. 1-dimensional lanes are passed as mutable references to the reducer, allowing for side-effects.

Elements are visited in arbitrary order.

Return the result as an Array.

Panics if axis is out of bounds.

pub fn to_vec(&self) -> Vec<A> where
    A: Clone
[src]

Return an vector with the elements of the one-dimensional array.

pub fn row(&self, index: usize) -> ArrayBase<ViewRepr<&A>, Dim<[usize; 1]>>[src]

Return an array view of row index.

Panics if index is out of bounds.

pub fn row_mut(
    &mut self,
    index: usize
) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
    S: DataMut
[src]

Return a mutable array view of row index.

Panics if index is out of bounds.

pub fn rows(&self) -> usize[src]

Return the number of rows (length of Axis(0)) in the two-dimensional array.

pub fn column(&self, index: usize) -> ArrayBase<ViewRepr<&A>, Dim<[usize; 1]>>[src]

Return an array view of column index.

Panics if index is out of bounds.

pub fn column_mut(
    &mut self,
    index: usize
) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
    S: DataMut
[src]

Return a mutable array view of column index.

Panics if index is out of bounds.

pub fn cols(&self) -> usize[src]

Return the number of columns (length of Axis(1)) in the two-dimensional array.

pub fn is_square(&self) -> bool[src]

Return true if the array is square, false otherwise.

pub fn insert_axis_inplace(&mut self, axis: Axis)[src]

Insert new array axis of length 1 at axis, modifying the shape and strides in-place.

Panics if the axis is out of bounds.

use ndarray::{Axis, arr2, arr3};

let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn();
assert_eq!(a.shape(), &[2, 3]);

a.insert_axis_inplace(Axis(1));
assert_eq!(a, arr3(&[[[1, 2, 3]], [[4, 5, 6]]]).into_dyn());
assert_eq!(a.shape(), &[2, 1, 3]);

pub fn index_axis_inplace(&mut self, axis: Axis, index: usize)[src]

Collapses the array to index along the axis and removes the axis, modifying the shape and strides in-place.

Panics if axis or index is out of bounds.

use ndarray::{Axis, arr1, arr2};

let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn();
assert_eq!(a.shape(), &[2, 3]);

a.index_axis_inplace(Axis(1), 1);
assert_eq!(a, arr1(&[2, 5]).into_dyn());
assert_eq!(a.shape(), &[2]);

pub fn sum(&self) -> A where
    A: Clone + Add<A, Output = A> + Zero
[src]

Return the sum of all elements in the array.

use ndarray::arr2;

let a = arr2(&[[1., 2.],
               [3., 4.]]);
assert_eq!(a.sum(), 10.);

pub fn scalar_sum(&self) -> A where
    A: Clone + Add<A, Output = A> + Zero
[src]

Return the sum of all elements in the array.

This method has been renamed to .sum() and will be deprecated in the next version.

pub fn product(&self) -> A where
    A: Clone + Mul<A, Output = A> + One
[src]

Return the product of all elements in the array.

use ndarray::arr2;

let a = arr2(&[[1., 2.],
               [3., 4.]]);
assert_eq!(a.product(), 24.);

pub fn sum_axis(
    &self,
    axis: Axis
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
    A: Clone + Zero<Output = A> + Add<A>,
    D: RemoveAxis
[src]

Return sum along axis.

use ndarray::{aview0, aview1, arr2, Axis};

let a = arr2(&[[1., 2.],
               [3., 4.]]);
assert!(
    a.sum_axis(Axis(0)) == aview1(&[4., 6.]) &&
    a.sum_axis(Axis(1)) == aview1(&[3., 7.]) &&

    a.sum_axis(Axis(0)).sum_axis(Axis(0)) == aview0(&10.)
);

Panics if axis is out of bounds.

pub fn mean_axis(
    &self,
    axis: Axis
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
    A: Clone + Zero<Output = A> + One + Add<A> + Div<A, Output = A>,
    D: RemoveAxis
[src]

Return mean along axis.

Panics if axis is out of bounds or if the length of the axis is zero and division by zero panics for type A.

use ndarray::{aview1, arr2, Axis};

let a = arr2(&[[1., 2.],
               [3., 4.]]);
assert!(
    a.mean_axis(Axis(0)) == aview1(&[2.0, 3.0]) &&
    a.mean_axis(Axis(1)) == aview1(&[1.5, 3.5])
);

pub fn var_axis(
    &self,
    axis: Axis,
    ddof: A
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
    A: Float,
    D: RemoveAxis
[src]

Return variance along axis.

The variance is computed using the Welford one-pass algorithm.

The parameter ddof specifies the "delta degrees of freedom". For example, to calculate the population variance, use ddof = 0, or to calculate the sample variance, use ddof = 1.

The variance is defined as:

              1       n
variance = ――――――――   ∑ (xᵢ - x̅)²
           n - ddof  i=1

where

    1   n
x̅ = ―   ∑ xᵢ
    n  i=1

Panics if ddof is greater than or equal to the length of the axis, if axis is out of bounds, or if the length of the axis is zero.

Example

use ndarray::{aview1, arr2, Axis};

let a = arr2(&[[1., 2.],
               [3., 4.],
               [5., 6.]]);
let var = a.var_axis(Axis(0), 1.);
assert_eq!(var, aview1(&[4., 4.]));

pub fn std_axis(
    &self,
    axis: Axis,
    ddof: A
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
    A: Float,
    D: RemoveAxis
[src]

Return standard deviation along axis.

The standard deviation is computed from the variance using the Welford one-pass algorithm.

The parameter ddof specifies the "delta degrees of freedom". For example, to calculate the population standard deviation, use ddof = 0, or to calculate the sample standard deviation, use ddof = 1.

The standard deviation is defined as:

                   1       n
stddev = sqrt ( ――――――――   ∑ (xᵢ - x̅)² )
                n - ddof  i=1

where

    1   n
x̅ = ―   ∑ xᵢ
    n  i=1

Panics if ddof is greater than or equal to the length of the axis, if axis is out of bounds, or if the length of the axis is zero.

Example

use ndarray::{aview1, arr2, Axis};

let a = arr2(&[[1., 2.],
               [3., 4.],
               [5., 6.]]);
let stddev = a.std_axis(Axis(0), 1.);
assert_eq!(stddev, aview1(&[2., 2.]));

pub fn all_close<S2, E>(&self, rhs: &ArrayBase<S2, E>, tol: A) -> bool where
    A: Float,
    E: Dimension,
    S2: Data<Elem = A>, 
[src]

Return true if the arrays' elementwise differences are all within the given absolute tolerance, false otherwise.

If their shapes disagree, rhs is broadcast to the shape of self.

Panics if broadcasting to the same shape isn’t possible.

pub fn dot<Rhs>(
    &self,
    rhs: &Rhs
) -> <ArrayBase<S, Dim<[usize; 1]>> as Dot<Rhs>>::Output where
    ArrayBase<S, Dim<[usize; 1]>>: Dot<Rhs>, 
[src]

Perform dot product or matrix multiplication of arrays self and rhs.

Rhs may be either a one-dimensional or a two-dimensional array.

If Rhs is one-dimensional, then the operation is a vector dot product, which is the sum of the elementwise products (no conjugation of complex operands, and thus not their inner product). In this case, self and rhs must be the same length.

If Rhs is two-dimensional, then the operation is matrix multiplication, where self is treated as a row vector. In this case, if self is shape M, then rhs is shape M × N and the result is shape N.

Panics if the array shapes are incompatible.
Note: If enabled, uses blas dot for elements of f32, f64 when memory layout allows.

pub fn dot<Rhs>(
    &self,
    rhs: &Rhs
) -> <ArrayBase<S, Dim<[usize; 2]>> as Dot<Rhs>>::Output where
    ArrayBase<S, Dim<[usize; 2]>>: Dot<Rhs>, 
[src]

Perform matrix multiplication of rectangular arrays self and rhs.

Rhs may be either a one-dimensional or a two-dimensional array.

If Rhs is two-dimensional, they array shapes must agree in the way that if self is M × N, then rhs is N × K.

Return a result array with shape M × K.

Panics if shapes are incompatible or the number of elements in the result would overflow isize.

Note: If enabled, uses blas gemv/gemm for elements of f32, f64 when memory layout allows. The default matrixmultiply backend is otherwise used for f32, f64 for all memory layouts.

use ndarray::arr2;

let a = arr2(&[[1., 2.],
               [0., 1.]]);
let b = arr2(&[[1., 2.],
               [2., 3.]]);

assert!(
    a.dot(&b) == arr2(&[[5., 8.],
                        [2., 3.]])
);

pub fn scaled_add<S2, E>(&mut self, alpha: A, rhs: &ArrayBase<S2, E>) where
    A: LinalgScalar,
    E: Dimension,
    S: DataMut,
    S2: Data<Elem = A>, 
[src]

Perform the operation self += alpha * rhs efficiently, where alpha is a scalar and rhs is another array. This operation is also known as axpy in BLAS.

If their shapes disagree, rhs is broadcast to the shape of self.

Panics if broadcasting isn’t possible.

pub fn into_slice(&self) -> Option<&'a [A]>[src]

Return the array’s data as a slice, if it is contiguous and in standard order. Return None otherwise.

Trait Implementations

impl<T> Clone for Array2<T> where
    T: Clone

impl<T> Debug for Array2<T> where
    T: Debug

impl<T> Deref for Array2<T>

type Target = ArrayBase<OwnedRepr<T>, Dim<[usize; 2]>>

The resulting type after dereferencing.

impl<T> DerefMut for Array2<T>

impl<T> Index<(usize, usize)> for Array2<T>

type Output = T

The returned type after indexing.

impl<T> IndexMut<(usize, usize)> for Array2<T>

impl<T> PartialEq<Array2<T>> for Array2<T> where
    T: PartialEq<T>, 

impl<T> StructuralPartialEq for Array2<T>

Auto Trait Implementations

impl<T> RefUnwindSafe for Array2<T> where
    T: RefUnwindSafe

impl<T> Send for Array2<T> where
    T: Send

impl<T> Sync for Array2<T> where
    T: Sync

impl<T> Unpin for Array2<T> where
    T: Unpin

impl<T> UnwindSafe for Array2<T> where
    T: RefUnwindSafe + UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Pointable for T

type Init = T

The type for initializers.

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>,