Table of Contents

Struct Shape

Namespace
NumSharp
Assembly
NumSharp.dll

Represents a shape of an N-D array. Immutable after construction (NumPy-aligned).

public readonly struct Shape : ICloneable, IEquatable<Shape>
Implements
Inherited Members
Extension Methods

Remarks

Handles slicing, indexing based on coordinates or linear offset and broadcastted indexing.

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

other Shape

Shape(params int[])

public Shape(params int[] dims)

Parameters

dims int[]

Shape(int[], int[])

public Shape(int[] dims, int[] strides)

Parameters

dims int[]
strides int[]

Shape(int[], int[], Shape)

public Shape(int[] dims, int[] strides, Shape originalShape)

Parameters

dims int[]
strides int[]
originalShape Shape

Fields

IsScalar

public readonly bool IsScalar

Field Value

bool

Scalar

Singleton instance of a Shape that represents a scalar.

public static readonly Shape Scalar

Field Value

Shape

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 int BufferSize { get; }

Property Value

int

Dimensions

public int[] Dimensions { get; }

Property Value

int[]

Flags

Get all array flags as a single integer. Use ArrayFlags enum for bit meanings.

public ArrayFlags Flags { get; }

Property Value

ArrayFlags

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

bool

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

bool

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

bool

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

bool

IsSimpleSlice

public bool IsSimpleSlice { get; }

Property Value

bool

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

bool

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

bool

this[int]

public int this[int dim] { get; set; }

Parameters

dim int

Property Value

int

NDim

public int NDim { get; }

Property Value

int

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 int Offset { get; }

Property Value

int

Order

public char Order { get; }

Property Value

char

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 int OriginalSize { get; }

Property Value

int

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

bool

Size

The linear size of this shape.

public int Size { get; }

Property Value

int

Strides

public int[] Strides { get; }

Property Value

int[]

Methods

Clean()

Returns a clean shape based on this (offset=0, standard strides).

public Shape Clean()

Returns

Shape

Clone(bool, bool, bool)

Creates a complete copy of this Shape.

public Shape Clone(bool deep = true, bool unview = false, bool unbroadcast = false)

Parameters

deep bool

Should make a complete deep clone or a shallow if false.

unview bool
unbroadcast bool

Returns

Shape

Deconstruct(out int, out int)

public void Deconstruct(out int dim1, out int dim2)

Parameters

dim1 int
dim2 int

Deconstruct(out int, out int, out int)

public void Deconstruct(out int dim1, out int dim2, out int dim3)

Parameters

dim1 int
dim2 int
dim3 int

Deconstruct(out int, out int, out int, out int)

public void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4)

Parameters

dim1 int
dim2 int
dim3 int
dim4 int

Deconstruct(out int, out int, out int, out int, out int)

public void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5)

Parameters

dim1 int
dim2 int
dim3 int
dim4 int
dim5 int

Deconstruct(out int, out int, out int, out int, out int, out int)

public void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5, out int dim6)

Parameters

dim1 int
dim2 int
dim3 int
dim4 int
dim5 int
dim6 int

Empty(int)

An empty shape without any fields set (all dimensions are 0).

public static Shape Empty(int ndim)

Parameters

ndim int

Returns

Shape

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

other Shape

An object to compare with this object.

Returns

bool

true if the current object is equal to the other parameter; otherwise, false.

Equals(object)

Indicates whether this instance and a specified object are equal.

public override bool Equals(object obj)

Parameters

obj object

The object to compare with the current instance.

Returns

bool

true if obj and 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

axis int

Returns

Shape

ExtractShape(Array)

Extracts the shape of given array.

public static int[] ExtractShape(Array array)

Parameters

array Array

Returns

int[]

Remarks

Supports both jagged and multi-dim.

GetAxis(Shape, int)

public static int[] GetAxis(Shape shape, int axis)

Parameters

shape Shape
axis int

Returns

int[]

GetAxis(ref Shape, int)

public static int[] GetAxis(ref Shape shape, int axis)

Parameters

shape Shape
axis int

Returns

int[]

GetAxis(int[], int)

public static int[] GetAxis(int[] dims, int axis)

Parameters

dims int[]
axis int

Returns

int[]

GetCoordinates(int)

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 int[] GetCoordinates(int offset)

Parameters

offset int

the index if you would iterate from 0 to shape.size in row major order

Returns

int[]

GetHashCode()

Serves as the default hash function.

public override int GetHashCode()

Returns

int

A hash code for the current object.

GetOffset(int*, int)

Get offset index out of coordinate indices (pointer version). NumPy-aligned: offset + sum(indices * strides)

public int GetOffset(int* indices, int ndims)

Parameters

indices int*

A pointer to the coordinates to turn into linear offset

ndims int

The number of dimensions

Returns

int

The index in the memory block that refers to a specific value.

GetOffset(params int[])

Get offset index out of coordinate indices. NumPy-aligned: offset + sum(indices * strides)

public int GetOffset(params int[] indices)

Parameters

indices int[]

