Struct Shape
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
Broadcasting operations for Shape.
public readonly struct Shape : ICloneable, IEquatable<Shape>
- Implements
- Inherited Members
- Extension Methods
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[])
Primary constructor with long dimensions.
public Shape(params long[] dims)
Parameters
dimslong[]
Shape(long[], long[])
public Shape(long[] dims, long[] strides)
Parameters
Shape(long[], long[], Shape)
public Shape(long[] dims, long[] strides, Shape originalShape)
Parameters
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
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
public long[] Dimensions { get; }
Property Value
- long[]
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
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
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]
public long this[int dim] { get; set; }
Parameters
dimint
Property Value
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
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? False for views (slices, transposes, broadcasts). Cached flag set at storage level.
public bool OwnsData { get; }
Property Value
Size
The linear size of this shape.
public long Size { get; }
Property Value
Strides
public long[] Strides { get; }
Property Value
- long[]
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[]
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
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)
public static long[] GetAxis(long[] dims, int axis)
Parameters
Returns
- long[]
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[]
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
offsetlongThe offset within the bounds of NumSharp.Shape.size.
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).
public Shape WithFlags(ArrayFlags flagsToSet = ArrayFlags.None, ArrayFlags flagsToClear = ArrayFlags.None)
Parameters
flagsToSetArrayFlagsflagsToClearArrayFlags
Returns
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)