numgo

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 7 Imported by: 0

README

numgo

Package numgo provides n-dimensional array operations, linear algebra, and numerical primitives. It serves as the NumPy equivalent for datascience.

import "github.com/asymmetric-effort/datascience/lib/numgo"

NDArray Creation

// Zero-initialized array
a := numgo.Zeros(3, 4)

// All ones
b := numgo.Ones(2, 3)

// Fill with a constant
c := numgo.Full(7.0, 2, 2)

// Identity matrix
eye := numgo.Eye(3)

// From flat slice (1-D)
v := numgo.FromSlice([]float64{1, 2, 3, 4})

// From 2-D slice
m := numgo.FromSlice2D([][]float64{
    {1, 2, 3},
    {4, 5, 6},
})

// General constructor with explicit shape and data
arr := numgo.NewNDArray([]int{2, 3}, []float64{1, 2, 3, 4, 5, 6})

NDArray Properties and Manipulation

a := numgo.Ones(3, 4)

a.Shape()   // []int{3, 4}
a.Ndim()    // 2
a.Size()    // 12
a.Data()    // []float64 copy of underlying data

a.Get(1, 2)         // element at row 1, col 2
a.Set(9.0, 1, 2)    // set element

a.Reshape(4, 3)     // new array with different shape, same data
a.Flatten()          // 1-D copy
a.Copy()             // deep copy
a.T()                // transpose (reverses axes)

Arithmetic Operations

All element-wise operations support broadcasting between compatible shapes.

a := numgo.FromSlice2D([][]float64{{1, 2}, {3, 4}})
b := numgo.FromSlice2D([][]float64{{5, 6}, {7, 8}})

numgo.Add(a, b)          // element-wise addition (broadcasts)
numgo.Sub(a, b)          // element-wise subtraction
numgo.Mul(a, b)          // element-wise multiplication
numgo.Div(a, b)          // element-wise division

numgo.AddScalar(a, 10)   // add scalar to every element
numgo.SubScalar(a, 1)
numgo.MulScalar(a, 2)
numgo.DivScalar(a, 3)

Reductions

a := numgo.FromSlice2D([][]float64{{1, 2}, {3, 4}})

numgo.Sum(a)         // sum all elements -> [10]
numgo.Sum(a, 0)      // sum along axis 0 -> [4, 6]
numgo.Sum(a, 1)      // sum along axis 1 -> [3, 7]

numgo.Prod(a)        // product of all elements
numgo.Max(a)         // maximum value
numgo.ArgMax(a, 1)   // index of max along axis

Broadcasting

NumPy-style broadcasting rules: dimensions are compared right-to-left; size-1 dimensions are stretched to match.

shape, err := numgo.BroadcastShapes([]int{3, 1}, []int{1, 4})
// shape = []int{3, 4}, err = nil

a := numgo.Ones(3, 1)
b, err := numgo.BroadcastTo(a, []int{3, 4})

Linear Algebra (Einsum)

Einstein summation supports arbitrary subscript notation with optimized paths for common patterns.

a := numgo.FromSlice2D([][]float64{{1, 2}, {3, 4}})
b := numgo.FromSlice2D([][]float64{{5, 6}, {7, 8}})

// Matrix multiply: C[i,k] = sum_j A[i,j] * B[j,k]
c, _ := numgo.Einsum("ij,jk->ik", a, b)

// Dot product
u := numgo.FromSlice([]float64{1, 2, 3})
v := numgo.FromSlice([]float64{4, 5, 6})
dot, _ := numgo.Einsum("i,i->", u, v)

// Outer product
outer, _ := numgo.Einsum("i,j->ij", u, v)

// Trace
trace, _ := numgo.Einsum("ii->", a)

// Row sums, column sums
rowSums, _ := numgo.Einsum("ij->i", a)
colSums, _ := numgo.Einsum("ij->j", a)

// Batch matrix multiply
// batchC, _ := numgo.Einsum("bij,bjk->bik", batchA, batchB)

Random Number Generation

All RNG methods use a seeded source for reproducibility.

rng := numgo.NewRNG(42)

rng.Rand(3, 3)             // uniform [0, 1)
rng.Randn(3, 3)            // standard normal
rng.Normal(5.0, 2.0, 100)  // normal with mean=5, std=2
rng.Uniform(0, 10, 50)     // uniform [0, 10)
rng.RandInt(0, 10, 3, 3)   // integer values in [0, 10)

rng.Choice(100, 5, false)  // 5 unique indices from [0, 100)
rng.Choice(10, 20, true)   // 20 indices with replacement

rng.Shuffle(arr)            // in-place shuffle along axis 0

rng.Dirichlet([]float64{1, 1, 1})      // Dirichlet sample
rng.Multinomial(100, []float64{0.2, 0.3, 0.5}) // multinomial sample

Sorting, Searching, and Set Operations

a := numgo.FromSlice([]float64{3, 1, 4, 1, 5})

numgo.Sort(a, 0)         // sorted copy along axis
numgo.ArgSort(a, 0)      // indices that would sort the array
numgo.Unique(a)          // sorted unique values -> [1, 3, 4, 5]

// Conditional selection
cond := numgo.FromSlice([]float64{1, 0, 1, 0, 1})
x := numgo.FromSlice([]float64{10, 20, 30, 40, 50})
y := numgo.Zeros(5)
numgo.Where(cond, x, y)  // [10, 0, 30, 0, 50]

numgo.Nonzero(a)          // indices of nonzero elements

