Class NDArray<TDType>
public class NDArray<TDType> : NDArray, IIndex, ICloneable, IEnumerable, IDisposable where TDType : unmanaged
Type Parameters
TDType
- Inheritance
-
NDArray<TDType>
- Implements
- Inherited Members
- Extension Methods
Constructors
NDArray()
Constructor for init data type internal storage is 1D with 1 element
public NDArray()
Remarks
This constructor does not call allocation/>
NDArray(IArraySlice, Shape, char)
Wraps an IArraySlice of TDType as a typed array — NumPy's
np.ndarray(shape, buffer=values, order=order), as NDArray(IArraySlice, Shape, char)
describes: shape contributes its DIMENSIONS only, and the slice is laid out densely in
order.
public NDArray(IArraySlice values, Shape shape = default, char order = 'C')
Parameters
valuesIArraySliceThe buffer, wrapped without a copy. Its element type must be
TDType.shapeShapeThe dimensions of the result;
defaultmakes a one-dimensional array ofvalues.Countelements.orderchar'C'(default) row-major,'F'column-major;'A'and'K'mean'C'; lowercase is accepted.
Exceptions
- NullReferenceException
valuesis null.- ValueError
orderis not 'C', 'F', 'A' or 'K' in either case.- ArgumentException
The element count of
valuesis not the size ofshape, or the slice's element type is notTDType(checked after the base constructor has wrapped the slice).
NDArray(UnmanagedStorage)
Creates a new NDArray with this storage.
protected NDArray(UnmanagedStorage storage)
Parameters
storageUnmanagedStorage
NDArray(UnmanagedStorage, Shape)
Creates a new NDArray with this storage.
protected NDArray(UnmanagedStorage storage, Shape shape)
Parameters
storageUnmanagedStorageshapeShape
NDArray(UnmanagedStorage, ref Shape)
Creates a new NDArray with this storage.
protected NDArray(UnmanagedStorage storage, ref Shape shape)
Parameters
storageUnmanagedStorageshapeShape
NDArray(Shape)
Constructor which initialize elements with 0 type and shape are given.
public NDArray(Shape shape)
Parameters
shapeShapeShape of NDArray
Remarks
This constructor calls Allocate(Shape, DType, bool)
NDArray(Shape, bool)
Constructor which initialize elements with 0 type and shape are given.
public NDArray(Shape shape, bool fillZeros)
Parameters
shapeShapeShape of NDArray
fillZerosboolShould set the values of the new allocation to default(dtype)? otherwise - old memory noise
Remarks
This constructor calls Allocate(Shape, DType, bool)
NDArray(Shape, bool, TensorEngine)
The allocation constructor behind NewArray<T>(Shape, bool): a new typed
array bound to engine instead of Default.
public NDArray(Shape shape, bool fillZeros, TensorEngine engine)
Parameters
shapeShapeThe dimensions (a view's layout is laid out again in C order, as for every allocation).
fillZerosboolZero the buffer; false leaves pool noise the caller must overwrite completely.
engineTensorEngineThe engine the array binds (the engine computing the result it will hold), or
nullfor Default as it is now.
Remarks
Footgun: fillZeros false hands out whatever bytes the buffer pool held - the
caller must overwrite every element before anything reads the array.
Exceptions
- ValueError
A dimension is negative, or the byte count overflows.
NDArray(TensorEngine)
Constructor for init data type internal storage is 1D with 1 element
protected NDArray(TensorEngine engine)
Parameters
engineTensorEngineThe engine of this NDArray
Remarks
This constructor does not call allocation/>
NDArray(Array, Shape, char)
Wraps a .NET array of TDType as a typed array — NumPy's
np.ndarray(shape, buffer=values, order=order), as NDArray(Array, Shape, char) describes:
shape contributes its DIMENSIONS only, and the values are laid out densely in
order.
public NDArray(Array values, Shape shape = default, char order = 'C')
Parameters
valuesArrayThe elements; a one-dimensional array is wrapped without a copy, a multi-dimensional or jagged one is flattened row by row first. Its element type must be
TDType.shapeShapeThe dimensions of the result (a view's shape gives the same array as a fresh shape of the same dimensions);
defaultuses the dimensions ofvalues.orderchar'C'(default) row-major,'F'column-major;'A'and'K'mean'C'; lowercase is accepted.
Exceptions
- NullReferenceException
valuesis null.- ValueError
orderis not 'C', 'F', 'A' or 'K' in either case.- ArgumentException
The element count of
valuesis not the size ofshape, or the element type ofvaluesis notTDType(checked after the base constructor has wrapped the values).
NDArray(int)
Constructor which initialize elements with length of size
public NDArray(int size)
Parameters
sizeintThe size as a single dimension shape
Remarks
This constructor calls Allocate(Shape, DType, bool)
NDArray(int, bool)
Constructor which initialize elements with length of size
public NDArray(int size, bool fillZeros)
Parameters
sizeintThe size as a single dimension shape
fillZerosboolShould set the values of the new allocation to default(dtype)? otherwise - old memory noise
Remarks
This constructor calls Allocate(Shape, DType, bool)
NDArray(long)
Constructor which initialize elements with length of size
public NDArray(long size)
Parameters
sizelongThe size as a single dimension shape
Remarks
This constructor calls Allocate(Shape, DType, bool)
NDArray(long, bool)
Constructor which initialize elements with length of size
public NDArray(long size, bool fillZeros)
Parameters
sizelongThe size as a single dimension shape
fillZerosboolShould set the values of the new allocation to default(dtype)? otherwise - old memory noise
Remarks
This constructor calls Allocate(Shape, DType, bool)
Properties
Address
Gets the address that this NDArray starts from.
protected TDType* Address { get; }
Property Value
- TDType*
Array
Array access to storage data - overridden on purpose
protected ArraySlice<TDType> Array { get; set; }
Property Value
- ArraySlice<TDType>
this[object[]]
NumPy's ndarray.getitem(key) for a typed array: the selection this[object[]]
makes, typed as this array's element type (typed["1:3"], typed[0], typed[mask] are all
NDArray<TDType>). Assigning uses NDArray's setter (NumPy's setitem).
public override NDArray<TDType> this[params object[] key] { get; }
Parameters
keyobject[]The index tuple, as for this[object[]].
Property Value
- NDArray<TDType>
GET: the selection as an NDArray<TDType> — for one integer per axis NumPy's scalar, a read-only 0-d COPY of the element (read its value with a cast,
(double)typed[0], or GetValue<T>(params long[]); write an element through the setter); a view for any other index of integers and slices (a 0-d one is an explicit 0-d array); a new array for an advanced index. SET (inherited): the value is stored by NumPy's rules. Through an NDArray<TDType> variable the value must be an NDArray<TDType> or aTDType(which converts implicitly to a 0-d array); assign any other value through an NDArray reference or __setitem__(object, object).
Remarks
The override is GETTER-ONLY on purpose: C# lets an override narrow its type only when it does not declare a
setter (a read-write override must keep NDArray, error CS1715), and the setter stays
NDArray's. The typed scalar indexers TDType this[params long[]] /
TDType this[int[]] are gone with the rule of one NumPy signature: an element is a 0-d array, as for
every other array.
Virtual dispatch reaches this getter also through an NDArray reference: the selection of a typed array is a typed array object at run time, with the same elements and the same view relationship as the untyped selection (the basic index builds ONE typed object, an item's scalar copy or a view of the storage; an advanced index wraps the untyped result's own storage object, so a gather still owns its data, and disposes the untyped wrapper).
Exceptions
- ArgumentNullException
keyor one of its entries isnull.- IndexError
The index is invalid for this array (NumPy's texts).
- InvalidOperationException
An advanced selection came back in another element type (the indexer never changes the element type; the guard keeps a future change from returning a wrongly typed array).
T
The transposed array.
Same as self.transpose().
public NDArray<TDType> T { get; }
Property Value
- NDArray<TDType>
Remarks
flat
A 1-D iterator over the array.
public NDArray<TDType> flat { get; }
Property Value
- NDArray<TDType>
Remarks
Methods
Clone()
Clone the array while preserving the typed NDArray wrapper.
public override NDArray Clone()
Returns
GetAtIndex(long)
public TDType GetAtIndex(long index)
Parameters
indexlong
Returns
- TDType
reshape(Shape, char, bool?)
Gives a new shape to a typed array without changing its data, reading the elements in the specified index
order — NumPy's a.reshape(shape, /, *, order='C', copy=None), keeping the typed wrapper.
public NDArray<TDType> reshape(Shape shape, char order = 'C', bool? copy = null)
Parameters
shapeShapeThe new shape (one dimension may be -1, inferred): an int, a tuple, an
int[]/long[], a C# collection expression or a Shape. Only its DIMENSIONS are a request, as in NumPy, whose reshape takes a shape tuple: a Shape taken from a view also carries that view's strides, offset and buffer size, and none of them reaches the result.orderchar'C' (default), 'F', or 'A' ('F' when this array is F-contiguous and not C-contiguous); 'K' is NumPy's
ValueError("order 'K' is not permitted for reshaping").copybool?NumPy's
copykeyword: null copies only when needed, true always copies, false raisesUnable to avoid creating a copy while reshaping.when no view can express the reshape.
Returns
- NDArray<TDType>
A typed view whenever the reshape can be expressed over the existing strides, otherwise a typed view over an internal copy (see reshape(Shape, char, bool?)).
Remarks
API-parity batch 9: this replaces the typed (Shape), (ref Shape) and (int[]) forms,
which had no order or copy, so t.reshape(s, order: 'F') fell
through to the untyped method and returned an untyped array. The default spelling (C order, copy None) keeps
the typed alias engine the (Shape) form always ran, at its cost (the loose-int forms' allocation, pinned
by Shape.CallerArrays.Tests); an order or copy request runs the untyped reshape engine (NumPy's
_reshape_with_copy_arg, so a non-contiguous source gives NumPy's strided view where one exists) and
re-wraps the result typed.
https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
Exceptions
- IncorrectShapeException
The size does not match: NumPy's
cannot reshape array of size {n} into shape {s}.- ValueError
'K', more than one -1, or the refusal of
copyfalse.- ArgumentException
An order letter outside NumPy's vocabulary.
reshape(params long[])
Gives a new shape to an array without changing its data.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray<TDType> reshape(params long[] shape)
Parameters
shapelong[]The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
Returns
- NDArray<TDType>
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
Remarks
reshape(params ReadOnlySpan<long>)
Gives a new shape to an array without changing its data, keeping the typed wrapper. This is the overload
inline values bind (a.reshape(2, 3)): the call allocates only the dimension array the new shape keeps.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray<TDType> reshape(params ReadOnlySpan<long> shape)
Parameters
shapeReadOnlySpan<long>The new dimensions; one may be negative (inferred from the size).
Returns
- NDArray<TDType>
An alias of this array's storage with the new shape (a copy first when this array is not contiguous).
Remarks
Hides the untyped reshape(params ReadOnlySpan<long>) so a typed array stays typed. An array argument binds reshape(params long[]) instead, which copies it (bug 2d).
Exceptions
- IncorrectShapeException
The size does not match: NumPy's
cannot reshape array of size {n} into shape {s}.- ValueError
More than one dimension is negative.
reshape_unsafe(Shape)
Gives a new shape to an array without changing its data.
public NDArray<TDType> reshape_unsafe(Shape newshape)
Parameters
newshapeShapeThe new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
Returns
- NDArray<TDType>
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
Remarks
reshape_unsafe(ref Shape)
Gives a new shape to an array without changing its data.
public NDArray<TDType> reshape_unsafe(ref Shape newShape)
Parameters
newShapeShape
Returns
- NDArray<TDType>
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
Remarks
reshape_unsafe(int[])
Gives a new shape to an array without changing its data.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray<TDType> reshape_unsafe(int[] shape)
Parameters
shapeint[]The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
Returns
- NDArray<TDType>
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
Remarks
reshape_unsafe(params long[])
Gives a new shape to an array without changing its data.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray<TDType> reshape_unsafe(params long[] shape)
Parameters
shapelong[]The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
Returns
- NDArray<TDType>
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
Remarks
reshape_unsafe(params ReadOnlySpan<long>)
Gives a new shape to an array without changing its data and without the size check, keeping the typed
wrapper. This is the overload inline values bind (a.reshape_unsafe(2, 3)): the call allocates only
the dimension array the new shape keeps.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray<TDType> reshape_unsafe(params ReadOnlySpan<long> shape)
Parameters
shapeReadOnlySpan<long>The new dimensions; one may be negative (inferred from the size).
Returns
- NDArray<TDType>
An alias of this array's storage with the new shape (a copy first when this array is not contiguous).
Remarks
Unsafe because the element count is not validated against the buffer: a shape larger than the buffer reads past it. Hides the untyped reshape_unsafe(params ReadOnlySpan<long>); an array argument binds reshape_unsafe(params long[]) instead, which copies it.
Operators
operator &(NDArray<TDType>, NDArray<TDType>)
Element-wise bitwise AND for typed arrays. Resolves ambiguity when using NDArray<bool> operands.
public static NDArray<TDType> operator &(NDArray<TDType> lhs, NDArray<TDType> rhs)
Parameters
Returns
- NDArray<TDType>
operator |(NDArray<TDType>, NDArray<TDType>)
Element-wise bitwise OR for typed arrays. Resolves ambiguity when using NDArray<bool> operands.
public static NDArray<TDType> operator |(NDArray<TDType> lhs, NDArray<TDType> rhs)
Parameters
Returns
- NDArray<TDType>
operator ^(NDArray<TDType>, NDArray<TDType>)
Element-wise bitwise XOR for typed arrays.
public static NDArray<TDType> operator ^(NDArray<TDType> lhs, NDArray<TDType> rhs)
Parameters
Returns
- NDArray<TDType>
explicit operator NDArray<TDType>(TDType[])
public static explicit operator NDArray<TDType>(TDType[] tArray)
Parameters
tArrayTDType[]
Returns
- NDArray<TDType>
implicit operator ArraySlice<TDType>(NDArray<TDType>)
public static implicit operator ArraySlice<TDType>(NDArray<TDType> nd)
Parameters
ndNDArray<TDType>
Returns
- ArraySlice<TDType>
implicit operator NDArray<TDType>(TDType)
A TDType value as a 0-d array of its own type: what lets an element be assigned through
a typed variable's indexer (typed[0] = 3.14, mask[m] = false), whose setter value is an
NDArray<TDType> (see this[object[]]).
public static implicit operator NDArray<TDType>(TDType value)
Parameters
valueTDTypeThe element value.
Returns
- NDArray<TDType>
A new writeable 0-d array holding
value, its dtypeTDType's.
Remarks
The array is a plain (STRONG) typed scalar, not NumPy's Python scalar: it already has the destination's type,
so a store never range-checks or converts it. Where both this conversion and NDArray's scalar
conversions apply, C# prefers this one only for an NDArray<TDType> parameter (the typed
operators &, |, ^), whose results are the same.