The coordinates to turn into linear offset

Returns

int

The index in the memory block that refers to a specific value.

GetSize(int[])

public static int GetSize(int[] dims)

Parameters

dims int[]

Returns

int

GetSubshape(int*, int)

Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage.

public (Shape Shape, int Offset) GetSubshape(int* dims, int ndims)

Parameters

dims int*
ndims int

Returns

(Shape Shape, int Offset)

Remarks

Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.

GetSubshape(params int[])

Gets the shape based on given indicies and the index offset (C-Contiguous) inside the current storage.

public (Shape Shape, int Offset) GetSubshape(params int[] indicies)

Parameters

indicies int[]

The selection of indexes 0 based.

Returns

(Shape Shape, int Offset)

Remarks

Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.

InferNegativeCoordinates(int[], int*, 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(int[] dimensions, int* coords, int coordsCount)

Parameters

dimensions int[]

The dimensions these coordinates are targeting

coords int*

The coordinates.

coordsCount int

InferNegativeCoordinates(int[], 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 int[] InferNegativeCoordinates(int[] dimensions, int[] coords)

Parameters

dimensions int[]

The dimensions these coordinates are targeting

coords int[]

The coordinates.

Returns

int[]

Coordinates without negative indices.

Matrix(int, int)

Create a shape that represents a matrix.

public static Shape Matrix(int rows, int cols)

Parameters

rows int
cols int

Returns

Shape

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

newShape Shape
unsafe bool

When true, then guards are skipped.

Returns

Shape

Exceptions

IncorrectShapeException

If shape's size mismatches current shape size.

ArgumentException

If newShape's size == 0

Slice(params Slice[])

public Shape Slice(params Slice[] input_slices)

Parameters

input_slices Slice[]

Returns

Shape

Slice(string)

public Shape Slice(string slicing_notation)

Parameters

slicing_notation string

Returns

Shape

ToString()

Returns the fully qualified type name of this instance.

public override string ToString()

Returns

string

The fully qualified type name.

TransformOffset(int)

Retrieve the transformed offset if the shape is non-contiguous, otherwise returns offset.

public int TransformOffset(int offset)

Parameters

offset int

The offset within the bounds of NumSharp.Shape.size.

Returns

int

The transformed offset.

Remarks

For contiguous shapes, returns offset directly. For non-contiguous, translates through coordinates.

Vector(int)

Create a shape that represents a vector.

public static Shape Vector(int length)

Parameters

length int

Returns

Shape

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

flagsToSet ArrayFlags
flagsToClear ArrayFlags

Returns

Shape

Operators

operator ==(Shape, Shape)

public static bool operator ==(Shape a, Shape b)

Parameters

a Shape
b Shape

Returns

bool

explicit operator int(Shape)

public static explicit operator int(Shape shape)

Parameters

shape Shape

Returns

int

explicit operator int[](Shape)

public static explicit operator int[](Shape shape)

Parameters

shape Shape

Returns

int[]

explicit operator (int, int, int, int, int, int)(Shape)

public static explicit operator (int, int, int, int, int, int)(Shape shape)

Parameters

shape Shape

Returns

(int, int, int, int, int, int)

explicit operator (int, int, int, int, int)(Shape)

public static explicit operator (int, int, int, int, int)(Shape shape)

Parameters

shape Shape

Returns

(int, int, int, int, int)

explicit operator (int, int, int, int)(Shape)

public static explicit operator (int, int, int, int)(Shape shape)

Parameters

shape Shape

Returns

(int, int, int, int)

explicit operator (int, int, int)(Shape)

public static explicit operator (int, int, int)(Shape shape)

Parameters

shape Shape

Returns

(int, int, int)

explicit operator (int, int)(Shape)

public static explicit operator (int, int)(Shape shape)

Parameters

shape Shape

Returns

(int, int)

explicit operator Shape(int)

public static explicit operator Shape(int dim)

Parameters

dim int

Returns

Shape

implicit operator Shape(int[])

public static implicit operator Shape(int[] dims)

Parameters

dims int[]

Returns

Shape

implicit operator Shape((int, int, int, int, int, int))

public static implicit operator Shape((int, int, int, int, int, int) dims)

Parameters

dims (int, int, int, int, int, int)

Returns

Shape

implicit operator Shape((int, int, int, int, int))

public static implicit operator Shape((int, int, int, int, int) dims)

Parameters

dims (int, int, int, int, int)

Returns

Shape

implicit operator Shape((int, int, int, int))

public static implicit operator Shape((int, int, int, int) dims)

Parameters

dims (int, int, int, int)

Returns

Shape

implicit operator Shape((int, int, int))

public static implicit operator Shape((int, int, int) dims)

Parameters

dims (int, int, int)

Returns

Shape

implicit operator Shape((int, int))

public static implicit operator Shape((int, int) dims)

Parameters

dims (int, int)

Returns

Shape

operator !=(Shape, Shape)

public static bool operator !=(Shape a, Shape b)

Parameters

a Shape
b Shape

Returns

bool