sorted := numgo.FromSlice([]float64{1, 3, 5, 7, 9})
vals := numgo.FromSlice([]float64{2, 6})
numgo.SearchSorted(sorted, vals) // insertion points -> [1, 3]
Set Operations
a := numgo.FromSlice([]float64{1, 2, 3, 4})
b := numgo.FromSlice([]float64{3, 4, 5, 6})

numgo.Intersect1D(a, b)  // [3, 4]
numgo.Union1D(a, b)      // [1, 2, 3, 4, 5, 6]
numgo.SetDiff1D(a, b)    // [1, 2]

Comparison

numgo.AllClose(a, b, 1e-8, 1e-5) // true if all elements are close

API Summary

Category Functions / Methods
Creation NewNDArray, Zeros, Ones, Full, Eye, FromSlice, FromSlice2D
Properties Shape, Ndim, Size, Data, String
Indexing Get, Set
Manipulation Reshape, Flatten, Copy, T
Arithmetic Add, Sub, Mul, Div, AddScalar, SubScalar, MulScalar, DivScalar
Reductions Sum, Prod, Max, ArgMax
Broadcasting BroadcastShapes, BroadcastTo
Linear Algebra Einsum
Random NewRNG, Rand, Randn, Normal, Uniform, RandInt, Choice, Shuffle, Dirichlet, Multinomial
Sorting Sort, ArgSort, Unique, Where, Nonzero, SearchSorted
Set Ops Intersect1D, Union1D, SetDiff1D
Comparison AllClose

Documentation

Overview

Package numgo provides n-dimensional array operations, linear algebra, and numerical primitives. It serves as the numpy equivalent for datascience.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllClose

func AllClose(a, b *NDArray, atol, rtol float64) bool

AllClose returns true if two arrays have the same shape and all corresponding elements satisfy |a-b| <= atol + rtol*|b|.

func Argwhere

func Argwhere(a *NDArray) [][]int

Argwhere returns the coordinates of nonzero elements. This is the same as Nonzero.

func ArrayEqual

func ArrayEqual(a, b *NDArray) bool

ArrayEqual returns true if a and b have the same shape and all elements are equal.

func ArrayEquiv

func ArrayEquiv(a, b *NDArray) bool

ArrayEquiv returns true if a and b are equal after broadcasting to a common shape.

func BroadcastShapes

func BroadcastShapes(a, b []int) ([]int, error)

BroadcastShapes computes the result shape from two input shapes using numpy-style broadcasting rules:

  1. If arrays differ in number of dimensions, pad the shorter shape with 1s on the left.
  2. Dimensions with size 1 are stretched to match the other array's size.
  3. If sizes differ and neither is 1, an error is returned.

func Cond

func Cond(a *NDArray) (float64, error)

Cond computes the condition number of a matrix (ratio of largest to smallest singular value).

func Det

func Det(a *NDArray) (float64, error)

Det computes the determinant of a square matrix via LU decomposition (Gaussian elimination).

func MatrixRank

func MatrixRank(a *NDArray) (int, error)

MatrixRank computes the rank of a matrix by counting non-negligible singular values.

func Nonzero

func Nonzero(a *NDArray) [][]int

Nonzero returns the indices of all nonzero elements in a. The result is a slice of coordinate tuples, where each tuple has length equal to a.Ndim().

func Seed

func Seed(seed int64)

Seed sets the seed for the package-level default RNG. Safe for concurrent use.

func Slogdet

func Slogdet(a *NDArray) (sign float64, logdet float64, err error)

Slogdet computes the sign and natural logarithm of the determinant of a square matrix.

func Trace

func Trace(a *NDArray) (float64, error)

Trace returns the sum of the diagonal elements of a 2D matrix.

Types

type NDArray

type NDArray struct {
	// contains filtered or unexported fields
}

NDArray is a multidimensional array backed by a flat []float64 slice.

func Absolute

func Absolute(a *NDArray) *NDArray

Absolute returns the element-wise absolute value of the array.

func Add

func Add(a, b *NDArray) *NDArray

Add returns the element-wise sum of two arrays. Arrays with compatible shapes are broadcast to a common shape before the operation.

func AddScalar

func AddScalar(a *NDArray, s float64) *NDArray

AddScalar adds a scalar to every element.

func All

func All(a *NDArray, axes ...int) *NDArray

All returns 1.0 if all elements along the given axes are nonzero, 0.0 otherwise. If no axes are given, checks all elements.

func Any

func Any(a *NDArray, axes ...int) *NDArray

Any returns 1.0 if any element along the given axes is nonzero, 0.0 otherwise. If no axes are given, checks all elements.

func Append

func Append(a, values *NDArray, axis int) (*NDArray, error)

Append appends values to the end of the array along the given axis.

func Arange

func Arange(start, stop, step float64) *NDArray

Arange returns a 1D array of evenly spaced values in [start, stop) with the given step.

func Arccos

func Arccos(a *NDArray) *NDArray

Arccos returns the element-wise arccosine of the array.

func Arcsin

func Arcsin(a *NDArray) *NDArray

Arcsin returns the element-wise arcsine of the array.

func Arctan

func Arctan(a *NDArray) *NDArray

Arctan returns the element-wise arctangent of the array.

func Arctan2

func Arctan2(y, x *NDArray) *NDArray

Arctan2 returns the element-wise two-argument arctangent of y/x with broadcasting.

func ArgMax

func ArgMax(a *NDArray, axis int) *NDArray

ArgMax returns the index of the maximum value along the given axis. Only a single axis is supported. Returns an NDArray of float64 indices.

func ArgMin

func ArgMin(a *NDArray, axis int) *NDArray

