Documentation
¶
Overview ¶
Package ndarray is a pure-Go (CGO=0) NumPy-style N-dimensional array library.
An array holds one of thirteen element types (DType), chosen at run time as in NumPy and combined by NumPy's promotion rules; Float64 is the default and the most optimised. The numeric kernels live in internal/kernels behind a contiguous-slice API: go-asmgen SIMD kernels on amd64, arm64, ppc64le, loong64, riscv64 and s390x, pure Go on the 32-bit targets. See docs/plan-ndarray.md for the roadmap.
Large operations are spread over GOMAXPROCS goroutines. After the first one, the package keeps up to GOMAXPROCS-1 helper goroutines for this: when an operation ends they poll for the next one for 200 µs, then block until it comes. They are never stopped, so a goroutine-leak check that runs after ndarray operations will see them.
Arrays are stored row-major (C-order). An Array is a view over a flat data slice described by a shape, per-axis strides (in elements) and a base offset, so reshaping and transposing can be zero-copy where possible.
Index ¶
- Variables
- func Data[T elemT](a *Array) (data []T, ok bool)
- func Item[T elemT](a *Array, idx ...int) T
- type Array
- func Arange(start, stop, step float64) (*Array, error)
- func Concatenate(arrays []*Array, axis int) (*Array, error)
- func Eye(n, m, k int) (*Array, error)
- func FromData(data []float64, shape ...int) (*Array, error)
- func FromSlice[T elemT](data []T, shape ...int) (*Array, error)
- func Full(v float64, shape ...int) (*Array, error)
- func FullOf(dt DType, v complex128, shape ...int) (*Array, error)
- func HStack(arrays []*Array) (*Array, error)
- func Identity(n int) (*Array, error)
- func Linspace(start, stop float64, num int) (*Array, error)
- func New(shape ...int) (*Array, error)
- func Ones(shape ...int) (*Array, error)
- func OnesOf(dt DType, shape ...int) (*Array, error)
- func Scalar(v any) *Array
- func Stack(arrays []*Array, axis int) (*Array, error)
- func VStack(arrays []*Array) (*Array, error)
- func Where(cond, t, f *Array) (*Array, error)
- func Zeros(shape ...int) (*Array, error)
- func ZerosOf(dt DType, shape ...int) (*Array, error)
- func (a *Array) Abs() *Array
- func (a *Array) Add(b *Array) (*Array, error)
- func (a *Array) AddInto(out, b *Array) error
- func (a *Array) AddScalar(v float64) *Array
- func (a *Array) All() bool
- func (a *Array) Angle() *Array
- func (a *Array) Any() bool
- func (a *Array) ArgMax() (int, error)
- func (a *Array) ArgMaxAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) ArgMin() (int, error)
- func (a *Array) ArgMinAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) AsType(dt DType) *Array
- func (a *Array) At(idx ...int) float64
- func (a *Array) AtComplex(idx ...int) complex128
- func (a *Array) Ceil() *Array
- func (a *Array) Clip(lo, hi float64) (*Array, error)
- func (a *Array) Conj() *Array
- func (a *Array) Copy() *Array
- func (a *Array) Cos() *Array
- func (a *Array) CumProd(axis int) (*Array, error)
- func (a *Array) CumProdFlat() *Array
- func (a *Array) CumSum(axis int) (*Array, error)
- func (a *Array) CumSumFlat() *Array
- func (a *Array) DType() DType
- func (a *Array) Detach() *Array
- func (a *Array) Display() map[string][]byte
- func (a *Array) Div(b *Array) (*Array, error)
- func (a *Array) DivInto(out, b *Array) error
- func (a *Array) DivScalar(v float64) *Array
- func (a *Array) Dot(b *Array) (*Array, error)
- func (a *Array) Equal(b *Array) (*Array, error)
- func (a *Array) Exp() *Array
- func (a *Array) ExpandDims(axis int) (*Array, error)
- func (a *Array) Flatten() *Array
- func (a *Array) Floor() *Array
- func (a *Array) Greater(b *Array) (*Array, error)
- func (a *Array) GreaterEqual(b *Array) (*Array, error)
- func (a *Array) Imag() *Array
- func (a *Array) Inner(b *Array) (*Array, error)
- func (a *Array) Less(b *Array) (*Array, error)
- func (a *Array) LessEqual(b *Array) (*Array, error)
- func (a *Array) Log() *Array
- func (a *Array) Log2() *Array
- func (a *Array) Log10() *Array
- func (a *Array) LogicalAnd(b *Array) (*Array, error)
- func (a *Array) LogicalNot() *Array
- func (a *Array) LogicalOr(b *Array) (*Array, error)
- func (a *Array) LogicalXor(b *Array) (*Array, error)
- func (a *Array) Map(f func(float64) float64) *Array
- func (a *Array) MarshalBinary() ([]byte, error)
- func (a *Array) MaskSelect(mask *Array) (*Array, error)
- func (a *Array) MatMul(b *Array) (*Array, error)
- func (a *Array) Max() (float64, error)
- func (a *Array) MaxAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) Maximum(b *Array) (*Array, error)
- func (a *Array) Mean() (float64, error)
- func (a *Array) MeanAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) Min() (float64, error)
- func (a *Array) MinAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) Minimum(b *Array) (*Array, error)
- func (a *Array) Mul(b *Array) (*Array, error)
- func (a *Array) MulInto(out, b *Array) error
- func (a *Array) MulScalar(v float64) *Array
- func (a *Array) Ndim() int
- func (a *Array) Neg() *Array
- func (a *Array) Nonzero() *Array
- func (a *Array) NotEqual(b *Array) (*Array, error)
- func (a *Array) Outer(b *Array) *Array
- func (a *Array) Power(p float64) *Array
- func (a *Array) Prod() float64
- func (a *Array) ProdAll() *Array
- func (a *Array) ProdAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) Ravel() *Array
- func (a *Array) Real() *Array
- func (a *Array) Repr() string
- func (a *Array) Reshape(shape ...int) (*Array, error)
- func (a *Array) Round() *Array
- func (a *Array) Set(v float64, idx ...int)
- func (a *Array) SetComplex(v complex128, idx ...int)
- func (a *Array) Shape() []int
- func (a *Array) Sin() *Array
- func (a *Array) Size() int
- func (a *Array) Slice(idx ...Index) (*Array, error)
- func (a *Array) Sqrt() *Array
- func (a *Array) SqrtInto(out *Array) error
- func (a *Array) Square() *Array
- func (a *Array) Squeeze(axes ...int) (*Array, error)
- func (a *Array) String() string
- func (a *Array) Sub(b *Array) (*Array, error)
- func (a *Array) SubInto(out, b *Array) error
- func (a *Array) SubScalar(v float64) *Array
- func (a *Array) Sum() float64
- func (a *Array) SumAll() *Array
- func (a *Array) SumAxis(axis int, keepdims bool) (*Array, error)
- func (a *Array) Take(indices ...int) (*Array, error)
- func (a *Array) Tan() *Array
- func (a *Array) Transpose() *Array
- func (a *Array) UnmarshalBinary(b []byte) error
- type DType
- type Index
- type Workspace
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrAxis = errors.New("ndarray: axis out of range")
ErrAxis is returned when an axis argument is out of range for the array.
var ErrBroadcast = errors.New("ndarray: shapes are not broadcastable")
ErrBroadcast is returned when two shapes cannot be broadcast together.
var ErrDType = fmt.Errorf("ndarray: unsupported dtype")
ErrDType is returned when an operation is not defined for an array's dtype, or a dtype name is not known.
var ErrFormat = errors.New("ndarray: not an encoded array")
ErrFormat is returned by UnmarshalBinary for bytes that are not an array.
var ErrIndex = errors.New("ndarray: index out of range")
ErrIndex is returned when an integer index or slice argument is out of range for the axis it addresses, or when the number of index arguments does not match the array's rank.
var ErrLinalg = fmt.Errorf("ndarray: incompatible shapes for linear algebra")
ErrLinalg is returned when operands have shapes incompatible with the requested linear-algebra operation (e.g. a dimension mismatch in matrix multiply).
var ErrShapeMismatch = errors.New("ndarray: shape mismatch")
ErrShapeMismatch is returned when a requested shape is invalid or incompatible with the data it must describe.
Functions ¶
func Data ¶ added in v0.10.0
Data returns the array's elements as a contiguous row-major []T. T must be the element type of the array's dtype (int8 for Int8, complex128 for Complex128 ...); otherwise ok is false. The slice is the array's own storage when the array is contiguous and a copy otherwise, so write through it only to an array you made.
Types ¶
type Array ¶
type Array struct {
// contains filtered or unexported fields
}
Array is an N-dimensional, row-major array. Its element type is a runtime property, DType (Float64 unless made otherwise).
func Arange ¶
Arange returns a 1-D array of evenly spaced values over [start, stop) with the given step, matching numpy.arange. step must be non-zero.
It follows numpy's algorithm rather than accumulating v += step: the length is ceil((stop-start)/step), and element i is start + i*delta with delta = (start+step) - start. Accumulating drifts (Arange(1, 1.3, 0.1) gave 3 elements; numpy gives 4), and it never terminates when start+step == start (Arange(1e16, 1e16+10, 1)) or stop is infinite. A NaN operand or a length beyond the addressable size is an error, as in numpy.
func Concatenate ¶
Concatenate joins the given arrays along an existing axis, matching numpy.concatenate. Every array must have the same rank and the same shape on every axis except the concatenation axis; a negative axis counts from the end. At least one array is required. The result is a fresh contiguous array.
func Eye ¶
Eye returns an array with ones on the k-th diagonal and zeros elsewhere, matching numpy.eye(n, m, k). A non-positive m defaults to n (a square matrix), the common case; pass m > 0 for a rectangular result. k > 0 selects a superdiagonal, k < 0 a subdiagonal. n must be non-negative.
func FromData ¶
FromData wraps data in an array of the given shape. The data slice is copied, so later mutations of the caller's slice do not affect the array. The number of elements implied by shape must equal len(data).
func FromSlice ¶ added in v0.10.0
FromSlice wraps a copy of data in an array of the given shape. The dtype is the one whose element type is T. It is the typed counterpart of FromData.
func FullOf ¶ added in v0.10.0
func FullOf(dt DType, v complex128, shape ...int) (*Array, error)
FullOf returns an array of the given dtype and shape filled with v, converted to the dtype as AsType converts.
func HStack ¶
HStack stacks arrays horizontally (column-wise), matching numpy.hstack: concatenation along axis 1, except that 1-D inputs are joined along axis 0 (their only axis).
func Linspace ¶
Linspace returns num evenly spaced samples over the closed interval [start, stop], matching numpy.linspace with the default endpoint=True. num must be non-negative; num == 0 yields an empty array and num == 1 yields [start]. The spacing is (stop-start)/(num-1) for num > 1.
func OnesOf ¶ added in v0.10.0
OnesOf returns an array of the given dtype and shape filled with one.
func Scalar ¶ added in v0.10.0
Scalar returns a 0-d array holding v, to combine with arrays. A Go int, float or complex (of any size) is "weak", as a Python scalar is in NumPy 2: it takes the other operand's dtype when that can hold it, so
int8Array.Add(Scalar(1)) // int8 float32Array.Mul(Scalar(0.5)) // float32 int8Array.Add(Scalar(0.5)) // float64
A bool gives a Bool array. Scalar panics on any other type.
func Stack ¶
Stack joins the given arrays along a new axis, matching numpy.stack. Every array must have identical shape; the new axis is inserted at the given position, which may range over [-(Ndim+1), Ndim]. The result has rank Ndim+1.
func VStack ¶
VStack stacks arrays vertically (row-wise), matching numpy.vstack: 1-D inputs of length n are treated as (1, n) rows, then all inputs are concatenated along axis 0.
func Where ¶
Where returns an array selecting from t where cond is truthy (non-zero) and from f otherwise, elementwise with full NumPy broadcasting across all three operands — matching numpy.where(cond, t, f). cond is typically a Bool mask from the comparison ufuncs; any dtype is read by truthiness. The result has the common dtype of t and f.
func (*Array) Abs ¶
Abs returns the elementwise absolute value. For a complex array it is the modulus, as a float array of the same precision; other dtypes are kept.
func (*Array) AddInto ¶
AddInto writes a+b into out (no allocation), the parity-path analogue of np.add(a, b, out=out). out must be contiguous and the broadcast result shape; it may alias a or b. See binOpInto.
func (*Array) All ¶ added in v0.10.0
All reports whether every element is non-zero (true for an empty array).
func (*Array) Angle ¶ added in v0.10.0
Angle returns the argument of each element in radians, as numpy.angle: a float array (float32 for complex64, float64 otherwise).
func (*Array) ArgMax ¶
ArgMax returns the flat index of the first maximum element over the array in row-major order, matching numpy.argmax with no axis. It errors on an empty array.
func (*Array) ArgMaxAxis ¶
ArgMaxAxis returns the indices of the first maxima along the given axis, matching numpy.argmax(axis=...). The result is an Int64 array of the reduced shape (the axis removed, or kept as length 1 with keepdims). A negative axis counts from the end.
func (*Array) ArgMin ¶
ArgMin returns the flat index of the first minimum element over the array in row-major order, matching numpy.argmin with no axis. It errors on an empty array.
func (*Array) ArgMinAxis ¶
ArgMinAxis returns the indices of the first minima along the given axis, matching numpy.argmin(axis=...). See ArgMaxAxis for the shape semantics.
func (*Array) AsType ¶ added in v0.10.0
AsType returns a contiguous copy of the array converted to dtype dt, like NumPy's astype. Conversions follow Go's, with these definitions where Go leaves the result to the platform or NumPy to the hardware:
- float to integer truncates toward zero and saturates: values beyond the type's range, and infinities, give its minimum or maximum, and NaN gives 0. NumPy leaves these casts undefined and they differ by platform (on arm64 it saturates to 64 bits and then wraps, so +Inf to int8 is -1; on x86 NaN gives the minimum); here they are the same everywhere;
- complex to real keeps the real part (NumPy warns, Go cannot);
- anything to Bool is "not zero", so NaN is true.
func (*Array) At ¶
At returns the element at the given multi-dimensional index. For a dtype other than Float64 the element is converted to float64; on a complex array At panics (the imaginary part would be lost): use AtComplex.
func (*Array) AtComplex ¶ added in v0.10.0
func (a *Array) AtComplex(idx ...int) complex128
AtComplex returns the element at the given index as a complex128, for an array of any dtype.
func (*Array) Clip ¶
Clip returns a new array with every element limited to the range [lo, hi], matching numpy.clip. It errors if lo > hi.
func (*Array) CumProd ¶
CumProd returns the cumulative product along the given axis, matching numpy.cumprod(axis=...). The result has the same shape as the input.
func (*Array) CumProdFlat ¶
CumProdFlat returns the cumulative product over the flattened array (1-D, row-major order), matching numpy.cumprod with no axis.
func (*Array) CumSum ¶
CumSum returns the cumulative sum along the given axis, matching numpy.cumsum(axis=...). The result has the same shape as the input. A negative axis counts from the end.
func (*Array) CumSumFlat ¶
CumSumFlat returns the cumulative sum over the flattened array (1-D, row-major order), matching numpy.cumsum with no axis.
func (*Array) Detach ¶ added in v0.2.0
Detach returns a heap copy of a that is not bound to any workspace: the way a result computed in a workspace outlives its Reset.
func (*Array) Display ¶ added in v0.10.0
Display shows the array in a notebook: its Repr as text, and as an HTML table for one and two dimensions.
func (*Array) Dot ¶
Dot returns the dot product following numpy.dot for 1-D and 2-D operands:
- 1-D · 1-D -> a 0-d (scalar) array, the inner product.
- 2-D · 2-D -> matrix multiply (m x k)·(k x n) = (m x n).
- 2-D · 1-D -> matrix-vector (m x k)·(k,) = (m,).
- 1-D · 2-D -> vector-matrix (k,)·(k x n) = (n,).
Higher-rank operands are rejected (the general tensordot is a later phase).
func (*Array) Exp ¶
Exp returns the elementwise base-e exponential.
It runs a table-driven port of Arm's optimized-routines exp (0.51 ULP worst case, measured), split across cores: several times faster than math.Exp per element, and finite up to ln(MaxFloat64) on amd64, where math.Exp returns +Inf from x ~ 709.436 (golang/go#81995; Go 1.26.8 and 1.27.1).
func (*Array) ExpandDims ¶
ExpandDims returns a view with a new length-1 axis inserted at the given position, matching numpy.expand_dims. axis may range over [-(Ndim+1), Ndim]; a negative axis counts from the end of the result.
func (*Array) Flatten ¶
Flatten returns a contiguous 1-D copy of the array's elements in row-major order. Unlike Ravel, the result is always an independent copy (NumPy flatten semantics; here Ravel is also a copy, but Flatten documents the always-copy contract).
func (*Array) GreaterEqual ¶
GreaterEqual returns the elementwise a >= b mask.
func (*Array) Imag ¶ added in v0.10.0
Imag returns the imaginary part of the elements: a float array of the same precision for a complex array, zeros of a's dtype otherwise (as numpy.imag).
func (*Array) Inner ¶
Inner returns the inner product over the last axes, matching numpy.inner for 1-D and 2-D operands: a sum-product over the last axis, which must have the same length in both operands.
- 1-D · 1-D -> scalar (same as Dot).
- 2-D · 2-D -> (m x p) where a is (m x k), b is (p x k): out[i,j] is the dot of row i of a with row j of b.
func (*Array) Log ¶
Log returns the elementwise natural logarithm.
It runs a table-driven port of Arm's optimized-routines log (0.51 ULP worst case, measured), split across cores: about twice as fast as math.Log, and correct for subnormal inputs on amd64, where math.Log is not (log(5e-324) gives -709.09 instead of -744.44; golang/go#56600).
func (*Array) Log10 ¶
Log10 returns the elementwise base-10 logarithm, log(x)*(1/ln10) as math.Log10 computes it, on the same log as Log (so subnormals are right).
func (*Array) LogicalAnd ¶ added in v0.10.0
LogicalAnd returns the elementwise "a and b" of the operands' truthiness, with broadcasting, as a Bool array.
func (*Array) LogicalNot ¶ added in v0.10.0
LogicalNot returns the elementwise "not zero is false" of a, as a Bool array.
func (*Array) LogicalOr ¶ added in v0.10.0
LogicalOr returns the elementwise "a or b" of the operands' truthiness.
func (*Array) LogicalXor ¶ added in v0.10.0
LogicalXor returns the elementwise "a xor b" of the operands' truthiness.
func (*Array) Map ¶
Map returns a new contiguous array with f applied to every element. For a contiguous receiver the elements are read in place (no materialise copy); the elementwise pass is parallelised across cores above the kernel threshold. f must be safe to call concurrently (the package's math ufuncs are), and should not panic: on a large array a panic may happen on a worker goroutine, which ends the program as any unrecovered goroutine panic does. A panic on the calling goroutine propagates once the workers have stopped writing.
On an array of another dtype, f is applied to the elements converted to float64 and the result is Float64; on a complex array Map panics.
func (*Array) MarshalBinary ¶ added in v0.10.0
MarshalBinary encodes the array: its dtype, its shape and its elements in row-major order. A view is encoded as the array it shows. It implements encoding.BinaryMarshaler, so an array can be kept by gob and by a notebook kernel.
func (*Array) MaskSelect ¶
MaskSelect returns a 1-D array of the elements of a where mask is truthy (non-zero), in row-major order: NumPy's a[mask] for a mask of a's shape, the usual case (a mask from a.Greater(...)). mask may also broadcast to a's shape, which NumPy rejects (IndexError): a (3,) mask selects the same columns of every row of a (2, 3). Two NumPy forms differ: a mask covering only the leading axes, a[rowmask], is rejected here unless it broadcasts; and a 0-d mask selects all or none of a, flattened, where NumPy returns a with a new leading axis of length 1 or 0.
func (*Array) MatMul ¶
MatMul returns the matrix product of two 2-D arrays, matching numpy.matmul (the @ operator) for the 2-D case: a is (m x k), b is (k x n), the result is (m x n). Both operands must be 2-D and the inner dimensions must agree.
func (*Array) Max ¶
Max returns the maximum element. It returns an error for an empty array. On a complex array it panics; use MaxAxis.
func (*Array) MaxAxis ¶
MaxAxis returns the maximum along the given axis. See SumAxis for the axis/keepdims semantics.
func (*Array) Mean ¶
Mean returns the arithmetic mean of all elements. It returns an error for an empty array. On a complex array it panics; use MeanAxis.
func (*Array) MeanAxis ¶
MeanAxis returns the arithmetic mean along the given axis. See SumAxis for the axis/keepdims semantics.
The mean of an integer or Bool array is Float64; Float32 and complex arrays keep their dtype.
func (*Array) Min ¶
Min returns the minimum element. It returns an error for an empty array. On a complex array it panics; use MinAxis.
func (*Array) MinAxis ¶
MinAxis returns the minimum along the given axis. See SumAxis for the axis/keepdims semantics.
func (*Array) Neg ¶
Neg returns the elementwise negation.
Integer arrays wrap, as in NumPy; negating a Bool array panics (use LogicalNot).
func (*Array) Nonzero ¶
Nonzero returns a 1-D Int64 array of the flat (row-major) indices at which a is non-zero — NumPy's np.flatnonzero(a). For a mask this is the positions of the true elements.
func (*Array) Outer ¶
Outer returns the outer product of two arrays, matching numpy.outer: both operands are flattened to 1-D vectors u (length m) and v (length n), and the result is the (m x n) array out[i,j] = u[i]*v[j].
func (*Array) Power ¶
Power returns the elementwise a**p (every element raised to p).
p is a weak float: Float32 and complex arrays keep their dtype, integer and Bool arrays give Float64.
func (*Array) Prod ¶
Prod returns the product of all elements (1 for an empty array). See Sum for other dtypes; ProdAll keeps the dtype.
func (*Array) ProdAll ¶ added in v0.10.0
ProdAll returns the product of all elements as a 0-d array; see SumAll.
func (*Array) ProdAxis ¶
ProdAxis returns the product along the given axis. See SumAxis for the axis/keepdims semantics.
func (*Array) Ravel ¶
Ravel returns a contiguous 1-D array containing the elements in row-major order.
func (*Array) Real ¶ added in v0.10.0
Real returns the real part of the elements: a float array of the same precision for a complex array, a copy otherwise (as numpy.real).
func (*Array) Repr ¶ added in v0.10.0
Repr returns the array as NumPy's repr shows it: array([...]), followed by the shape when the elements are summarised or the array is empty, and the dtype when the values do not imply it (float64, int64, bool and complex128 do) or the array is empty.
func (*Array) Reshape ¶
Reshape returns a view (or copy) of the array with a new shape of the same total size. The data is preserved in row-major order. At most one dimension may be -1, which is inferred from the total size (NumPy semantics).
func (*Array) Set ¶
Set stores v at the given multi-dimensional index, converted to the array's dtype as AsType converts.
func (*Array) SetComplex ¶ added in v0.10.0
func (a *Array) SetComplex(v complex128, idx ...int)
SetComplex stores v at the given index, converted to the array's dtype as AsType converts (a real dtype keeps the real part).
func (*Array) Slice ¶
Slice returns a view of the array selected by per-axis indices, following NumPy basic-indexing semantics. It accepts up to Ndim index arguments (build them with A, All, R, Rng, From, To, Step); as in NumPy, the axes left unindexed are taken whole, so a.Slice(A(1)) of a matrix is its second row and a.Slice() is a view of all of a. Integer indices (A) drop their axis; range indices keep the axis as a strided view that shares the receiver's backing data — writes through the view are visible in the original and vice versa. The result may have a non-zero offset and arbitrary strides.
func (*Array) Sqrt ¶
Sqrt returns the elementwise non-negative square root. It is routed through the dedicated SIMD sqrt kernel (packed SQRTPD on amd64; the intrinsic FSQRTD scalar loop on arm64/others) rather than the generic Map, because passing math.Sqrt as a func(float64)float64 blocks both the compiler's FSQRTD intrinsic and the packed kernel. The result is bit-identical to a scalar math.Sqrt loop (sqrt(-x)=NaN, sqrt(+Inf)=+Inf, matching NumPy).
func (*Array) SqrtInto ¶
SqrtInto writes the elementwise square root of a into the caller-provided contiguous out array (no allocation), the analogue of np.sqrt(a, out=out) and the parity path for small arrays where Go's per-op make would otherwise cost more than NumPy's cached temp buffer. out must be contiguous and the same shape as a; it may alias a (each index is read before it is written). It routes through the same SIMD sqrt kernel as Sqrt (packed SQRTPD on amd64, the FSQRTD-intrinsic scalar loop on arm64/others), bit-identical to math.Sqrt.
func (*Array) Square ¶
Square returns the elementwise square x*x. Integers wrap and keep their dtype; a Bool array gives Int8, as in NumPy.
func (*Array) Squeeze ¶
Squeeze returns a view with length-1 axes removed. With no axes given, every length-1 axis is removed; otherwise only the listed axes are removed and each must have length 1 (NumPy semantics). Negative axes count from the end.
func (*Array) String ¶
String renders the array's shape and its elements in row-major order, and its dtype when that is not Float64.
func (*Array) Sum ¶
Sum returns the sum of all elements (0 for an empty array). Large sums are computed as a tree of per-core partials, so the result can differ from a strictly left-to-right sum by a few ULP (floating-point addition is not associative) — the same trade-off NumPy's pairwise summation makes.
For another dtype the sum is accumulated as NumPy accumulates it (exactly, in int64 or uint64, for integers) and converted to float64; on a complex array Sum panics: SumAll keeps the dtype.
func (*Array) SumAll ¶ added in v0.10.0
SumAll returns the sum of all elements as a 0-d array of the dtype NumPy gives it: Int64 for bools and signed integers, Uint64 for unsigned, the array's own dtype otherwise. Unlike Sum, it holds every dtype exactly, including the complex ones and integers beyond 2^53.
func (*Array) SumAxis ¶
SumAxis returns the sum along the given axis. With keepdims the reduced axis is kept with length 1 (e.g. (2,3) summed over axis 0 -> (1,3)); otherwise it is removed (-> (3,)). A negative axis counts from the end.
func (*Array) Take ¶
Take returns a 1-D array gathering a's flattened (row-major) elements at the given integer indices — NumPy's a.take(indices) / fancy indexing a[idx]. Negative indices count from the end; an out-of-range index errors.
func (*Array) Transpose ¶
Transpose returns a view with the axes reversed. No data is copied; only the shape and strides are permuted.
func (*Array) UnmarshalBinary ¶ added in v0.10.0
UnmarshalBinary decodes what MarshalBinary wrote into a, replacing its contents. The bytes may come from anywhere: a shape the length of the data does not account for is an error before anything is allocated.
type DType ¶ added in v0.10.0
type DType uint8
DType is the element type of an Array. It is a runtime property, as in NumPy: one Array type holds any of them, and operations on two arrays pick the result type from both operands (see ResultType). The zero value is Float64, so every array built before dtypes existed keeps its meaning.
const ( Float64 DType = iota Bool Int8 Int16 Int32 Int64 Uint8 Uint16 Uint32 Uint64 Float32 Complex64 Complex128 )
The element types. Their names, sizes and promotion follow NumPy.
func ParseDType ¶ added in v0.10.0
ParseDType returns the dtype with the given NumPy name.
func ResultType ¶ added in v0.10.0
ResultType returns the dtype NumPy gives the result of combining arrays of dtypes a and b, numpy.result_type(a, b):
- Bool gives way to anything.
- Two integers of the same signedness give the larger; a signed and an unsigned give the smallest signed type holding both, and Float64 when there is none (Int64 with Uint64).
- An integer with a float or complex type gives that type when the integer fits its mantissa exactly (8- and 16-bit integers with Float32 and Complex64), else the 64-bit float or complex type.
- Floats and complexes give the wider, complex when either is.
The table this produces is checked against NumPy 2.5.3 cell by cell.
func (DType) IsInteger ¶ added in v0.10.0
IsInteger reports whether d is a signed or unsigned integer type.
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index describes how a single axis is indexed by Slice. It is either an integer index (which removes that axis from the result, NumPy basic-indexing semantics) or a half-open range start:stop:step (which keeps the axis as a strided view). Construct one with A (integer) or R / Rng (range).
func A ¶
A returns an integer Index that selects position i along an axis and removes that axis from the result, mirroring NumPy's a[i] basic indexing. A negative i counts from the end of the axis.
func All ¶
func All() Index
All returns a range Index covering an entire axis with step 1, the equivalent of NumPy's a[:].
func From ¶
From returns a range Index for start: (to the end of the axis) with step 1 (NumPy a[start:]).
func R ¶
R returns a range Index for start:stop with step 1, keeping the axis as a view (NumPy a[start:stop]). Negative bounds count from the end of the axis.
func Rng ¶
Rng returns a range Index for start:stop:step, keeping the axis as a view (NumPy a[start:stop:step]). Negative bounds count from the end; step may be negative to reverse, but must not be zero.
type Workspace ¶ added in v0.2.0
type Workspace struct {
// contains filtered or unexported fields
}
Workspace is an arena for the results of array operations, for loops that compute the same shapes over and over. Bind an input with Use; every result computed from a bound array (and every result computed from those) takes its memory from the workspace instead of the Go heap, and Reset hands all of it back at once:
ws := ndarray.NewWorkspace()
for step := 0; step < n; step++ {
x := ws.Use(state)
y, _ := x.Mul(w) // from the workspace
z, _ := y.Add(bias) // from the workspace
state = z.Detach() // the one result that must outlive the step
ws.Reset()
}
After the first pass the arena holds the peak footprint of one pass in a single block, and later passes allocate nothing: no garbage-collector cycles, no zeroing of memory the kernel overwrites anyway, and the same cache-warm bytes every time. This is the workspace pattern of ND4J, the Java ndarray library, and the scoped counterpart of NumPy's reference-count free-list, which a garbage-collected language does not have. The *Into methods (AddInto, SqrtInto, ...) remain the way to reuse one named buffer.
⚠ Reset invalidates every array allocated from the workspace since the previous Reset, and every view of one: their memory is reused by the next results, so reading them afterwards returns other values. Detach (a heap copy, unbound) is how a result leaves the workspace. Arrays bound with Use but not allocated from it (the inputs) are not affected.
A Workspace may be used from several goroutines; allocation is serialized. The zero value is an empty workspace ready to use.
Example ¶
package main
import (
"fmt"
"github.com/go-ndarray/ndarray"
)
func main() {
state, _ := ndarray.FromData([]float64{1, 4, 9}, 3)
w, _ := ndarray.FromData([]float64{2, 2, 2}, 3)
bias, _ := ndarray.FromData([]float64{0, 1, 2}, 3)
ws := ndarray.NewWorkspace()
for step := 0; step < 3; step++ {
x := ws.Use(state) // results computed from x come from ws
p, _ := x.Mul(w)
q, _ := p.Add(bias)
state = q.Sqrt().Detach() // the one result that outlives the pass
ws.Reset() // everything else is recycled
}
fmt.Printf("%.4f %.4f %.4f\n", state.At(0), state.At(1), state.At(2))
}
Output: 1.8340 2.5083 2.9354
func NewWorkspace ¶ added in v0.2.0
func NewWorkspace() *Workspace
NewWorkspace returns an empty workspace. It holds no memory until the first allocation.
func (*Workspace) Reset ¶ added in v0.2.0
func (w *Workspace) Reset()
Reset makes all memory allocated from w since the last Reset available again (see the warning on Workspace). If the pass needed more than one block, they are replaced by a single block of the pass's total, so a repeated pass settles into one contiguous block.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fft is numpy.fft for ndarray arrays: the discrete Fourier transforms of go-fft (github.com/go-fft/fft), applied along any axes of an N-dimensional array, with numpy's n/s, axes and norm arguments and its dtypes.
|
Package fft is numpy.fft for ndarray arrays: the discrete Fourier transforms of go-fft (github.com/go-fft/fft), applied along any axes of an N-dimensional array, with numpy's n/s, axes and norm arguments and its dtypes. |
|
internal
|
|
|
kernels
Package kernels holds the inner numeric loops for the ndarray package.
|
Package kernels holds the inner numeric loops for the ndarray package. |
|
kernels/asmgen
module
|
|
|
Package linalg is numpy.linalg for ndarray arrays, in pure Go: solving, inverting, determinants, the Cholesky, QR, singular-value and eigenvalue decompositions, least squares, pseudo-inverses, ranks, norms and condition numbers.
|
Package linalg is numpy.linalg for ndarray arrays, in pure Go: solving, inverting, determinants, the Cholesky, QR, singular-value and eigenvalue decompositions, least squares, pseudo-inverses, ranks, norms and condition numbers. |
|
Package random is numpy.random for go-ndarray: the same numbers as NumPy for the same seed.
|
Package random is numpy.random for go-ndarray: the same numbers as NumPy for the same seed. |
