moonvec

    N-dimensional arrays with dtypes, broadcasting, universal functions and linear algebra.

    numpy
    ndarray
    array
    broadcasting
    broadcast
    linear-algebra
    linalg
    matrix
    matrix-multiplication
    matmul
    tensor
    dtype
    ufunc
    universal-function
    reduction
    slice
    stride
    view
    reshape
    transpose
    solve
    inverse
    determinant
    cholesky
    qr
    svd
    eigenvalue
    least-squares
    norm
    kron
    complex
    half-precision
    float16
    numerics
    scientific-computing
    signal-processing
    machine-learning
    simd
    vectorization
    cute
    layout
    Download zip
    Version
    0.0.1
    License
    Apache-2.0
    Last updated
    3 hours ago
    Downloads
    1

    #Numerical MoonBit Library

    moonvec — N-dimensional arrays for MoonBit: dtypes, broadcasting, universal functions and linear algebra.

    Overview  ·  Guide  ·  API  ·  mooncakes

    moonvec is a numerical array library. An array is a view over a flat buffer: a dtype, a shape, a stride per axis and an offset. Slicing and transposing move those numbers instead of copying elements, and every elementwise operation runs over broadcast shapes with the type promotion NumPy uses.

    • One array type over fourteen dtypes, including half precision and complex.
    • Broadcasting for every elementwise function, with no temporary arrays.
    • The reduction, shape, joining and sorting operations an array library is expected to have.
    • Dense linear algebra: solving, determinants, Cholesky, QR, least squares, SVD and symmetric eigenvalues.
    • A layout algebra for tiling, the description a kernel needs to know where its elements sit.
    • A backend contract, so an elementwise loop can be replaced by a faster one without touching anything above it.

    moon add moonbitstack/moonvec

    let a = @moonvec.from_doubles([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
    let b = @moonvec.transpose(a)
    println(@moonvec.matmul(a, b).to_string())

    array([[14.0, 32.0], [32.0, 77.0]], dtype=float64)

    #Contents

    #Making an array

    Every constructor takes the dtype as a labelled argument; float64 is the default, as it is in NumPy.

    let zeros = @moonvec.zeros([2, 3])
    let ones = @moonvec.ones([2, 3], dtype=@moonvec.I32)
    let filled = @moonvec.full([2, 2], @moonvec.Real(0.5), dtype=@moonvec.F32)
    let stepped = @moonvec.arange(start=0.0, stop=1.0, step=0.25)
    let spaced = @moonvec.linspace(start=0.0, stop=1.0, num=5)
    let identity = @moonvec.eye(n=3, dtype=@moonvec.F64)
    println(stepped.to_string())
    println(spaced.to_string())

    array([0.0, 0.25, 0.5, 0.75], dtype=float64) array([0.0, 0.25, 0.5, 0.75, 1.0], dtype=float64)

    arange counts the steps from the span, so arange(start=0.0, stop=1.0, step=0.3) has four elements and stops just below 0.9. A step that points away from the stop gives an empty array rather than an endless loop.

    There is also from_doubles for a flat list with a shape, from_numbers when the values are already typed, from_bytes for data read from a file, matrix for a list of rows, and the *_like constructors that take their shape and dtype from an array you already have.

    #Reading and writing

    let a = @moonvec.from_doubles([1.0, 2.0, 3.0, 4.0], [2, 2])
    a.set_at([1, 0], @moonvec.Real(9.0))
    println(a.to_string())
    println(a.at([1, 0]).to_string())

    array([[1.0, 2.0], [9.0, 4.0]], dtype=float64) 9.0

    item() reads the single value of a 0-dimensional array, which is what a full reduction returns. to_numbers() and to_doubles() copy the elements out in row-major order, whatever strides the view has.

    #Slicing

    A slice is a view: nothing is copied, and a write through the slice is a write into the original.

    let a = @moonvec.from_doubles([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
    let row = @moonvec.slice(a, [@moonvec.At(1)])
    let column = @moonvec.slice(a, [@moonvec.All, @moonvec.At(2)])
    let window = @moonvec.slice(a, [@moonvec.All, @moonvec.span(1, 3)])
    println(row.to_string())
    println(column.to_string())
    println(window.is_contiguous())

    array([4.0, 5.0, 6.0], dtype=float64) array([3.0, 6.0], dtype=float64) false

    At removes an axis, NewAxis adds one, and span(start, stop, step) walks an axis forwards or backwards with the bounds clamped the way NumPy clamps them. Integer array indexing and boolean masks cannot be expressed by strides, so take and mask copy:

    let a = @moonvec.arange(start=0.0, stop=6.0)
    let picked = @moonvec.take(a, [4, 0, 2])
    let kept = @moonvec.mask(a, [true, false, true, false, false, true])
    println(picked.to_string())
    println(kept.to_string())

    array([4.0, 0.0, 2.0], dtype=float64) array([0.0, 2.0, 5.0], dtype=float64)

    #Universal functions

    An elementwise function broadcasts its operands, promotes their dtypes and writes into one new array. The binary ones have operator forms as well.

    let column = @moonvec.from_doubles([1.0, 2.0, 3.0], [3, 1])
    let row = @moonvec.from_doubles([10.0, 20.0, 30.0], [1, 3])
    println((column + row).to_string())
    let counts = @moonvec.full([3], @moonvec.Signed(7L), dtype=@moonvec.I32)
    println(@moonvec.divide(counts, counts).to_string())

    array([[11.0, 21.0, 31.0], [12.0, 22.0, 32.0], [13.0, 23.0, 33.0]], dtype=float64) array([1.0, 1.0, 1.0], dtype=float64)

    The operator forms (+, -, *, /, % and unary -) abort on a shape mismatch, because MoonBit does not let an operator carry an error. The named functions raise VecError, which carries both shapes in the message.

    Arithmetic keeps integers exact and wraps on overflow. The division family and power promote booleans to int8, as NumPy does. Everything else — trigonometric, exponential, rounding, the special functions — answers in floating point.

    let angles = @moonvec.linspace(start=0.0, stop=3.141592653589793, num=3)
    println(@moonvec.sin(angles).to_string())
    println(@moonvec.erf(@moonvec.from_doubles([0.0, 1.0, 2.0], [3])).to_string())

    array([0.0, 1.0, 1.2246467991473532e-16], dtype=float64) array([0.0, 0.8427007929497147, 0.9953222650189527], dtype=float64)

    #Reductions

    Each reduction takes an optional axis and a keepdims switch. Without an axis the whole array is reduced and the answer is 0-dimensional.

    let a = @moonvec.from_doubles([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
    println(@moonvec.sum(a, axis=0).to_string())
    println(@moonvec.max(a, axis=1, keepdims=true).to_string())
    println(@moonvec.argmax(a).to_string())
    println(@moonvec.mean(a).to_string())

    array([5.0, 7.0, 9.0], dtype=float64) array([[3.0], [6.0]], dtype=float64) array(5, dtype=int64) array(3.5, dtype=float64)

    sum, prod, min, max, mean, variance, std, any, all, argmin and argmax are the whole set. A sum of booleans or of a narrow integer counts in int64, which is what NumPy does; a mean is float64 for exact input and keeps the width of a float one. variance and std take ddof.

    #Reshaping and joining

    let a = @moonvec.arange(start=0.0, stop=6.0)
    println(@moonvec.reshape(a, [2, 3]).to_string())
    println(@moonvec.reshape(a, [-1, 2]).shape().map(fn(n) { n.to_string() }).join(" by "))
    let rows = @moonvec.stack([a, a], axis=0)
    println(rows.shape().map(fn(n) { n.to_string() }).join(" by "))
    for part in @moonvec.split(rows, parts=2, axis=1) {
    println(part.shape().map(fn(n) { n.to_string() }).join(" by "))
    }

    array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], dtype=float64) 3 by 2 2 by 6 2 by 3 2 by 3

    reshape gives a view when the array is contiguous and copies when it is not; ravel and flatten differ in the same way. transpose, swap_axes, move_axis, squeeze and expand_dims are views, and concatenate, stack, hstack, vstack, split and split_at allocate.

    #Sorting and choosing

    let a = @moonvec.from_doubles([3.0, 1.0, 2.0, 5.0, 4.0], [5])
    println(@moonvec.sort(a).to_string())
    println(@moonvec.argsort(a).to_string())
    let values = @moonvec.from_doubles([-2.0, 0.5, 3.0], [3])
    let zeros = @moonvec.zeros([3])
    println(@moonvec.select(@moonvec.greater(values, zeros), values, zeros).to_string())
    println(@moonvec.clip(values, min=0.0, max=1.0).to_string())

    array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=float64) array([1, 2, 0, 4, 3], dtype=int64) array([0.0, 0.5, 3.0], dtype=float64) array([0.0, 0.5, 1.0], dtype=float64)

    Both sorts are stable and put NaNs last. where is a keyword in MoonBit, so the choice function is called select.

    #Linear algebra

    matmul contracts the last axis of one array with the second-to-last of the other, broadcasts the leading axes, and drops the axes a 1-D operand borrowed. dot, inner, outer and trace are the companions.

    let a = @moonvec.matrix([[3.0, 1.0], [1.0, 2.0]])
    let b = @moonvec.from_doubles([9.0, 8.0], [2])
    println(@linalg.solve(a, b).to_string())
    println(@moonvec.format_real(@linalg.det(a)))

    array([2.0, 3.0], dtype=float64) 5.0

    The linalg package holds solve, inv, det, cholesky, qr, lstsq, svd, eigh, matrix_power, kron, norm and matrix_norm. Factorisations run in double precision and store their answer in the caller's dtype. lstsq returns the shortest solution when there are fewer rows than columns, and refuses a matrix whose columns are linearly dependent.

    #Layouts

    The cute package is the layout algebra: shapes and strides that nest, with the tiling operations a kernel needs. It holds no data, so an array view is built from one.

    let layout = @cute.compact([2, 3])
    println(layout.to_string())
    println(layout.offset([1, 2]))
    let (tile, tiles) = @cute.compact([6]).divide(tile=3)
    println(tile.to_string())
    println(tiles.to_string())

    (_2:_3, _3:_1) 5 (_3:_1) (_2:_3)

    coalesce merges modes that walk without a gap, product combines a thread layout with a value layout, and strides() hands the result to NDArray::new.

    #The interface table

    The root package moonbitstack/moonvec:

    AreaInterface
    dtypeDType with Bool, I8, I16, I32, I64, U8, U16, U32, U64, F16, F32, F64, C64, C128; item_size, name, parse, is_bool, is_integer, is_signed, is_float, is_complex, is_real, is_exact, to_real, float_size
    promotionpromote, promote_all, division_dtype
    valuesNumber (Boolean, Signed, Unsigned, Real, Complex), Complex, format_real
    bufferBuffer (new, from_bytes, dtype, len, read, write, fill, to_bytes)
    arrayNDArray (new, shape, strides, offset, ndim, size, dtype, buffer, is_contiguous, is_scalar, at, set_at, item, to_numbers, to_doubles, copy, to_string)
    creationzeros, ones, full, zeros_like, ones_like, full_like, arange, linspace, eye, from_doubles, from_numbers, from_bytes, array, matrix
    castingastype
    indexingIndex (All, At, Span, NewAxis, Take, Mask), span, slice, take, mask
    broadcastingbroadcast, broadcast_to, broadcast_shape, broadcast_strides
    arithmeticadd, subtract, multiply, divide, floor_divide, remainder, mod, power, maximum, minimum, arctan2, hypot, bitwise_and, bitwise_or, bitwise_xor, left_shift, right_shift, invert, negative, positive, absolute, fabs, sign, square, reciprocal, clip, select, and the scalar forms add_scalar, subtract_scalar, multiply_scalar, divide_scalar, power_scalar, maximum_scalar, minimum_scalar
    comparisonsequal, not_equal, less, less_equal, greater, greater_equal, equal_nan, logical_and, logical_or, logical_xor, logical_not, isnan, isinf, isfinite, signbit
    mathematicssqrt, cbrt, exp, exp2, expm1, log, log2, log10, log1p, sin, cos, tan, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, floor, ceil, trunc, rint, round, degrees, radians, real, imag, angle, conj
    special functionsgamma, lgamma, digamma, erf, erfc, erfinv, erfcinv, beta, zeta, bessel_j, bessel_y, bessel_i, bessel_k
    reductionssum, prod, min, max, mean, variance, std, any, all, argmin, argmax
    shapereshape, transpose, swap_axes, move_axis, ravel, flatten, squeeze, expand_dims
    joiningconcatenate, stack, hstack, vstack, split, split_at
    orderingsort, argsort
    productsmatmul, dot, inner, outer, trace
    backendKernel (name, binary, unary, reduce, matmul), Cpu, cpu, BinaryOp, UnaryOp, ReduceOp
    errorsVecError (ByteCountMismatch, IndexOutOfBounds, ShapeMismatch, AxisOutOfRange, CannotReshape, EmptyAxis, Domain, NotSolvable), message

    moonbitstack/moonvec/linalg:

    AreaInterface
    solvingsolve, inv, det, cholesky
    factoringqr, lstsq, svd, eigh, matrix_power, kron
    measuringNorm (Frobenius, One, Two, Infinity, NegInfinity, P), norm, matrix_norm

    moonbitstack/moonvec/cute:

    AreaInterface
    layoutLayout (Mode, Tuple), mode, compact, product
    measuringsize, cosize, shape, strides, offset, offset_of_index
    algebracoalesce, divide
    errorsLayoutError (RankMismatch, IndexOutOfRange, NotDivisible, EmptyLayout), message

    #Rules that surprise people

    A view shares its buffer. slice, transpose, reshape on a contiguous array, squeeze, expand_dims and broadcast_to return views. Writing through one is visible through the other. copy, flatten, astype, take, mask, sort and every arithmetic function allocate.

    The dtype of an operation is fixed before any element is read. Promotion follows a table that is transcribed from NumPy and checked cell by cell against it. uint64 with int8 gives float64, because no integer holds both ranges.

    Arithmetic wraps, division does not. Adding two int8 arrays wraps at 128, as C does. Dividing an integer by zero is refused with Domain rather than answered with zero, because there is no honest integer answer.

    NaNs propagate and sort last. maximum and minimum propagate a NaN. A comparison with a NaN is false, and equal_nan is there for when you want the other answer. A sort puts NaN at the end.

    Complex numbers are ordered lexicographically. less, greater and their neighbours compare the real part first and the imaginary part when the real parts agree, which is what NumPy does.

    #Consistency

    The behaviour of this library is compared against NumPy 2.5.4 on fixed inputs. scripts/gen_vectors.py writes the inputs and NumPy's answers as raw little-endian bytes; the test suite replays them and compares element by element, including the dtype of the answer.

    GroupCasesPassing
    dtype promotion, every pair of the fourteen dtypes196196
    arithmetic, comparison and logical operations over 24 dtype pairs and 10 shape pairs1 2671 267
    mathematics over float and complex values, including the edges106106
    reductions with every axis and keepdims, over five dtypes and two ranks880880
    products, shape, joining, slicing, sorting, choice and casting110110
    linear algebra: solving, determinants, Cholesky, least squares, norms, powers, products2929
    total2 5882 588

    Where the answers may differ in the last bits — a variance is a sum of squares, a complex power goes through a logarithm — the vector file records a relative tolerance and the test uses it. Every integer answer, and every elementwise +, -, * and /, must match exactly.

    One deliberate difference: integer division by zero is refused rather than answered with zero.

    #Licence

    Apache-2.0.

    Kernel

    pub(open) trait Kernel {
    fn name(Self) -> String
    fn binary(Self, op : BinaryOp, dtype : DType, a : Buffer, a_at : Int, a_step : Int, b : Buffer, b_at : Int, b_step : Int, out : Buffer, out_at : Int, out_step : Int, len : Int) -> Unit raise VecError
    fn unary(Self, op : UnaryOp, dtype : DType, a : Buffer, a_at : Int, a_step : Int, out : Buffer, out_at : Int, out_step : Int, len : Int) -> Unit raise VecError
    fn matmul(Self, dtype : DType, a : Buffer, a_at : Int, b : Buffer, b_at : Int, out : Buffer, out_at : Int, m : Int, k : Int, n : Int) -> Unit raise VecError
    fn reduce(Self, op : ReduceOp, dtype : DType, a : Buffer, a_at : Int, a_step : Int, len : Int, into : Number) -> Number raise VecError
    }

    What an array backend has to provide: the arithmetic over runs of contiguous elements.

    Everything else — broadcasting, striding, dtype promotion, allocation — belongs to the array layer above, so a backend only has to be fast on long flat runs and never sees a shape. A run is always within one buffer and one dtype, and the offsets are in elements.

    Implement this trait to add a backend: a C stub, a compute shader, a vector unit. The array layer takes it as a parameter and does not change.

    VecError

    pub(all) suberror VecError {
    ByteCountMismatch(total~ : Int, item_size~ : Int)
    IndexOutOfBounds(index~ : Int, len~ : Int)
    ShapeMismatch(want~ : Array[Int], got~ : Array[Int])
    AxisOutOfRange(axis~ : Int, ndim~ : Int)
    CannotReshape(size~ : Int, shape~ : Array[Int])
    EmptyAxis(axis~ : Int)
    Domain(message~ : String)
    NotSolvable(message~ : String)
    }

    What an array operation refuses to do.

    Shapes and axes are checked before any element is touched, so an error never leaves an array half written. Arithmetic that has no answer — an integer divided by zero, an overflowing cast — also lands here rather than returning a number that looks valid.

    VecError::message

    fn VecError::message(self : VecError) -> String

    One line naming what was refused, for a caller that holds only the error.

    BinaryOp

    pub(all) enum BinaryOp {
    Add
    Subtract
    Multiply
    Divide
    FloorDivide
    Remainder
    Power
    Maximum
    Minimum
    ArcTangent2
    Hypotenuse
    BitAnd
    BitOr
    BitXor
    LeftShift
    RightShift
    Equal
    NotEqual
    Less
    LessEqual
    Greater
    GreaterEqual
    LogicalAnd
    LogicalOr
    LogicalXor
    }

    The binary operations a backend has to provide. They are named here rather than passed as closures so that a backend that cannot call back into MoonBit — a shader, say — can still run them.

    Buffer

    pub struct Buffer {
    data : FixedArray[Byte]
    dtype : DType
    len : Int
    }

    A flat block of elements of one dtype, which views of an array share.

    The bytes are little endian on every target, so a buffer written on one machine reads back the same on another and a file of vectors can carry raw values. Storage is a byte array rather than a typed one because one code path has to hold every dtype; the accessors below are the only place that knows the widths.

    Buffer::dtype

    fn Buffer::dtype(self : Buffer) -> DType

    The element type this buffer stores.

    Buffer::fill

    fn Buffer::fill(self : Buffer, value : Number) -> Unit raise VecError

    Sets every element to value.

    Buffer::from_bytes

    fn Buffer::from_bytes(bytes : Bytes, dtype~ : DType) -> Buffer raise VecError

    Wraps bytes that already hold elements; the length comes from the byte count, so a partial element is an error rather than a silently dropped tail.

    Buffer::len

    fn Buffer::len(self : Buffer) -> Int

    How many elements the buffer holds.

    Buffer::new

    fn Buffer::new(dtype~ : DType, len~ : Int) -> Buffer

    Allocates len elements of dtype, zeroed.

    Buffer::read

    fn Buffer::read(self : Buffer, index : Int) -> Number raise VecError

    The element at index, widened to the class its dtype belongs to.

    Buffer::to_bytes

    fn Buffer::to_bytes(self : Buffer) -> Bytes

    A copy of the bytes, for handing to another library or writing to a file.

    Buffer::write

    fn Buffer::write(self : Buffer, index : Int, value : Number) -> Unit raise VecError

    Stores value at index, converted the way C converts it to the buffer's dtype.

    Complex

    pub(all) struct Complex {
    re : Double
    im : Double
    }

    A complex number, held as a pair of doubles.

    complex64 arrays store the two parts as single precision floats; the value type always widens to doubles so that arithmetic in a loop does not lose the bits the storage kept.
    impl Add for Complex
    impl Div for Complex
    impl Eq for Complex
    impl Mul for Complex
    impl Neg for Complex
    impl Show for Complex
    impl Sub for Complex

    Complex::abs

    fn Complex::abs(self : Complex) -> Double

    The modulus, computed as a hypotenuse so that large components do not overflow.

    Complex::arg

    fn Complex::arg(self : Complex) -> Double

    The angle in radians, in (-pi, pi], the argument atan2 returns.

    Complex::conj

    fn Complex::conj(self : Complex) -> Complex

    The conjugate: the imaginary part negated.

    Complex::cos

    fn Complex::cos(self : Complex) -> Complex

    The cosine, extended to the complex plane.

    Complex::cosh

    fn Complex::cosh(self : Complex) -> Complex

    The hyperbolic cosine, extended to the complex plane.

    Complex::exp

    fn Complex::exp(self : Complex) -> Complex

    e raised to this value, by Euler's formula.

    Complex::is_nonzero

    fn Complex::is_nonzero(self : Complex) -> Bool

    True when either part is non-zero.

    Complex::log

    fn Complex::log(self : Complex) -> Complex

    The principal logarithm: ln|z| + i arg z.

    Complex::neg

    fn Complex::neg(self : Complex) -> Complex

    The additive inverse.

    Complex::new

    fn Complex::new(re : Double, im : Double) -> Complex

    A complex number from its real and imaginary parts.

    Complex::pow

    fn Complex::pow(self : Complex, exponent : Complex) -> Complex

    self raised to exponent, through exp(exponent * log self).

    Complex::sin

    fn Complex::sin(self : Complex) -> Complex

    The sine, extended to the complex plane.

    Complex::sinh

    fn Complex::sinh(self : Complex) -> Complex

    The hyperbolic sine, extended to the complex plane.

    Complex::sqrt

    fn Complex::sqrt(self : Complex) -> Complex

    The principal square root, on the branch where the result's real part is non-negative.

    Complex::tan

    fn Complex::tan(self : Complex) -> Complex

    The tangent, extended to the complex plane.

    Complex::tanh

    fn Complex::tanh(self : Complex) -> Complex

    The hyperbolic tangent, extended to the complex plane.

    Cpu

    pub struct Cpu {
    lanes : Int
    }

    The only backend there is for now: plain MoonBit, with a vector path where the elements are doubles or floats and the operation is one of the four arithmetic ones.

    Cpu::new

    fn Cpu::new() -> Cpu

    The default backend, sized for the vector registers the build target provides.

    DType

    pub(all) enum DType {
    Bool
    I8
    I16
    I32
    I64
    U8
    U16
    U32
    U64
    F16
    F32
    F64
    C64
    C128
    }

    The element type of an array.

    The set a numerical array needs: one boolean type, the signed and unsigned integers, the half, single and double precision floats, and the two complex widths. There is no platform integer type, because an array's dtype has to mean the same thing on every target.
    impl Eq for DType
    impl Show for DType

    DType::float_size

    fn DType::float_size(self : DType) -> Int

    The dtype that holds every value of self without loss, the smallest such float being F64.

    DType::is_bool

    fn DType::is_bool(self : DType) -> Bool

    True for the boolean dtype.

    DType::is_complex

    fn DType::is_complex(self : DType) -> Bool

    True for the two complex dtypes.

    DType::is_exact

    fn DType::is_exact(self : DType) -> Bool

    True for the dtypes an operation on integers keeps exact: integers and bool.

    DType::is_float

    fn DType::is_float(self : DType) -> Bool

    True for F16, F32 and F64; the complex dtypes are not floats.

    DType::is_integer

    fn DType::is_integer(self : DType) -> Bool

    True for the signed and unsigned integer dtypes, false for bool.

    DType::is_real

    fn DType::is_real(self : DType) -> Bool

    True for anything whose values are stored as a real number: floats and complex.

    DType::is_signed

    fn DType::is_signed(self : DType) -> Bool

    True for the four signed integer dtypes.

    DType::item_size

    fn DType::item_size(self : DType) -> Int

    The number of bytes one element takes in a buffer.

    DType::name

    fn DType::name(self : DType) -> String

    The name this type is written as, lower case and without spaces.

    DType::parse

    fn DType::parse(text : StringView) -> DType?

    Reads a dtype back from its name, as written by to_string or a vector file.

    DType::to_real

    fn DType::to_real(self : DType) -> DType

    The float dtype that holds this one at the same width, for operations that leave the integer domain: I8 gives F16, I32 gives F64. Complex dtypes are returned unchanged.

    Index

    pub(all) enum Index {
    All
    At(Int)
    Span(Int, Int, Int)
    NewAxis
    Take(Array[Int])
    Mask(Array[Bool])
    }

    One axis selector in a slice, read left to right, one per axis.

    NDArray

    pub struct NDArray {
    buffer : Buffer
    shape : Array[Int]
    strides : Array[Int]
    offset : Int
    }

    An N-dimensional array: a view over a flat buffer, described by a shape and a stride per axis.

    The strides are counted in elements, not bytes, and follow C order: the last axis varies fastest. Any axis may have stride 0, which is how a size-one axis broadcasts without copying its data, and any axis may be negative, which is how a reversed view is made. Two arrays made by slicing the same array share one buffer, so a write through one is visible through the other.
    impl Add for NDArray
    impl Div for NDArray
    impl Eq for NDArray
    impl Mod for NDArray
    impl Mul for NDArray
    impl Neg for NDArray
    impl Show for NDArray
    impl Sub for NDArray

    NDArray::at

    fn NDArray::at(self : NDArray, index : Array[Int]) -> Number raise VecError

    The element at index, one integer per axis.

    NDArray::buffer

    fn NDArray::buffer(self : NDArray) -> Buffer

    The buffer this view reads, shared with every other view of the same data.

    NDArray::copy

    fn NDArray::copy(self : NDArray) -> NDArray raise VecError

    A contiguous copy, whatever the layout of this view.

    NDArray::dtype

    fn NDArray::dtype(self : NDArray) -> DType

    The element type of the buffer.

    NDArray::is_contiguous

    fn NDArray::is_contiguous(self : NDArray) -> Bool

    True when the elements sit next to each other in buffer order, so a backend can take the whole array as one run.

    NDArray::is_scalar

    fn NDArray::is_scalar(self : NDArray) -> Bool

    True for a 0-dimensional array, the result of a full reduction.

    NDArray::item

    fn NDArray::item(self : NDArray) -> Number raise VecError

    The one value of a 0-dimensional array.

    NDArray::ndim

    fn NDArray::ndim(self : NDArray) -> Int

    How many axes the shape has.

    NDArray::new

    fn NDArray::new(buffer~ : Buffer, shape~ : Array[Int], strides? : Array[Int], offset? : Int) -> NDArray raise VecError

    Builds a view over buffer; the strides default to the contiguous layout of shape.

    NDArray::offset

    fn NDArray::offset(self : NDArray) -> Int

    The index in the buffer of the first element, after any slicing.

    NDArray::set_at

    fn NDArray::set_at(self : NDArray, index : Array[Int], value : Number) -> Unit raise VecError

    Writes one element at index.

    NDArray::shape

    fn NDArray::shape(self : NDArray) -> Array[Int]

    The size of each axis; a copy, so changing it cannot break the view.

    NDArray::size

    fn NDArray::size(self : NDArray) -> Int

    How many elements the shape holds, counting a stretched axis once per position.

    NDArray::strides

    fn NDArray::strides(self : NDArray) -> Array[Int]

    The element distance between neighbours along each axis; a copy.

    NDArray::to_doubles

    fn NDArray::to_doubles(self : NDArray) -> Array[Double] raise VecError

    Every element as a double, in row-major order. Complex values lose their imaginary part, as any conversion to a real type does.

    NDArray::to_numbers

    fn NDArray::to_numbers(self : NDArray) -> Array[Number] raise VecError

    Every element in row-major order, as a fresh array.

    NDArray::to_string

    fn NDArray::to_string(self : NDArray) -> String raise VecError

    The array laid out one row per line, with the dtype after the values.

    Number

    pub(all) enum Number {
    Boolean(Bool)
    Signed(Int64)
    Unsigned(UInt64)
    Real(Double)
    Complex(Complex)
    }

    One element of an array, widened to the type that holds its whole range.

    The variants name the class the value belongs to rather than one variant per dtype: reading an int16 gives Signed too, and writing it back checks the width. This keeps a kernel written once per operation instead of once per dtype.
    impl Eq for Number
    impl Show for Number

    Number::cast

    fn Number::cast(self : Number, dtype : DType) -> Number

    The same value, stored as dtype would store it: integers wrap to their width, floats round.

    Number::compare_value

    fn Number::compare_value(self : Number, other : Number) -> Int

    Compares two values by magnitude only; complex pairs compare by real part then imaginary part, which is the order values sort in.

    Number::to_bool

    fn Number::to_bool(self : Number) -> Bool

    True when the value is not zero; a complex number is true when either part is.

    Number::to_complex

    fn Number::to_complex(self : Number) -> Complex

    The value as a complex number, with a zero imaginary part.

    Number::to_double

    fn Number::to_double(self : Number) -> Double

    The value as a double; an integer above 2^53 loses its low bits.

    Number::to_int64

    fn Number::to_int64(self : Number) -> Int64

    The value truncated toward zero, the rule C uses when a float is stored into an integer.

    Number::to_string

    fn Number::to_string(self : Number) -> String

    The value as the array printer writes it.

    Plan

    pub struct Plan {
    outer_sizes : Array[Int]
    outer_strides : Array[Array[Int]]
    run : Int
    run_strides : Array[Int]
    operands : Int
    starts : Array[Int]
    }

    A loop schedule over a shape: the axes that vary between runs, and the length of the innermost run that stays contiguous for every operand.

    Adjacent axes are merged when every operand walks them at a constant step, which turns a contiguous pair of arrays into a single tight loop instead of one call per element. Each run hands the loop body the buffer offsets of all operands at the start of the run.

    ReduceOp

    pub(all) enum ReduceOp {
    Sum
    Product
    Minimum
    Maximum
    Any
    All
    }

    The reductions a backend has to provide, as an associative pair of values.

    UnaryOp

    pub(all) enum UnaryOp {
    Negate
    Absolute
    Square
    Reciprocal
    Sign
    Sqrt
    Cbrt
    Exp
    Exp2
    Expm1
    Log
    Log2
    Log10
    Log1p
    Sin
    Cos
    Tan
    ArcSin
    ArcCos
    ArcTan
    Sinh
    Cosh
    Tanh
    ArcSinh
    ArcCosh
    ArcTanh
    Floor
    Ceil
    Trunc
    Rint
    Degrees
    Radians
    LogicalNot
    Conjugate
    }

    The unary operations a backend has to provide.

    absolute

    fn absolute(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The magnitude; a complex array answers in its real dtype.

    add

    fn add(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise sum; the two shapes broadcast.

    add_scalar

    fn add_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    Adds a scalar to every element, keeping the array's dtype; 1 added to an int8 array stays int8, because a scalar does not widen the array.

    all

    fn all(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    True where every element is true; a full reduction over an empty array is true.

    angle

    fn angle(a : NDArray) -> NDArray raise VecError

    The angle of each complex value in radians; a real array is 0 where positive and pi where negative.

    any

    fn any(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    True where any element is true.

    apply_binary

    fn apply_binary(op : BinaryOp, dtype : DType, left : Number, right : Number) -> Number raise VecError

    Applies a binary operation to two values already in dtype.

    The result may have a wider class than dtype — a comparison gives a boolean, absolute value of a complex gives a real — and the caller's output buffer decides what it is stored as.

    apply_reduce

    fn apply_reduce(op : ReduceOp, dtype : DType, left : Number, right : Number) -> Number raise VecError

    Combines two values in a reduction; the pair must be associative and have the identity the caller started from.

    apply_unary

    fn apply_unary(op : UnaryOp, dtype : DType, value : Number) -> Number raise VecError

    Applies a unary operation to a value already cast to dtype.

    arange

    fn arange(start~ : Double, stop~ : Double, step? : Double, dtype? : DType) -> NDArray raise VecError

    Evenly spaced values in [start, stop), stepping by step.

    The count is computed from the span and the step, so arange(0, 1, 0.3) stops at 0.9 rather than at 1.2. A step whose sign does not lead towards stop gives an empty array instead of looping forever.

    arccos

    fn arccos(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Inverse cosine of each element, in radians; outside [-1, 1] it is NaN.

    arccosh

    fn arccosh(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Inverse hyperbolic cosine of each element; below one it is NaN.

    arcsin

    fn arcsin(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Inverse sine of each element, in radians; outside [-1, 1] it is NaN.

    arcsinh

    fn arcsinh(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Inverse hyperbolic sine of each element.

    arctan

    fn arctan(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Inverse tangent of each element, in radians.

    arctan2

    fn arctan2(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise arctangent of a / b, choosing the quadrant from both signs.

    arctanh

    fn arctanh(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Inverse hyperbolic tangent of each element; outside (-1, 1) it is NaN.

    argmax

    fn argmax(a : NDArray, axis? : Int, keepdims? : Bool) -> NDArray raise VecError

    The index of the largest element along the axis; the first one wins a tie.

    argmin

    fn argmin(a : NDArray, axis? : Int, keepdims? : Bool) -> NDArray raise VecError

    The index of the smallest element along the axis; the first one wins a tie.

    argsort

    fn argsort(array : NDArray, axis? : Int) -> NDArray raise VecError

    The positions that would sort each run along the axis, as int64; stable for equal values.

    array

    fn array(values : Array[Double], dtype? : DType) -> NDArray raise VecError

    A 1-D array from a list of values.

    astype

    fn astype(a : NDArray, dtype~ : DType) -> NDArray raise VecError

    A copy of the array with every element converted to dtype.

    The conversion is the one C makes: an integer that does not fit wraps, a float is truncated towards zero when it becomes an integer, and a NaN becomes zero, because there is no integer it could honestly become.

    bessel_i

    fn bessel_i(order~ : Double, a : NDArray) -> NDArray raise VecError

    The modified Bessel function of the first kind of order order.

    bessel_j

    fn bessel_j(order~ : Double, a : NDArray) -> NDArray raise VecError

    The Bessel function of the first kind of order order.

    bessel_k

    fn bessel_k(order~ : Double, a : NDArray) -> NDArray raise VecError

    The modified Bessel function of the second kind of order order.

    bessel_y

    fn bessel_y(order~ : Double, a : NDArray) -> NDArray raise VecError

    The Bessel function of the second kind of order order.

    beta

    fn beta(a : NDArray, b : NDArray) -> NDArray raise VecError

    The beta function, elementwise over two broadcast operands.

    bitwise_and

    fn bitwise_and(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise bitwise and; both operands must be integers.

    bitwise_or

    fn bitwise_or(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise bitwise or; both operands are read as integers.

    bitwise_xor

    fn bitwise_xor(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise bitwise exclusive or; both operands are read as integers.

    broadcast

    fn broadcast(shape_a : Array[Int], shape_b : Array[Int]) -> Array[Int] raise VecError

    The shape an elementwise operation of these two arrays has, without doing the work.

    broadcast_shape

    fn broadcast_shape(left : Array[Int], right : Array[Int]) -> Array[Int] raise VecError

    The shape two arrays take when an elementwise operation meets them.

    The axes are aligned from the right; an axis missing on one side counts as 1, and an axis of 1 stretches to the other side's length. Any other pair of different lengths is an error, because there is no honest way to pair those elements up.

    broadcast_strides

    fn broadcast_strides(shape : Array[Int], strides : Array[Int], out_shape : Array[Int]) -> Array[Int]

    The strides an operand of this shape takes when it is broadcast to out_shape: an axis it does not have, or has with length 1, gets stride 0 so every element along that axis reads the same.

    broadcast_to

    fn broadcast_to(array : NDArray, shape : Array[Int]) -> NDArray raise VecError

    The same array seen with a larger shape, without copying, by giving stretched axes stride 0.

    The new shape must broadcast up to shape, so a size-one axis may grow and a leading axis may be added; anything else cannot be expressed as a view and is refused rather than copied silently.

    cbrt

    fn cbrt(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise cube root, defined for negative inputs too: cbrt(-8) is -2.

    ceil

    fn ceil(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Rounds up.

    clip

    fn clip(a : NDArray, min? : Double, max? : Double, kernel? : &Kernel) -> NDArray raise VecError

    Clamps every element into [min, max]; either bound may be left out, and the bounds broadcast like any other operand.

    compare_real

    fn compare_real(left : Double, right : Double) -> Int

    Orders two doubles with NaN last, so a sort puts the values that cannot be compared at the end instead of scattering them.

    complex_number

    fn complex_number(re : Double, im : Double) -> Number

    A complex value as a Number, spelling out both types so the variant and the struct do not shadow each other.

    concatenate

    fn concatenate(arrays : Array[NDArray], axis? : Int) -> NDArray raise VecError

    Joins arrays along an existing axis; the other axes must agree in length, and the dtypes promote.

    conj

    fn conj(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise conjugate; a real array is returned as it is.

    cos

    fn cos(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Cosine of each element, in radians.

    cosh

    fn cosh(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Hyperbolic cosine of each element.

    cpu

    let cpu : Cpu

    The backend every function uses when the caller does not name one.

    degrees

    fn degrees(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Converts radians to degrees.

    digamma

    fn digamma(a : NDArray) -> NDArray raise VecError

    The logarithmic derivative of gamma.

    divide

    fn divide(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    True division: two integer arrays give float64, so 1 / 2 is 0.5 rather than 0.

    divide_scalar

    fn divide_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    Divides by a scalar; an integer array gives float64, as with divide.

    division_dtype

    fn division_dtype(left : DType, right : DType) -> DType

    The dtype the true division of these two dtypes produces: integers turn into float64.

    dot

    fn dot(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The dot product of two arrays: a's last axis against b's second-to-last, with the axes that are left over kept in order.

    For 1-D and 2-D operands this is matmul. For higher ranks it differs: a stack times a matrix contracts every row of the stack against the same matrix.

    equal

    fn equal(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise a == b, answering with a boolean array.

    equal_nan

    fn equal_nan(a : NDArray, b : NDArray) -> NDArray raise VecError

    Elementwise equality that also holds for two NaNs in the same place, which equal does not.

    erf

    fn erf(a : NDArray) -> NDArray raise VecError

    The error function.

    erfc

    fn erfc(a : NDArray) -> NDArray raise VecError

    The complementary error function, 1 - erf(x), accurate for large arguments.

    erfcinv

    fn erfcinv(a : NDArray) -> NDArray raise VecError

    The inverse of the complementary error function.

    erfinv

    fn erfinv(a : NDArray) -> NDArray raise VecError

    The inverse of the error function.

    exp

    fn exp(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    e raised to each element.

    exp2

    fn exp2(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Two raised to each element.

    expand_dims

    fn expand_dims(array : NDArray, axis~ : Int) -> NDArray raise VecError

    A view with a new axis of length 1 at axis.

    expm1

    fn expm1(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    exp(a) - 1, accurate near zero.

    eye

    fn eye(n~ : Int, m? : Int, k? : Int, dtype? : DType) -> NDArray raise VecError

    A matrix with ones on the k-th diagonal and zeros elsewhere.

    k counts diagonals from the main one: positive towards the upper right, negative towards the lower left. m defaults to n, so the result is square.

    fabs

    fn fabs(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The magnitude of a real array, as floating point; the same as absolute for floats.

    flatten

    fn flatten(array : NDArray) -> NDArray raise VecError

    A 1-D copy, always.

    floor

    fn floor(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Rounds down.

    floor_divide

    fn floor_divide(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Division rounded towards negative infinity; both operands keep their integer type.

    for_each_offset

    fn for_each_offset(array : NDArray, body : (Int) -> Unit raise VecError) -> Unit raise VecError

    Visits every element of array in row-major order, passing the buffer offset of each.

    The offsets are produced by an odometer over the shape rather than by recomputing a dot product per element, so a strided or reversed view costs one addition per axis crossed.

    format_real

    fn format_real(value : Double) -> String

    A double as the printer writes it: 1.0 rather than 1, with nan and inf spelled out.

    from_bytes

    fn from_bytes(bytes : Bytes, shape : Array[Int], dtype~ : DType) -> NDArray raise VecError

    An array from raw bytes, which must be a whole number of elements of dtype.

    from_doubles

    fn from_doubles(values : Array[Double], shape : Array[Int], dtype? : DType) -> NDArray raise VecError

    An array of shape from doubles in row-major order.

    from_numbers

    fn from_numbers(values : Array[Number], shape : Array[Int], dtype? : DType) -> NDArray raise VecError

    An array of shape from values in row-major order.

    full

    fn full(shape : Array[Int], value : Number, dtype? : DType) -> NDArray raise VecError

    An array of shape filled with value, which is converted to dtype.

    full_like

    fn full_like(prototype : NDArray, value : Number, dtype? : DType) -> NDArray raise VecError

    An array with the same shape as prototype, filled with value; the dtype follows prototype unless dtype says otherwise.

    gamma

    fn gamma(a : NDArray) -> NDArray raise VecError

    The gamma function, from the special-function library.

    greater

    fn greater(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise a > b as a boolean array.

    greater_equal

    fn greater_equal(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise a >= b as a boolean array.

    hstack

    fn hstack(arrays : Array[NDArray]) -> NDArray raise VecError

    Joins 1-D arrays end to end, and 2-D arrays along the second axis.

    hypot

    fn hypot(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise sqrt(a * a + b * b), without the overflow the naive form has.

    imag

    fn imag(a : NDArray) -> NDArray raise VecError

    The imaginary part; a real array gives zeros.

    inner

    fn inner(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The inner product: a sum over the last axis of both, so the result has the shape of the operands without their last axis, added together.

    invert

    fn invert(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise ~, flipping every bit of an integer array.

    isfinite

    fn isfinite(a : NDArray) -> NDArray raise VecError

    True where the value is neither infinite nor a NaN; integers are always finite.

    isinf

    fn isinf(a : NDArray) -> NDArray raise VecError

    True where the value is an infinity.

    isnan

    fn isnan(a : NDArray) -> NDArray raise VecError

    True where the value is not a number; an integer array is never.

    left_shift

    fn left_shift(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise left shift, with the second array as the count.

    less

    fn less(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise a < b; complex arrays are not ordered and are refused.

    less_equal

    fn less_equal(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise a <= b as a boolean array.

    lgamma

    fn lgamma(a : NDArray) -> NDArray raise VecError

    The natural logarithm of the absolute value of gamma, which stays finite where gamma overflows.

    linspace

    fn linspace(start~ : Double, stop~ : Double, num? : Int, endpoint? : Bool, dtype? : DType) -> NDArray raise VecError

    num values from start to stop; with endpoint (the default) the last value is exactly stop, so the spacing is (stop - start) / (num - 1). With one value the result is start, not stop.

    log

    fn log(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Natural logarithm; zero gives minus infinity and a negative input gives NaN.

    log10

    fn log10(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Base-ten logarithm, with the same treatment of non-positive input as log.

    log1p

    fn log1p(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    log(1 + a), accurate near zero.

    log2

    fn log2(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Base-two logarithm, with the same treatment of non-positive input as log.

    logical_and

    fn logical_and(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise logical and, reading both operands as truth values.

    logical_not

    fn logical_not(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise not, answering with a boolean array; zero is false, everything else true.

    logical_or

    fn logical_or(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise logical or, reading both operands as truth values.

    logical_xor

    fn logical_xor(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    True where exactly one side is true.

    mask

    fn mask(array : NDArray, keep : Array[Bool], axis? : Int) -> NDArray raise VecError

    Keeps the positions where the mask is true along one axis; the mask must have the axis's length.

    matmul

    fn matmul(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Matrix multiplication, with the usual rules for the shapes that are not both matrices.

    The last axis of a contracts with the second-to-last of b. A 1-D operand is taken as a row or a column and the axis it borrowed is removed from the result, so a vector times a vector is a 0-dimensional array. Leading axes broadcast against each other, which makes a stack of matrices multiply as a stack.

    matrix

    fn matrix(rows : Array[Array[Double]], dtype? : DType) -> NDArray raise VecError

    A 2-D array from rows that all have the same length.

    max

    fn max(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    The largest element.

    maximum

    fn maximum(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise larger of the two; a NaN on either side gives NaN.

    maximum_scalar

    fn maximum_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    The larger of each element and a scalar, elementwise.

    mean

    fn mean(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    The arithmetic mean: an integer array answers in float64, and an empty axis gives NaN rather than an error, since there is a count to divide by, namely zero.

    min

    fn min(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    The smallest element; an empty axis has no smallest element and is refused.

    minimum

    fn minimum(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise smaller of the two; a NaN on either side gives NaN.

    minimum_scalar

    fn minimum_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    The smaller of each element and a scalar, elementwise.

    mod

    fn mod(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The same as remainder, under the name Python uses for the operator.

    move_axis

    fn move_axis(array : NDArray, from : Int, to : Int) -> NDArray raise VecError

    A view with one axis moved to another position, the other axes keeping their order.

    multiply

    fn multiply(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise product.

    multiply_scalar

    fn multiply_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    Multiplies every element by a scalar, keeping the array's dtype.

    negative

    fn negative(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise negation.

    not_equal

    fn not_equal(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise a != b as a boolean array; NaN is not equal to anything, itself included.

    ones

    fn ones(shape : Array[Int], dtype? : DType) -> NDArray raise VecError

    An array of shape filled with ones.

    ones_like

    fn ones_like(prototype : NDArray, dtype? : DType) -> NDArray raise VecError

    An array of ones shaped like prototype.

    outer

    fn outer(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The outer product: a as a column, b as a row, their product a matrix. Both are read flat.

    positive

    fn positive(a : NDArray) -> NDArray raise VecError

    A copy with every value's sign flipped, which for bool gives -1 for true.

    power

    fn power(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise power; an integer base with a negative integer exponent is refused.

    power_scalar

    fn power_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    Raises every element to a scalar power, by the same rules as power.

    prod

    fn prod(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    Multiplies the elements.

    promote

    fn promote(left : DType, right : DType) -> DType

    The dtype two arrays of these dtypes produce when an arithmetic operation meets them.

    This is not a widening hierarchy: uint64 with int8 gives float64, because no integer type holds both ranges. The table is symmetric, so the order of the arguments does not matter.

    promote_all

    fn promote_all(dtypes : ArrayView[DType]) -> DType

    The dtype every one of dtypes promotes to; F64 for an empty list, the neutral element.

    radians

    fn radians(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Converts degrees to radians.

    ravel

    fn ravel(array : NDArray) -> NDArray raise VecError

    A 1-D view when the array is contiguous, a 1-D copy when it is not.

    real

    fn real(a : NDArray) -> NDArray raise VecError

    The real part; a real array is returned as it is.

    reciprocal

    fn reciprocal(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise reciprocal, which for integers gives float64.

    reduce_identity

    fn reduce_identity(op : ReduceOp, dtype : DType) -> Number

    The value a reduction starts from: the identity that leaves every element unchanged.

    The bounds are written per width rather than by casting one wide value, because a cast would wrap: the largest int8 is 127, not int64's maximum truncated to eight bits.

    remainder

    fn remainder(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    The remainder with the sign of the divisor, so -3 % 2 is 1.

    reshape

    fn reshape(array : NDArray, shape : Array[Int]) -> NDArray raise VecError

    A view with the same elements in a new shape; -1 in one position asks for the size that fits.

    A contiguous array reshapes as a view. A strided one is copied first, because there is no stride pattern that would make the new shape a view of the old.

    right_shift

    fn right_shift(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise right shift, with the second array as the count.

    rint

    fn rint(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Rounds to the nearest integer with a tie going to the even one, the way IEEE 754 does.

    round

    fn round(a : NDArray) -> NDArray raise VecError

    Rounds to the nearest integer, a tie going away from zero; round in Python 3 goes to even, so this is rint's sibling, not a replacement for it.

    select

    fn select(condition : NDArray, x : NDArray, y : NDArray) -> NDArray raise VecError

    Chooses elementwise from x where condition holds and from y elsewhere; all three broadcast together. It is named select because where is a keyword in MoonBit.

    sign

    fn sign(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    -1, 0 or 1 by sign; a complex argument gives the value divided by its magnitude.

    signbit

    fn signbit(a : NDArray) -> NDArray raise VecError

    True where the value is negative, including -0.0.

    sin

    fn sin(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Sine of each element, in radians.

    sinh

    fn sinh(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Hyperbolic sine of each element.

    slice

    fn slice(array : NDArray, indices : Array[Index]) -> NDArray raise VecError

    A view of array selected axis by axis; axes past the end of indices are taken whole.

    Slicing a contiguous array stays a view: nothing is copied, so a write through the slice is a write into the original. At removes an axis and NewAxis adds one. Take and Mask cannot be expressed by strides, so they copy.

    sort

    fn sort(array : NDArray, axis? : Int) -> NDArray raise VecError

    A sorted copy along one axis, the last by default; NaNs go to the end.

    The sort is stable, so equal values keep the order they had, which argsort relies on.

    span

    fn span(start : Int, stop : Int, step? : Int) -> Index

    A run of positions, the common case written without spelling out the step.

    split

    fn split(array : NDArray, parts~ : Int, axis? : Int) -> Array[NDArray] raise VecError

    Splits an axis into equal parts; the length must divide evenly.

    split_at

    fn split_at(array : NDArray, at : Array[Int], axis? : Int) -> Array[NDArray] raise VecError

    Splits an axis at the given positions, which are the lengths of the parts before them. A position outside the axis is clamped, which lets split_at stand in for split.

    sqrt

    fn sqrt(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise square root; a negative input gives NaN, as IEEE 754 says, rather than an error.

    square

    fn square(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise square.

    squeeze

    fn squeeze(array : NDArray, axis? : Int) -> NDArray raise VecError

    A view with axes of length 1 removed; with axis, only that axis and only if it has length 1.

    stack

    fn stack(arrays : Array[NDArray], axis? : Int) -> NDArray raise VecError

    Joins arrays along a new axis, so the result has one more axis than the inputs.

    std

    fn std(a : NDArray, axis? : Int, ddof? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    The standard deviation, the square root of the variance.

    subtract

    fn subtract(a : NDArray, b : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Elementwise difference.

    subtract_scalar

    fn subtract_scalar(a : NDArray, value : Double, kernel? : &Kernel) -> NDArray raise VecError

    Subtracts a scalar from every element, keeping the array's dtype.

    sum

    fn sum(a : NDArray, axis? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    Sums the elements, either all of them or along one axis.

    A full reduction returns a 0-dimensional array; keepdims keeps the reduced axis with length 1 so the result still broadcasts against the input.

    swap_axes

    fn swap_axes(array : NDArray, first : Int, second : Int) -> NDArray raise VecError

    A view with two axes exchanged.

    take

    fn take(array : NDArray, picks : Array[Int], axis? : Int) -> NDArray raise VecError

    Picks positions along one axis by an integer array, keeping the number of axes; the result is a copy.

    tan

    fn tan(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Tangent of each element, in radians.

    tanh

    fn tanh(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Hyperbolic tangent of each element.

    trace

    fn trace(a : NDArray, offset? : Int) -> NDArray raise VecError

    The sum of the diagonal, or of a diagonal chosen by offset; a 2-D only operation.

    transpose

    fn transpose(array : NDArray, axes? : Array[Int]) -> NDArray raise VecError

    A view with the axes permuted; without axes the order is reversed.

    trunc

    fn trunc(a : NDArray, kernel? : &Kernel) -> NDArray raise VecError

    Drops the fractional part, towards zero.

    variance

    fn variance(a : NDArray, axis? : Int, ddof? : Int, keepdims? : Bool, kernel? : &Kernel) -> NDArray raise VecError

    The variance with ddof degrees of freedom removed from the count: the population variance by default, the sample variance with ddof=1.

    vstack

    fn vstack(arrays : Array[NDArray]) -> NDArray raise VecError

    Rows one after another: a 1-D array becomes a single row, and anything with two or more axes is joined along axis 0.

    zeros

    fn zeros(shape : Array[Int], dtype? : DType) -> NDArray raise VecError

    An array of shape filled with zeros.

    zeros_like

    fn zeros_like(prototype : NDArray, dtype? : DType) -> NDArray raise VecError

    The common body of the *_like constructors.

    zeta

    fn zeta(a : NDArray) -> NDArray raise VecError

    The Riemann zeta function.