ArgMin returns the index of the minimum value along the given axis. Only a single axis is supported. Returns an NDArray of float64 indices.

func ArgSort

func ArgSort(a *NDArray, axis int) *NDArray

ArgSort returns a new NDArray containing the indices that would sort the input array along the given axis. The result has the same shape as the input, with float64 index values.

func Argpartition

func Argpartition(a *NDArray, kth int, axis int) *NDArray

Argpartition returns the indices that would partition the array.

func Around

func Around(a *NDArray, decimals int) *NDArray

Around rounds every element to the given number of decimal places.

func AsStrided

func AsStrided(a *NDArray, shape, strides []int) *NDArray

AsStrided creates a view of the array with the given shape and strides. This is an unsafe operation: the returned array shares the same underlying data. Out-of-bounds strides can cause reads beyond the original data.

func Average

func Average(a *NDArray, weights *NDArray, axes ...int) *NDArray

Average computes the weighted average along the given axes. If weights is nil, all weights are equal (equivalent to Mean). When axes are specified, weights must have length equal to the axis size.

func Bincount

func Bincount(a *NDArray) *NDArray

Bincount counts the number of occurrences of each non-negative integer value. Values are truncated to integers. The result length is max(a)+1.

func BroadcastTo

func BroadcastTo(a *NDArray, shape []int) (*NDArray, error)

BroadcastTo broadcasts an NDArray to the given target shape, returning a new NDArray with data repeated as needed. The source array must be broadcast-compatible with the target shape (each source dimension must be 1 or equal to the target dimension).

func Cbrt

func Cbrt(a *NDArray) *NDArray

Cbrt returns the element-wise cube root of the array.

func Ceil

func Ceil(a *NDArray) *NDArray

Ceil returns the element-wise ceiling of the array.

func Cholesky

func Cholesky(a *NDArray) (*NDArray, error)

Cholesky computes the Cholesky decomposition of a symmetric positive-definite matrix. Returns the lower-triangular matrix L such that A = L * L^T.

func Choose

func Choose(indices *NDArray, choices []*NDArray) (*NDArray, error)

Choose selects elements from choices based on indices. indices is a 1D array of ints selecting which choice array to pick from. All choices must have the same shape as indices.

func Clip

func Clip(a *NDArray, min, max float64) *NDArray

Clip clamps every element of a to the range [min, max].

func Compress

func Compress(condition []bool, a *NDArray, axis int) (*NDArray, error)

Compress selects elements from a along the given axis where condition is true. If axis < 0, operates on the flattened array.

func Concatenate

func Concatenate(arrays []*NDArray, axis int) (*NDArray, error)

Concatenate joins a sequence of arrays along an existing axis.

func Convolve

func Convolve(a, v *NDArray) (*NDArray, error)

Convolve computes the discrete linear convolution of two 1-D arrays (full mode). The result has length len(a) + len(v) - 1.

func Corrcoef

func Corrcoef(x, y *NDArray) (*NDArray, error)

Corrcoef returns the Pearson correlation coefficient matrix for x and y. x and y must be 1-D arrays of the same length. Returns a 2x2 correlation matrix.

func Correlate

func Correlate(a, v *NDArray) (*NDArray, error)

Correlate computes the cross-correlation of two 1-D arrays (full mode). The result has length len(a) + len(v) - 1.

func Cos

func Cos(a *NDArray) *NDArray

Cos returns the element-wise cosine of the array.

func Cosh

func Cosh(a *NDArray) *NDArray

Cosh returns the element-wise hyperbolic cosine of the array.

func CountNonzero

func CountNonzero(a *NDArray, axes ...int) *NDArray

CountNonzero counts the number of nonzero elements along the given axes. If no axes are given, counts all nonzero elements.

func Cov

func Cov(x *NDArray) (*NDArray, error)

Cov returns the covariance matrix for a 2-D array where each row is a variable and each column is an observation. For a 1-D array, returns a 1x1 matrix.

func Cross

func Cross(a, b *NDArray) (*NDArray, error)

Cross computes the cross product of two 3-element vectors.

func Cumprod

func Cumprod(a *NDArray, axis int) *NDArray

Cumprod returns the cumulative product along the given axis.

func Cumsum

func Cumsum(a *NDArray, axis int) *NDArray

Cumsum returns the cumulative sum along the given axis.

func Delete

func Delete(a *NDArray, indices []int, axis int) (*NDArray, error)

Delete removes elements at the given indices along the specified axis.

func Diag

func Diag(a *NDArray, k int) *NDArray

Diag extracts or constructs a diagonal.

  • If a is 1D, returns a 2D matrix with a on the k-th diagonal.
  • If a is 2D, extracts the k-th diagonal as a 1D array.

func Diagflat

func Diagflat(a *NDArray, k int) *NDArray

Diagflat creates a 2D array with the flattened input as the k-th diagonal.

func Diagonal

func Diagonal(a *NDArray, offset, axis1, axis2 int) (*NDArray, error)

Diagonal extracts the diagonal from a 2D array. offset > 0 selects superdiagonals, offset < 0 selects subdiagonals. axis1 and axis2 specify the 2D sub-array to extract from (for higher dims).

func Div

func Div(a, b *NDArray) *NDArray

Div returns the element-wise quotient of two arrays. Arrays with compatible shapes are broadcast to a common shape before the operation.

func DivScalar

func DivScalar(a *NDArray, s float64) *NDArray

DivScalar divides every element by a scalar.

func Divmod

func Divmod(x, y *NDArray) (quotient, remainder *NDArray)

