-
Notifications
You must be signed in to change notification settings - Fork 308
/
lib.rs
1625 lines (1563 loc) · 54.3 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014-2020 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_name = "ndarray"]
#![doc(html_root_url = "https://docs.rs/ndarray/0.15/")]
#![doc(html_logo_url = "https://rust-ndarray.github.io/images/rust-ndarray_logo.svg")]
#![allow(
unstable_name_collisions, // our `PointerExt` collides with upcoming inherent methods on `NonNull`
clippy::deref_addrof,
clippy::manual_map, // is not an error
clippy::while_let_on_iterator, // is not an error
clippy::from_iter_instead_of_collect, // using from_iter is good style
clippy::incompatible_msrv, // false positive PointerExt::offset
)]
#![doc(test(attr(deny(warnings))))]
#![doc(test(attr(allow(unused_variables))))]
#![doc(test(attr(allow(deprecated))))]
#![cfg_attr(not(feature = "std"), no_std)]
//! The `ndarray` crate provides an *n*-dimensional container for general elements
//! and for numerics.
//!
//! In *n*-dimensional we include, for example, 1-dimensional rows or columns,
//! 2-dimensional matrices, and higher dimensional arrays. If the array has *n*
//! dimensions, then an element in the array is accessed by using that many indices.
//! Each dimension is also called an *axis*.
//!
//! - **[`ArrayBase`]**:
//! The *n*-dimensional array type itself.<br>
//! It is used to implement both the owned arrays and the views; see its docs
//! for an overview of all array features.<br>
//! - The main specific array type is **[`Array`]**, which owns
//! its elements.
//!
//! ## Highlights
//!
//! - Generic *n*-dimensional array
//! - [Slicing](ArrayBase#slicing), also with arbitrary step size, and negative
//! indices to mean elements from the end of the axis.
//! - Views and subviews of arrays; iterators that yield subviews.
//! - Higher order operations and arithmetic are performant
//! - Array views can be used to slice and mutate any `[T]` data using
//! `ArrayView::from` and `ArrayViewMut::from`.
//! - [`Zip`] for lock step function application across two or more arrays or other
//! item producers ([`NdProducer`] trait).
//!
//! ## Crate Status
//!
//! - Still iterating on and evolving the crate
//! + The crate is continuously developing, and breaking changes are expected
//! during evolution from version to version. We adopt the newest stable
//! rust features if we need them.
//! + Note that functions/methods/traits/etc. hidden from the docs are not
//! considered part of the public API, so changes to them are not
//! considered breaking changes.
//! - Performance:
//! + Prefer higher order methods and arithmetic operations on arrays first,
//! then iteration, and as a last priority using indexed algorithms.
//! + The higher order functions like [`.map()`](ArrayBase::map),
//! [`.map_inplace()`](ArrayBase::map_inplace), [`.zip_mut_with()`](ArrayBase::zip_mut_with),
//! [`Zip`] and [`azip!()`](azip) are the most efficient ways
//! to perform single traversal and lock step traversal respectively.
//! + Performance of an operation depends on the memory layout of the array
//! or array view. Especially if it's a binary operation, which
//! needs matching memory layout to be efficient (with some exceptions).
//! + Efficient floating point matrix multiplication even for very large
//! matrices; can optionally use BLAS to improve it further.
//!
//! - **MSRV: Requires Rust 1.64 or later**
//!
//! ## Crate Feature Flags
//!
//! The following crate feature flags are available. They are configured in your
//! `Cargo.toml`. See [`doc::crate_feature_flags`] for more information.
//!
//! - `std`: Rust standard library-using functionality (enabled by default)
//! - `serde`: serialization support for serde 1.x
//! - `rayon`: Parallel iterators, parallelized methods, the [`parallel`] module and [`par_azip!`].
//! - `approx` Implementations of traits from the [`approx`] crate.
//! - `blas`: transparent BLAS support for matrix multiplication, needs configuration.
//! - `matrixmultiply-threading`: Use threading from `matrixmultiply`.
//!
//! ## Documentation
//!
//! * The docs for [`ArrayBase`] provide an overview of
//! the *n*-dimensional array type. Other good pages to look at are the
//! documentation for the [`s![]`](s!) and
//! [`azip!()`](azip!) macros.
//!
//! * If you have experience with NumPy, you may also be interested in
//! [`ndarray_for_numpy_users`](doc::ndarray_for_numpy_users).
//!
//! ## The ndarray ecosystem
//!
//! `ndarray` provides a lot of functionality, but it's not a one-stop solution.
//!
//! `ndarray` includes matrix multiplication and other binary/unary operations out of the box.
//! More advanced linear algebra routines (e.g. SVD decomposition or eigenvalue computation)
//! can be found in [`ndarray-linalg`](https://crates.io/crates/ndarray-linalg).
//!
//! The same holds for statistics: `ndarray` provides some basic functionalities (e.g. `mean`)
//! but more advanced routines can be found in [`ndarray-stats`](https://crates.io/crates/ndarray-stats).
//!
//! If you are looking to generate random arrays instead, check out [`ndarray-rand`](https://crates.io/crates/ndarray-rand).
//!
//! For conversion between `ndarray`, [`nalgebra`](https://crates.io/crates/nalgebra) and
//! [`image`](https://crates.io/crates/image) check out [`nshare`](https://crates.io/crates/nshare).
extern crate alloc;
#[cfg(not(feature = "std"))]
extern crate core as std;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "blas")]
extern crate cblas_sys;
#[cfg(feature = "docs")]
pub mod doc;
#[cfg(target_has_atomic = "ptr")]
use alloc::sync::Arc;
#[cfg(not(target_has_atomic = "ptr"))]
use portable_atomic_util::Arc;
use std::marker::PhantomData;
pub use crate::dimension::dim::*;
pub use crate::dimension::{Axis, AxisDescription, Dimension, IntoDimension, RemoveAxis};
pub use crate::dimension::{DimAdd, DimMax};
pub use crate::dimension::IxDynImpl;
pub use crate::dimension::NdIndex;
pub use crate::error::{ErrorKind, ShapeError};
pub use crate::indexes::{indices, indices_of};
pub use crate::order::Order;
pub use crate::slice::{MultiSliceArg, NewAxis, Slice, SliceArg, SliceInfo, SliceInfoElem, SliceNextDim};
use crate::iterators::Baseiter;
use crate::iterators::{ElementsBase, ElementsBaseMut, Iter, IterMut};
pub use crate::arraytraits::AsArray;
pub use crate::linalg_traits::LinalgScalar;
#[cfg(feature = "std")]
pub use crate::linalg_traits::NdFloat;
pub use crate::stacking::{concatenate, stack};
pub use crate::impl_views::IndexLonger;
pub use crate::math_cell::MathCell;
pub use crate::shape_builder::{Shape, ShapeArg, ShapeBuilder, StrideShape};
#[macro_use]
mod macro_utils;
#[macro_use]
mod private;
mod aliases;
#[macro_use]
mod itertools;
mod argument_traits;
#[cfg(feature = "serde")]
mod array_serde;
mod arrayformat;
mod arraytraits;
pub use crate::argument_traits::AssignElem;
mod data_repr;
mod data_traits;
pub use crate::aliases::*;
pub use crate::data_traits::{Data, DataMut, DataOwned, DataShared, RawData, RawDataClone, RawDataMut, RawDataSubst};
mod free_functions;
pub use crate::free_functions::*;
pub use crate::iterators::iter;
mod error;
mod extension;
mod geomspace;
mod indexes;
mod iterators;
mod layout;
mod linalg_traits;
mod linspace;
#[cfg(feature = "std")]
pub use crate::linspace::{linspace, range, Linspace};
mod logspace;
#[cfg(feature = "std")]
pub use crate::logspace::{logspace, Logspace};
mod math_cell;
mod numeric_util;
mod order;
mod partial;
mod shape_builder;
#[macro_use]
mod slice;
mod split_at;
mod stacking;
mod low_level_util;
#[macro_use]
mod zip;
mod dimension;
pub use crate::zip::{FoldWhile, IntoNdProducer, NdProducer, Zip};
pub use crate::layout::Layout;
/// Implementation's prelude. Common types used everywhere.
mod imp_prelude
{
pub use crate::dimension::DimensionExt;
pub use crate::prelude::*;
pub use crate::ArcArray;
pub use crate::{
CowRepr,
Data,
DataMut,
DataOwned,
DataShared,
Ix,
Ixs,
RawData,
RawDataMut,
RawViewRepr,
RemoveAxis,
ViewRepr,
};
}
pub mod prelude;
/// Array index type
pub type Ix = usize;
/// Array index type (signed)
pub type Ixs = isize;
/// An *n*-dimensional array.
///
/// The array is a general container of elements.
/// The array supports arithmetic operations by applying them elementwise, if the
/// elements are numeric, but it supports non-numeric elements too.
///
/// The arrays rarely grow or shrink, since those operations can be costly. On
/// the other hand there is a rich set of methods and operations for taking views,
/// slices, and making traversals over one or more arrays.
///
/// In *n*-dimensional we include for example 1-dimensional rows or columns,
/// 2-dimensional matrices, and higher dimensional arrays. If the array has *n*
/// dimensions, then an element is accessed by using that many indices.
///
/// The `ArrayBase<S, D>` is parameterized by `S` for the data container and
/// `D` for the dimensionality.
///
/// Type aliases [`Array`], [`ArcArray`], [`CowArray`], [`ArrayView`], and
/// [`ArrayViewMut`] refer to `ArrayBase` with different types for the data
/// container: arrays with different kinds of ownership or different kinds of array views.
///
/// ## Contents
///
/// + [Array](#array)
/// + [ArcArray](#arcarray)
/// + [CowArray](#cowarray)
/// + [Array Views](#array-views)
/// + [Indexing and Dimension](#indexing-and-dimension)
/// + [Loops, Producers and Iterators](#loops-producers-and-iterators)
/// + [Slicing](#slicing)
/// + [Subviews](#subviews)
/// + [Arithmetic Operations](#arithmetic-operations)
/// + [Broadcasting](#broadcasting)
/// + [Conversions](#conversions)
/// + [Constructor Methods for Owned Arrays](#constructor-methods-for-owned-arrays)
/// + [Methods For All Array Types](#methods-for-all-array-types)
/// + [Methods For 1-D Arrays](#methods-for-1-d-arrays)
/// + [Methods For 2-D Arrays](#methods-for-2-d-arrays)
/// + [Methods for Dynamic-Dimensional Arrays](#methods-for-dynamic-dimensional-arrays)
/// + [Numerical Methods for Arrays](#numerical-methods-for-arrays)
///
/// ## `Array`
///
/// [`Array`] is an owned array that owns the underlying array
/// elements directly (just like a `Vec`) and it is the default way to create and
/// store n-dimensional data. `Array<A, D>` has two type parameters: `A` for
/// the element type, and `D` for the dimensionality. A particular
/// dimensionality's type alias like `Array3<A>` just has the type parameter
/// `A` for element type.
///
/// An example:
///
/// ```
/// // Create a three-dimensional f64 array, initialized with zeros
/// use ndarray::Array3;
/// let mut temperature = Array3::<f64>::zeros((3, 4, 5));
/// // Increase the temperature in this location
/// temperature[[2, 2, 2]] += 0.5;
/// ```
///
/// ## `ArcArray`
///
/// [`ArcArray`] is an owned array with reference counted
/// data (shared ownership).
/// Sharing requires that it uses copy-on-write for mutable operations.
/// Calling a method for mutating elements on `ArcArray`, for example
/// [`view_mut()`](Self::view_mut) or [`get_mut()`](Self::get_mut),
/// will break sharing and require a clone of the data (if it is not uniquely held).
///
/// ## `CowArray`
///
/// [`CowArray`] is analogous to [`std::borrow::Cow`].
/// It can represent either an immutable view or a uniquely owned array. If a
/// `CowArray` instance is the immutable view variant, then calling a method
/// for mutating elements in the array will cause it to be converted into the
/// owned variant (by cloning all the elements) before the modification is
/// performed.
///
/// ## Array Views
///
/// [`ArrayView`] and [`ArrayViewMut`] are read-only and read-write array views
/// respectively. They use dimensionality, indexing, and almost all other
/// methods the same way as the other array types.
///
/// Methods for `ArrayBase` apply to array views too, when the trait bounds
/// allow.
///
/// Please see the documentation for the respective array view for an overview
/// of methods specific to array views: [`ArrayView`], [`ArrayViewMut`].
///
/// A view is created from an array using [`.view()`](ArrayBase::view),
/// [`.view_mut()`](ArrayBase::view_mut), using
/// slicing ([`.slice()`](ArrayBase::slice), [`.slice_mut()`](ArrayBase::slice_mut)) or from one of
/// the many iterators that yield array views.
///
/// You can also create an array view from a regular slice of data not
/// allocated with `Array` — see array view methods or their `From` impls.
///
/// Note that all `ArrayBase` variants can change their view (slicing) of the
/// data freely, even when their data can’t be mutated.
///
/// ## Indexing and Dimension
///
/// The dimensionality of the array determines the number of *axes*, for example
/// a 2D array has two axes. These are listed in “big endian” order, so that
/// the greatest dimension is listed first, the lowest dimension with the most
/// rapidly varying index is the last.
///
/// In a 2D array the index of each element is `[row, column]` as seen in this
/// 4 × 3 example:
///
/// ```ignore
/// [[ [0, 0], [0, 1], [0, 2] ], // row 0
/// [ [1, 0], [1, 1], [1, 2] ], // row 1
/// [ [2, 0], [2, 1], [2, 2] ], // row 2
/// [ [3, 0], [3, 1], [3, 2] ]] // row 3
/// // \ \ \
/// // column 0 \ column 2
/// // column 1
/// ```
///
/// The number of axes for an array is fixed by its `D` type parameter: `Ix1`
/// for a 1D array, `Ix2` for a 2D array etc. The dimension type `IxDyn` allows
/// a dynamic number of axes.
///
/// A fixed size array (`[usize; N]`) of the corresponding dimensionality is
/// used to index the `Array`, making the syntax `array[[` i, j, ...`]]`
///
/// ```
/// use ndarray::Array2;
/// let mut array = Array2::zeros((4, 3));
/// array[[1, 1]] = 7;
/// ```
///
/// Important traits and types for dimension and indexing:
///
/// - A [`struct@Dim`] value represents a dimensionality or index.
/// - Trait [`Dimension`] is implemented by all
/// dimensionalities. It defines many operations for dimensions and indices.
/// - Trait [`IntoDimension`] is used to convert into a
/// `Dim` value.
/// - Trait [`ShapeBuilder`] is an extension of
/// `IntoDimension` and is used when constructing an array. A shape describes
/// not just the extent of each axis but also their strides.
/// - Trait [`NdIndex`] is an extension of `Dimension` and is
/// for values that can be used with indexing syntax.
///
///
/// The default memory order of an array is *row major* order (a.k.a “c” order),
/// where each row is contiguous in memory.
/// A *column major* (a.k.a. “f” or fortran) memory order array has
/// columns (or, in general, the outermost axis) with contiguous elements.
///
/// The logical order of any array’s elements is the row major order
/// (the rightmost index is varying the fastest).
/// The iterators `.iter(), .iter_mut()` always adhere to this order, for example.
///
/// ## Loops, Producers and Iterators
///
/// Using [`Zip`] is the most general way to apply a procedure
/// across one or several arrays or *producers*.
///
/// [`NdProducer`] is like an iterable but for
/// multidimensional data. All producers have dimensions and axes, like an
/// array view, and they can be split and used with parallelization using `Zip`.
///
/// For example, `ArrayView<A, D>` is a producer, it has the same dimensions
/// as the array view and for each iteration it produces a reference to
/// the array element (`&A` in this case).
///
/// Another example, if we have a 10 × 10 array and use `.exact_chunks((2, 2))`
/// we get a producer of chunks which has the dimensions 5 × 5 (because
/// there are *10 / 2 = 5* chunks in either direction). The 5 × 5 chunks producer
/// can be paired with any other producers of the same dimension with `Zip`, for
/// example 5 × 5 arrays.
///
/// ### `.iter()` and `.iter_mut()`
///
/// These are the element iterators of arrays and they produce an element
/// sequence in the logical order of the array, that means that the elements
/// will be visited in the sequence that corresponds to increasing the
/// last index first: *0, ..., 0, 0*; *0, ..., 0, 1*; *0, ...0, 2* and so on.
///
/// ### `.outer_iter()` and `.axis_iter()`
///
/// These iterators produce array views of one smaller dimension.
///
/// For example, for a 2D array, `.outer_iter()` will produce the 1D rows.
/// For a 3D array, `.outer_iter()` produces 2D subviews.
///
/// `.axis_iter()` is like `outer_iter()` but allows you to pick which
/// axis to traverse.
///
/// The `outer_iter` and `axis_iter` are one dimensional producers.
///
/// ## `.rows()`, `.columns()` and `.lanes()`
///
/// [`.rows()`][gr] is a producer (and iterable) of all rows in an array.
///
/// ```
/// use ndarray::Array;
///
/// // 1. Loop over the rows of a 2D array
/// let mut a = Array::zeros((10, 10));
/// for mut row in a.rows_mut() {
/// row.fill(1.);
/// }
///
/// // 2. Use Zip to pair each row in 2D `a` with elements in 1D `b`
/// use ndarray::Zip;
/// let mut b = Array::zeros(a.nrows());
///
/// Zip::from(a.rows())
/// .and(&mut b)
/// .for_each(|a_row, b_elt| {
/// *b_elt = a_row[a.ncols() - 1] - a_row[0];
/// });
/// ```
///
/// The *lanes* of an array are 1D segments along an axis and when pointed
/// along the last axis they are *rows*, when pointed along the first axis
/// they are *columns*.
///
/// A *m* × *n* array has *m* rows each of length *n* and conversely
/// *n* columns each of length *m*.
///
/// To generalize this, we say that an array of dimension *a* × *m* × *n*
/// has *a m* rows. It's composed of *a* times the previous array, so it
/// has *a* times as many rows.
///
/// All methods: [`.rows()`][gr], [`.rows_mut()`][grm],
/// [`.columns()`][gc], [`.columns_mut()`][gcm],
/// [`.lanes(axis)`][l], [`.lanes_mut(axis)`][lm].
///
/// [gr]: Self::rows
/// [grm]: Self::rows_mut
/// [gc]: Self::columns
/// [gcm]: Self::columns_mut
/// [l]: Self::lanes
/// [lm]: Self::lanes_mut
///
/// Yes, for 2D arrays `.rows()` and `.outer_iter()` have about the same
/// effect:
///
/// + `rows()` is a producer with *n* - 1 dimensions of 1 dimensional items
/// + `outer_iter()` is a producer with 1 dimension of *n* - 1 dimensional items
///
/// ## Slicing
///
/// You can use slicing to create a view of a subset of the data in
/// the array. Slicing methods include [`.slice()`], [`.slice_mut()`],
/// [`.slice_move()`], and [`.slice_collapse()`].
///
/// The slicing argument can be passed using the macro [`s![]`](s!),
/// which will be used in all examples. (The explicit form is an instance of
/// [`SliceInfo`] or another type which implements [`SliceArg`]; see their docs
/// for more information.)
///
/// If a range is used, the axis is preserved. If an index is used, that index
/// is selected and the axis is removed; this selects a subview. See
/// [*Subviews*](#subviews) for more information about subviews. If a
/// [`NewAxis`] instance is used, a new axis is inserted. Note that
/// [`.slice_collapse()`] panics on `NewAxis` elements and behaves like
/// [`.collapse_axis()`] by preserving the number of dimensions.
///
/// [`.slice()`]: Self::slice
/// [`.slice_mut()`]: Self::slice_mut
/// [`.slice_move()`]: Self::slice_move
/// [`.slice_collapse()`]: Self::slice_collapse
///
/// When slicing arrays with generic dimensionality, creating an instance of
/// [`SliceInfo`] to pass to the multi-axis slicing methods like [`.slice()`]
/// is awkward. In these cases, it's usually more convenient to use
/// [`.slice_each_axis()`]/[`.slice_each_axis_mut()`]/[`.slice_each_axis_inplace()`]
/// or to create a view and then slice individual axes of the view using
/// methods such as [`.slice_axis_inplace()`] and [`.collapse_axis()`].
///
/// [`.slice_each_axis()`]: Self::slice_each_axis
/// [`.slice_each_axis_mut()`]: Self::slice_each_axis_mut
/// [`.slice_each_axis_inplace()`]: Self::slice_each_axis_inplace
/// [`.slice_axis_inplace()`]: Self::slice_axis_inplace
/// [`.collapse_axis()`]: Self::collapse_axis
///
/// It's possible to take multiple simultaneous *mutable* slices with
/// [`.multi_slice_mut()`] or (for [`ArrayViewMut`] only)
/// [`.multi_slice_move()`].
///
/// [`.multi_slice_mut()`]: Self::multi_slice_mut
/// [`.multi_slice_move()`]: ArrayViewMut#method.multi_slice_move
///
/// ```
/// use ndarray::{arr2, arr3, s, ArrayBase, DataMut, Dimension, NewAxis, Slice};
///
/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
///
/// let a = arr3(&[[[ 1, 2, 3], // -- 2 rows \_
/// [ 4, 5, 6]], // -- /
/// [[ 7, 8, 9], // \_ 2 submatrices
/// [10, 11, 12]]]); // /
/// // 3 columns ..../.../.../
///
/// assert_eq!(a.shape(), &[2, 2, 3]);
///
/// // Let’s create a slice with
/// //
/// // - Both of the submatrices of the greatest dimension: `..`
/// // - Only the first row in each submatrix: `0..1`
/// // - Every element in each row: `..`
///
/// let b = a.slice(s![.., 0..1, ..]);
/// let c = arr3(&[[[ 1, 2, 3]],
/// [[ 7, 8, 9]]]);
/// assert_eq!(b, c);
/// assert_eq!(b.shape(), &[2, 1, 3]);
///
/// // Let’s create a slice with
/// //
/// // - Both submatrices of the greatest dimension: `..`
/// // - The last row in each submatrix: `-1..`
/// // - Row elements in reverse order: `..;-1`
/// let d = a.slice(s![.., -1.., ..;-1]);
/// let e = arr3(&[[[ 6, 5, 4]],
/// [[12, 11, 10]]]);
/// assert_eq!(d, e);
/// assert_eq!(d.shape(), &[2, 1, 3]);
///
/// // Let’s create a slice while selecting a subview and inserting a new axis with
/// //
/// // - Both submatrices of the greatest dimension: `..`
/// // - The last row in each submatrix, removing that axis: `-1`
/// // - Row elements in reverse order: `..;-1`
/// // - A new axis at the end.
/// let f = a.slice(s![.., -1, ..;-1, NewAxis]);
/// let g = arr3(&[[ [6], [5], [4]],
/// [[12], [11], [10]]]);
/// assert_eq!(f, g);
/// assert_eq!(f.shape(), &[2, 3, 1]);
///
/// // Let's take two disjoint, mutable slices of a matrix with
/// //
/// // - One containing all the even-index columns in the matrix
/// // - One containing all the odd-index columns in the matrix
/// let mut h = arr2(&[[0, 1, 2, 3],
/// [4, 5, 6, 7]]);
/// let (s0, s1) = h.multi_slice_mut((s![.., ..;2], s![.., 1..;2]));
/// let i = arr2(&[[0, 2],
/// [4, 6]]);
/// let j = arr2(&[[1, 3],
/// [5, 7]]);
/// assert_eq!(s0, i);
/// assert_eq!(s1, j);
///
/// // Generic function which assigns the specified value to the elements which
/// // have indices in the lower half along all axes.
/// fn fill_lower<S, D>(arr: &mut ArrayBase<S, D>, x: S::Elem)
/// where
/// S: DataMut,
/// S::Elem: Clone,
/// D: Dimension,
/// {
/// arr.slice_each_axis_mut(|ax| Slice::from(0..ax.len / 2)).fill(x);
/// }
/// fill_lower(&mut h, 9);
/// let k = arr2(&[[9, 9, 2, 3],
/// [4, 5, 6, 7]]);
/// assert_eq!(h, k);
/// ```
///
/// ## Subviews
///
/// Subview methods allow you to restrict the array view while removing one
/// axis from the array. Methods for selecting individual subviews include
/// [`.index_axis()`], [`.index_axis_mut()`], [`.index_axis_move()`], and
/// [`.index_axis_inplace()`]. You can also select a subview by using a single
/// index instead of a range when slicing. Some other methods, such as
/// [`.fold_axis()`], [`.axis_iter()`], [`.axis_iter_mut()`],
/// [`.outer_iter()`], and [`.outer_iter_mut()`] operate on all the subviews
/// along an axis.
///
/// A related method is [`.collapse_axis()`], which modifies the view in the
/// same way as [`.index_axis()`] except for removing the collapsed axis, since
/// it operates *in place*. The length of the axis becomes 1.
///
/// Methods for selecting an individual subview take two arguments: `axis` and
/// `index`.
///
/// [`.axis_iter()`]: Self::axis_iter
/// [`.axis_iter_mut()`]: Self::axis_iter_mut
/// [`.fold_axis()`]: Self::fold_axis
/// [`.index_axis()`]: Self::index_axis
/// [`.index_axis_inplace()`]: Self::index_axis_inplace
/// [`.index_axis_mut()`]: Self::index_axis_mut
/// [`.index_axis_move()`]: Self::index_axis_move
/// [`.collapse_axis()`]: Self::collapse_axis
/// [`.outer_iter()`]: Self::outer_iter
/// [`.outer_iter_mut()`]: Self::outer_iter_mut
///
/// ```
///
/// use ndarray::{arr3, aview1, aview2, s, Axis};
///
///
/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
///
/// let a = arr3(&[[[ 1, 2, 3], // \ axis 0, submatrix 0
/// [ 4, 5, 6]], // /
/// [[ 7, 8, 9], // \ axis 0, submatrix 1
/// [10, 11, 12]]]); // /
/// // \
/// // axis 2, column 0
///
/// assert_eq!(a.shape(), &[2, 2, 3]);
///
/// // Let’s take a subview along the greatest dimension (axis 0),
/// // taking submatrix 0, then submatrix 1
///
/// let sub_0 = a.index_axis(Axis(0), 0);
/// let sub_1 = a.index_axis(Axis(0), 1);
///
/// assert_eq!(sub_0, aview2(&[[ 1, 2, 3],
/// [ 4, 5, 6]]));
/// assert_eq!(sub_1, aview2(&[[ 7, 8, 9],
/// [10, 11, 12]]));
/// assert_eq!(sub_0.shape(), &[2, 3]);
///
/// // This is the subview picking only axis 2, column 0
/// let sub_col = a.index_axis(Axis(2), 0);
///
/// assert_eq!(sub_col, aview2(&[[ 1, 4],
/// [ 7, 10]]));
///
/// // You can take multiple subviews at once (and slice at the same time)
/// let double_sub = a.slice(s![1, .., 0]);
/// assert_eq!(double_sub, aview1(&[7, 10]));
/// ```
///
/// ## Arithmetic Operations
///
/// Arrays support all arithmetic operations the same way: they apply elementwise.
///
/// Since the trait implementations are hard to overview, here is a summary.
///
/// ### Binary Operators with Two Arrays
///
/// Let `A` be an array or view of any kind. Let `B` be an array
/// with owned storage (either `Array` or `ArcArray`).
/// Let `C` be an array with mutable data (either `Array`, `ArcArray`
/// or `ArrayViewMut`).
/// The following combinations of operands
/// are supported for an arbitrary binary operator denoted by `@` (it can be
/// `+`, `-`, `*`, `/` and so on).
///
/// - `&A @ &A` which produces a new `Array`
/// - `B @ A` which consumes `B`, updates it with the result, and returns it
/// - `B @ &A` which consumes `B`, updates it with the result, and returns it
/// - `C @= &A` which performs an arithmetic operation in place
///
/// Note that the element type needs to implement the operator trait and the
/// `Clone` trait.
///
/// ```
/// use ndarray::{array, ArrayView1};
///
/// let owned1 = array![1, 2];
/// let owned2 = array![3, 4];
/// let view1 = ArrayView1::from(&[5, 6]);
/// let view2 = ArrayView1::from(&[7, 8]);
/// let mut mutable = array![9, 10];
///
/// let sum1 = &view1 + &view2; // Allocates a new array. Note the explicit `&`.
/// // let sum2 = view1 + &view2; // This doesn't work because `view1` is not an owned array.
/// let sum3 = owned1 + view1; // Consumes `owned1`, updates it, and returns it.
/// let sum4 = owned2 + &view2; // Consumes `owned2`, updates it, and returns it.
/// mutable += &view2; // Updates `mutable` in-place.
/// ```
///
/// ### Binary Operators with Array and Scalar
///
/// The trait [`ScalarOperand`] marks types that can be used in arithmetic
/// with arrays directly. For a scalar `K` the following combinations of operands
/// are supported (scalar can be on either the left or right side, but
/// `ScalarOperand` docs has the detailed conditions).
///
/// - `&A @ K` or `K @ &A` which produces a new `Array`
/// - `B @ K` or `K @ B` which consumes `B`, updates it with the result and returns it
/// - `C @= K` which performs an arithmetic operation in place
///
/// ### Unary Operators
///
/// Let `A` be an array or view of any kind. Let `B` be an array with owned
/// storage (either `Array` or `ArcArray`). The following operands are supported
/// for an arbitrary unary operator denoted by `@` (it can be `-` or `!`).
///
/// - `@&A` which produces a new `Array`
/// - `@B` which consumes `B`, updates it with the result, and returns it
///
/// ## Broadcasting
///
/// Arrays support limited *broadcasting*, where arithmetic operations with
/// array operands of different sizes can be carried out by repeating the
/// elements of the smaller dimension array. See
/// [`.broadcast()`](Self::broadcast) for a more detailed
/// description.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 1.],
/// [1., 2.],
/// [0., 3.],
/// [0., 4.]]);
///
/// let b = arr2(&[[0., 1.]]);
///
/// let c = arr2(&[[1., 2.],
/// [1., 3.],
/// [0., 4.],
/// [0., 5.]]);
/// // We can add because the shapes are compatible even if not equal.
/// // The `b` array is shape 1 × 2 but acts like a 4 × 2 array.
/// assert!(
/// c == a + b
/// );
/// ```
///
/// ## Conversions
///
/// ### Conversions Between Array Types
///
/// This table is a summary of the conversions between arrays of different
/// ownership, dimensionality, and element type. All of the conversions in this
/// table preserve the shape of the array.
///
/// <table>
/// <tr>
/// <th rowspan="2">Output</th>
/// <th colspan="5">Input</th>
/// </tr>
///
/// <tr>
/// <td>
///
/// `Array<A, D>`
///
/// </td>
/// <td>
///
/// `ArcArray<A, D>`
///
/// </td>
/// <td>
///
/// `CowArray<'a, A, D>`
///
/// </td>
/// <td>
///
/// `ArrayView<'a, A, D>`
///
/// </td>
/// <td>
///
/// `ArrayViewMut<'a, A, D>`
///
/// </td>
/// </tr>
///
/// <!--Conversions to `Array<A, D>`-->
///
/// <tr>
/// <td>
///
/// `Array<A, D>`
///
/// </td>
/// <td>
///
/// no-op
///
/// </td>
/// <td>
///
/// [`a.into_owned()`][.into_owned()]
///
/// </td>
/// <td>
///
/// [`a.into_owned()`][.into_owned()]
///
/// </td>
/// <td>
///
/// [`a.to_owned()`][.to_owned()]
///
/// </td>
/// <td>
///
/// [`a.to_owned()`][.to_owned()]
///
/// </td>
/// </tr>
///
/// <!--Conversions to `ArcArray<A, D>`-->
///
/// <tr>
/// <td>
///
/// `ArcArray<A, D>`
///
/// </td>
/// <td>
///
/// [`a.into_shared()`][.into_shared()]
///
/// </td>
/// <td>
///
/// no-op
///
/// </td>
/// <td>
///
/// [`a.into_owned().into_shared()`][.into_shared()]
///
/// </td>
/// <td>
///
/// [`a.to_owned().into_shared()`][.into_shared()]
///
/// </td>
/// <td>
///
/// [`a.to_owned().into_shared()`][.into_shared()]
///
/// </td>
/// </tr>
///
/// <!--Conversions to `CowArray<'a, A, D>`-->
///
/// <tr>
/// <td>
///
/// `CowArray<'a, A, D>`
///
/// </td>
/// <td>
///
/// [`CowArray::from(a)`](CowArray#impl-From<ArrayBase<OwnedRepr<A>%2C%20D>>)
///
/// </td>
/// <td>
///
/// [`CowArray::from(a.into_owned())`](CowArray#impl-From<ArrayBase<OwnedRepr<A>%2C%20D>>)
///
/// </td>
/// <td>
///
/// no-op
///
/// </td>
/// <td>
///
/// [`CowArray::from(a)`](CowArray#impl-From<ArrayBase<ViewRepr<%26%27a%20A>%2C%20D>>)
///
/// </td>
/// <td>
///
/// [`CowArray::from(a.view())`](CowArray#impl-From<ArrayBase<ViewRepr<%26%27a%20A>%2C%20D>>)
///
/// </td>
/// </tr>
///
/// <!--Conversions to `ArrayView<'b, A, D>`-->
///
/// <tr>
/// <td>
///
/// `ArrayView<'b, A, D>`
///
/// </td>
/// <td>
///
/// [`a.view()`][.view()]
///
/// </td>
/// <td>
///
/// [`a.view()`][.view()]
///
/// </td>
/// <td>
///
/// [`a.view()`][.view()]
///
/// </td>
/// <td>
///
/// [`a.view()`][.view()] or [`a.reborrow()`][ArrayView::reborrow()]
///
/// </td>
/// <td>
///
/// [`a.view()`][.view()]
///
/// </td>
/// </tr>
///
/// <!--Conversions to `ArrayViewMut<'b, A, D>`-->
///
/// <tr>
/// <td>
///
/// `ArrayViewMut<'b, A, D>`
///
/// </td>
/// <td>
///
/// [`a.view_mut()`][.view_mut()]
///
/// </td>
/// <td>
///
/// [`a.view_mut()`][.view_mut()]
///
/// </td>
/// <td>
///
/// [`a.view_mut()`][.view_mut()]
///
/// </td>
/// <td>
///
/// illegal
///
/// </td>
/// <td>
///
/// [`a.view_mut()`][.view_mut()] or [`a.reborrow()`][ArrayViewMut::reborrow()]
///
/// </td>
/// </tr>
///
/// <!--Conversions to equivalent with dim `D2`-->
///
/// <tr>
/// <td>
///
/// equivalent with dim `D2` (e.g. converting from dynamic dim to const dim)
///
/// </td>
/// <td colspan="5">
///
/// [`a.into_dimensionality::<D2>()`][.into_dimensionality()]
///
/// </td>
/// </tr>
///