Struct Shape
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
Broadcasting operations for Shape.
public readonly struct Shape : ICloneable, IEquatable<Shape>
- Implements
- Inherited Members
Remarks
Based on https://numpy.org/doc/stable-1.16.1/user/basics.broadcasting.html These are pure shape operations - they compute output shapes without touching array data.
Constructors
Shape()
Creates a scalar shape (ndim=0, size=1). Equivalent to NumPy's empty tuple shape ().
public Shape()
Remarks
In NumPy: np.array(42).shape == () In NumSharp: new Shape() creates a scalar shape.
Shape(Shape)
public Shape(Shape other)
Parameters
otherShape
Shape(IEnumerable<long>)
Primary constructor with long dimensions.
public Shape(IEnumerable<long> dims)
Parameters
dimsIEnumerable<long>
Shape(int[])
Backward-compatible constructor with int dimensions.
public Shape(int[] dims)
Parameters
dimsint[]
Shape(params long[])
A C-contiguous shape over a COPY of the caller's dimensions (NumPy's np.empty(shape) layout). Changing
dims afterwards never changes this shape or an array built on it: NumPy copies the sequence
(PyArray_IntpConverter) and an array owns its dimensions (PyArray_NewFromDescr_int).
public Shape(params long[] dims)
Parameters
dimslong[]The extent of every axis;
nullor empty is the 0-d shape. Copied.
Remarks
Why a copy. Shapes and arrays SHARE dimension arrays, so keeping the caller's array let
long[] s = {3, 4}; var a = np.zeros(s); s[0] = 100; turn a into (100, 4) over 12
elements: the cached size and the buffer stayed, so the new rows read past the buffer (plan
docs/plans/view-shape-open-bugs.md, bug 2d).
Inline values (new Shape(3, 4)) bind the Shape(params ReadOnlySpan<long>) overload, which
allocates the one array this shape keeps; a C# 12 caller, which has no span params, binds this one. An
array argument costs one copy. A caller that built the array itself and will never write into it again
skips the copy with Shape(long[], char, bool): new Shape(dims, copy: false).
Shape(long[], char, bool)
A C- or F-contiguous shape (NumPy's np.empty(shape, order=order) layout). By default it keeps a COPY of
dims, so changing the array afterwards never changes this shape or an array built on it
(NumPy copies every shape sequence it is given; bug 2d). copy: false keeps the array itself, for one
nothing will write into.
public Shape(long[] dims, char order = 'C', bool copy = true)
Parameters
dimslong[]The extent of every axis;
nullor empty is the 0-d shape. Copied unlesscopyisfalse.ordercharPhysical memory order: 'C' (row-major, the default) or 'F' (column-major). A logical order ('A', 'K') must be resolved to a physical one first, through
OrderResolver.copybooltrue(the default, NumPy's behaviour): the shape keeps a copy ofdims.false: the shape keepsdimsitself and saves one small allocation; the caller must never write into the array again (see remarks). Pass it by name,new Shape(dims, copy: false): a positionalfalselands onorderand does not compile.
Remarks
new Shape(dims) binds Shape(params long[]) and copies; this overload serves an explicit order,
copy: false, or both.
copy: false. For an array nothing will write into: one the caller just built, or another shape's own (a
shape never writes into its arrays). The shape caches its size and flags when it is built, and every array
built on it shares dims, so a later write into it changes those arrays' dimensions but not
their size or buffer: long[] s = {3, 4}; var a = np.zeros(new Shape(s, copy: false)); s[0] = 100;
makes a (100, 4) over its 12 elements, and a[99, 3] addresses element 399. NumPy has no
such mode; its arrays always own their dimensions.
Exceptions
- ArgumentException
orderis not 'C' or 'F' (checked before anything is copied).
Shape(long[], long[], Shape)
A shape with explicit element strides over COPIES of the caller's arrays, at offset 0, whose
buffer is originalShape's (its buffer size, or its size when the buffer size is unset): the
form a broadcast of originalShape takes. Changing either array afterwards never changes this
shape (bug 2d).
public Shape(long[] dims, long[] strides, Shape originalShape)
Parameters
dimslong[]The extent of every axis. Copied.
strideslong[]The stride of every axis, in elements. Copied.
originalShapeShapeThe shape whose buffer this one addresses; only its buffer size is read.
Exceptions
- ArgumentNullException
dimsorstridesisnull.- ArgumentException
The two arrays differ in length.
Shape(long[], long[], bool)
A shape with explicit element strides, at offset 0 over a buffer of exactly size
elements. By default it keeps COPIES of both arrays, so changing either array afterwards never changes this
shape or an array built on it (NumPy copies every shape or strides sequence it is given; plan
docs/plans/view-shape-open-bugs.md, bug 2d).
public Shape(long[] dims, long[] strides, bool copy = true)
Parameters
dimslong[]The extent of every axis. Copied unless
copyisfalse.strideslong[]The stride of every axis, in ELEMENTS (0 for a broadcast axis, negative for a reversed one). Copied unless
copyisfalse. Not validated against a buffer: an array that installs this shape must own enough memory.copybooltrue(the default, NumPy's behaviour): the shape keeps copies of both arrays.false: the shape keeps the two arrays themselves and saves two small allocations; the caller must never write into either of them again (see remarks).
Remarks
copy: false is for arrays nothing will write into: ones the caller just built, or another shape's own
(a shape never writes into its arrays). The shape caches its size and flags when it is built, and every array
built on it shares the two arrays, so a later write into one passed with copy: false changes those
arrays' layout but not their size or buffer: indexing then reads and writes past the buffer. NumPy has no
such mode; its arrays always own their dimensions and strides.
Exceptions
- ArgumentNullException
dimsorstridesisnull.- ArgumentException
The two arrays differ in length.
Shape(long[], long[], long, long)
Complete constructor for views/broadcasts (NumPy-aligned). All parameters are set explicitly, flags computed from dims/strides.
public Shape(long[] dims, long[] strides, long offset, long bufferSize)
Parameters
dimslong[]Dimension sizes (not cloned - caller must provide fresh array)
strideslong[]Stride values (not cloned - caller must provide fresh array)
offsetlongOffset into underlying buffer
bufferSizelongSize of underlying buffer
Remarks
The constructor a bridge package lays a strided, offset view over a foreign buffer with. Footguns: it ADOPTS both
arrays (the caller must never write into them afterwards, see dimensions), and it checks nothing -
an element reached through offset and strides outside
bufferSize is read or written outside the buffer. Shape(long[], long[]) copies
and validates; use it when the input is not already known to be valid.
Shape(params ReadOnlySpan<long>)
A C-contiguous shape over the given dimensions, copied into the one array the shape keeps. This is the
overload inline values bind (new Shape(3, 4), new Shape(n)): the values arrive on the caller's
stack, so building the shape allocates its dimension array once, as the array form did before it copied.
public Shape(params ReadOnlySpan<long> dims)
Parameters
dimsReadOnlySpan<long>The extent of every axis; empty is the 0-d shape.
Fields
IsScalar
public readonly bool IsScalar
Field Value
Scalar
Singleton instance of a Shape that represents a scalar.
public static readonly Shape Scalar
Field Value
bufferSize
Size of the underlying buffer (NumPy-aligned architecture). For non-view shapes, equals size. For sliced/broadcast shapes, this is the actual buffer size (not the view size), used for bounds checking and InternalArray slicing.
public readonly long bufferSize
Field Value
Remarks
The same value as BufferSize, read without a property call.
dimensions
The extent of every axis: the shape's OWN array, shared with every shape and array built on it - no copy, unlike Dimensions.
public readonly long[] dimensions
Field Value
- long[]
Remarks
For hot reads (an interop bridge, a kernel's setup) that cannot afford Dimensions' allocation per read. Footgun: writing into it changes this shape, and every array sharing the array, without updating the cached size, flags or hash - a later read goes past the buffer with no check. Treat it as read-only; build a new shape to change one.
offset
Base offset into storage (NumPy-aligned architecture). Computed at slice/broadcast time, enabling simple element access: element[indices] = data[offset + sum(indices * strides)]
public readonly long offset
Field Value
Remarks
The same value as Offset, counted in elements, read without a property call.
size
The element count (the product of dimensions; 1 for a 0-d shape), read without a property call - the same value as Size.
public readonly long size
Field Value
strides
The stride of every axis in ELEMENTS (0 on a broadcast axis, negative on a reversed one): the shape's OWN array, shared like dimensions - no copy, unlike Strides.
public readonly long[] strides
Field Value
- long[]
Remarks
Footgun, as for dimensions: writing into it retargets every array sharing it with stale flags and no bounds check. Read-only by contract.
Properties
BufferSize
Size of the underlying buffer (NumPy-aligned architecture). For non-view shapes, equals Size. For sliced/broadcast shapes, this is the actual buffer size (not the view size).
public long BufferSize { get; }
Property Value
Dimensions
The extent of every axis (NumPy's ndarray.shape), as a NEW array on every read: NumPy hands out an
immutable tuple, so writing into the returned array never changes this shape or any array built on it.
public long[] Dimensions { get; }
Property Value
- long[]
A copy of the dimensions, the caller's to keep or change. A 0-d shape returns its empty array (there is no element to write into) and an uninitialized
default(Shape)returnsnull.
Remarks
Why a copy. Shapes and arrays SHARE dimension arrays (an allocation keeps its caller's shape, an
elementwise result keeps its input's), so returning the shared array let x.Shape.Dimensions[0] = 100
change x, and every array sharing it, to (100, 4) over 12 elements: the cached size, flags and
buffer stayed, so the new rows read past the buffer. Plan docs/plans/view-shape-open-bugs.md, bug 2c.
The copy costs one small allocation per read. Code inside NumSharp reads the internal dimensions field
instead; a caller that needs one extent should use this[int] or NDim, which do not
allocate, and a caller that reads the whole array in a hot loop should hoist it.
Flags
Get all array flags as a single integer. Use ArrayFlags enum for bit meanings.
public ArrayFlags Flags { get; }
Property Value
IsBroadcasted
Is this shape a broadcast (has any stride=0 with dimension > 1)? Cached flag computed at shape creation for O(1) access.
public bool IsBroadcasted { get; }
Property Value
IsContiguous
Does this Shape represent contiguous unmanaged memory in C-order (row-major)? Cached flag computed at shape creation, matching NumPy's flags['C_CONTIGUOUS'] algorithm.
public bool IsContiguous { get; }
Property Value
Remarks
NumPy algorithm (from numpy/_core/src/multiarray/flagsobject.c:116-160): Scan right-to-left. stride[-1] must equal 1 (itemsize in NumPy, but NumSharp uses element strides). stride[i] must equal shape[i+1] * stride[i+1]. Size-1 dimensions are skipped (stride doesn't matter). Empty arrays (any dimension is 0) are considered contiguous by definition.
IsEmpty
True if the shape is not initialized. Note: A scalar shape is not empty.
public bool IsEmpty { get; }
Property Value
IsFContiguous
Does this Shape represent contiguous unmanaged memory in F-order (column-major)? Cached flag computed at shape creation, matching NumPy's flags['F_CONTIGUOUS'] algorithm.
public bool IsFContiguous { get; }
Property Value
Remarks
NumPy algorithm: scan left-to-right. stride[0] must equal 1. stride[i] must equal shape[i-1] * stride[i-1]. Size-1 dimensions are skipped. Empty arrays are considered contiguous by definition. A 1-D array that is C-contiguous is also F-contiguous (same memory layout).
IsScalarBroadcast
Is this shape a scalar that was broadcast to a larger shape? True when all strides are 0, meaning all dimensions are broadcast from a scalar. Used for optimization: when iterating, we can use a single value instead of indexing.
public bool IsScalarBroadcast { get; }
Property Value
IsSimpleSlice
Is this a simple sliced shape that uses the fast GetOffsetSimple path?
True when: IsSliced && !IsBroadcasted
For simple slices, element access is: offset + sum(indices * strides)
public bool IsSimpleSlice { get; }
Property Value
IsSliced
True if this shape represents a view (sliced) into underlying data. A shape is "sliced" if it doesn't represent the full original buffer. This includes: non-zero offset, different size than buffer, or non-contiguous strides.
public bool IsSliced { get; }
Property Value
IsWriteable
Is this array writeable? False for broadcast views (NumPy behavior). Cached flag computed at shape creation for O(1) access.
public bool IsWriteable { get; }
Property Value
this[int]
The extent of dimension dim — NumPy's a.shape[dim]. Read-only: a
Shape is immutable, like the tuple NumPy hands out.
public long this[int dim] { get; }
Parameters
dimintThe axis; a negative axis counts from the end (
-1is the last).
Property Value
- long
The number of elements along that axis.
Remarks
There is no setter, on purpose. Shapes and arrays SHARE dimension arrays (an allocation keeps the caller's
shape, an elementwise result keeps its input's), so a setter that wrote into the array changed every array
sharing it — and only its dimensions: the cached size and the buffer stayed, so the new rows read past the
buffer (var s = new Shape(3, 4); var a = np.zeros(s); s[0] = 100; made a (100, 4) over
12 elements). NumPy's arrays own their dimensions and hand out immutable tuples; build a new shape instead
(new Shape(...), reshape).
Exceptions
- IndexOutOfRangeException
dimis outside[-NDim, NDim).
NDim
public int NDim { get; }
Property Value
Offset
Base offset into storage (like NumPy's adjusted data pointer). For non-view shapes this is 0. For sliced/broadcast shapes, this will be computed at slice/broadcast time in future phases.
public long Offset { get; }
Property Value
Order
Physical memory layout: 'F' if strictly F-contiguous, otherwise 'C'. 1-D and scalar shapes (both C- and F-contig) report 'C' by convention. Non-contiguous shapes also report 'C' as the default reference order.
public char Order { get; }
Property Value
OriginalSize
Computes the size of the original (non-broadcast) data. This is the product of all dimensions where stride != 0. For a non-broadcast shape, this equals size. For a broadcast shape, this is the actual data size before broadcast.
public long OriginalSize { get; }
Property Value
OwnsData
Does this array own its data buffer (NumPy's flags.owndata)?
True for freshly allocated arrays (np.arange, np.zeros, .copy());
false for views (slices, transposes, broadcasts) and foreign-memory wraps (memmaps).
Maintained at the UnmanagedStorage funnels
(OnReshaped()), mirroring
UnmanagedStorage.OwnsData — meaningful only on a shape read off a storage
(nd.Shape); a hand-built Shape carries no ownership claim.
public bool OwnsData { get; }
Property Value
Size
The linear size of this shape.
public long Size { get; }
Property Value
Strides
The stride of every axis in ELEMENTS, as a NEW array on every read: writing into the returned array never
changes this shape or any array built on it. NumPy's ndarray.strides counts BYTES; that is
strides, which scales these by the item size.
public long[] Strides { get; }
Property Value
- long[]
A copy of the element strides (0 on a broadcast axis, negative on a reversed one), the caller's to keep or change. A 0-d shape returns its empty array and an uninitialized
default(Shape)returnsnull.
Remarks
Why a copy. Shapes and arrays SHARE stride arrays, and the cached flags (C/F-contiguity, broadcast,
writeable) and every kernel's addressing come from them. Returning the shared array let
x.Shape.Strides[0] = 1000 retarget x's reads past its buffer with no check and with stale flags.
NumPy has no unchecked route: its strides setter validates the request (PyArray_CheckStrides).
Plan docs/plans/view-shape-open-bugs.md, bug 2c.
The copy costs one small allocation per read. Code inside NumSharp reads the internal strides field
instead; a caller that reads the whole array in a hot loop should hoist it.
Methods
AreBroadcastable(params Shape[])
Checks if the given shapes can be broadcast together.
public static bool AreBroadcastable(params Shape[] shapes)
Parameters
shapesShape[]Shapes to check.
Returns
- bool
True if all shapes are broadcastable, false otherwise.
AreBroadcastable(params int[][])
Checks if the given dimension arrays can be broadcast together.
public static bool AreBroadcastable(params int[][] shapes)
Parameters
shapesint[][]Dimension arrays to check.
Returns
- bool
True if all shapes are broadcastable, false otherwise.
Broadcast(Shape, Shape)
Broadcasts two shapes and returns the broadcasted shapes with computed strides.
public static (Shape LeftShape, Shape RightShape) Broadcast(Shape leftShape, Shape rightShape)
Parameters
Returns
- (Shape LeftShape, Shape RightShape)
Tuple of (LeftBroadcastedShape, RightBroadcastedShape).
Exceptions
- IncorrectShapeException
If shapes cannot be broadcast together.
Broadcast(params Shape[])
Broadcasts multiple shapes and returns the broadcasted shapes with computed strides.
public static Shape[] Broadcast(params Shape[] shapes)
Parameters
shapesShape[]Shapes to broadcast.
Returns
- Shape[]
Array of broadcasted shapes with stride=0 where dimensions were stretched.
Exceptions
- IncorrectShapeException
If shapes cannot be broadcast together.
Clean()
Returns a clean shape based on this (offset=0, standard strides).
public Shape Clean()
Returns
Clone(bool, bool, bool)
Creates a complete copy of this Shape.
public Shape Clone(bool deep = true, bool unview = false, bool unbroadcast = false)
Parameters
Returns
ComputeLongShape(int[])
Converts int[] dimensions to long[] for backwards compatibility.
public static long[] ComputeLongShape(int[] dimensions)
Parameters
dimensionsint[]
Returns
- long[]
Create(ReadOnlySpan<long>)
Builds the shape a C# collection expression writes (Shape s = [2, 3];, np.zeros([2, 3]),
np.zeros([])): the C# spelling of NumPy's list shape. The compiler calls it; it is public only because
CollectionBuilderAttribute needs a builder the caller can reach.
public static Shape Create(ReadOnlySpan<long> dims)
Parameters
dimsReadOnlySpan<long>The dimensions, in order (one may be -1 where the consumer infers it, as reshape does); empty is the 0-d shape
().
Returns
- Shape
A C-order shape over a copy of
dims(the span lives on the caller's stack, so the shape cannot keep it).
Remarks
Added in API-parity batch 9. Batch 8 removed the int[] overloads (one NumPy signature), which were what
[2, 3] bound to, so the collection expressions stopped compiling (CS9174); making Shape the collection
type restores them on every Shape and Shape? parameter, including those that never had an
array overload. C#'s rules prefer an array or a span parameter over this type (an int[] / long[]
converts to Shape, and a span beats any non-span), so a call that binds an array or span overload today keeps
binding it (proven at C# 12 / net8.0 and C# 14 / net10.0).
Deconstruct(out long, out long)
public void Deconstruct(out long dim1, out long dim2)
Parameters
Deconstruct(out long, out long, out long)
public void Deconstruct(out long dim1, out long dim2, out long dim3)
Parameters
Deconstruct(out long, out long, out long, out long)
public void Deconstruct(out long dim1, out long dim2, out long dim3, out long dim4)
Parameters
Deconstruct(out long, out long, out long, out long, out long)
public void Deconstruct(out long dim1, out long dim2, out long dim3, out long dim4, out long dim5)
Parameters
Deconstruct(out long, out long, out long, out long, out long, out long)
public void Deconstruct(out long dim1, out long dim2, out long dim3, out long dim4, out long dim5, out long dim6)
Parameters
Empty(int)
An empty shape without any fields set (all dimensions are 0).
public static Shape Empty(int ndim)
Parameters
ndimint
Returns
Remarks
Used internally for building shapes that will be filled in.
Equals(Shape)
Indicates whether the current object is equal to another object of the same type.
public bool Equals(Shape other)
Parameters
otherShapeAn object to compare with this object.
Returns
- bool
true if the current object is equal to the
otherparameter; otherwise, false.
Equals(object)
Indicates whether this instance and a specified object are equal.
public override bool Equals(object obj)
Parameters
objobjectThe object to compare with the current instance.
Returns
- bool
true if
objand this instance are the same type and represent the same value; otherwise, false.
ExpandDimension(int)
Expands a specific axis with 1 dimension.
[SuppressMessage("ReSharper", "LocalVariableHidesMember")]
public Shape ExpandDimension(int axis)
Parameters
axisint
Returns
ExpandDimensions(int[])
Expands one or more axes with size-1 dimensions, matching NumPy's
np.expand_dims(a, axis) tuple-axis semantics.
public Shape ExpandDimensions(int[] axes)
Parameters
axesint[]Positions in the expanded output where size-1 axes are placed.
Returns
Remarks
Each axis is normalized against the FINAL output ndim
(inputNdim + axes.Length) by NumPy's normalize_axis_tuple
(normalize_axis_tuple(int[], int, object, bool)).
Exceptions
- AxisError
An axis is out of range for the output's rank (the axis as given).
- ValueError
Two axes name the same output position ("repeated axis").
ExtractShape(Array)
Extracts the shape of given array.
public static int[] ExtractShape(Array array)
Parameters
arrayArray
Returns
- int[]
Remarks
Supports both jagged and multi-dim.
GetAxis(Shape, int)
public static long[] GetAxis(Shape shape, int axis)
Parameters
Returns
- long[]
GetAxis(ref Shape, int)
public static long[] GetAxis(ref Shape shape, int axis)
Parameters
Returns
- long[]
GetAxis(long[], int)
The dimensions with one axis removed — the shape a reduction over axis leaves.
public static long[] GetAxis(long[] dims, int axis)
Parameters
Returns
- long[]
A new array without
axis(empty for 0-d dimensions, whatever the axis).
Remarks
A negative axis is NumPy's normalization (-2 is the second-to-last axis). This helper used to map
EVERY negative axis to the last one and raise the legacy parenthesized axis exception (deleted in API-parity
batch 13); its callers
pass normalized axes, so only a direct caller ever saw the difference.
Exceptions
- ArgumentNullException
dimsis null.- AxisError
axisis out of range for a 1-D or higher shape.
GetCoordinates(long)
Gets coordinates in this shape from index in this shape (slicing is ignored). Example: Shape (2,3) 0 => [0, 0] 1 => [0, 1] ... 6 => [1, 2]
public long[] GetCoordinates(long offset)
Parameters
offsetlongthe index if you would iterate from 0 to shape.size in row major order
Returns
- long[]
GetEnumerator()
Enumerates the dimensions, outermost first — what Python's for d in a.shape walks, and what makes Shape a
C# collection type for Create(ReadOnlySpan<long>).
public Shape.Enumerator GetEnumerator()
Returns
- Shape.Enumerator
A value-type enumerator over the dimension array this shape already holds (no copy, no boxing); a 0-d shape yields nothing.
Remarks
A pattern-based enumerator, not IEnumerable<T>: implementing the interface would box every
foreach through it and would add LINQ's extension methods to every shape. Read
shape.dimensions directly in Core code; this exists for callers and for the collection-expression
contract.
GetHashCode()
Serves as the default hash function.
public override int GetHashCode()
Returns
- int
A hash code for the current object.
GetOffset(int[])
Backward-compatible GetOffset with int indices.
public long GetOffset(int[] indices)
Parameters
indicesint[]
Returns
GetOffset(long*, int)
Get offset index out of coordinate indices (pointer version). NumPy-aligned: offset + sum(indices * strides)
public long GetOffset(long* indices, int ndims)
Parameters
indiceslong*A pointer to the coordinates to turn into linear offset
ndimsintThe number of dimensions
Returns
- long
The index in the memory block that refers to a specific value.
GetOffset(params long[])
Get offset index out of coordinate indices. NumPy-aligned: offset + sum(indices * strides)
public long GetOffset(params long[] indices)
Parameters
indiceslong[]The coordinates to turn into linear offset
Returns
- long
The index in the memory block that refers to a specific value.
GetSize(int[])
Backward-compatible GetSize with int dimensions.
public static long GetSize(int[] dims)
Parameters
dimsint[]
Returns
GetSize(long[])
public static long GetSize(long[] dims)
Parameters
dimslong[]
Returns
GetSubshape(int[])
Backward-compatible GetSubshape with int indices.
public (Shape Shape, long Offset) GetSubshape(int[] indicies)
Parameters
indiciesint[]
Returns
GetSubshape(long*, int)
Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage.
public (Shape Shape, long Offset) GetSubshape(long* dims, int ndims)
Parameters
Returns
Remarks
Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.
GetSubshape(params long[])
Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage.
public (Shape Shape, long Offset) GetSubshape(params long[] indicies)
Parameters
indicieslong[]The selection of indexes 0 based.
Returns
Remarks
Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.
InferNegativeCoordinates(long[], int*, int)
InferNegativeCoordinates via int pointer (backward-compatible, for internal use). See Shape.Unmanaged.cs for the long* version.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public static void InferNegativeCoordinates(long[] dimensions, int* coords, int ndims)
Parameters
InferNegativeCoordinates(long[], int[])
Backward-compatible InferNegativeCoordinates with int arrays.
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public static int[] InferNegativeCoordinates(long[] dimensions, int[] coords)
Parameters
Returns
- int[]
InferNegativeCoordinates(long[], long*, int)
Translates coordinates with negative indices, e.g:
np.arange(9)[-1] == np.arange(9)[8]
np.arange(9)[-2] == np.arange(9)[7]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public static void InferNegativeCoordinates(long[] dimensions, long* coords, int coordsCount)
Parameters
dimensionslong[]The dimensions these coordinates are targeting
coordslong*The coordinates.
coordsCountint
InferNegativeCoordinates(long[], long[])
Translates coordinates with negative indices, e.g:
np.arange(9)[-1] == np.arange(9)[8]
np.arange(9)[-2] == np.arange(9)[7]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public static long[] InferNegativeCoordinates(long[] dimensions, long[] coords)
Parameters
Returns
- long[]
Coordinates without negative indices.
Matrix(long, long)
Create a shape that represents a matrix.
public static Shape Matrix(long rows, long cols)
Parameters
Returns
Remarks
Faster than calling Shape's constructor
Reshape(Shape, bool)
Changes the shape representing this storage.
public Shape Reshape(Shape newShape, bool @unsafe = true)
Parameters
Returns
Exceptions
- IncorrectShapeException
If shape's size mismatches current shape size.
- ArgumentException
If
newShape's size == 0
ResolveReturnShape(Shape, Shape)
Resolves the output shape when broadcasting two shapes together.
public static Shape ResolveReturnShape(Shape leftShape, Shape rightShape)
Parameters
Returns
- Shape
The resulting broadcast shape.
Exceptions
- IncorrectShapeException
If shapes cannot be broadcast together.
ResolveReturnShape(params Shape[])
Resolves the output shape when broadcasting multiple shapes together.
public static Shape ResolveReturnShape(params Shape[] shapes)
Parameters
shapesShape[]Shapes to broadcast.
Returns
- Shape
The resulting broadcast shape.
Exceptions
- IncorrectShapeException
If shapes cannot be broadcast together.
Slice(params Slice[])
public Shape Slice(params Slice[] input_slices)
Parameters
input_slicesSlice[]
Returns
Slice(string)
public Shape Slice(string slicing_notation)
Parameters
slicing_notationstring
Returns
ToString()
Returns the fully qualified type name of this instance.
public override string ToString()
Returns
- string
The fully qualified type name.
TransformOffset(long)
Retrieve the transformed offset if the shape is non-contiguous,
otherwise returns offset.
public long TransformOffset(long offset)
Parameters
Returns
- long
The transformed offset.
Remarks
For contiguous shapes, returns offset directly. For non-contiguous, translates through coordinates.
Vector(long)
Create a shape that represents a vector.
public static Shape Vector(long length)
Parameters
lengthlong
Returns
Remarks
Faster than calling Shape's constructor
WithFlags(ArrayFlags, ArrayFlags)
Creates a shape with modified flags (for clearing WRITEABLE on broadcasts, or setting/clearing OWNDATA at the UnmanagedStorage funnels).
public Shape WithFlags(ArrayFlags flagsToSet = ArrayFlags.None, ArrayFlags flagsToClear = ArrayFlags.None)
Parameters
flagsToSetArrayFlagsflagsToClearArrayFlags
Returns
Remarks
Dimensions and strides are unchanged, so size and NumSharp.Shape._hashCode are carried over verbatim through the no-walk constructor instead of being recomputed.
Operators
operator ==(Shape, Shape)
public static bool operator ==(Shape a, Shape b)
Parameters
Returns
explicit operator int(Shape)
public static explicit operator int(Shape shape)
Parameters
shapeShape
Returns
explicit operator int[](Shape)
public static explicit operator int[](Shape shape)
Parameters
shapeShape
Returns
- int[]
explicit operator long(Shape)
public static explicit operator long(Shape shape)
Parameters
shapeShape
Returns
explicit operator long[](Shape)
public static explicit operator long[](Shape shape)
Parameters
shapeShape
Returns
- long[]
explicit operator (long, long, long, long, long, long)(Shape)
public static explicit operator (long, long, long, long, long, long)(Shape shape)
Parameters
shapeShape
Returns
explicit operator (long, long, long, long, long)(Shape)
public static explicit operator (long, long, long, long, long)(Shape shape)
Parameters
shapeShape
Returns
explicit operator (long, long, long, long)(Shape)
public static explicit operator (long, long, long, long)(Shape shape)
Parameters
shapeShape
Returns
explicit operator (long, long, long)(Shape)
public static explicit operator (long, long, long)(Shape shape)
Parameters
shapeShape
Returns
explicit operator (long, long)(Shape)
public static explicit operator (long, long)(Shape shape)
Parameters
shapeShape
Returns
explicit operator int[](Shape?)
public static explicit operator int[](Shape? shape)
Parameters
shapeShape?
Returns
- int[]
explicit operator long[](Shape?)
public static explicit operator long[](Shape? shape)
Parameters
shapeShape?
Returns
- long[]
implicit operator Shape(int)
public static implicit operator Shape(int dim)
Parameters
dimint
Returns
implicit operator Shape(int[])
public static implicit operator Shape(int[] dims)
Parameters
dimsint[]
Returns
implicit operator Shape?(int[]?)
public static implicit operator Shape?(int[]? shape)
Parameters
shapeint[]
Returns
implicit operator Shape(long)
public static implicit operator Shape(long dim)
Parameters
dimlong
Returns
implicit operator Shape(long[])
public static implicit operator Shape(long[] dims)
Parameters
dimslong[]
Returns
implicit operator Shape?(long[]?)
public static implicit operator Shape?(long[]? shape)
Parameters
shapelong[]
Returns
implicit operator Shape((int, int, int, int, int, int))
public static implicit operator Shape((int, int, int, int, int, int) dims)
Parameters
Returns
implicit operator Shape((int, int, int, int, int))
public static implicit operator Shape((int, int, int, int, int) dims)
Parameters
Returns
implicit operator Shape((int, int, int, int))
public static implicit operator Shape((int, int, int, int) dims)
Parameters
Returns
implicit operator Shape((int, int, int))
public static implicit operator Shape((int, int, int) dims)
Parameters
Returns
implicit operator Shape((int, int))
public static implicit operator Shape((int, int) dims)
Parameters
Returns
implicit operator Shape((long, long, long, long, long, long))
public static implicit operator Shape((long, long, long, long, long, long) dims)
Parameters
Returns
implicit operator Shape((long, long, long, long, long))
public static implicit operator Shape((long, long, long, long, long) dims)
Parameters
Returns
implicit operator Shape((long, long, long, long))
public static implicit operator Shape((long, long, long, long) dims)
Parameters
Returns
implicit operator Shape((long, long, long))
public static implicit operator Shape((long, long, long) dims)
Parameters
Returns
implicit operator Shape((long, long))
public static implicit operator Shape((long, long) dims)
Parameters
Returns
operator !=(Shape, Shape)
public static bool operator !=(Shape a, Shape b)