Divmod returns element-wise quotient and remainder of x/y with broadcasting. Quotient is floor(x/y), remainder is x - quotient*y.

func Dot

func Dot(a, b *NDArray) (*NDArray, error)

Dot computes the dot product of two arrays.

  • 1D-1D: inner product (scalar result wrapped in 0-D array)
  • 2D-2D: matrix multiplication
  • 2D-1D: matrix-vector product

func Dsplit

func Dsplit(a *NDArray, sections int) ([]*NDArray, error)

Dsplit splits an array along axis 2.

func Dstack

func Dstack(arrays []*NDArray) (*NDArray, error)

Dstack stacks arrays along the third axis (axis 2).

func Eig

func Eig(a *NDArray) (values, vectors *NDArray, err error)

Eig computes the eigenvalues and right eigenvectors of a square matrix using the QR algorithm. Only supports real eigenvalues.

func Eigh

func Eigh(a *NDArray) (values, vectors *NDArray, err error)

Eigh computes eigenvalues and eigenvectors of a symmetric matrix. Uses the same QR algorithm but assumes symmetry for better convergence.

func Eigvals

func Eigvals(a *NDArray) (*NDArray, error)

Eigvals returns only the eigenvalues of a square matrix.

func Einsum

func Einsum(notation string, operands ...*NDArray) (*NDArray, error)

Einsum performs Einstein summation on the given operands according to the notation string. It supports numpy-style einsum notation such as:

  • "ij,jk->ik" (matrix multiply)
  • "ii->" (trace)
  • "ij->" (sum all elements)
  • "ij->i" (row sums)
  • "ij->j" (column sums)
  • "i,j->ij" (outer product)
  • "bij,bjk->bik" (batch matrix multiply)

If no "->" is given, implicit mode outputs the sorted labels that appear exactly once across all inputs.

func Empty

func Empty(shape ...int) *NDArray

Empty returns a zero-initialized NDArray of the given shape. In Go, float64 slices are zero-initialized, so this is identical to Zeros.

func Equal

func Equal(a, b *NDArray) *NDArray

Equal returns 1.0 where a == b, 0.0 otherwise (element-wise with broadcasting).

func Exp

func Exp(a *NDArray) *NDArray

Exp returns the element-wise exponential (e^x) of the array.

func Exp2

func Exp2(a *NDArray) *NDArray

Exp2 returns the element-wise 2^x of the array.

func ExpandDims

func ExpandDims(a *NDArray, axis int) *NDArray

ExpandDims inserts a new axis of size 1 at the given position.

func Expm1

func Expm1(a *NDArray) *NDArray

Expm1 returns the element-wise exp(x)-1 of the array.

func Extract

func Extract(condition, a *NDArray) *NDArray

Extract returns a 1-D array of elements from a where the corresponding element in condition is nonzero. Both arrays are treated as flat.

func Eye

func Eye(n int) *NDArray

Eye returns a 2-D identity matrix of size n x n.

func Fabs

func Fabs(a *NDArray) *NDArray

Fabs returns the element-wise absolute value of the array (same as Absolute for float64).

func Flatnonzero

func Flatnonzero(a *NDArray) *NDArray

Flatnonzero returns the flat indices of nonzero elements.

func Flip

func Flip(a *NDArray, axis int) *NDArray

Flip reverses the order of elements along the given axis.

func Fliplr

func Fliplr(a *NDArray) *NDArray

Fliplr flips the array left-right (reverses axis 1).

func Flipud

func Flipud(a *NDArray) *NDArray

Flipud flips the array up-down (reverses axis 0).

func Floor

func Floor(a *NDArray) *NDArray

Floor returns the element-wise floor of the array.

func Fmod

func Fmod(x, y *NDArray) *NDArray

Fmod returns the element-wise floating-point remainder (math.Mod) with broadcasting.

func FromFunction

func FromFunction(shape []int, fn func(indices []int) float64) *NDArray

FromFunction constructs an NDArray by calling fn for each set of indices.

func FromIter

func FromIter(ch <-chan float64, count int) *NDArray

FromIter constructs a 1D NDArray by reading count values from a channel.

func FromSlice

func FromSlice(data []float64) *NDArray

FromSlice creates a 1-D NDArray from a float64 slice.

func FromSlice2D

func FromSlice2D(data [][]float64) *NDArray

FromSlice2D creates a 2-D NDArray from a slice of slices. All rows must have the same length.

func Full

func Full(value float64, shape ...int) *NDArray

Full returns an NDArray of the given shape filled with the specified value.

func Geomspace

func Geomspace(start, stop float64, num int) *NDArray

Geomspace returns num values spaced evenly on a log scale (geometric progression) from start to stop. Both start and stop must be positive.

func Greater

func Greater(a, b *NDArray) *NDArray

Greater returns 1.0 where a > b, 0.0 otherwise (element-wise with broadcasting).

func GreaterEqual

func GreaterEqual(a, b *NDArray) *NDArray

GreaterEqual returns 1.0 where a >= b, 0.0 otherwise (element-wise with broadcasting).

func Heaviside

func Heaviside(x, h0 *NDArray) *NDArray

Heaviside computes the Heaviside step function element-wise with broadcasting. Returns 0 where x < 0, h0 where x == 0, and 1 where x > 0.

func Histogram

func Histogram(a *NDArray, bins int) (counts, edges *NDArray)

Histogram computes a histogram of a flat array. Returns counts (length bins) and edges (length bins+1).

func Hsplit

func Hsplit(a *NDArray, sections int) ([]*NDArray, error)

