Documentation
¶
Overview ¶
Package numgo is a numpy-compatible N-dimensional array library for float32/float64/complex64/complex128 element types. Binary IO covers .npy streams and .npz zip archives; PackBits/UnpackBits are pending integer dtype support.
Text IO with missing-value handling (numpy genfromtxt, simplified to uniform float columns — no structured dtypes, converters, usecols or masking; missing/failed-parse fields become the filling value and jagged rows are errors, like LoadTxt).
Index ¶
- func CopyInto[T Number](dst, src *Array[T])
- func Histogram2D[T Number](x, y *Array[T], bins int) (*Array[float64], *Array[float64], *Array[float64])
- func LoadNpz(r io.Reader) (map[string]AnyArray, error)
- func LoadNpzFile(path string) (map[string]AnyArray, error)
- func NormalizeRange(r Range, dim int) (start, n, step int)
- func Save[T Number](w io.Writer, a *Array[T]) error
- func SaveFile[T Number](path string, a *Array[T]) error
- func SaveTxt[T Number](w io.Writer, a *Array[T], format string) error
- func SaveTxtFile[T Number](path string, a *Array[T], format string) error
- func SaveZ(w io.Writer, arrays map[string]AnyArray) error
- func SaveZCompressed(w io.Writer, arrays map[string]AnyArray) error
- func SaveZFile(path string, compressed bool, arrays map[string]AnyArray) error
- type AnyArray
- type Array
- func AbsToReal[F Number, P Float](a *Array[F]) *Array[P]
- func Arange[T Number](start, stop, step T) *Array[T]
- func AsArray[T Number](data []T, shape ...int) *Array[T]
- func AsType[F, P Number](a *Array[F]) *Array[P]
- func BorrowSlice[T Number](data []T, shape ...int) *Array[T]
- func BroadcastArrays[T Number](as ...*Array[T]) []*Array[T]
- func Concatenate[T Number](axis int, as ...*Array[T]) *Array[T]
- func CorrCoef[T Number](a, b *Array[T]) *Array[float64]
- func Cov[T Number](a, b *Array[T]) *Array[float64]
- func Einsum[T Number](subscript string, as ...*Array[T]) *Array[T]
- func Eye[T Number](n int) *Array[T]
- func Flip[T Number](a *Array[T], axes ...int) *Array[T]
- func FromByteSlice[T Number](b []byte, shape ...int) *Array[T]
- func FromFunction[T Number](shape []int, f func(coords ...int) T) *Array[T]
- func FromRegex(r io.Reader, regex string) (*Array[float64], error)
- func FromSlice[T Number](data []T, shape ...int) *Array[T]
- func Full[T Number](v T, shape ...int) *Array[T]
- func GenFromTxt(r io.Reader, cfg GenConfig) (*Array[float64], []string, error)
- func Identity[T Number](n int) *Array[T]
- func Interp[T Number](x, xp, fp *Array[T]) *Array[T]
- func Linspace[T Number](start, stop T, num int) *Array[T]
- func LoadTxt(r io.Reader) (*Array[float64], error)
- func LoadTxtFile(path string) (*Array[float64], error)
- func MeshGrid[T Number](as ...*Array[T]) []*Array[T]
- func New1DArray[T Number](data []T) *Array[T]
- func New2DArray[T Number](rows [][]T) *Array[T]
- func Ones[T Number](shape ...int) *Array[T]
- func Pad[T Number](a *Array[T], pads [][2]int, mode PadMode, constantValue T) *Array[T]
- func Repeat[T Number](a *Array[T], count int, axis int) *Array[T]
- func Roll[T Number](a *Array[T], shift int, axes ...int) *Array[T]
- func Split[T Number](a *Array[T], indices []int, axis int) []*Array[T]
- func Stack[T Number](axis int, as ...*Array[T]) *Array[T]
- func Tile[T Number](a *Array[T], reps ...int) *Array[T]
- func Zeros[T Number](shape ...int) *Array[T]
- func (a *Array[T]) Abs() *Array[T]
- func (a *Array[T]) Acos() *Array[T]
- func (a *Array[T]) Acosh() *Array[T]
- func (a *Array[T]) Add(b *Array[T]) *Array[T]
- func (a *Array[T]) AddInto(dst *Array[T], b *Array[T]) *Array[T]
- func (a *Array[T]) AddValue(v T) *Array[T]
- func (a *Array[T]) All() bool
- func (a *Array[T]) Any() bool
- func (a *Array[T]) ArgMax(axis int) []int
- func (a *Array[T]) ArgMin(axis int) []int
- func (a *Array[T]) ArgPartition(kth int, axis int) []int
- func (a *Array[T]) Argsort(axis int) []int
- func (a *Array[T]) AsStrided(shape, strides []int) *Array[T]
- func (a *Array[T]) Asin() *Array[T]
- func (a *Array[T]) Asinh() *Array[T]
- func (a *Array[T]) At(coords ...int) T
- func (a *Array[T]) Atan() *Array[T]
- func (a *Array[T]) Atanh() *Array[T]
- func (a *Array[T]) BroadcastTo(shape ...int) *Array[T]
- func (a *Array[T]) ByteSize() uintptr
- func (a *Array[T]) Cbrt() *Array[T]
- func (a *Array[T]) Ceil() *Array[T]
- func (a *Array[T]) Compress(mask []bool, axis int) *Array[T]
- func (a *Array[T]) Conj() *Array[T]
- func (a *Array[T]) Copy() *Array[T]
- func (a *Array[T]) Cos() *Array[T]
- func (a *Array[T]) Cosh() *Array[T]
- func (a *Array[T]) CumProd(axes ...int) *Array[T]
- func (a *Array[T]) CumSum(axes ...int) *Array[T]
- func (a *Array[T]) Data() []T
- func (a *Array[T]) Div(b *Array[T]) *Array[T]
- func (a *Array[T]) DivInto(dst *Array[T], b *Array[T]) *Array[T]
- func (a *Array[T]) DivValue(v T) *Array[T]
- func (a *Array[T]) Dot(b *Array[T]) *Array[T]
- func (a *Array[T]) Exp() *Array[T]
- func (a *Array[T]) Exp2() *Array[T]
- func (a *Array[T]) ExpandDims(axis int) *Array[T]
- func (a *Array[T]) Expm1() *Array[T]
- func (a *Array[T]) Floor() *Array[T]
- func (a *Array[T]) Gradient() []*Array[float64]
- func (a *Array[T]) Histogram(bins int) (*Array[float64], *Array[float64])
- func (a *Array[T]) HistogramBinEdges(bins int) *Array[float64]
- func (a *Array[T]) HistogramDD(bins []int, ranges ...[2]float64) (*Array[float64], []*Array[float64])
- func (a *Array[T]) Idx(coords ...int) int
- func (a *Array[T]) Imag() *Array[float64]
- func (a *Array[T]) Index(idx ...[]int) *Array[T]
- func (a *Array[T]) IsContiguous() bool
- func (a *Array[T]) IsIn(testElements *Array[T], invert bool) []bool
- func (a *Array[T]) Log() *Array[T]
- func (a *Array[T]) Log1p() *Array[T]
- func (a *Array[T]) Log2() *Array[T]
- func (a *Array[T]) Log10() *Array[T]
- func (a *Array[T]) MaskSelect(mask []bool) *Array[T]
- func (a *Array[T]) Matmul(b *Array[T]) *Array[T]
- func (a *Array[T]) Max(axes ...int) *Array[T]
- func (a *Array[T]) MaxKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Mean(axes ...int) *Array[T]
- func (a *Array[T]) MeanKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Median(axes ...int) *Array[T]
- func (a *Array[T]) Min(axes ...int) *Array[T]
- func (a *Array[T]) MinKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Mul(b *Array[T]) *Array[T]
- func (a *Array[T]) MulInto(dst *Array[T], b *Array[T]) *Array[T]
- func (a *Array[T]) MulValue(v T) *Array[T]
- func (a *Array[T]) NanArgMax(axis int) []int
- func (a *Array[T]) NanArgMin(axis int) []int
- func (a *Array[T]) NanCumProd(axes ...int) *Array[T]
- func (a *Array[T]) NanCumSum(axes ...int) *Array[T]
- func (a *Array[T]) NanMax(axes ...int) *Array[T]
- func (a *Array[T]) NanMaxKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanMean(axes ...int) *Array[T]
- func (a *Array[T]) NanMeanKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanMedian(axes ...int) *Array[T]
- func (a *Array[T]) NanMedianKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanMin(axes ...int) *Array[T]
- func (a *Array[T]) NanMinKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanProd(axes ...int) *Array[T]
- func (a *Array[T]) NanProdKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanStd(axes ...int) *Array[T]
- func (a *Array[T]) NanStdDDof(ddof int, axes ...int) *Array[T]
- func (a *Array[T]) NanStdKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanSum(axes ...int) *Array[T]
- func (a *Array[T]) NanSumKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) NanToNum(nan, posinf, neginf T) *Array[T]
- func (a *Array[T]) NanToNumDefault() *Array[T]
- func (a *Array[T]) NanVar(axes ...int) *Array[T]
- func (a *Array[T]) NanVarDDof(ddof int, axes ...int) *Array[T]
- func (a *Array[T]) NanVarKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Ndim() int
- func (a *Array[T]) Partition(kth int, axis int) *Array[T]
- func (a *Array[T]) Percentile(q float64, axes ...int) *Array[float64]
- func (a *Array[T]) Prod(axes ...int) *Array[T]
- func (a *Array[T]) ProdKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Put(indices []int, axis int, values *Array[T]) *Array[T]
- func (a *Array[T]) PutIndices(values *Array[T], idx ...[]int) *Array[T]
- func (a *Array[T]) Quantile(q float64, axes ...int) *Array[float64]
- func (a *Array[T]) Ravel() *Array[T]
- func (a *Array[T]) Real() *Array[float64]
- func (a *Array[T]) RealIfClose(tol float64) *Array[float64]
- func (a *Array[T]) Reshape(shape ...int) *Array[T]
- func (a *Array[T]) Round() *Array[T]
- func (a *Array[T]) Set(coords []int, v T) *Array[T]
- func (a *Array[T]) SetMask(mask []bool, v T) *Array[T]
- func (a *Array[T]) Shape() []int
- func (a *Array[T]) Sin() *Array[T]
- func (a *Array[T]) Sinh() *Array[T]
- func (a *Array[T]) Size() int
- func (a *Array[T]) Slice(rs ...Range) *Array[T]
- func (a *Array[T]) SlidingWindowView(windowShape ...int) *Array[T]
- func (a *Array[T]) Sort(axes ...int) *Array[T]
- func (a *Array[T]) SortInto(axes ...int) *Array[T]
- func (a *Array[T]) Sqrt() *Array[T]
- func (a *Array[T]) Squeeze(axes ...int) *Array[T]
- func (a *Array[T]) Std(axes ...int) *Array[T]
- func (a *Array[T]) StdDDof(ddof int, axes ...int) *Array[T]
- func (a *Array[T]) StdKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Sub(b *Array[T]) *Array[T]
- func (a *Array[T]) SubInto(dst *Array[T], b *Array[T]) *Array[T]
- func (a *Array[T]) SubValue(v T) *Array[T]
- func (a *Array[T]) Sum(axes ...int) *Array[T]
- func (a *Array[T]) SumKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) SwapAxes(i, j int) *Array[T]
- func (a *Array[T]) Take(indices []int, axis int) *Array[T]
- func (a *Array[T]) Tan() *Array[T]
- func (a *Array[T]) Tanh() *Array[T]
- func (a *Array[T]) Transpose(axes ...int) *Array[T]
- func (a *Array[T]) Trunc() *Array[T]
- func (a *Array[T]) Unique() *Array[T]
- func (a *Array[T]) UniqueCounts() (*Array[T], []int)
- func (a *Array[T]) UnsafeData() unsafe.Pointer
- func (a *Array[T]) Var(axes ...int) *Array[T]
- func (a *Array[T]) VarDDof(ddof int, axes ...int) *Array[T]
- func (a *Array[T]) VarKeepdims(axes ...int) *Array[T]
- func (a *Array[T]) Vdot(b *Array[T]) T
- type Float
- type GenConfig
- type Number
- type PadMode
- type Range
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CopyInto ¶
Into: CopyInto mutates dst by filling it with src broadcast to dst's shape. This is the Into-style mutation primitive later operations build on.
func Histogram2D ¶
func Histogram2D[T Number](x, y *Array[T], bins int) (*Array[float64], *Array[float64], *Array[float64])
Histogram2D histograms paired samples: returns the counts H (x bins × y bins, H[i][j] counts x in bin i and y in bin j) then the x and y edges. x and y are read flattened and must have equal length; defaults follow numpy histogram2d (range min..max per axis, last edge inclusive).
func LoadNpz ¶
LoadNpz reads every .npy member of an npz zip archive, keyed by member name with the .npy suffix stripped (np.load's NpzFile mapping). Non-.npy members are ignored; an archive without any .npy member is an error.
func LoadNpzFile ¶
LoadNpzFile reads path as an .npz archive.
func NormalizeRange ¶
Pure: NormalizeRange exposes range normalization for subpackages that build views from numgo.Range values (numgo/strings).
func Save ¶
Save writes a as a NumPy .npy 1.0 stream (2.0 only if the header length field would overflow uint16). Data is written C-order (fortran_order false); non-contiguous input is raveled first, matching numpy's save of a strided view.
func SaveFile ¶
SaveFile writes a to path as .npy, appending the .npy suffix when missing (numpy np.save).
func SaveTxt ¶
SaveTxt writes a row per line with space-delimited format-formatted values (numpy savetxt defaults: delimiter ' ', fmt '%g'). Rank above 2 panics.
func SaveTxtFile ¶
SaveTxtFile writes a to path as text; an empty format means "%g".
func SaveZ ¶
SaveZ writes arrays as an uncompressed .npz zip archive (numpy savez): one "name.npy" member per map entry, each a plain .npy stream written by Save. Member order follows Go's randomized map order; numpy tolerates any order.
func SaveZCompressed ¶
SaveZCompressed writes arrays as a deflate-compressed .npz archive (numpy savez_compressed).
Types ¶
type AnyArray ¶
type AnyArray struct {
F64 *Array[float64]
F32 *Array[float32]
C128 *Array[complex128]
C64 *Array[complex64]
Shape []int
Descr string
}
AnyArray is the dynamic-dtype result of Load: exactly one typed field is non-nil and matches Shape. Use AsFloat64/AsComplex128 to unwrap.
func AnyOf ¶
AnyOf builds the tagged AnyArray for a so arrays of different dtypes can be mixed in one SaveZ map. Descr is the little-endian descriptor Save writes.
func Load ¶
Load reads a NumPy .npy stream. Supported dtypes: float32/float64/ complex64/complex128, either endianness. fortran_order data is transposed into C order on read.
func LoadFile ¶
LoadFile reads path as .npy; a zip-magic file (.npz) is an error pointing at LoadNpzFile, since archives hold multiple arrays.
func (AnyArray) AsComplex128 ¶
func (a AnyArray) AsComplex128() *Array[complex128]
AsComplex128 returns the loaded complex array; it panics on real data.
type Array ¶
type Array[T Number] struct { // contains filtered or unexported fields }
Array is an N-dimensional strided view over a flat data slice. Strides are in element units. Views share data; use Copy for an independent array.
func AbsToReal ¶
Pure: AbsToReal is the package-level element-wise modulus with an explicit float result type P (methods cannot add type parameters): for complex input it is |z| as P; for real input it is the absolute value converted to P. P cannot be inferred, so callers must name both types, e.g. AbsToReal[complex128, float64](a).
func Arange ¶
Pure: Arange returns evenly spaced values in [start, stop), stepping by step. Complex operands are ordered by their real part.
func AsArray ¶
Pure: AsArray returns a new array holding a copy of data, shaped as given. It is numpy's asarray naming for FromSlice.
func AsType ¶
Pure: AsType returns a new array with every element converted to P. Real values converted to a complex type get a zero imaginary part; a complex value converted to a real type drops its imaginary part.
The conversion dispatches once per call on the concrete slice type and runs a typed copy loop (compiler-vectorizable); named types under Number keep the generic parts/scalarFromParts path. Same conversions as the generic path — bit-identical by construction.
func BorrowSlice ¶
Shares data: BorrowSlice wraps a caller-owned slice ZERO-COPY (numpy asarray semantics — the one explicit exception to the constructors-copy rule, named Borrow* to flag the aliasing). Mutations through the array write through to the slice and vice versa. The caller guarantees the slice is not resized or reused for the array's lifetime. With no shape the result is 1-D.
func BroadcastArrays ¶
Pure-broadcast: BroadcastArrays returns views of all inputs expanded to their common broadcast shape (stride-0 dimensions, numpy broadcast_arrays). Incompatible shapes panic. The views share each input's data.
func Concatenate ¶
Pure: Concatenate joins arrays along axis (negative allowed). All dimensions except axis must match exactly. The result is new data.
func CorrCoef ¶
CorrCoef returns the Pearson correlation coefficients of the variables in a's rows (b's rows appended, as with Cov): Cov normalized by the outer product of the per-variable standard deviations, clipped to [-1, 1].
func Cov ¶
Cov returns the covariance matrix of the variables in a's rows, with b's rows appended as further variables when given — numpy cov with rowvar=true, bias=false (ddof=1). Every row must hold the same number of observations. Complex arrays panic: the float64 result cannot represent complex covariance (numpy's result is complex there).
func Einsum ¶
Einsum evaluates the Einstein summation convention on one or more arrays.
Grammar (numpy np.einsum subset):
subscript := operand ("," operand)* ("->" output)?
operand := (letter | "...")*
output := (letter | "...")*
- Explicit output after "->"; or implicit (no "->"): labels occurring
exactly once across all operands, sorted alphabetically, with "..."
placed before the free labels when any operand has one ("ij,jk" is
"ik"; "i...j" yields shape [ellipsis, i, j] like numpy).
- "..." stands for the operand's remaining dimensions (explicit labels
take axes from the front and back around it); the operands' ellipsis
dimensions broadcast together, so "...ij,...jk->...ik" batches. An
explicit output lacking "..." sums the broadcast tail away.
- A label repeated within ONE operand takes the diagonal of its axes
("ii->i" main diagonal, bare "ii" the trace); "...ii" traces the last
two axes per batch. A non-square diagonal takes the min dimension.
- Output labels must each appear once and be present in some input.
Unsupported relative to numpy: integer dtypes (Number excludes them); the grammar above is otherwise complete. Deliberate deviations: non-square diagonals take the min dimension (numpy einsum errors; np.diagonal agrees with us), an explicit output without "..." sums the ellipsis tail (numpy errors), and scalar results are one-element arrays (the package has no 0-d arrays).
Pure: returns new data; operands are never written.
With two or more operands the contraction runs as a left fold of dense matmuls (einsumMatmul in einsum_matmul.go, on dot.go's matmulKernel): each step flattens the pair's shared labels to K in sorted order — the same ascending order the generic path sums in, so results are bit-identical — with the left's remaining output labels as M and the right's as N. Anything the pattern cannot express falls back to the generic transpose-broadcast-multiply-sum path below.
func Flip ¶
Pure: Flip reverses the order of elements along axes (default: all axes). The result is new data; a negative-stride view is deliberately not attempted.
func FromByteSlice ¶
Shares data: FromByteSlice reinterprets raw LITTLE-ENDIAN bytes as T elements (numpy frombuffer semantics). When len(b) is a multiple of sizeof(T) AND b is suitably aligned for T, it is a zero-copy reinterpretation that ALIASES b (mutations flow both ways); misaligned input is silently copied into aligned storage instead, so sharing only holds on the aligned path. Panics when len(b) is not a sizeof(T) multiple or product(shape) mismatches the element count.
func FromFunction ¶
Pure: FromFunction fills a new array in C order, calling f with the coordinates of each element.
func FromRegex ¶
FromRegex parses every regex match's capture groups as float columns (numpy fromregex, with all groups taken as numeric fields).
func FromSlice ¶
Pure: FromSlice returns a new array holding a copy of data. With no shape the result is 1-D; otherwise the element count must match.
func GenFromTxt ¶
GenFromTxt reads delimited float text with missing-value handling (numpy genfromtxt port, float columns only). It returns the data array and the column names — nil unless configured via Names or UseHeaderNames. A field equal to Missing (or empty) or one that fails float parsing becomes FillingValues; after that, a row with a different field count is an error.
func Identity ¶
Pure: Identity returns the n-by-n matrix with ones on the diagonal. Eye with a single argument; no Empty constructor exists because Go's make already zeroes.
func Interp ¶
Interp linearly interpolates fp (sampled at the increasing abscissae xp) at each point of x: values below xp[0] clamp to fp[0] and above xp[-1] to fp[-1] (numpy interp with left/right defaulted to the endpoints). x keeps its shape; xp and fp are read flattened, must have equal length, and x/xp compare by real part; fp may be complex. xp with duplicate abscissae resolves to the last of them, as numpy's search does.
func LoadTxt ¶
LoadTxt parses whitespace-delimited float text (numpy loadtxt defaults). Blank lines are skipped; the first data row fixes the column count. A ragged file is an error, not a panic — IO failures are returned.
func LoadTxtFile ¶
LoadTxtFile reads path as whitespace-delimited float text.
func MeshGrid ¶
Pure: MeshGrid returns len(as) arrays with 'ij' (matrix) indexing semantics: result[k] has shape len(as[0]) × … × len(as[n-1]) and varies only along dimension k, taking as[k]'s values there.
func New1DArray ¶
Pure: New1DArray returns a new 1-D array holding a copy of data.
func New2DArray ¶
Pure: New2DArray returns a new 2-D array holding a copy of rows; it panics on jagged input.
func Pad ¶
Pure: Pad returns a new array grown by pads[ax] = {before, after} along each axis, filled per mode. pads must have one entry per axis and no negative widths.
func Repeat ¶
Pure: Repeat repeats each element count times along axis (negative allowed). The result is new data.
func Roll ¶
Pure: Roll shifts elements by shift along axes (default: the flattened array in C order). Negative shifts roll backwards, wrapping around. The result is new data.
func Split ¶
View: Split slices a at the given ascending boundaries along axis into len(indices)+1 views sharing data with a. Indices may equal the axis size.
func Stack ¶
Pure: Stack joins same-shaped arrays along a new axis (negative allowed, ndim+1 positions valid). The result is new data.
func Tile ¶
Pure: Tile repeats a along each axis by reps, right-aligned like numpy.tile (shorter reps are padded with leading ones; a longer reps list prepends size-1 axes to a). The result is new data.
func (*Array[T]) Abs ¶
Pure: Abs returns the element-wise absolute value. For real T this is the magnitude; for complex T the result is real and not representable in Array[T], so it panics and points at AbsToReal.
func (*Array[T]) Add ¶
Pure: Add returns a new array with the element-wise sum of a and b, broadcasting both operands with full numpy right-alignment.
func (*Array[T]) AddInto ¶
In-place: AddInto writes the broadcast sum of a and b into dst and returns dst. dst must already have the broadcast result shape.
func (*Array[T]) All ¶
Pure: All reports whether every element is nonzero. The zero-size array is vacuously all-nonzero.
func (*Array[T]) ArgMax ¶
Pure: ArgMax returns the coordinate of each maximum along axis (first occurrence wins ties), one entry per kept slot in C order. It returns a plain []int: index results are not element data, and Array's Number constraint excludes integer element types.
func (*Array[T]) ArgMin ¶
Pure: ArgMin returns the coordinate of each minimum along axis (first occurrence wins ties), one entry per kept slot in C order.
func (*Array[T]) ArgPartition ¶
Pure: ArgPartition returns the indices that would partition each channel along axis, as a flat []int (same shortcut and stability as Argsort).
shortcut: O(n log n) sort-based partition, upgrade to introselect if profiling needs O(n).
func (*Array[T]) Argsort ¶
Pure: Argsort returns the coordinates that would sort each channel along axis as a flat []int (one entry per element, kept slots in C order). The order is STABLE: equal values keep their original order, a Go-friendly superset of numpy's non-stable quicksort default. Negative axes resolve.
func (*Array[T]) AsStrided ¶
View: AsStrided builds a low-level view with explicit shape and strides over a's data starting at a's offset (numpy as_strided). SAFER than numpy: every reachable element position is validated against [0, len(a.data)) — numpy silently reads out of bounds, this panics. Negative strides are allowed; shape entries must be non-negative. The result shares data with no aliasing protection.
func (*Array[T]) At ¶
Pure: At returns the element at coords. It panics if the rank or index is invalid.
func (*Array[T]) BroadcastTo ¶
View: BroadcastTo expands the array to shape with stride-0 dimensions. The shape must be right-align-compatible: every trailing dimension is equal to the input's or the input dimension is one. The result shares data, and writes through it alias across expanded slots — numpy's broadcast_to is read-only, but this package cannot enforce that, so treat the result as read-only.
func (*Array[T]) ByteSize ¶
Pure: ByteSize returns the number of bytes from UnsafeData to the end of the VIEW: Size()·sizeof(T) — NOT the size of the whole backing store, which may be longer (a view starting at offset > 0 covers less than len(data)).
func (*Array[T]) Cbrt ¶
Pure: Cbrt returns the element-wise cube root. Complex elements get the real cube root applied per-component (math/cmplx has no Cbrt).
func (*Array[T]) Ceil ¶
Pure: Ceil returns the element-wise ceiling, per-component on complex elements.
func (*Array[T]) Compress ¶
Pure: Compress selects the entries of a along axis where mask is true. The result shape is a's with the axis dimension replaced by the number of true entries (possibly zero); the result is new data.
func (*Array[T]) Conj ¶
Pure: Conj returns the element-wise complex conjugate; a real array is copied unchanged.
func (*Array[T]) CumProd ¶
Pure: CumProd prefixes products along axes (no axes = C-order prefix over the raveled array). The result has the input's shape.
func (*Array[T]) CumSum ¶
Pure: CumSum prefixes sums along axes (no axes = C-order prefix over the raveled array, numpy's cumsum default). The result has the input's shape.
func (*Array[T]) Data ¶
func (a *Array[T]) Data() []T
Shares data: Data returns the underlying storage starting at the view offset. For contiguous arrays it reads in C order; for non-contiguous views the element order does NOT match C order — use Ravel().Data() instead. Mutating it affects every array sharing the storage.
func (*Array[T]) Div ¶
Pure: Div returns a new array with the element-wise quotient of a and b. Division by zero follows IEEE (Inf/NaN), never panics.
func (*Array[T]) DivInto ¶
In-place: DivInto writes the broadcast quotient of a and b into dst and returns dst.
func (*Array[T]) DivValue ¶
Pure: DivValue returns a new array with every element divided by v. Division by zero follows IEEE (Inf/NaN), never panics.
func (*Array[T]) Dot ¶
Pure: Dot dispatches exactly like numpy's dot (PyArray_MatrixProduct_int in numpy/_core/src/multiarray/multiarraymodule.c): 1-D·1-D gives the scalar product as a one-element array; otherwise the last axis of a contracts with the second-to-last axis of b (axis 0 when b is 1-D). The result shape is a.shape[:-1] ++ b.shape[:b.ndim-2] ++ b.shape[-1:]: b's leading dimensions become MIDDLE dimensions of the result (an outer product of batches, not matmul's broadcasting — numpy deprecates this placement for a.ndim>=2 with b.ndim>2 and suggests tensordot), and b is shared whenever b is 1-D or 2-D. Inner dimension mismatches panic.
func (*Array[T]) Exp2 ¶
Pure: Exp2 returns the element-wise base-2 exponential, 2**x. Complex elements use exp(x·ln2).
func (*Array[T]) ExpandDims ¶
View: ExpandDims inserts a size-1 dimension at axis (negative counts from the end). The result shares data.
func (*Array[T]) Expm1 ¶
Pure: Expm1 returns e**x - 1, accurate near zero. Complex elements use Exp(x)-1.
func (*Array[T]) Floor ¶
Pure: Floor returns the element-wise floor, per-component on complex elements (numpy applies to both parts).
func (*Array[T]) Gradient ¶
Pure: Gradient returns one float64 array per axis with numpy's default gradient: second-order central differences in the interior and first-order one-sided differences at the edges, unit spacing. Every axis must have at least two elements (numpy raises for fewer).
func (*Array[T]) Histogram ¶
Pure: Histogram counts the raveled values of a into bins equal-width bins over [min, max] — numpy's histogram defaults: the last edge is inclusive and out-of-range values (NaN included) are dropped. Returns the counts then the edges.
func (*Array[T]) HistogramBinEdges ¶
Pure: HistogramBinEdges returns the bins+1 equal-width edges numpy's histogram would use: linspace over [min, max] of the raveled values, widened by 0.5 on both sides when min == max and [0, 1] when a is empty.
func (*Array[T]) HistogramDD ¶
func (a *Array[T]) HistogramDD(bins []int, ranges ...[2]float64) (*Array[float64], []*Array[float64])
Pure: HistogramDD counts a's points into bins[d] equal-width bins per dimension: a's last axis holds the D coordinates of each point (numpy's sample of shape (N, D) with the points along the leading axes). Optional ranges override the autodetected [min, max] per dimension. Returns the counts array of shape bins and one edges array per dimension.
func (*Array[T]) Imag ¶
Pure: Imag returns the element-wise imaginary parts as float64. Real element types yield all zeros (documented numpy behavior: .imag of a real array is zeros).
func (*Array[T]) Index ¶
Pure: Index gathers elements of a by integer fancy indexing on the leading axes: each list is a 1-d index array, the lists broadcast to one common length k, and the result shape is (k,) ++ a's trailing axes. Negative indices count from the end, repeats allowed; the result is new data. With no lists Index returns a Copy.
func (*Array[T]) IsContiguous ¶
Pure: IsContiguous reports whether the array is laid out in C order.
func (*Array[T]) IsIn ¶
Pure: IsIn tests every element of testElements against a's flattened unique values (numpy isin, Unique-based) and returns a []bool in C order of testElements. NaN only matches NaN. invert swaps the membership test. The result is a plain []bool because bool is not a Number element type.
func (*Array[T]) Log1p ¶
Pure: Log1p returns log(1+x), accurate near zero. Complex elements use Log(1+x).
func (*Array[T]) Log2 ¶
Pure: Log2 returns the element-wise base-2 logarithm. Complex elements use Log(x)/ln2.
func (*Array[T]) Log10 ¶
Pure: Log10 returns the element-wise base-10 logarithm. Complex elements use Log(x)/ln10.
func (*Array[T]) MaskSelect ¶
Pure: MaskSelect selects every element whose flattened C-order position has mask true (numpy a[mask] for the whole array). The result is a new 1-d array.
func (*Array[T]) Matmul ¶
Pure: Matmul returns the numpy matmul product: the last two dimensions are the matrix dimensions (M,K)@(K,N), leading dimensions broadcast. A 1-D left operand is treated as a (1,K) row and a 1-D right operand as a (K,1) column, that dimension dropped from the result. Two 1-D operands panic (use Vdot). Incompatible inner dimensions panic.
func (*Array[T]) Max ¶
Pure: Max folds max along axes (no axes = whole array, [1]). The zero-size identity is -Inf: every element compares greater, so the fold adopts the first element and the empty result stays -Inf.
func (*Array[T]) MaxKeepdims ¶
Pure: MaxKeepdims folds max along axes, keeping reduced axes as size 1.
func (*Array[T]) Mean ¶
Pure: Mean divides the sum along axes by the reduced element count. It accumulates in T (documented); the zero-size identity is NaN.
func (*Array[T]) MeanKeepdims ¶
Pure: MeanKeepdims folds the mean along axes, keeping reduced axes as size 1.
func (*Array[T]) Median ¶
Pure: Median computes the median along axes (linear interpolation between the two middle values for even counts). A channel containing NaN yields NaN for it; an empty channel yields NaN (numpy raises).
func (*Array[T]) Min ¶
Pure: Min folds min along axes (no axes = whole array, [1]). The zero-size identity is +Inf: every element compares less, so the fold adopts the first element and the empty result stays +Inf.
func (*Array[T]) MinKeepdims ¶
Pure: MinKeepdims folds min along axes, keeping reduced axes as size 1.
func (*Array[T]) MulInto ¶
In-place: MulInto writes the broadcast product of a and b into dst and returns dst.
func (*Array[T]) NanArgMax ¶
Pure: NanArgMax returns the coordinate of each maximum along axis, skipping NaNs (first occurrence wins ties among non-NaN values), one entry per kept slot in C order. A slice holding only NaNs panics, as numpy's nanargmax raises.
func (*Array[T]) NanArgMin ¶
Pure: NanArgMin returns the coordinate of each minimum along axis, skipping NaNs (first occurrence wins ties among non-NaN values), one entry per kept slot in C order. A slice holding only NaNs panics.
func (*Array[T]) NanCumProd ¶
Pure: NanCumProd prefixes NaN-free products along axes (no axes = C-order prefix over the raveled array): NaN contributes 1, mirroring numpy's nancumprod.
func (*Array[T]) NanCumSum ¶
Pure: NanCumSum prefixes NaN-free sums along axes (no axes = C-order prefix over the raveled array, like CumSum): NaN contributes 0, mirroring numpy's nancumsum.
func (*Array[T]) NanMax ¶
Pure: NanMax folds max along axes, skipping NaNs; a slice with no non-NaN values (including an empty one) yields NaN.
func (*Array[T]) NanMaxKeepdims ¶
Pure: NanMaxKeepdims folds the NaN-skipping max along axes, keeping reduced axes as size 1.
func (*Array[T]) NanMean ¶
Pure: NanMean averages the non-NaN values along axes; a slice without non-NaN values yields NaN.
func (*Array[T]) NanMeanKeepdims ¶
Pure: NanMeanKeepdims folds the NaN-skipping mean along axes, keeping reduced axes as size 1.
func (*Array[T]) NanMedian ¶
Pure: NanMedian computes the median of the non-NaN values along axes (linear interpolation between the two middle values for even counts); a slice without non-NaN values yields NaN.
func (*Array[T]) NanMedianKeepdims ¶
Pure: NanMedianKeepdims folds the NaN-skipping median along axes, keeping reduced axes as size 1.
func (*Array[T]) NanMin ¶
Pure: NanMin folds min along axes, skipping NaNs; a slice with no non-NaN values (including an empty one) yields NaN.
func (*Array[T]) NanMinKeepdims ¶
Pure: NanMinKeepdims folds the NaN-skipping min along axes, keeping reduced axes as size 1.
func (*Array[T]) NanProd ¶
Pure: NanProd folds multiplication along axes, treating NaN as 1 (numpy nanprod; an all-NaN slice therefore multiplies to 1).
func (*Array[T]) NanProdKeepdims ¶
Pure: NanProdKeepdims folds the NaN-skipping product along axes, keeping reduced axes as size 1.
func (*Array[T]) NanStd ¶
Pure: NanStd computes the NaN-skipping standard deviation along axes with ddof=0.
func (*Array[T]) NanStdDDof ¶
Pure: NanStdDDof computes the NaN-skipping standard deviation along axes with the given delta degrees of freedom.
func (*Array[T]) NanStdKeepdims ¶
Pure: NanStdKeepdims folds the NaN-skipping standard deviation along axes, keeping reduced axes as size 1.
func (*Array[T]) NanSum ¶
Pure: NanSum folds addition along axes, treating NaN as 0 (numpy nansum; an all-NaN slice therefore sums to 0).
func (*Array[T]) NanSumKeepdims ¶
Pure: NanSumKeepdims folds the NaN-skipping sum along axes, keeping reduced axes as size 1.
func (*Array[T]) NanToNum ¶
Pure: NanToNum replaces NaN with nan and ±Inf with posinf/neginf element-wise (numpy nan_to_num). For complex elements each component is replaced independently; replacing a component leaves the other intact, so a complex NaN-replacement writes NaN+0i parts as (nan value, 0).
func (*Array[T]) NanToNumDefault ¶
Pure: NanToNumDefault is NanToNum with numpy's defaults: NaN becomes 0 and ±Inf become the largest/smallest finite values of the element type (math.MaxFloat64 for float64; float32 elements use math.MaxFloat32).
func (*Array[T]) NanVar ¶
Pure: NanVar computes the NaN-skipping population variance (ddof=0) along axes. Complex arrays panic as with Var. A slice with fewer non-NaN values than ddof+1 yields NaN.
func (*Array[T]) NanVarDDof ¶
Pure: NanVarDDof computes the NaN-skipping variance along axes with the given delta degrees of freedom.
func (*Array[T]) NanVarKeepdims ¶
Pure: NanVarKeepdims folds the NaN-skipping variance along axes, keeping reduced axes as size 1.
func (*Array[T]) Partition ¶
Pure: Partition returns a new array where the element at position kth (negative counts from the end) along each channel of axis is in its sorted place, with smaller elements left and larger right (numpy partition).
shortcut: O(n log n) sort-based partition, upgrade to introselect if profiling needs O(n).
func (*Array[T]) Percentile ¶
Pure: Percentile computes the q-th percentile (q in [0, 100]) along axes with numpy's linear interpolation method — the only method in this batch. The result is always float64: percentiles of complex values are not representable here (numpy raises TypeError). A channel containing NaN yields NaN for it.
func (*Array[T]) ProdKeepdims ¶
Pure: ProdKeepdims folds multiplication along axes, keeping reduced axes as size 1.
func (*Array[T]) Put ¶
Into: Put mutates the receiver by writing values at the given indices along axis (negative indices count from the end, repeats allowed). values broadcast against the gathered shape (a's shape with the axis dimension replaced by len(indices)). Returns the receiver for chaining.
func (*Array[T]) PutIndices ¶
Into: PutIndices mutates the receiver by assigning values at the positions selected by integer fancy indexing (same rules as Index): values are broadcast against the gathered shape. Returns the receiver for chaining.
func (*Array[T]) Ravel ¶
View: Ravel flattens to 1-D in C order. A contiguous array returns a view sharing data; a non-contiguous array is copied first, so sharing is not guaranteed.
func (*Array[T]) Real ¶
Pure: Real returns the element-wise real parts as float64. Real element types are converted (float32 widens to float64); complex elements drop the imaginary part.
func (*Array[T]) RealIfClose ¶
Pure: RealIfClose returns Real unless a is complex with any |imag| >= tol, where it panics. tol is a multiple of the machine epsilon (numpy real_if_close); tol <= 1 uses the absolute value as the tolerance, matching numpy's "if the tolerance is <=1, use the absolute tolerance". Documented deviation: numpy returns the COMPLEX array unchanged in that case; this package panics because the caller asked for real values that cannot be given losslessly.
func (*Array[T]) Reshape ¶
View: Reshape views the array with a new shape when the data is contiguous; a non-contiguous array is copied first, so the result may not share data. At most one dimension may be -1 and is inferred.
func (*Array[T]) Round ¶
Pure: Round returns the element-wise round-half-to-even (numpy's round), per-component on complex elements.
func (*Array[T]) SetMask ¶
Into: SetMask mutates the receiver by assigning v to every element whose flattened C-order position has mask true (numpy a[mask] = v flat semantics). Returns the receiver for chaining.
func (*Array[T]) Slice ¶
View: Slice views a strided sub-array. Ranges cover the leading axes; trailing axes not mentioned are taken whole (numpy a[:2] semantics), so a zero Range or a missing axis means the entire axis. The result shares data. Bounds follow numpy: negative indices count from the end and a negative Step reverses the axis.
func (*Array[T]) SlidingWindowView ¶
View: SlidingWindowView appends len(windowShape) window axes to a trimmed copy of a's shape: view.shape = trimmed + window, where trimmed[k] = shape[k] - (window[k] - 1). The window axes run over ALL of a's axes in order, so len(windowShape) must equal a.Ndim() (numpy's axis=None branch; there is no last-k-axes default in numpy either). The result shares data and the same element is reachable from many window slots, so writes alias — treat the result as read-only like numpy's default writeable=False.
func (*Array[T]) Sort ¶
Pure: Sort returns a new array with each channel along the given axes sorted ascending; with no axes the LAST axis is sorted (numpy axis=-1). Each listed axis is sorted independently, one pass per axis in the order given. NaN sorts last. Negative axes resolve.
func (*Array[T]) SortInto ¶
In-place: SortInto sorts the receiver's channels in place (same semantics as Sort) and returns it.
func (*Array[T]) Sqrt ¶
Pure: Sqrt returns the element-wise square root: the math/cmplx square root (principal branch; real Sqrt(-1) is NaN).
func (*Array[T]) Squeeze ¶
View: Squeeze drops size-1 dimensions. With no axes all size-1 dimensions are dropped; named axes must have size one. The result shares data.
func (*Array[T]) StdDDof ¶
Pure: StdDDof computes the standard deviation along axes with the given delta degrees of freedom.
func (*Array[T]) StdKeepdims ¶
Pure: StdKeepdims folds the standard deviation along axes, keeping reduced axes as size 1.
func (*Array[T]) SubInto ¶
In-place: SubInto writes the broadcast difference of a and b into dst and returns dst.
func (*Array[T]) SubValue ¶
Pure: SubValue returns a new array with v subtracted from every element.
func (*Array[T]) Sum ¶
Pure: Sum folds addition along axes (no axes = whole array, result shape [1]). Negative axes resolve as axis+ndim; invalid axes panic.
func (*Array[T]) SumKeepdims ¶
Pure: SumKeepdims folds addition along axes, keeping reduced axes as size 1.
func (*Array[T]) SwapAxes ¶
View: SwapAxes exchanges dimensions i and j (negative allowed). The result shares data.
func (*Array[T]) Take ¶
Pure: Take gathers the elements of a at indices along axis (negative indices count from the end, repeats allowed). The result shape is a's with the axis dimension replaced by len(indices); the result is new data.
func (*Array[T]) Transpose ¶
View: Transpose views the array with its axes permuted. With no axes it reverses them (numpy .T). The result shares data.
func (*Array[T]) Trunc ¶
Pure: Trunc returns the element-wise integer part, per-component on complex elements.
func (*Array[T]) Unique ¶
Pure: Unique returns the flattened (C-order ravel) unique values, sorted. NaN — compared by real part — groups into a single NaN placed last, as complex values order by (real, imag).
func (*Array[T]) UniqueCounts ¶
Pure: UniqueCounts returns Unique's values together with each value's occurrence count.
func (*Array[T]) UnsafeData ¶
Interop primitives for handing array memory to foreign code (cgo, syscalls, binary decoders) — the Go-side analog of numpy's __array_interface__ / ctypeslib. These are the ONLY ways this package aliases caller memory: every constructor otherwise copies its input (design.md P0-2).
cgo example (a is *Array[float64], C-order contiguous):
p := (*C.double)(a.UnsafeData()) C.process(p, C.int(a.Size())) // ByteSize() bytes, C float64 == Go float64
The pointer stays valid while a is reachable (the GC keeps the backing array alive) and its data is not resized.
func (*Array[T]) Var ¶
Pure: Var computes the population variance (ddof=0) along axes. The result is real-valued: Var/Std of complex arrays are not representable in T and panic (numpy raises TypeError for the same reason). The zero-size identity is NaN.
func (*Array[T]) VarDDof ¶
Pure: VarDDof computes the variance along axes with the given delta degrees of freedom.
func (*Array[T]) VarKeepdims ¶
Pure: VarKeepdims folds the variance along axes, keeping reduced axes as size 1.
type Float ¶
Float is the real-valued subset of Number: the result element type of operations whose value is real even for complex input (Abs).
type GenConfig ¶
type GenConfig struct {
Delimiter string // "" splits on any run of whitespace; otherwise a literal separator
SkipHeader int // lines skipped at the start, before names detection
Comments []string // lines starting with any entry are skipped (default "#")
Names []string // explicit column names to return
UseHeaderNames bool // the first non-skipped row supplies the names
FillingValues float64 // substituted for missing/failed-parse fields (default NaN)
Missing string // a field equal to this string counts as missing ("" is always missing)
}
GenConfig configures GenFromTxt; zero values match numpy's defaults except FillingValues, which defaults to NaN (numpy's fill for float columns).
type Number ¶
type Number interface {
~float32 | ~float64 | ~complex64 | ~complex128
}
Number is the element type constraint for Array. Integers are excluded: Mean/Div would silently truncate without numpy-style dtype promotion.
type PadMode ¶
type PadMode int
PadMode selects how Pad fills the padded area.
const ( PadConstant PadMode = iota // fill with the given constant value PadEdge // repeat the edge value PadReflect // reflect about the edge, edge value NOT repeated PadSymmetric // reflect including the edge value PadWrap // circular shift (numpy wrap) PadEmpty // leave Go zero values: numpy's uninitialized )
type Range ¶
type Range struct {
Start, Stop, Step int
}
Range is one slice axis. A zero Range means the whole axis. Step 0 is treated as 1. Negative Start/Stop count from the end. With a negative Step and no bounds, the whole axis is reversed (Range{Step: -1}).
func From ¶
Pure: From builds a Range from start to the end of the axis with step 1. Stop uses an explicit sentinel because a zero Stop would be ambiguous with an explicit 0.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package assert provides numpy.testing-style assertions for numgo arrays, for use in downstream tests.
|
Package assert provides numpy.testing-style assertions for numgo arrays, for use in downstream tests. |
|
Package emath ports numpy.emath (lib.scimath): math functions that return mathematically valid answers in the complex domain instead of NaN.
|
Package emath ports numpy.emath (lib.scimath): math functions that return mathematically valid answers in the complex domain instead of NaN. |
|
Package fft provides numpy.fft-semantics discrete Fourier transforms over numgo arrays, backed by an own FFT: mixed-radix Cooley-Tukey + Bluestein for large primes.
|
Package fft provides numpy.fft-semantics discrete Fourier transforms over numgo arrays, backed by an own FFT: mixed-radix Cooley-Tukey + Bluestein for large primes. |
|
internal
|
|
|
cmath
Package cmath provides pure-Go double-precision exp, log, log1p and pow whose results are bit-identical to the glibc functions used by numpy's distributions (npy_pow→pow, log, log1p, exp) on x86-64 (glibc ≥ 2.28 lineage).
|
Package cmath provides pure-Go double-precision exp, log, log1p and pow whose results are bit-identical to the glibc functions used by numpy's distributions (npy_pow→pow, log, log1p, exp) on x86-64 (glibc ≥ 2.28 lineage). |
|
fixtures
Package fixtures provides golden-data helpers for numpy comparison tests.
|
Package fixtures provides golden-data helpers for numpy comparison tests. |
|
lapack
Package lapack provides pure-Go numeric kernels for the linalg package: dense LU, Cholesky, Householder QR, one-sided Jacobi SVD, cyclic-Jacobi symmetric eigendecomposition, and general eigenvalues via Hessenberg reduction plus shifted QR iteration.
|
Package lapack provides pure-Go numeric kernels for the linalg package: dense LU, Cholesky, Householder QR, one-sided Jacobi SVD, cyclic-Jacobi symmetric eigendecomposition, and general eigenvalues via Hessenberg reduction plus shifted QR iteration. |
|
nditer
Package nditer is the single place where strided index arithmetic lives.
|
Package nditer is the single place where strided index arithmetic lives. |
|
Package linalg provides numpy.linalg-semantics dense linear algebra over numgo arrays.
|
Package linalg provides numpy.linalg-semantics dense linear algebra over numgo arrays. |
|
Package ma provides numpy.ma-style masked arrays over numgo.Array (numpy/ma/core.py semantics, narrowed to this batch — see docs/design.md §2).
|
Package ma provides numpy.ma-style masked arrays over numgo.Array (numpy/ma/core.py semantics, narrowed to this batch — see docs/design.md §2). |
|
Package polynomial is a Go port of numpy.polynomial: the six polynomial classes sharing the ABCPolyBase API (numpy _polybase.py), each with its own basis arithmetic ported from the corresponding numpy module.
|
Package polynomial is a Go port of numpy.polynomial: the six polynomial classes sharing the ABCPolyBase API (numpy _polybase.py), each with its own basis arithmetic ported from the corresponding numpy module. |
|
Package random is the numgo equivalent of numpy.random: SeedSequence + bit-generator engines + the Generator distribution layer, ported for bit-exact agreement with numpy 2.x for identical seeds.
|
Package random is the numgo equivalent of numpy.random: SeedSequence + bit-generator engines + the Generator distribution layer, ported for bit-exact agreement with numpy 2.x for identical seeds. |
|
Package strings ports numpy.strings: elementwise string operations over an N-dimensional array of Go strings.
|
Package strings ports numpy.strings: elementwise string operations over an N-dimensional array of Go strings. |