ndarray/lib.rs
1// Copyright 2014-2020 bluss and ndarray developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8#![crate_name = "ndarray"]
9#![doc(html_root_url = "https://docs.rs/ndarray/0.15/")]
10#![allow(
11 clippy::many_single_char_names,
12 clippy::deref_addrof,
13 clippy::unreadable_literal,
14 clippy::manual_map, // is not an error
15)]
16#![cfg_attr(not(feature = "std"), no_std)]
17
18//! The `ndarray` crate provides an *n*-dimensional container for general elements
19//! and for numerics.
20//!
21//! In *n*-dimensional we include for example 1-dimensional rows or columns,
22//! 2-dimensional matrices, and higher dimensional arrays. If the array has *n*
23//! dimensions, then an element in the array is accessed by using that many indices.
24//! Each dimension is also called an *axis*.
25//!
26//! - **[`ArrayBase`](struct.ArrayBase.html)**:
27//! The *n*-dimensional array type itself.<br>
28//! It is used to implement both the owned arrays and the views; see its docs
29//! for an overview of all array features.<br>
30//! - The main specific array type is **[`Array`](type.Array.html)**, which owns
31//! its elements.
32//!
33//! ## Highlights
34//!
35//! - Generic *n*-dimensional array
36//! - Slicing, also with arbitrary step size, and negative indices to mean
37//! elements from the end of the axis.
38//! - Views and subviews of arrays; iterators that yield subviews.
39//! - Higher order operations and arithmetic are performant
40//! - Array views can be used to slice and mutate any `[T]` data using
41//! `ArrayView::from` and `ArrayViewMut::from`.
42//! - [`Zip`](struct.Zip.html) for lock step function application across two or more arrays or other
43//! item producers ([`NdProducer`](trait.NdProducer.html) trait).
44//!
45//! ## Crate Status
46//!
47//! - Still iterating on and evolving the crate
48//! + The crate is continuously developing, and breaking changes are expected
49//! during evolution from version to version. We adopt the newest stable
50//! rust features if we need them.
51//! + Note that functions/methods/traits/etc. hidden from the docs are not
52//! considered part of the public API, so changes to them are not
53//! considered breaking changes.
54//! - Performance:
55//! + Prefer higher order methods and arithmetic operations on arrays first,
56//! then iteration, and as a last priority using indexed algorithms.
57//! + The higher order functions like [`.map()`](ArrayBase::map),
58//! [`.map_inplace()`](ArrayBase::map_inplace), [`.zip_mut_with()`](ArrayBase::zip_mut_with),
59//! [`Zip`] and [`azip!()`](azip) are the most efficient ways
60//! to perform single traversal and lock step traversal respectively.
61//! + Performance of an operation depends on the memory layout of the array
62//! or array view. Especially if it's a binary operation, which
63//! needs matching memory layout to be efficient (with some exceptions).
64//! + Efficient floating point matrix multiplication even for very large
65//! matrices; can optionally use BLAS to improve it further.
66//! - **Requires Rust 1.49 or later**
67//!
68//! ## Crate Feature Flags
69//!
70//! The following crate feature flags are available. They are configured in your
71//! `Cargo.toml`.
72//!
73//! - `std`
74//! - Rust standard library (enabled by default)
75//! - This crate can be used without the standard library by disabling the
76//! default `std` feature. To do so, use `default-features = false` in
77//! your `Cargo.toml`.
78//! - The `geomspace` `linspace` `logspace` `range` `std` `var` `var_axis`
79//! and `std_axis` methods are only available when `std` is enabled.
80//! - `serde`
81//! - Enables serialization support for serde 1.x
82//! - `rayon`
83//! - Enables parallel iterators, parallelized methods and [`par_azip!`].
84//! - Implies std
85//! - `approx`
86//! - Enables implementations of traits from the [`approx`] crate.
87//! - `blas`
88//! - Enable transparent BLAS support for matrix multiplication.
89//! Uses ``blas-src`` for pluggable backend, which needs to be configured
90//! separately (see the README).
91//! - `matrixmultiply-threading`
92//! - Enable the ``threading`` feature in the matrixmultiply package
93//!
94//! ## Documentation
95//!
96//! * The docs for [`ArrayBase`](struct.ArrayBase.html) provide an overview of
97//! the *n*-dimensional array type. Other good pages to look at are the
98//! documentation for the [`s![]`](macro.s.html) and
99//! [`azip!()`](macro.azip.html) macros.
100//!
101//! * If you have experience with NumPy, you may also be interested in
102//! [`ndarray_for_numpy_users`](doc/ndarray_for_numpy_users/index.html).
103//!
104//! ## The ndarray ecosystem
105//!
106//! `ndarray` provides a lot of functionality, but it's not a one-stop solution.
107//!
108//! `ndarray` includes matrix multiplication and other binary/unary operations out of the box.
109//! More advanced linear algebra routines (e.g. SVD decomposition or eigenvalue computation)
110//! can be found in [`ndarray-linalg`](https://crates.io/crates/ndarray-linalg).
111//!
112//! The same holds for statistics: `ndarray` provides some basic functionalities (e.g. `mean`)
113//! but more advanced routines can be found in [`ndarray-stats`](https://crates.io/crates/ndarray-stats).
114//!
115//! If you are looking to generate random arrays instead, check out [`ndarray-rand`](https://crates.io/crates/ndarray-rand).
116//!
117//! For conversion between `ndarray`, [`nalgebra`](https://crates.io/crates/nalgebra) and
118//! [`image`](https://crates.io/crates/image) check out [`nshare`](https://crates.io/crates/nshare).
119
120
121extern crate alloc;
122
123#[cfg(feature = "std")]
124extern crate std;
125#[cfg(not(feature = "std"))]
126extern crate core as std;
127
128#[cfg(feature = "blas")]
129extern crate cblas_sys;
130
131#[cfg(feature = "docs")]
132pub mod doc;
133
134use std::marker::PhantomData;
135use alloc::sync::Arc;
136
137pub use crate::dimension::dim::*;
138pub use crate::dimension::{Axis, AxisDescription, Dimension, IntoDimension, RemoveAxis};
139pub use crate::dimension::{DimAdd, DimMax};
140
141pub use crate::dimension::IxDynImpl;
142pub use crate::dimension::NdIndex;
143pub use crate::error::{ErrorKind, ShapeError};
144pub use crate::indexes::{indices, indices_of};
145pub use crate::slice::{
146 MultiSliceArg, NewAxis, Slice, SliceArg, SliceInfo, SliceInfoElem, SliceNextDim,
147};
148
149use crate::iterators::Baseiter;
150use crate::iterators::{ElementsBase, ElementsBaseMut, Iter, IterMut, Lanes};
151
152pub use crate::arraytraits::AsArray;
153#[cfg(feature = "std")]
154pub use crate::linalg_traits::NdFloat;
155pub use crate::linalg_traits::LinalgScalar;
156
157#[allow(deprecated)] // stack_new_axis
158pub use crate::stacking::{concatenate, stack, stack_new_axis};
159
160pub use crate::math_cell::MathCell;
161pub use crate::impl_views::IndexLonger;
162pub use crate::shape_builder::{Shape, ShapeBuilder, StrideShape};
163
164#[macro_use]
165mod macro_utils;
166#[macro_use]
167mod private;
168mod aliases;
169#[macro_use]
170mod itertools;
171mod argument_traits;
172#[cfg(feature = "serde")]
173mod array_serde;
174mod arrayformat;
175mod arraytraits;
176pub use crate::argument_traits::AssignElem;
177mod data_repr;
178mod data_traits;
179
180pub use crate::aliases::*;
181
182pub use crate::data_traits::{
183 Data, DataMut, DataOwned, DataShared, RawData, RawDataClone, RawDataMut,
184 RawDataSubst,
185};
186
187mod free_functions;
188pub use crate::free_functions::*;
189pub use crate::iterators::iter;
190
191mod error;
192mod extension;
193mod geomspace;
194mod indexes;
195mod iterators;
196mod layout;
197mod linalg_traits;
198mod linspace;
199mod logspace;
200mod math_cell;
201mod numeric_util;
202mod partial;
203mod shape_builder;
204#[macro_use]
205mod slice;
206mod split_at;
207mod stacking;
208#[macro_use]
209mod zip;
210
211mod dimension;
212
213pub use crate::zip::{FoldWhile, IntoNdProducer, NdProducer, Zip};
214
215pub use crate::layout::Layout;
216
217/// Implementation's prelude. Common types used everywhere.
218mod imp_prelude {
219 pub use crate::dimension::DimensionExt;
220 pub use crate::prelude::*;
221 pub use crate::ArcArray;
222 pub use crate::{
223 CowRepr, Data, DataMut, DataOwned, DataShared, Ix, Ixs, RawData, RawDataMut, RawViewRepr,
224 RemoveAxis, ViewRepr,
225 };
226}
227
228pub mod prelude;
229
230/// Array index type
231pub type Ix = usize;
232/// Array index type (signed)
233pub type Ixs = isize;
234
235/// An *n*-dimensional array.
236///
237/// The array is a general container of elements. It cannot grow or shrink, but
238/// can be sliced into subsets of its data.
239/// The array supports arithmetic operations by applying them elementwise.
240///
241/// In *n*-dimensional we include for example 1-dimensional rows or columns,
242/// 2-dimensional matrices, and higher dimensional arrays. If the array has *n*
243/// dimensions, then an element is accessed by using that many indices.
244///
245/// The `ArrayBase<S, D>` is parameterized by `S` for the data container and
246/// `D` for the dimensionality.
247///
248/// Type aliases [`Array`], [`ArcArray`], [`CowArray`], [`ArrayView`], and
249/// [`ArrayViewMut`] refer to `ArrayBase` with different types for the data
250/// container.
251///
252/// [`Array`]: type.Array.html
253/// [`ArcArray`]: type.ArcArray.html
254/// [`ArrayView`]: type.ArrayView.html
255/// [`ArrayViewMut`]: type.ArrayViewMut.html
256/// [`CowArray`]: type.CowArray.html
257///
258/// ## Contents
259///
260/// + [Array](#array)
261/// + [ArcArray](#arcarray)
262/// + [CowArray](#cowarray)
263/// + [Array Views](#array-views)
264/// + [Indexing and Dimension](#indexing-and-dimension)
265/// + [Loops, Producers and Iterators](#loops-producers-and-iterators)
266/// + [Slicing](#slicing)
267/// + [Subviews](#subviews)
268/// + [Arithmetic Operations](#arithmetic-operations)
269/// + [Broadcasting](#broadcasting)
270/// + [Conversions](#conversions)
271/// + [Constructor Methods for Owned Arrays](#constructor-methods-for-owned-arrays)
272/// + [Methods For All Array Types](#methods-for-all-array-types)
273/// + [Methods For 1-D Arrays](#methods-for-1-d-arrays)
274/// + [Methods For 2-D Arrays](#methods-for-2-d-arrays)
275/// + [Methods for Dynamic-Dimensional Arrays](#methods-for-dynamic-dimensional-arrays)
276/// + [Numerical Methods for Arrays](#numerical-methods-for-arrays)
277///
278/// ## `Array`
279///
280/// [`Array`](type.Array.html) is an owned array that owns the underlying array
281/// elements directly (just like a `Vec`) and it is the default way to create and
282/// store n-dimensional data. `Array<A, D>` has two type parameters: `A` for
283/// the element type, and `D` for the dimensionality. A particular
284/// dimensionality's type alias like `Array3<A>` just has the type parameter
285/// `A` for element type.
286///
287/// An example:
288///
289/// ```
290/// // Create a three-dimensional f64 array, initialized with zeros
291/// use ndarray::Array3;
292/// let mut temperature = Array3::<f64>::zeros((3, 4, 5));
293/// // Increase the temperature in this location
294/// temperature[[2, 2, 2]] += 0.5;
295/// ```
296///
297/// ## `ArcArray`
298///
299/// [`ArcArray`](type.ArcArray.html) is an owned array with reference counted
300/// data (shared ownership).
301/// Sharing requires that it uses copy-on-write for mutable operations.
302/// Calling a method for mutating elements on `ArcArray`, for example
303/// [`view_mut()`](#method.view_mut) or [`get_mut()`](#method.get_mut),
304/// will break sharing and require a clone of the data (if it is not uniquely held).
305///
306/// ## `CowArray`
307///
308/// [`CowArray`](type.CowArray.html) is analogous to
309/// [`std::borrow::Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html).
310/// It can represent either an immutable view or a uniquely owned array. If a
311/// `CowArray` instance is the immutable view variant, then calling a method
312/// for mutating elements in the array will cause it to be converted into the
313/// owned variant (by cloning all the elements) before the modification is
314/// performed.
315///
316/// ## Array Views
317///
318/// [`ArrayView`] and [`ArrayViewMut`] are read-only and read-write array views
319/// respectively. They use dimensionality, indexing, and almost all other
320/// methods the same way as the other array types.
321///
322/// Methods for `ArrayBase` apply to array views too, when the trait bounds
323/// allow.
324///
325/// Please see the documentation for the respective array view for an overview
326/// of methods specific to array views: [`ArrayView`], [`ArrayViewMut`].
327///
328/// A view is created from an array using [`.view()`](ArrayBase::view),
329/// [`.view_mut()`](ArrayBase::view_mut), using
330/// slicing ([`.slice()`](ArrayBase::slice), [`.slice_mut()`](ArrayBase::slice_mut)) or from one of
331/// the many iterators that yield array views.
332///
333/// You can also create an array view from a regular slice of data not
334/// allocated with `Array` — see array view methods or their `From` impls.
335///
336/// Note that all `ArrayBase` variants can change their view (slicing) of the
337/// data freely, even when their data can’t be mutated.
338///
339/// ## Indexing and Dimension
340///
341/// The dimensionality of the array determines the number of *axes*, for example
342/// a 2D array has two axes. These are listed in “big endian” order, so that
343/// the greatest dimension is listed first, the lowest dimension with the most
344/// rapidly varying index is the last.
345///
346/// In a 2D array the index of each element is `[row, column]` as seen in this
347/// 4 × 3 example:
348///
349/// ```ignore
350/// [[ [0, 0], [0, 1], [0, 2] ], // row 0
351/// [ [1, 0], [1, 1], [1, 2] ], // row 1
352/// [ [2, 0], [2, 1], [2, 2] ], // row 2
353/// [ [3, 0], [3, 1], [3, 2] ]] // row 3
354/// // \ \ \
355/// // column 0 \ column 2
356/// // column 1
357/// ```
358///
359/// The number of axes for an array is fixed by its `D` type parameter: `Ix1`
360/// for a 1D array, `Ix2` for a 2D array etc. The dimension type `IxDyn` allows
361/// a dynamic number of axes.
362///
363/// A fixed size array (`[usize; N]`) of the corresponding dimensionality is
364/// used to index the `Array`, making the syntax `array[[` i, j, ...`]]`
365///
366/// ```
367/// use ndarray::Array2;
368/// let mut array = Array2::zeros((4, 3));
369/// array[[1, 1]] = 7;
370/// ```
371///
372/// Important traits and types for dimension and indexing:
373///
374/// - A [`Dim`](struct.Dim.html) value represents a dimensionality or index.
375/// - Trait [`Dimension`](trait.Dimension.html) is implemented by all
376/// dimensionalities. It defines many operations for dimensions and indices.
377/// - Trait [`IntoDimension`](trait.IntoDimension.html) is used to convert into a
378/// `Dim` value.
379/// - Trait [`ShapeBuilder`](trait.ShapeBuilder.html) is an extension of
380/// `IntoDimension` and is used when constructing an array. A shape describes
381/// not just the extent of each axis but also their strides.
382/// - Trait [`NdIndex`](trait.NdIndex.html) is an extension of `Dimension` and is
383/// for values that can be used with indexing syntax.
384///
385///
386/// The default memory order of an array is *row major* order (a.k.a “c” order),
387/// where each row is contiguous in memory.
388/// A *column major* (a.k.a. “f” or fortran) memory order array has
389/// columns (or, in general, the outermost axis) with contiguous elements.
390///
391/// The logical order of any array’s elements is the row major order
392/// (the rightmost index is varying the fastest).
393/// The iterators `.iter(), .iter_mut()` always adhere to this order, for example.
394///
395/// ## Loops, Producers and Iterators
396///
397/// Using [`Zip`](struct.Zip.html) is the most general way to apply a procedure
398/// across one or several arrays or *producers*.
399///
400/// [`NdProducer`](trait.NdProducer.html) is like an iterable but for
401/// multidimensional data. All producers have dimensions and axes, like an
402/// array view, and they can be split and used with parallelization using `Zip`.
403///
404/// For example, `ArrayView<A, D>` is a producer, it has the same dimensions
405/// as the array view and for each iteration it produces a reference to
406/// the array element (`&A` in this case).
407///
408/// Another example, if we have a 10 × 10 array and use `.exact_chunks((2, 2))`
409/// we get a producer of chunks which has the dimensions 5 × 5 (because
410/// there are *10 / 2 = 5* chunks in either direction). The 5 × 5 chunks producer
411/// can be paired with any other producers of the same dimension with `Zip`, for
412/// example 5 × 5 arrays.
413///
414/// ### `.iter()` and `.iter_mut()`
415///
416/// These are the element iterators of arrays and they produce an element
417/// sequence in the logical order of the array, that means that the elements
418/// will be visited in the sequence that corresponds to increasing the
419/// last index first: *0, ..., 0, 0*; *0, ..., 0, 1*; *0, ...0, 2* and so on.
420///
421/// ### `.outer_iter()` and `.axis_iter()`
422///
423/// These iterators produce array views of one smaller dimension.
424///
425/// For example, for a 2D array, `.outer_iter()` will produce the 1D rows.
426/// For a 3D array, `.outer_iter()` produces 2D subviews.
427///
428/// `.axis_iter()` is like `outer_iter()` but allows you to pick which
429/// axis to traverse.
430///
431/// The `outer_iter` and `axis_iter` are one dimensional producers.
432///
433/// ## `.rows()`, `.columns()` and `.lanes()`
434///
435/// [`.rows()`][gr] is a producer (and iterable) of all rows in an array.
436///
437/// ```
438/// use ndarray::Array;
439///
440/// // 1. Loop over the rows of a 2D array
441/// let mut a = Array::zeros((10, 10));
442/// for mut row in a.rows_mut() {
443/// row.fill(1.);
444/// }
445///
446/// // 2. Use Zip to pair each row in 2D `a` with elements in 1D `b`
447/// use ndarray::Zip;
448/// let mut b = Array::zeros(a.nrows());
449///
450/// Zip::from(a.rows())
451/// .and(&mut b)
452/// .for_each(|a_row, b_elt| {
453/// *b_elt = a_row[a.ncols() - 1] - a_row[0];
454/// });
455/// ```
456///
457/// The *lanes* of an array are 1D segments along an axis and when pointed
458/// along the last axis they are *rows*, when pointed along the first axis
459/// they are *columns*.
460///
461/// A *m* × *n* array has *m* rows each of length *n* and conversely
462/// *n* columns each of length *m*.
463///
464/// To generalize this, we say that an array of dimension *a* × *m* × *n*
465/// has *a m* rows. It's composed of *a* times the previous array, so it
466/// has *a* times as many rows.
467///
468/// All methods: [`.rows()`][gr], [`.rows_mut()`][grm],
469/// [`.columns()`][gc], [`.columns_mut()`][gcm],
470/// [`.lanes(axis)`][l], [`.lanes_mut(axis)`][lm].
471///
472/// [gr]: #method.rows
473/// [grm]: #method.rows_mut
474/// [gc]: #method.columns
475/// [gcm]: #method.columns_mut
476/// [l]: #method.lanes
477/// [lm]: #method.lanes_mut
478///
479/// Yes, for 2D arrays `.rows()` and `.outer_iter()` have about the same
480/// effect:
481///
482/// + `rows()` is a producer with *n* - 1 dimensions of 1 dimensional items
483/// + `outer_iter()` is a producer with 1 dimension of *n* - 1 dimensional items
484///
485/// ## Slicing
486///
487/// You can use slicing to create a view of a subset of the data in
488/// the array. Slicing methods include [`.slice()`], [`.slice_mut()`],
489/// [`.slice_move()`], and [`.slice_collapse()`].
490///
491/// The slicing argument can be passed using the macro [`s![]`](macro.s!.html),
492/// which will be used in all examples. (The explicit form is an instance of
493/// [`SliceInfo`] or another type which implements [`SliceArg`]; see their docs
494/// for more information.)
495///
496/// If a range is used, the axis is preserved. If an index is used, that index
497/// is selected and the axis is removed; this selects a subview. See
498/// [*Subviews*](#subviews) for more information about subviews. If a
499/// [`NewAxis`] instance is used, a new axis is inserted. Note that
500/// [`.slice_collapse()`] panics on `NewAxis` elements and behaves like
501/// [`.collapse_axis()`] by preserving the number of dimensions.
502///
503/// [`.slice()`]: #method.slice
504/// [`.slice_mut()`]: #method.slice_mut
505/// [`.slice_move()`]: #method.slice_move
506/// [`.slice_collapse()`]: #method.slice_collapse
507/// [`NewAxis`]: struct.NewAxis.html
508///
509/// When slicing arrays with generic dimensionality, creating an instance of
510/// [`SliceInfo`] to pass to the multi-axis slicing methods like [`.slice()`]
511/// is awkward. In these cases, it's usually more convenient to use
512/// [`.slice_each_axis()`]/[`.slice_each_axis_mut()`]/[`.slice_each_axis_inplace()`]
513/// or to create a view and then slice individual axes of the view using
514/// methods such as [`.slice_axis_inplace()`] and [`.collapse_axis()`].
515///
516/// [`.slice_each_axis()`]: #method.slice_each_axis
517/// [`.slice_each_axis_mut()`]: #method.slice_each_axis_mut
518/// [`.slice_each_axis_inplace()`]: #method.slice_each_axis_inplace
519/// [`.slice_axis_inplace()`]: #method.slice_axis_inplace
520/// [`.collapse_axis()`]: #method.collapse_axis
521///
522/// It's possible to take multiple simultaneous *mutable* slices with
523/// [`.multi_slice_mut()`] or (for [`ArrayViewMut`] only)
524/// [`.multi_slice_move()`].
525///
526/// [`.multi_slice_mut()`]: #method.multi_slice_mut
527/// [`.multi_slice_move()`]: type.ArrayViewMut.html#method.multi_slice_move
528///
529/// ```
530/// use ndarray::{arr2, arr3, s, ArrayBase, DataMut, Dimension, NewAxis, Slice};
531///
532/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
533///
534/// let a = arr3(&[[[ 1, 2, 3], // -- 2 rows \_
535/// [ 4, 5, 6]], // -- /
536/// [[ 7, 8, 9], // \_ 2 submatrices
537/// [10, 11, 12]]]); // /
538/// // 3 columns ..../.../.../
539///
540/// assert_eq!(a.shape(), &[2, 2, 3]);
541///
542/// // Let’s create a slice with
543/// //
544/// // - Both of the submatrices of the greatest dimension: `..`
545/// // - Only the first row in each submatrix: `0..1`
546/// // - Every element in each row: `..`
547///
548/// let b = a.slice(s![.., 0..1, ..]);
549/// let c = arr3(&[[[ 1, 2, 3]],
550/// [[ 7, 8, 9]]]);
551/// assert_eq!(b, c);
552/// assert_eq!(b.shape(), &[2, 1, 3]);
553///
554/// // Let’s create a slice with
555/// //
556/// // - Both submatrices of the greatest dimension: `..`
557/// // - The last row in each submatrix: `-1..`
558/// // - Row elements in reverse order: `..;-1`
559/// let d = a.slice(s![.., -1.., ..;-1]);
560/// let e = arr3(&[[[ 6, 5, 4]],
561/// [[12, 11, 10]]]);
562/// assert_eq!(d, e);
563/// assert_eq!(d.shape(), &[2, 1, 3]);
564///
565/// // Let’s create a slice while selecting a subview and inserting a new axis with
566/// //
567/// // - Both submatrices of the greatest dimension: `..`
568/// // - The last row in each submatrix, removing that axis: `-1`
569/// // - Row elements in reverse order: `..;-1`
570/// // - A new axis at the end.
571/// let f = a.slice(s![.., -1, ..;-1, NewAxis]);
572/// let g = arr3(&[[ [6], [5], [4]],
573/// [[12], [11], [10]]]);
574/// assert_eq!(f, g);
575/// assert_eq!(f.shape(), &[2, 3, 1]);
576///
577/// // Let's take two disjoint, mutable slices of a matrix with
578/// //
579/// // - One containing all the even-index columns in the matrix
580/// // - One containing all the odd-index columns in the matrix
581/// let mut h = arr2(&[[0, 1, 2, 3],
582/// [4, 5, 6, 7]]);
583/// let (s0, s1) = h.multi_slice_mut((s![.., ..;2], s![.., 1..;2]));
584/// let i = arr2(&[[0, 2],
585/// [4, 6]]);
586/// let j = arr2(&[[1, 3],
587/// [5, 7]]);
588/// assert_eq!(s0, i);
589/// assert_eq!(s1, j);
590///
591/// // Generic function which assigns the specified value to the elements which
592/// // have indices in the lower half along all axes.
593/// fn fill_lower<S, D>(arr: &mut ArrayBase<S, D>, x: S::Elem)
594/// where
595/// S: DataMut,
596/// S::Elem: Clone,
597/// D: Dimension,
598/// {
599/// arr.slice_each_axis_mut(|ax| Slice::from(0..ax.len / 2)).fill(x);
600/// }
601/// fill_lower(&mut h, 9);
602/// let k = arr2(&[[9, 9, 2, 3],
603/// [4, 5, 6, 7]]);
604/// assert_eq!(h, k);
605/// ```
606///
607/// ## Subviews
608///
609/// Subview methods allow you to restrict the array view while removing one
610/// axis from the array. Methods for selecting individual subviews include
611/// [`.index_axis()`], [`.index_axis_mut()`], [`.index_axis_move()`], and
612/// [`.index_axis_inplace()`]. You can also select a subview by using a single
613/// index instead of a range when slicing. Some other methods, such as
614/// [`.fold_axis()`], [`.axis_iter()`], [`.axis_iter_mut()`],
615/// [`.outer_iter()`], and [`.outer_iter_mut()`] operate on all the subviews
616/// along an axis.
617///
618/// A related method is [`.collapse_axis()`], which modifies the view in the
619/// same way as [`.index_axis()`] except for removing the collapsed axis, since
620/// it operates *in place*. The length of the axis becomes 1.
621///
622/// Methods for selecting an individual subview take two arguments: `axis` and
623/// `index`.
624///
625/// [`.axis_iter()`]: #method.axis_iter
626/// [`.axis_iter_mut()`]: #method.axis_iter_mut
627/// [`.fold_axis()`]: #method.fold_axis
628/// [`.index_axis()`]: #method.index_axis
629/// [`.index_axis_inplace()`]: #method.index_axis_inplace
630/// [`.index_axis_mut()`]: #method.index_axis_mut
631/// [`.index_axis_move()`]: #method.index_axis_move
632/// [`.collapse_axis()`]: #method.collapse_axis
633/// [`.outer_iter()`]: #method.outer_iter
634/// [`.outer_iter_mut()`]: #method.outer_iter_mut
635///
636/// ```
637///
638/// use ndarray::{arr3, aview1, aview2, s, Axis};
639///
640///
641/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
642///
643/// let a = arr3(&[[[ 1, 2, 3], // \ axis 0, submatrix 0
644/// [ 4, 5, 6]], // /
645/// [[ 7, 8, 9], // \ axis 0, submatrix 1
646/// [10, 11, 12]]]); // /
647/// // \
648/// // axis 2, column 0
649///
650/// assert_eq!(a.shape(), &[2, 2, 3]);
651///
652/// // Let’s take a subview along the greatest dimension (axis 0),
653/// // taking submatrix 0, then submatrix 1
654///
655/// let sub_0 = a.index_axis(Axis(0), 0);
656/// let sub_1 = a.index_axis(Axis(0), 1);
657///
658/// assert_eq!(sub_0, aview2(&[[ 1, 2, 3],
659/// [ 4, 5, 6]]));
660/// assert_eq!(sub_1, aview2(&[[ 7, 8, 9],
661/// [10, 11, 12]]));
662/// assert_eq!(sub_0.shape(), &[2, 3]);
663///
664/// // This is the subview picking only axis 2, column 0
665/// let sub_col = a.index_axis(Axis(2), 0);
666///
667/// assert_eq!(sub_col, aview2(&[[ 1, 4],
668/// [ 7, 10]]));
669///
670/// // You can take multiple subviews at once (and slice at the same time)
671/// let double_sub = a.slice(s![1, .., 0]);
672/// assert_eq!(double_sub, aview1(&[7, 10]));
673/// ```
674///
675/// ## Arithmetic Operations
676///
677/// Arrays support all arithmetic operations the same way: they apply elementwise.
678///
679/// Since the trait implementations are hard to overview, here is a summary.
680///
681/// ### Binary Operators with Two Arrays
682///
683/// Let `A` be an array or view of any kind. Let `B` be an array
684/// with owned storage (either `Array` or `ArcArray`).
685/// Let `C` be an array with mutable data (either `Array`, `ArcArray`
686/// or `ArrayViewMut`).
687/// The following combinations of operands
688/// are supported for an arbitrary binary operator denoted by `@` (it can be
689/// `+`, `-`, `*`, `/` and so on).
690///
691/// - `&A @ &A` which produces a new `Array`
692/// - `B @ A` which consumes `B`, updates it with the result, and returns it
693/// - `B @ &A` which consumes `B`, updates it with the result, and returns it
694/// - `C @= &A` which performs an arithmetic operation in place
695///
696/// Note that the element type needs to implement the operator trait and the
697/// `Clone` trait.
698///
699/// ```
700/// use ndarray::{array, ArrayView1};
701///
702/// let owned1 = array![1, 2];
703/// let owned2 = array![3, 4];
704/// let view1 = ArrayView1::from(&[5, 6]);
705/// let view2 = ArrayView1::from(&[7, 8]);
706/// let mut mutable = array![9, 10];
707///
708/// let sum1 = &view1 + &view2; // Allocates a new array. Note the explicit `&`.
709/// // let sum2 = view1 + &view2; // This doesn't work because `view1` is not an owned array.
710/// let sum3 = owned1 + view1; // Consumes `owned1`, updates it, and returns it.
711/// let sum4 = owned2 + &view2; // Consumes `owned2`, updates it, and returns it.
712/// mutable += &view2; // Updates `mutable` in-place.
713/// ```
714///
715/// ### Binary Operators with Array and Scalar
716///
717/// The trait [`ScalarOperand`](trait.ScalarOperand.html) marks types that can be used in arithmetic
718/// with arrays directly. For a scalar `K` the following combinations of operands
719/// are supported (scalar can be on either the left or right side, but
720/// `ScalarOperand` docs has the detailed condtions).
721///
722/// - `&A @ K` or `K @ &A` which produces a new `Array`
723/// - `B @ K` or `K @ B` which consumes `B`, updates it with the result and returns it
724/// - `C @= K` which performs an arithmetic operation in place
725///
726/// ### Unary Operators
727///
728/// Let `A` be an array or view of any kind. Let `B` be an array with owned
729/// storage (either `Array` or `ArcArray`). The following operands are supported
730/// for an arbitrary unary operator denoted by `@` (it can be `-` or `!`).
731///
732/// - `@&A` which produces a new `Array`
733/// - `@B` which consumes `B`, updates it with the result, and returns it
734///
735/// ## Broadcasting
736///
737/// Arrays support limited *broadcasting*, where arithmetic operations with
738/// array operands of different sizes can be carried out by repeating the
739/// elements of the smaller dimension array. See
740/// [`.broadcast()`](#method.broadcast) for a more detailed
741/// description.
742///
743/// ```
744/// use ndarray::arr2;
745///
746/// let a = arr2(&[[1., 1.],
747/// [1., 2.],
748/// [0., 3.],
749/// [0., 4.]]);
750///
751/// let b = arr2(&[[0., 1.]]);
752///
753/// let c = arr2(&[[1., 2.],
754/// [1., 3.],
755/// [0., 4.],
756/// [0., 5.]]);
757/// // We can add because the shapes are compatible even if not equal.
758/// // The `b` array is shape 1 × 2 but acts like a 4 × 2 array.
759/// assert!(
760/// c == a + b
761/// );
762/// ```
763///
764/// ## Conversions
765///
766/// ### Conversions Between Array Types
767///
768/// This table is a summary of the conversions between arrays of different
769/// ownership, dimensionality, and element type. All of the conversions in this
770/// table preserve the shape of the array.
771///
772/// <table>
773/// <tr>
774/// <th rowspan="2">Output</th>
775/// <th colspan="5">Input</th>
776/// </tr>
777///
778/// <tr>
779/// <td>
780///
781/// `Array<A, D>`
782///
783/// </td>
784/// <td>
785///
786/// `ArcArray<A, D>`
787///
788/// </td>
789/// <td>
790///
791/// `CowArray<'a, A, D>`
792///
793/// </td>
794/// <td>
795///
796/// `ArrayView<'a, A, D>`
797///
798/// </td>
799/// <td>
800///
801/// `ArrayViewMut<'a, A, D>`
802///
803/// </td>
804/// </tr>
805///
806/// <!--Conversions to `Array<A, D>`-->
807///
808/// <tr>
809/// <td>
810///
811/// `Array<A, D>`
812///
813/// </td>
814/// <td>
815///
816/// no-op
817///
818/// </td>
819/// <td>
820///
821/// [`a.into_owned()`][.into_owned()]
822///
823/// </td>
824/// <td>
825///
826/// [`a.into_owned()`][.into_owned()]
827///
828/// </td>
829/// <td>
830///
831/// [`a.to_owned()`][.to_owned()]
832///
833/// </td>
834/// <td>
835///
836/// [`a.to_owned()`][.to_owned()]
837///
838/// </td>
839/// </tr>
840///
841/// <!--Conversions to `ArcArray<A, D>`-->
842///
843/// <tr>
844/// <td>
845///
846/// `ArcArray<A, D>`
847///
848/// </td>
849/// <td>
850///
851/// [`a.into_shared()`][.into_shared()]
852///
853/// </td>
854/// <td>
855///
856/// no-op
857///
858/// </td>
859/// <td>
860///
861/// [`a.into_owned().into_shared()`][.into_shared()]
862///
863/// </td>
864/// <td>
865///
866/// [`a.to_owned().into_shared()`][.into_shared()]
867///
868/// </td>
869/// <td>
870///
871/// [`a.to_owned().into_shared()`][.into_shared()]
872///
873/// </td>
874/// </tr>
875///
876/// <!--Conversions to `CowArray<'a, A, D>`-->
877///
878/// <tr>
879/// <td>
880///
881/// `CowArray<'a, A, D>`
882///
883/// </td>
884/// <td>
885///
886/// [`CowArray::from(a)`](type.CowArray.html#impl-From<ArrayBase<OwnedRepr<A>%2C%20D>>)
887///
888/// </td>
889/// <td>
890///
891/// [`CowArray::from(a.into_owned())`](type.CowArray.html#impl-From<ArrayBase<OwnedRepr<A>%2C%20D>>)
892///
893/// </td>
894/// <td>
895///
896/// no-op
897///
898/// </td>
899/// <td>
900///
901/// [`CowArray::from(a)`](type.CowArray.html#impl-From<ArrayBase<ViewRepr<%26%27a%20A>%2C%20D>>)
902///
903/// </td>
904/// <td>
905///
906/// [`CowArray::from(a.view())`](type.CowArray.html#impl-From<ArrayBase<ViewRepr<%26%27a%20A>%2C%20D>>)
907///
908/// </td>
909/// </tr>
910///
911/// <!--Conversions to `ArrayView<'b, A, D>`-->
912///
913/// <tr>
914/// <td>
915///
916/// `ArrayView<'b, A, D>`
917///
918/// </td>
919/// <td>
920///
921/// [`a.view()`][.view()]
922///
923/// </td>
924/// <td>
925///
926/// [`a.view()`][.view()]
927///
928/// </td>
929/// <td>
930///
931/// [`a.view()`][.view()]
932///
933/// </td>
934/// <td>
935///
936/// [`a.view()`][.view()] or [`a.reborrow()`][ArrayView::reborrow()]
937///
938/// </td>
939/// <td>
940///
941/// [`a.view()`][.view()]
942///
943/// </td>
944/// </tr>
945///
946/// <!--Conversions to `ArrayViewMut<'b, A, D>`-->
947///
948/// <tr>
949/// <td>
950///
951/// `ArrayViewMut<'b, A, D>`
952///
953/// </td>
954/// <td>
955///
956/// [`a.view_mut()`][.view_mut()]
957///
958/// </td>
959/// <td>
960///
961/// [`a.view_mut()`][.view_mut()]
962///
963/// </td>
964/// <td>
965///
966/// [`a.view_mut()`][.view_mut()]
967///
968/// </td>
969/// <td>
970///
971/// illegal
972///
973/// </td>
974/// <td>
975///
976/// [`a.view_mut()`][.view_mut()] or [`a.reborrow()`][ArrayViewMut::reborrow()]
977///
978/// </td>
979/// </tr>
980///
981/// <!--Conversions to equivalent with dim `D2`-->
982///
983/// <tr>
984/// <td>
985///
986/// equivalent with dim `D2` (e.g. converting from dynamic dim to const dim)
987///
988/// </td>
989/// <td colspan="5">
990///
991/// [`a.into_dimensionality::<D2>()`][.into_dimensionality()]
992///
993/// </td>
994/// </tr>
995///
996/// <!--Conversions to equivalent with dim `IxDyn`-->
997///
998/// <tr>
999/// <td>
1000///
1001/// equivalent with dim `IxDyn`
1002///
1003/// </td>
1004/// <td colspan="5">
1005///
1006/// [`a.into_dyn()`][.into_dyn()]
1007///
1008/// </td>
1009/// </tr>
1010///
1011/// <!--Conversions to `Array<B, D>`-->
1012///
1013/// <tr>
1014/// <td>
1015///
1016/// `Array<B, D>` (new element type)
1017///
1018/// </td>
1019/// <td colspan="5">
1020///
1021/// [`a.map(|x| x.do_your_conversion())`][.map()]
1022///
1023/// </td>
1024/// </tr>
1025/// </table>
1026///
1027/// ### Conversions Between Arrays and `Vec`s/Slices/Scalars
1028///
1029/// This is a table of the safe conversions between arrays and
1030/// `Vec`s/slices/scalars. Note that some of the return values are actually
1031/// `Result`/`Option` wrappers around the indicated output types.
1032///
1033/// Input | Output | Methods
1034/// ------|--------|--------
1035/// `Vec<A>` | `ArrayBase<S: DataOwned, Ix1>` | [`::from_vec()`](#method.from_vec)
1036/// `Vec<A>` | `ArrayBase<S: DataOwned, D>` | [`::from_shape_vec()`](#method.from_shape_vec)
1037/// `&[A]` | `ArrayView1<A>` | [`::from()`](type.ArrayView.html#method.from)
1038/// `&[A]` | `ArrayView<A, D>` | [`::from_shape()`](type.ArrayView.html#method.from_shape)
1039/// `&mut [A]` | `ArrayViewMut1<A>` | [`::from()`](type.ArrayViewMut.html#method.from)
1040/// `&mut [A]` | `ArrayViewMut<A, D>` | [`::from_shape()`](type.ArrayViewMut.html#method.from_shape)
1041/// `&ArrayBase<S, Ix1>` | `Vec<A>` | [`.to_vec()`](#method.to_vec)
1042/// `Array<A, D>` | `Vec<A>` | [`.into_raw_vec()`](type.Array.html#method.into_raw_vec)<sup>[1](#into_raw_vec)</sup>
1043/// `&ArrayBase<S, D>` | `&[A]` | [`.as_slice()`](#method.as_slice)<sup>[2](#req_contig_std)</sup>, [`.as_slice_memory_order()`](#method.as_slice_memory_order)<sup>[3](#req_contig)</sup>
1044/// `&mut ArrayBase<S: DataMut, D>` | `&mut [A]` | [`.as_slice_mut()`](#method.as_slice_mut)<sup>[2](#req_contig_std)</sup>, [`.as_slice_memory_order_mut()`](#method.as_slice_memory_order_mut)<sup>[3](#req_contig)</sup>
1045/// `ArrayView<A, D>` | `&[A]` | [`.to_slice()`](type.ArrayView.html#method.to_slice)<sup>[2](#req_contig_std)</sup>
1046/// `ArrayViewMut<A, D>` | `&mut [A]` | [`.into_slice()`](type.ArrayViewMut.html#method.into_slice)<sup>[2](#req_contig_std)</sup>
1047/// `Array0<A>` | `A` | [`.into_scalar()`](type.Array.html#method.into_scalar)
1048///
1049/// <sup><a name="into_raw_vec">1</a></sup>Returns the data in memory order.
1050///
1051/// <sup><a name="req_contig_std">2</a></sup>Works only if the array is
1052/// contiguous and in standard order.
1053///
1054/// <sup><a name="req_contig">3</a></sup>Works only if the array is contiguous.
1055///
1056/// The table above does not include all the constructors; it only shows
1057/// conversions to/from `Vec`s/slices. See
1058/// [below](#constructor-methods-for-owned-arrays) for more constructors.
1059///
1060/// [ArrayView::reborrow()]: type.ArrayView.html#method.reborrow
1061/// [ArrayViewMut::reborrow()]: type.ArrayViewMut.html#method.reborrow
1062/// [.into_dimensionality()]: #method.into_dimensionality
1063/// [.into_dyn()]: #method.into_dyn
1064/// [.into_owned()]: #method.into_owned
1065/// [.into_shared()]: #method.into_shared
1066/// [.to_owned()]: #method.to_owned
1067/// [.map()]: #method.map
1068/// [.view()]: #method.view
1069/// [.view_mut()]: #method.view_mut
1070///
1071/// ### Conversions from Nested `Vec`s/`Array`s
1072///
1073/// It's generally a good idea to avoid nested `Vec`/`Array` types, such as
1074/// `Vec<Vec<A>>` or `Vec<Array2<A>>` because:
1075///
1076/// * they require extra heap allocations compared to a single `Array`,
1077///
1078/// * they can scatter data all over memory (because of multiple allocations),
1079///
1080/// * they cause unnecessary indirection (traversing multiple pointers to reach
1081/// the data),
1082///
1083/// * they don't enforce consistent shape within the nested
1084/// `Vec`s/`ArrayBase`s, and
1085///
1086/// * they are generally more difficult to work with.
1087///
1088/// The most common case where users might consider using nested
1089/// `Vec`s/`Array`s is when creating an array by appending rows/subviews in a
1090/// loop, where the rows/subviews are computed within the loop. However, there
1091/// are better ways than using nested `Vec`s/`Array`s.
1092///
1093/// If you know ahead-of-time the shape of the final array, the cleanest
1094/// solution is to allocate the final array before the loop, and then assign
1095/// the data to it within the loop, like this:
1096///
1097/// ```rust
1098/// use ndarray::{array, Array2, Axis};
1099///
1100/// let mut arr = Array2::zeros((2, 3));
1101/// for (i, mut row) in arr.axis_iter_mut(Axis(0)).enumerate() {
1102/// // Perform calculations and assign to `row`; this is a trivial example:
1103/// row.fill(i);
1104/// }
1105/// assert_eq!(arr, array![[0, 0, 0], [1, 1, 1]]);
1106/// ```
1107///
1108/// If you don't know ahead-of-time the shape of the final array, then the
1109/// cleanest solution is generally to append the data to a flat `Vec`, and then
1110/// convert it to an `Array` at the end with
1111/// [`::from_shape_vec()`](#method.from_shape_vec). You just have to be careful
1112/// that the layout of the data (the order of the elements in the flat `Vec`)
1113/// is correct.
1114///
1115/// ```rust
1116/// use ndarray::{array, Array2};
1117///
1118/// let ncols = 3;
1119/// let mut data = Vec::new();
1120/// let mut nrows = 0;
1121/// for i in 0..2 {
1122/// // Compute `row` and append it to `data`; this is a trivial example:
1123/// let row = vec![i; ncols];
1124/// data.extend_from_slice(&row);
1125/// nrows += 1;
1126/// }
1127/// let arr = Array2::from_shape_vec((nrows, ncols), data)?;
1128/// assert_eq!(arr, array![[0, 0, 0], [1, 1, 1]]);
1129/// # Ok::<(), ndarray::ShapeError>(())
1130/// ```
1131///
1132/// If neither of these options works for you, and you really need to convert
1133/// nested `Vec`/`Array` instances to an `Array`, the cleanest solution is
1134/// generally to use
1135/// [`Iterator::flatten()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flatten)
1136/// to get a flat `Vec`, and then convert the `Vec` to an `Array` with
1137/// [`::from_shape_vec()`](#method.from_shape_vec), like this:
1138///
1139/// ```rust
1140/// use ndarray::{array, Array2, Array3};
1141///
1142/// let nested: Vec<Array2<i32>> = vec![
1143/// array![[1, 2, 3], [4, 5, 6]],
1144/// array![[7, 8, 9], [10, 11, 12]],
1145/// ];
1146/// let inner_shape = nested[0].dim();
1147/// let shape = (nested.len(), inner_shape.0, inner_shape.1);
1148/// let flat: Vec<i32> = nested.iter().flatten().cloned().collect();
1149/// let arr = Array3::from_shape_vec(shape, flat)?;
1150/// assert_eq!(arr, array![
1151/// [[1, 2, 3], [4, 5, 6]],
1152/// [[7, 8, 9], [10, 11, 12]],
1153/// ]);
1154/// # Ok::<(), ndarray::ShapeError>(())
1155/// ```
1156///
1157/// Note that this implementation assumes that the nested `Vec`s are all the
1158/// same shape and that the `Vec` is non-empty. Depending on your application,
1159/// it may be a good idea to add checks for these assumptions and possibly
1160/// choose a different way to handle the empty case.
1161///
1162// # For implementors
1163//
1164// All methods must uphold the following constraints:
1165//
1166// 1. `data` must correctly represent the data buffer / ownership information,
1167// `ptr` must point into the data represented by `data`, and the `dim` and
1168// `strides` must be consistent with `data`. For example,
1169//
1170// * If `data` is `OwnedRepr<A>`, all elements represented by `ptr`, `dim`,
1171// and `strides` must be owned by the `Vec` and not aliased by multiple
1172// indices.
1173//
1174// * If `data` is `ViewRepr<&'a mut A>`, all elements represented by `ptr`,
1175// `dim`, and `strides` must be exclusively borrowed and not aliased by
1176// multiple indices.
1177//
1178// 2. If the type of `data` implements `Data`, then `ptr` must be aligned.
1179//
1180// 3. `ptr` must be non-null, and it must be safe to [`.offset()`] `ptr` by
1181// zero.
1182//
1183// 4. It must be safe to [`.offset()`] the pointer repeatedly along all axes
1184// and calculate the `count`s for the `.offset()` calls without overflow,
1185// even if the array is empty or the elements are zero-sized.
1186//
1187// More specifically, the set of all possible (signed) offset counts
1188// relative to `ptr` can be determined by the following (the casts and
1189// arithmetic must not overflow):
1190//
1191// ```rust
1192// /// Returns all the possible offset `count`s relative to `ptr`.
1193// fn all_offset_counts(shape: &[usize], strides: &[isize]) -> BTreeSet<isize> {
1194// assert_eq!(shape.len(), strides.len());
1195// let mut all_offsets = BTreeSet::<isize>::new();
1196// all_offsets.insert(0);
1197// for axis in 0..shape.len() {
1198// let old_offsets = all_offsets.clone();
1199// for index in 0..shape[axis] {
1200// assert!(index <= isize::MAX as usize);
1201// let off = (index as isize).checked_mul(strides[axis]).unwrap();
1202// for &old_offset in &old_offsets {
1203// all_offsets.insert(old_offset.checked_add(off).unwrap());
1204// }
1205// }
1206// }
1207// all_offsets
1208// }
1209// ```
1210//
1211// Note that it must be safe to offset the pointer *repeatedly* along all
1212// axes, so in addition for it being safe to offset `ptr` by each of these
1213// counts, the difference between the least and greatest address reachable
1214// by these offsets in units of `A` and in units of bytes must not be
1215// greater than `isize::MAX`.
1216//
1217// In other words,
1218//
1219// * All possible pointers generated by moving along all axes must be in
1220// bounds or one byte past the end of a single allocation with element
1221// type `A`. The only exceptions are if the array is empty or the element
1222// type is zero-sized. In these cases, `ptr` may be dangling, but it must
1223// still be safe to [`.offset()`] the pointer along the axes.
1224//
1225// * The offset in units of bytes between the least address and greatest
1226// address by moving along all axes must not exceed `isize::MAX`. This
1227// constraint prevents the computed offset, in bytes, from overflowing
1228// `isize` regardless of the starting point due to past offsets.
1229//
1230// * The offset in units of `A` between the least address and greatest
1231// address by moving along all axes must not exceed `isize::MAX`. This
1232// constraint prevents overflow when calculating the `count` parameter to
1233// [`.offset()`] regardless of the starting point due to past offsets.
1234//
1235// For example, if the shape is [2, 0, 3] and the strides are [3, 6, -1],
1236// the offsets of interest relative to `ptr` are -2, -1, 0, 1, 2, 3. So,
1237// `ptr.offset(-2)`, `ptr.offset(-1)`, …, `ptr.offset(3)` must be pointers
1238// within a single allocation with element type `A`; `(3 - (-2)) *
1239// size_of::<A>()` must not exceed `isize::MAX`, and `3 - (-2)` must not
1240// exceed `isize::MAX`. Note that this is a requirement even though the
1241// array is empty (axis 1 has length 0).
1242//
1243// A dangling pointer can be used when creating an empty array, but this
1244// usually means all the strides have to be zero. A dangling pointer that
1245// can safely be offset by zero bytes can be constructed with
1246// `::std::ptr::NonNull::<A>::dangling().as_ptr()`. (It isn't entirely clear
1247// from the documentation that a pointer created this way is safe to
1248// `.offset()` at all, even by zero bytes, but the implementation of
1249// `Vec<A>` does this, so we can too. See rust-lang/rust#54857 for details.)
1250//
1251// 5. The product of non-zero axis lengths must not exceed `isize::MAX`. (This
1252// also implies that the length of any individual axis must not exceed
1253// `isize::MAX`, and an array can contain at most `isize::MAX` elements.)
1254// This constraint makes various calculations easier because they don't have
1255// to worry about overflow and axis lengths can be freely cast to `isize`.
1256//
1257// Constraints 2–5 are carefully designed such that if they're upheld for the
1258// array, they're also upheld for any subset of axes of the array as well as
1259// slices/subviews/reshapes of the array. This is important for iterators that
1260// produce subviews (and other similar cases) to be safe without extra (easy to
1261// forget) checks for zero-length axes. Constraint 1 is similarly upheld for
1262// any subset of axes and slices/subviews/reshapes, except when removing a
1263// zero-length axis (since if the other axes are non-zero-length, that would
1264// allow accessing elements that should not be possible to access).
1265//
1266// Method/function implementations can rely on these constraints being upheld.
1267// The constraints can be temporarily violated within a method/function
1268// implementation since `ArrayBase` doesn't implement `Drop` and `&mut
1269// ArrayBase` is `!UnwindSafe`, but the implementation must not call
1270// methods/functions on the array while it violates the constraints.
1271//
1272// Users of the `ndarray` crate cannot rely on these constraints because they
1273// may change in the future.
1274//
1275// [`.offset()`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset-1
1276pub struct ArrayBase<S, D>
1277where
1278 S: RawData,
1279{
1280 /// Data buffer / ownership information. (If owned, contains the data
1281 /// buffer; if borrowed, contains the lifetime and mutability.)
1282 data: S,
1283 /// A non-null pointer into the buffer held by `data`; may point anywhere
1284 /// in its range. If `S: Data`, this pointer must be aligned.
1285 ptr: std::ptr::NonNull<S::Elem>,
1286 /// The lengths of the axes.
1287 dim: D,
1288 /// The element count stride per axis. To be parsed as `isize`.
1289 strides: D,
1290}
1291
1292/// An array where the data has shared ownership and is copy on write.
1293///
1294/// The `ArcArray<A, D>` is parameterized by `A` for the element type and `D` for
1295/// the dimensionality.
1296///
1297/// It can act as both an owner as the data as well as a shared reference (view
1298/// like).
1299/// Calling a method for mutating elements on `ArcArray`, for example
1300/// [`view_mut()`](struct.ArrayBase.html#method.view_mut) or
1301/// [`get_mut()`](struct.ArrayBase.html#method.get_mut), will break sharing and
1302/// require a clone of the data (if it is not uniquely held).
1303///
1304/// `ArcArray` uses atomic reference counting like `Arc`, so it is `Send` and
1305/// `Sync` (when allowed by the element type of the array too).
1306///
1307/// [**`ArrayBase`**](struct.ArrayBase.html) is used to implement both the owned
1308/// arrays and the views; see its docs for an overview of all array features.
1309///
1310/// See also:
1311///
1312/// + [Constructor Methods for Owned Arrays](struct.ArrayBase.html#constructor-methods-for-owned-arrays)
1313/// + [Methods For All Array Types](struct.ArrayBase.html#methods-for-all-array-types)
1314pub type ArcArray<A, D> = ArrayBase<OwnedArcRepr<A>, D>;
1315
1316/// An array that owns its data uniquely.
1317///
1318/// `Array` is the main n-dimensional array type, and it owns all its array
1319/// elements.
1320///
1321/// The `Array<A, D>` is parameterized by `A` for the element type and `D` for
1322/// the dimensionality.
1323///
1324/// [**`ArrayBase`**](struct.ArrayBase.html) is used to implement both the owned
1325/// arrays and the views; see its docs for an overview of all array features.
1326///
1327/// See also:
1328///
1329/// + [Constructor Methods for Owned Arrays](struct.ArrayBase.html#constructor-methods-for-owned-arrays)
1330/// + [Methods For All Array Types](struct.ArrayBase.html#methods-for-all-array-types)
1331/// + Dimensionality-specific type alises
1332/// [`Array1`](type.Array1.html),
1333/// [`Array2`](type.Array2.html),
1334/// [`Array3`](type.Array3.html), ...,
1335/// [`ArrayD`](type.ArrayD.html),
1336/// and so on.
1337pub type Array<A, D> = ArrayBase<OwnedRepr<A>, D>;
1338
1339/// An array with copy-on-write behavior.
1340///
1341/// An `CowArray` represents either a uniquely owned array or a view of an
1342/// array. The `'a` corresponds to the lifetime of the view variant.
1343///
1344/// This type is analogous to
1345/// [`std::borrow::Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html).
1346/// If a `CowArray` instance is the immutable view variant, then calling a
1347/// method for mutating elements in the array will cause it to be converted
1348/// into the owned variant (by cloning all the elements) before the
1349/// modification is performed.
1350///
1351/// Array views have all the methods of an array (see [`ArrayBase`][ab]).
1352///
1353/// See also [`ArcArray`](type.ArcArray.html), which also provides
1354/// copy-on-write behavior but has a reference-counted pointer to the data
1355/// instead of either a view or a uniquely owned copy.
1356///
1357/// [ab]: struct.ArrayBase.html
1358pub type CowArray<'a, A, D> = ArrayBase<CowRepr<'a, A>, D>;
1359
1360/// A read-only array view.
1361///
1362/// An array view represents an array or a part of it, created from
1363/// an iterator, subview or slice of an array.
1364///
1365/// The `ArrayView<'a, A, D>` is parameterized by `'a` for the scope of the
1366/// borrow, `A` for the element type and `D` for the dimensionality.
1367///
1368/// Array views have all the methods of an array (see [`ArrayBase`][ab]).
1369///
1370/// See also [`ArrayViewMut`](type.ArrayViewMut.html).
1371///
1372/// [ab]: struct.ArrayBase.html
1373pub type ArrayView<'a, A, D> = ArrayBase<ViewRepr<&'a A>, D>;
1374
1375/// A read-write array view.
1376///
1377/// An array view represents an array or a part of it, created from
1378/// an iterator, subview or slice of an array.
1379///
1380/// The `ArrayViewMut<'a, A, D>` is parameterized by `'a` for the scope of the
1381/// borrow, `A` for the element type and `D` for the dimensionality.
1382///
1383/// Array views have all the methods of an array (see [`ArrayBase`][ab]).
1384///
1385/// See also [`ArrayView`](type.ArrayView.html).
1386///
1387/// [ab]: struct.ArrayBase.html
1388pub type ArrayViewMut<'a, A, D> = ArrayBase<ViewRepr<&'a mut A>, D>;
1389
1390/// A read-only array view without a lifetime.
1391///
1392/// This is similar to [`ArrayView`] but does not carry any lifetime or
1393/// ownership information, and its data cannot be read without an unsafe
1394/// conversion into an [`ArrayView`]. The relationship between `RawArrayView`
1395/// and [`ArrayView`] is somewhat analogous to the relationship between `*const
1396/// T` and `&T`, but `RawArrayView` has additional requirements that `*const T`
1397/// does not, such as non-nullness.
1398///
1399/// [`ArrayView`]: type.ArrayView.html
1400///
1401/// The `RawArrayView<A, D>` is parameterized by `A` for the element type and
1402/// `D` for the dimensionality.
1403///
1404/// Raw array views have all the methods of an array (see
1405/// [`ArrayBase`](struct.ArrayBase.html)).
1406///
1407/// See also [`RawArrayViewMut`](type.RawArrayViewMut.html).
1408///
1409/// # Warning
1410///
1411/// You can't use this type with an arbitrary raw pointer; see
1412/// [`from_shape_ptr`](#method.from_shape_ptr) for details.
1413pub type RawArrayView<A, D> = ArrayBase<RawViewRepr<*const A>, D>;
1414
1415/// A mutable array view without a lifetime.
1416///
1417/// This is similar to [`ArrayViewMut`] but does not carry any lifetime or
1418/// ownership information, and its data cannot be read/written without an
1419/// unsafe conversion into an [`ArrayViewMut`]. The relationship between
1420/// `RawArrayViewMut` and [`ArrayViewMut`] is somewhat analogous to the
1421/// relationship between `*mut T` and `&mut T`, but `RawArrayViewMut` has
1422/// additional requirements that `*mut T` does not, such as non-nullness.
1423///
1424/// [`ArrayViewMut`]: type.ArrayViewMut.html
1425///
1426/// The `RawArrayViewMut<A, D>` is parameterized by `A` for the element type
1427/// and `D` for the dimensionality.
1428///
1429/// Raw array views have all the methods of an array (see
1430/// [`ArrayBase`](struct.ArrayBase.html)).
1431///
1432/// See also [`RawArrayView`](type.RawArrayView.html).
1433///
1434/// # Warning
1435///
1436/// You can't use this type with an arbitrary raw pointer; see
1437/// [`from_shape_ptr`](#method.from_shape_ptr) for details.
1438pub type RawArrayViewMut<A, D> = ArrayBase<RawViewRepr<*mut A>, D>;
1439
1440pub use data_repr::OwnedRepr;
1441
1442/// ArcArray's representation.
1443///
1444/// *Don’t use this type directly—use the type alias
1445/// [`ArcArray`](type.ArcArray.html) for the array type!*
1446#[derive(Debug)]
1447pub struct OwnedArcRepr<A>(Arc<OwnedRepr<A>>);
1448
1449impl<A> Clone for OwnedArcRepr<A> {
1450 fn clone(&self) -> Self {
1451 OwnedArcRepr(self.0.clone())
1452 }
1453}
1454
1455/// Array pointer’s representation.
1456///
1457/// *Don’t use this type directly—use the type aliases
1458/// [`RawArrayView`](type.RawArrayView.html) /
1459/// [`RawArrayViewMut`](type.RawArrayViewMut.html) for the array type!*
1460#[derive(Copy, Clone)]
1461// This is just a marker type, to carry the mutability and element type.
1462pub struct RawViewRepr<A> {
1463 ptr: PhantomData<A>,
1464}
1465
1466impl<A> RawViewRepr<A> {
1467 #[inline(always)]
1468 fn new() -> Self {
1469 RawViewRepr { ptr: PhantomData }
1470 }
1471}
1472
1473/// Array view’s representation.
1474///
1475/// *Don’t use this type directly—use the type aliases
1476/// [`ArrayView`](type.ArrayView.html)
1477/// / [`ArrayViewMut`](type.ArrayViewMut.html) for the array type!*
1478#[derive(Copy, Clone)]
1479// This is just a marker type, to carry the lifetime parameter.
1480pub struct ViewRepr<A> {
1481 life: PhantomData<A>,
1482}
1483
1484impl<A> ViewRepr<A> {
1485 #[inline(always)]
1486 fn new() -> Self {
1487 ViewRepr { life: PhantomData }
1488 }
1489}
1490
1491/// CowArray's representation.
1492///
1493/// *Don't use this type directly—use the type alias
1494/// [`CowArray`](type.CowArray.html) for the array type!*
1495pub enum CowRepr<'a, A> {
1496 /// Borrowed data.
1497 View(ViewRepr<&'a A>),
1498 /// Owned data.
1499 Owned(OwnedRepr<A>),
1500}
1501
1502impl<'a, A> CowRepr<'a, A> {
1503 /// Returns `true` iff the data is the `View` variant.
1504 pub fn is_view(&self) -> bool {
1505 match self {
1506 CowRepr::View(_) => true,
1507 CowRepr::Owned(_) => false,
1508 }
1509 }
1510
1511 /// Returns `true` iff the data is the `Owned` variant.
1512 pub fn is_owned(&self) -> bool {
1513 match self {
1514 CowRepr::View(_) => false,
1515 CowRepr::Owned(_) => true,
1516 }
1517 }
1518}
1519
1520// NOTE: The order of modules decides in which order methods on the type ArrayBase
1521// (mainly mentioning that as the most relevant type) show up in the documentation.
1522// Consider the doc effect of ordering modules here.
1523mod impl_clone;
1524
1525mod impl_internal_constructors;
1526mod impl_constructors;
1527
1528mod impl_methods;
1529mod impl_owned_array;
1530mod impl_special_element_types;
1531
1532/// Private Methods
1533impl<A, S, D> ArrayBase<S, D>
1534where
1535 S: Data<Elem = A>,
1536 D: Dimension,
1537{
1538 #[inline]
1539 fn broadcast_unwrap<E>(&self, dim: E) -> ArrayView<'_, A, E>
1540 where
1541 E: Dimension,
1542 {
1543 #[cold]
1544 #[inline(never)]
1545 fn broadcast_panic<D, E>(from: &D, to: &E) -> !
1546 where
1547 D: Dimension,
1548 E: Dimension,
1549 {
1550 panic!(
1551 "ndarray: could not broadcast array from shape: {:?} to: {:?}",
1552 from.slice(),
1553 to.slice()
1554 )
1555 }
1556
1557 match self.broadcast(dim.clone()) {
1558 Some(it) => it,
1559 None => broadcast_panic(&self.dim, &dim),
1560 }
1561 }
1562
1563 // Broadcast to dimension `E`, without checking that the dimensions match
1564 // (Checked in debug assertions).
1565 #[inline]
1566 fn broadcast_assume<E>(&self, dim: E) -> ArrayView<'_, A, E>
1567 where
1568 E: Dimension,
1569 {
1570 let dim = dim.into_dimension();
1571 debug_assert_eq!(self.shape(), dim.slice());
1572 let ptr = self.ptr;
1573 let mut strides = dim.clone();
1574 strides.slice_mut().copy_from_slice(self.strides.slice());
1575 unsafe { ArrayView::new(ptr, dim, strides) }
1576 }
1577
1578 fn raw_strides(&self) -> D {
1579 self.strides.clone()
1580 }
1581
1582 /// Remove array axis `axis` and return the result.
1583 fn try_remove_axis(self, axis: Axis) -> ArrayBase<S, D::Smaller> {
1584 let d = self.dim.try_remove_axis(axis);
1585 let s = self.strides.try_remove_axis(axis);
1586 // safe because new dimension, strides allow access to a subset of old data
1587 unsafe {
1588 self.with_strides_dim(s, d)
1589 }
1590 }
1591
1592 /// n-d generalization of rows, just like inner iter
1593 fn inner_rows(&self) -> iterators::Lanes<'_, A, D::Smaller> {
1594 let n = self.ndim();
1595 Lanes::new(self.view(), Axis(n.saturating_sub(1)))
1596 }
1597}
1598
1599// parallel methods
1600#[cfg(feature = "rayon")]
1601extern crate rayon_ as rayon;
1602#[cfg(feature = "rayon")]
1603pub mod parallel;
1604
1605mod impl_1d;
1606mod impl_2d;
1607mod impl_dyn;
1608
1609mod numeric;
1610
1611pub mod linalg;
1612
1613mod impl_ops;
1614pub use crate::impl_ops::ScalarOperand;
1615
1616#[cfg(feature = "approx")]
1617mod array_approx;
1618
1619// Array view methods
1620mod impl_views;
1621
1622// Array raw view methods
1623mod impl_raw_views;
1624
1625// Copy-on-write array methods
1626mod impl_cow;
1627
1628/// Returns `true` if the pointer is aligned.
1629pub(crate) fn is_aligned<T>(ptr: *const T) -> bool {
1630 (ptr as usize) % ::std::mem::align_of::<T>() == 0
1631}