Hsplit splits an array horizontally. For 1-D, splits along axis 0. For 2D+, splits along axis 1.

func Hstack

func Hstack(arrays []*NDArray) (*NDArray, error)

Hstack stacks arrays horizontally. For 1-D arrays, concatenate. For 2D+, concatenate along axis 1.

func Identity

func Identity(n int) *NDArray

Identity returns an n x n identity matrix. Alias for Eye.

func In1d

func In1d(a, b *NDArray) *NDArray

In1d returns a 1-D NDArray with 1.0 where the corresponding element of a is found in b, and 0.0 otherwise. Both inputs are treated as flat.

func Inner

func Inner(a, b *NDArray) (*NDArray, error)

Inner computes the inner product of two arrays. For 1D arrays, this is the dot product. For higher dimensions, it sums over the last axis of a and the second-to-last of b.

func Insert

func Insert(a *NDArray, index int, values *NDArray, axis int) (*NDArray, error)

Insert inserts values before the given index along the specified axis.

func Intersect1D

func Intersect1D(a, b *NDArray) *NDArray

Intersect1D returns a sorted 1D NDArray of values common to both a and b. Both inputs are treated as flattened 1D arrays.

func Inv

func Inv(a *NDArray) (*NDArray, error)

Inv computes the inverse of a square matrix via Gauss-Jordan elimination.

func Isclose

func Isclose(a, b *NDArray, atol, rtol float64) *NDArray

Isclose returns 1.0 where |a-b| <= atol + rtol*|b|, 0.0 otherwise (element-wise with broadcasting).

func Isfinite

func Isfinite(a *NDArray) *NDArray

Isfinite returns an NDArray with 1.0 where the element is finite, 0.0 otherwise.

func Isinf

func Isinf(a *NDArray) *NDArray

Isinf returns an NDArray with 1.0 where the element is +/-Inf, 0.0 otherwise.

func Isnan

func Isnan(a *NDArray) *NDArray

Isnan returns an NDArray with 1.0 where the element is NaN, 0.0 otherwise.

func Isneginf

func Isneginf(a *NDArray) *NDArray

Isneginf returns an NDArray with 1.0 where the element is -Inf, 0.0 otherwise.

func Isposinf

func Isposinf(a *NDArray) *NDArray

Isposinf returns an NDArray with 1.0 where the element is +Inf, 0.0 otherwise.

func Less

func Less(a, b *NDArray) *NDArray

Less returns 1.0 where a < b, 0.0 otherwise (element-wise with broadcasting).

func LessEqual

func LessEqual(a, b *NDArray) *NDArray

LessEqual returns 1.0 where a <= b, 0.0 otherwise (element-wise with broadcasting).

func Lexsort

func Lexsort(keys []*NDArray) *NDArray

Lexsort performs an indirect stable sort using a sequence of keys. The last key is the primary sort key, the second-to-last is secondary, etc. All keys must be 1-D arrays of the same length. Returns an NDArray of indices that sorts the data.

func Linspace

func Linspace(start, stop float64, num int) *NDArray

Linspace returns num evenly spaced values over [start, stop].

func Log

func Log(a *NDArray) *NDArray

Log returns the element-wise natural logarithm of the array.

func Log1p

func Log1p(a *NDArray) *NDArray

Log1p returns the element-wise log(1+x) of the array.

func Log2

func Log2(a *NDArray) *NDArray

Log2 returns the element-wise base-2 logarithm of the array.

func Log10

func Log10(a *NDArray) *NDArray

Log10 returns the element-wise base-10 logarithm of the array.

func LogicalAnd

func LogicalAnd(a, b *NDArray) *NDArray

LogicalAnd returns element-wise logical AND. Nonzero values are treated as true.

func LogicalNot

func LogicalNot(a *NDArray) *NDArray

LogicalNot returns element-wise logical NOT. Nonzero values become 0.0, zero becomes 1.0.

func LogicalOr

func LogicalOr(a, b *NDArray) *NDArray

LogicalOr returns element-wise logical OR. Nonzero values are treated as true.

func LogicalXor

func LogicalXor(a, b *NDArray) *NDArray

LogicalXor returns element-wise logical XOR. Nonzero values are treated as true.

func Logspace

func Logspace(start, stop float64, num int) *NDArray

Logspace returns num values spaced evenly on a log scale from 10^start to 10^stop.

func Lstsq

func Lstsq(a, b *NDArray) (*NDArray, error)

Lstsq finds the least squares solution to Ax = b via the normal equations (A^T A) x = A^T b.

func Matmul

func Matmul(a, b *NDArray) (*NDArray, error)

Matmul performs matrix multiplication of two 2D arrays.

func MatrixPower

func MatrixPower(a *NDArray, n int) (*NDArray, error)

MatrixPower computes A^n for a square matrix via repeated multiplication. n=0 returns identity, negative n uses the inverse.

func Max

func Max(a *NDArray, axes ...int) *NDArray

Max reduces the array by taking the maximum along the given axes.

func Mean

func Mean(a *NDArray, axes ...int) *NDArray

Mean reduces the array by computing the arithmetic mean along the given axes. If no axes are given, it returns the global mean.

func Median

func Median(a *NDArray, axes ...int) *NDArray

Median returns the median of the array along the given axes.

func Meshgrid

func Meshgrid(xi ...*NDArray) []*NDArray

Meshgrid returns coordinate matrices from coordinate vectors. Given N 1D arrays, returns N NDArrays each with N dimensions.

func Min

func Min(a *NDArray, axes ...int) *NDArray

Min reduces the array by taking the minimum along the given axes. If no axes are given, it returns the global minimum as a scalar (1-D, length-1) array.

func Modf

func Modf(x *NDArray) (frac, integer *NDArray)

Modf returns the fractional and integer parts of each element. Both returned arrays have the same shape as the input.

func Moveaxis

func Moveaxis(a *NDArray, source, destination int) *NDArray

Moveaxis moves an axis from source to destination position.

func Mul

func Mul(a, b *NDArray) *NDArray

Mul returns the element-wise product of two arrays. Arrays with compatible shapes are broadcast to a common shape before the operation.

func MulScalar

func MulScalar(a *NDArray, s float64) *NDArray

MulScalar multiplies every element by a scalar.

func Nanmax

func Nanmax(a *NDArray, axes ...int) *NDArray

Nanmax returns the maximum, ignoring NaN values.

func Nanmean

func Nanmean(a *NDArray, axes ...int) *NDArray

Nanmean computes the arithmetic mean, ignoring NaN values.

func Nanmin

func Nanmin(a *NDArray, axes ...int) *NDArray

Nanmin returns the minimum, ignoring NaN values.

func Nanprod

func Nanprod(a *NDArray, axes ...int) *NDArray

Nanprod returns the product, treating NaN as one.

func Nanstd

func Nanstd(a *NDArray, axes ...int) *NDArray

Nanstd computes the population standard deviation, ignoring NaN values.

func Nansum

func Nansum(a *NDArray, axes ...int) *NDArray

Nansum returns the sum, treating NaN as zero.

func Nanvar

func Nanvar(a *NDArray, axes ...int) *NDArray

Nanvar computes the population variance, ignoring NaN values.

func NewNDArray

func NewNDArray(shape []int, data []float64) *NDArray

NewNDArray creates an NDArray with the given shape and optional data. If data is nil, the array is zero-initialized. If data is provided, its length must equal the product of shape dimensions.

func Norm

func Norm(a *NDArray, ord int, axis int) (*NDArray, error)

Norm computes a vector or matrix norm.

ord=1: sum of absolute values (or max column sum for matrices)
ord=2: Euclidean norm (or spectral norm for matrices)
ord=-1: for vectors, min of absolute values

axis=-1 means compute over the flattened array.

func NotEqual

func NotEqual(a, b *NDArray) *NDArray

NotEqual returns 1.0 where a != b, 0.0 otherwise (element-wise with broadcasting).

func Ones

func Ones(shape ...int) *NDArray

Ones returns an NDArray of the given shape filled with ones.

func Outer

func Outer(a, b *NDArray) *NDArray

Outer computes the outer product of two 1D arrays.

func Partition

func Partition(a *NDArray, kth int, axis int) *NDArray

Partition rearranges elements along the given axis such that the element at position kth is in its sorted position, all smaller elements are before it, and all larger elements are after it (using introselect/quickselect).

func Percentile

func Percentile(a *NDArray, q float64, axes ...int) *NDArray

Percentile returns the q-th percentile of the array along the given axes. q must be in [0, 100]. Uses linear interpolation.

func Pinv

func Pinv(a *NDArray) (*NDArray, error)

Pinv computes the Moore-Penrose pseudo-inverse via SVD.

func Power

func Power(base, exp *NDArray) *NDArray

Power returns the element-wise base**exp with broadcasting.

func Prod

func Prod(a *NDArray, axes ...int) *NDArray

Prod reduces the array by multiplying along the given axes.

func QR

func QR(a *NDArray) (q, r *NDArray, err error)

QR computes the QR factorization of a 2D matrix using the Gram-Schmidt process. Returns Q (orthogonal) and R (upper triangular) such that A = Q * R.

func Quantile

func Quantile(a *NDArray, q float64, axes ...int) *NDArray

Quantile returns the q-th quantile of the array along the given axes. q must be in [0, 1]. Uses linear interpolation.

func Ravel

func Ravel(a *NDArray) *NDArray

Ravel returns a contiguous flattened copy of the array.

func Remainder

func Remainder(x, y *NDArray) *NDArray

Remainder returns the element-wise IEEE 754 remainder (math.Remainder) with broadcasting.

func Repeat

func Repeat(a *NDArray, repeats int, axis int) *NDArray

Repeat repeats elements of an array along the given axis.

func Rint

func Rint(a *NDArray) *NDArray

Rint rounds every element to the nearest integer (using banker's rounding).

func Roll

func Roll(a *NDArray, shift int, axis int) *NDArray

Roll performs a circular shift of elements along the given axis. If axis is -1, the array is flattened, rolled, then reshaped.

func Rollaxis

func Rollaxis(a *NDArray, axis, start int) *NDArray

Rollaxis rolls the specified axis backwards until it lies at start.

func Rot90

func Rot90(a *NDArray, k int) *NDArray

Rot90 rotates the array 90 degrees counter-clockwise k times in the plane defined by axes 0 and 1.

func SVD

func SVD(a *NDArray) (u, s, vt *NDArray, err error)

SVD computes the singular value decomposition A = U * diag(S) * Vt. Uses eigendecomposition of A^T A and A A^T.

func SearchSorted

func SearchSorted(sorted, values *NDArray) *NDArray

SearchSorted performs a binary search on a sorted 1D array, returning the indices at which the given values should be inserted to maintain sort order. The sorted array must be 1D. The result has the same shape as values.

func Select

func Select(conditions []*NDArray, choices []*NDArray, defaultVal float64) (*NDArray, error)

Select returns elements from choices based on conditions. The first true condition selects the corresponding choice. If no condition is true, defaultVal is used.

func SetDiff1D

func SetDiff1D(a, b *NDArray) *NDArray

SetDiff1D returns a sorted 1D NDArray of values in a that are not in b. Both inputs are treated as flattened 1D arrays.

func Setxor1d

func Setxor1d(a, b *NDArray) *NDArray

Setxor1d returns a sorted 1D NDArray of values that are in exactly one of a or b (symmetric difference). Both inputs are treated as flat.

func Sign

func Sign(a *NDArray) *NDArray

Sign returns the element-wise sign of the array: -1 for negative, 0 for zero, 1 for positive.

func Sin

func Sin(a *NDArray) *NDArray

Sin returns the element-wise sine of the array.

func Sinh

func Sinh(a *NDArray) *NDArray

Sinh returns the element-wise hyperbolic sine of the array.

func Solve

func Solve(a, b *NDArray) (*NDArray, error)

Solve solves the linear system Ax = b via Gaussian elimination with partial pivoting. a must be a square 2D matrix, b must be a 1D or 2D array.

For large systems (n >= Level2Threshold), uses LU factorization with BLAS triangular solve (Dtrsv) for better cache performance.

func Sort

func Sort(a *NDArray, axis int) *NDArray

Sort returns a new NDArray with elements sorted along the given axis. For a 1D array, axis must be 0. For an ND array, each 1D slice along the specified axis is sorted independently.

func Split

func Split(a *NDArray, sections int, axis int) ([]*NDArray, error)

Split divides an array into equal sections along the given axis.

func Sqrt

func Sqrt(a *NDArray) *NDArray

Sqrt returns the element-wise square root of the array.

func Square

func Square(a *NDArray) *NDArray

Square returns the element-wise x*x of the array.

func Squeeze

func Squeeze(a *NDArray) *NDArray

Squeeze removes all size-1 dimensions from the array.

func Stack

func Stack(arrays []*NDArray, axis int) (*NDArray, error)

Stack joins a sequence of arrays along a new axis.

func Std

func Std(a *NDArray, axes ...int) *NDArray

Std computes the population standard deviation along the given axes. If no axes are given, it returns the global standard deviation.

func Sub

func Sub(a, b *NDArray) *NDArray

Sub returns the element-wise difference of two arrays. Arrays with compatible shapes are broadcast to a common shape before the operation.

func SubScalar

func SubScalar(a *NDArray, s float64) *NDArray

SubScalar subtracts a scalar from every element.

func Sum

func Sum(a *NDArray, axes ...int) *NDArray

Sum reduces the array by summing along the given axes. If no axes are given, it sums over all elements and returns a scalar (1-D, length-1) array.

func Swapaxes

func Swapaxes(a *NDArray, axis1, axis2 int) *NDArray

Swapaxes returns a new array with two axes swapped.

func Take

func Take(a *NDArray, indices []int, axis int) (*NDArray, error)

Take returns elements from a along the given axis at the specified indices. If axis < 0, operates on the flattened array.

func TakeAlongAxis

func TakeAlongAxis(a, indices *NDArray, axis int) (*NDArray, error)

TakeAlongAxis gathers elements from a along the given axis using indices array. indices must have the same number of dimensions as a.

func Tan

func Tan(a *NDArray) *NDArray

Tan returns the element-wise tangent of the array.

func Tanh

func Tanh(a *NDArray) *NDArray

Tanh returns the element-wise hyperbolic tangent of the array.

func Tensordot

func Tensordot(a, b *NDArray, axes int) (*NDArray, error)

Tensordot computes the tensor contraction of a and b over the last `axes` axes of a and the first `axes` axes of b.

func Tile

func Tile(a *NDArray, reps []int) *NDArray

Tile constructs an array by repeating a the number of times given by reps.

func Tri

func Tri(n, m, k int) *NDArray

Tri returns an n x m matrix with ones at and below the k-th diagonal.

func Tril

func Tril(a *NDArray, k int) *NDArray

Tril returns the lower triangle of a 2D array. Elements above the k-th diagonal are zeroed.

func Triu

func Triu(a *NDArray, k int) *NDArray

Triu returns the upper triangle of a 2D array. Elements below the k-th diagonal are zeroed.

func Union1D

func Union1D(a, b *NDArray) *NDArray

Union1D returns a sorted 1D NDArray of the unique values from both a and b. Both inputs are treated as flattened 1D arrays.

func Unique

func Unique(a *NDArray) *NDArray

Unique returns a 1D NDArray containing the sorted unique values from a.

func Vander

func Vander(x *NDArray, n int) *NDArray

Vander returns the Vandermonde matrix of a 1D input. Column j of the output is x^(n-1-j). If n <= 0, n defaults to len(x).

func Var

func Var(a *NDArray, axes ...int) *NDArray

Var computes the population variance along the given axes. If no axes are given, it returns the global variance.

func Vsplit

func Vsplit(a *NDArray, sections int) ([]*NDArray, error)

Vsplit splits an array vertically (along axis 0).

func Vstack

func Vstack(arrays []*NDArray) (*NDArray, error)

Vstack stacks arrays vertically (along axis 0).

func Where

func Where(condition, x, y *NDArray) *NDArray

Where performs element-wise selection: for each element, if condition is nonzero (true), pick from x; otherwise pick from y. condition, x, and y must be broadcast-compatible.

func Zeros

func Zeros(shape ...int) *NDArray

Zeros returns an NDArray of the given shape filled with zeros.

func (*NDArray) Copy

func (a *NDArray) Copy() *NDArray

Copy returns a deep copy of the array.

func (*NDArray) Data

func (a *NDArray) Data() []float64

Data returns a copy of the underlying data slice.

func (*NDArray) Flatten

func (a *NDArray) Flatten() *NDArray

Flatten returns a 1-D copy of the array.

func (*NDArray) Get

func (a *NDArray) Get(indices ...int) float64

Get returns the element at the given indices.

func (*NDArray) Ndim

func (a *NDArray) Ndim() int

Ndim returns the number of dimensions.

func (*NDArray) Reshape

func (a *NDArray) Reshape(shape ...int) *NDArray

Reshape returns a new NDArray with the same data but a different shape. The total number of elements must remain the same.

func (*NDArray) Set

func (a *NDArray) Set(value float64, indices ...int)

Set sets the element at the given indices.

func (*NDArray) Shape

func (a *NDArray) Shape() []int

Shape returns a copy of the array's shape.

func (*NDArray) Size

func (a *NDArray) Size() int

Size returns the total number of elements.

func (*NDArray) String

func (a *NDArray) String() string

String returns a human-readable representation of the array.

func (*NDArray) T

func (a *NDArray) T() *NDArray

T returns the transpose of the array. For 1-D arrays it returns a copy. For N-D arrays it reverses the axes.

type RNG

type RNG struct {
	// contains filtered or unexported fields
}

RNG wraps a seeded random source for reproducible random number generation.

func NewRNG

func NewRNG(seed int64) *RNG

NewRNG creates a new RNG with the given seed.

func (*RNG) Beta

func (r *RNG) Beta(a, b float64, shape ...int) *NDArray

Beta returns samples from a Beta(a, b) distribution using the Gamma distribution.

func (*RNG) BinomialSample

func (r *RNG) BinomialSample(n int, p float64, shape ...int) *NDArray

BinomialSample returns samples from a binomial distribution with parameters n and p.

func (*RNG) Chisquare

func (r *RNG) Chisquare(df float64, shape ...int) *NDArray

Chisquare returns samples from a chi-squared distribution with df degrees of freedom. Chi-squared(df) = Gamma(df/2, 2).

func (*RNG) Choice

func (r *RNG) Choice(n int, size int, replace bool) []int

Choice returns a slice of random indices in [0, n). If replace is true, indices may repeat; otherwise they are unique and size must be <= n.

func (*RNG) Dirichlet

func (r *RNG) Dirichlet(alpha []float64) []float64

Dirichlet draws a single sample from the Dirichlet distribution with parameter vector alpha. It returns a probability vector of length len(alpha). The implementation draws independent Gamma(alpha_i, 1) samples and normalizes.

func (*RNG) Exponential

func (r *RNG) Exponential(scale float64, shape ...int) *NDArray

Exponential returns samples from an exponential distribution with the given scale.

func (*RNG) Gamma

func (r *RNG) Gamma(shapep, scale float64, shapeArr ...int) *NDArray

Gamma returns samples from a Gamma(shape, scale) distribution.

func (*RNG) Multinomial

func (r *RNG) Multinomial(n int, pvals []float64) []int

Multinomial draws a single sample from the multinomial distribution: distribute n trials among len(pvals) categories with the given probabilities. Returns a slice of counts (length len(pvals)) summing to n.

func (*RNG) Normal

func (r *RNG) Normal(mean, std float64, shape ...int) *NDArray

Normal returns an NDArray of the given shape with values drawn from a normal distribution with the specified mean and standard deviation.

func (*RNG) Permutation

func (r *RNG) Permutation(n int) *NDArray

Permutation returns an NDArray containing a random permutation of integers [0, n).

func (*RNG) Poisson

func (r *RNG) Poisson(lam float64, shape ...int) *NDArray

Poisson returns samples from a Poisson distribution with the given rate (lambda). Uses Knuth's algorithm for small lambda, and a rejection method for large lambda.

func (*RNG) Rand

func (r *RNG) Rand(shape ...int) *NDArray

Rand returns an NDArray of the given shape with values drawn uniformly from [0, 1).

func (*RNG) RandInt

func (r *RNG) RandInt(low, high int, shape ...int) *NDArray

RandInt returns an NDArray of the given shape with integer values drawn uniformly from [low, high).

func (*RNG) Randn

func (r *RNG) Randn(shape ...int) *NDArray

Randn returns an NDArray of the given shape with values drawn from the standard normal distribution (mean=0, std=1) using the Box-Muller transform.

func (*RNG) Random

func (r *RNG) Random(shape ...int) *NDArray

Random returns an NDArray of the given shape with values drawn uniformly from [0, 1). It is an alias for Rand.

func (*RNG) Shuffle

func (r *RNG) Shuffle(a *NDArray)

Shuffle performs an in-place Fisher-Yates shuffle on the first axis of the array. For 1-D arrays this shuffles elements; for N-D arrays it shuffles the sub-arrays along axis 0.

func (*RNG) StandardNormal

func (r *RNG) StandardNormal(shape ...int) *NDArray

StandardNormal returns samples from the standard normal distribution (mean=0, std=1). It is an alias for Randn.

func (*RNG) StandardT

func (r *RNG) StandardT(df float64, shape ...int) *NDArray

StandardT returns samples from Student's t-distribution with df degrees of freedom. Uses the ratio of a standard normal to the square root of a chi-squared/df.

func (*RNG) Uniform

func (r *RNG) Uniform(low, high float64, shape ...int) *NDArray

Uniform returns an NDArray of the given shape with values drawn uniformly from [low, high).

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL