RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

Arrays and linear algebra

n-dimensional arrays with NumPy semantics: float16, bfloat16 and complex dtypes, views, slicing, broadcasting, ufuncs, reductions, matmul and einsum. BLAS levels 1–3, LU, Cholesky, LDLᵀ, QR, SVD, eigenvalues, Schur, least squares and matrix functions.

import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray';
import 'package:riptide_numerics_cpu/linalg.ray';
29 classes297 functions and methods243 of 469 documented250 runnable examplesWhat NumPy and LAPACK do

Overview

n-dimensional arrays with NumPy's semantics, and dense linear algebra. The portable path is plain Raya (the web, and the reference in tests). Where raya:ffi exists a native backend takes the O(n^{3}) work: Apple Accelerate (BLAS/LAPACK, ILP64) on macOS and iOS, the Raya Native GEMM (packed FMA kernel, on every core) on Android. The GPU paths are riptide_numerics_gpu.

import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;

final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
final v = a['::2, 1:'];                 // a view (NumPy a[::2, 1:]); writes go through to a
final b = v * 2 + np.NDArray.arange(3); // broadcasting ufuncs, dtype promotion like NumPy 2
final c = np.matmul(a, a.T);            // blocked GEMM (Float64x2 micro-kernel)
final s = c.sum(axis: 0);               // pairwise summation
final e = np.einsum('ij,jk->ik', [a, a.T]);

The array

NDArray is one typed list (data) seen through shape, strides and offset. Strides count elements, not bytes (byteStrides gives NumPy's). Slicing, transpose, reshape of a compatible layout, broadcastTo, diagonal, real / imag are views; everything that makes a new array makes a C-order one.

dtypestoragenotes
booleanUint8List
int8..int64, uint8..uint64the matching typed listwrap on overflow, as NumPy; uint64 \ge 2^{63} reads back negative
float16, bfloat16Uint16List (IEEE bits)computed in double, rounded to nearest even once on store
float32, float64Float32List, Float64List
complex64, complex128Float32List, Float64List, interleaveda complex element is one element for strides
  • Indexing: a[2], a[Slice(1, null, 2)], a[[i, j]] (NumPy's tuple a[i, j]), a[[Slice.all, newAxis, ellipsis]], or the string form a['1:2, None... -1']. One advanced index (an int or bool NDArray) per operation: a[NDArray.fromList([3, 0])] takes rows, a[a.gt(0)] gives the selected elements. a[idx] = value assigns with broadcasting.
  • Promotion: DType.promote matches numpy.result_type for every pair of the 14 dtypes (tested); Raya scalars are NumPy 2 "weak" scalars (int8_array * 3 stays int8, float32_array + 1.5 stays float32).
  • Complex where defined), each with an optional out: array (aliasing-safe). where, clip, isClose, allClose, arrayEqual.
  • Reductions: sum (pairwise), mean, variance, std, prod, min, max, argmin, argmax, any, all, cumsum, cumprod over any axis or axes, with keepdims; sort / argsort (stable, NaNs last), take, takeAlongAxis, compress.
  • Products: matmul (batched and broadcast, 1-d rules), dot, tensordot, outer, vdot, kron, trace, einsum (explicit or implicit output, repeated indices, ..., any number of operands).
  • Zero copy: NDArray.fromTypedData, NDArray.fromBytes (byte strides and offset, e.g. struct fields), NDArray.fromStructList (Raya AOT; a fallback copy elsewhere), toTypedData / toBytes (views when contiguous).
  • Shape tools: reshape, ravel, flatten, transpose/T/H, swapAxes, moveAxis, expandDims, squeeze, concatenate, stack, vstack, hstack, split, flip, roll, tile, repeat, meshgrid.

Linear algebra

import 'package:riptide_numerics_cpu/linalg.ray' as la; (numpy.linalg / scipy.linalg names):

AreaAPI
BLAS 1-3la.Blas.dot/axpy/scal/nrm2/asum/iamax/swap/rot/rotg, gemv/ger/symv/trsv, gemm/trsm/syrk/symm (any strides)
Factorizationslu (blocked, partial pivoting; p, l, u, packed, solve, det), cholesky (blocked), ldl (Bunch-Kaufman), qr (blocked Householder; reduced/complete/r)
Spectralsvd (Golub-Kahan; full/reduced/values; complex values), eigh/eigvalsh (blocked tridiagonalization + divide and conquer from n = 48), eig/eigvals (Hessenberg + Francis double-shift QR), schur (real or complex)
Solverssolve (real or complex), solveTriangular, inv, det, slogdet, lstsq (minimum norm), pinv, solveRefined (low-precision LU + float64 refinement)
Measuresnorm (vector and matrix orders), cond, matrixRank
Matrix functionsexpm (Padé 3-13, real or complex), sqrtm, logm (Schur based)

Backends. la.Linalg.backend is the native backend (la.Linalg.backendName: accelerate, raya-native x6, raya). The default is picked on first use: Accelerate on macOS/iOS (lu, cholesky, qr, eigh, svd (dgesdd), eig, schur, GEMM), the Raya Native GEMM elsewhere (the blocked factorizations stay ours and their trailing updates run natively), none on the web. la.getrf, la.potrf, la.geqrf, la.orgqr, la.luSolveInPlace are the LAPACK-style row-major entry points.

The blocked LU, Cholesky and QR send their trailing updates through a GemmBackend (CpuGemm by default, CpuGemmF32, or GpuGemmBackend from riptide_numerics_gpu); an explicit backend: keeps them on our blocked code instead of the native LAPACK.

Not supported: object dtypes, structured dtypes, several advanced indices in one operation, np.nditer's full API.

Functions and constants

Functions

hypotfunction
double hypot(double x, double y)

\sqrt{x^{2} + y^{2}} without undue overflow or underflow.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('hypot(3, 4) = ${np.hypot(3, 4)}');
  // No overflow where x² would: 1e200² is out of range for a double.
  print('hypot(1e200, 1e200) = ${np.hypot(1e200, 1e200)}');
}
Output
hypot(3, 4) = 5.0
hypot(1e200, 1e200) = 1.414213562373095e+200
int doubleToHalfBits(double value)

IEEE binary16 bits of value, rounded to nearest, ties to even (overflow -> inf, NaN -> quiet NaN).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  for (final v in [1.0, 0.1, 65504.0, 1e5]) {
    final b = np.doubleToHalfBits(v);
    print('$v -> 0x${b.toRadixString(16).padLeft(4, '0')} -> ${np.halfBitsToDouble(b)}');
  }
}
Output
1.0 -> 0x3c00 -> 1.0
0.1 -> 0x2e66 -> 0.0999755859375
65504.0 -> 0x7bff -> 65504.0
100000.0 -> 0x7c00 -> Infinity
double halfBitsToDouble(int bits)

The value of IEEE binary16 bits.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('0x3c00 = ${np.halfBitsToDouble(0x3c00)}');
  print('0x7bff = ${np.halfBitsToDouble(0x7bff)} (largest half)');
  print('0x0001 = ${np.halfBitsToDouble(0x0001)} (smallest subnormal)');
  print('0x7c00 = ${np.halfBitsToDouble(0x7c00)}');
        {'label': 'half(x) − x', 'points': [for (var i = 0; i <= 200; i++) [1 + i / 200, np.halfBitsToDouble(np.doubleToHalfBits(1 + i / 200)) - (1 + i / 200)]]},
      ]})}');
}
Output
0x3c00 = 1.0
0x7bff = 65504.0 (largest half)
0x0001 = 5.960464477539063e-8 (smallest subnormal)
0x7c00 = Infinity
int doubleToBfloat16Bits(double value)

Bfloat16 bits of value (the top 16 bits of a float32), rounded to nearest, ties to even, directly from the double (no double rounding through float32).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  for (final v in [1.0, 3.14159, 1e30, 0.1]) {
    final b = np.doubleToBfloat16Bits(v);
    print('$v -> 0x${b.toRadixString(16).padLeft(4, '0')} -> ${np.bfloat16BitsToDouble(b)}');
  }
}
Output
1.0 -> 0x3f80 -> 1.0
3.14159 -> 0x4049 -> 3.140625
1e+30 -> 0x714a -> 1.0002555517425873e+30
0.1 -> 0x3dcd -> 0.10009765625
double bfloat16BitsToDouble(int bits)

The value of bfloat16 bits.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('0x3f80 = ${np.bfloat16BitsToDouble(0x3f80)}');
  print('0x4049 = ${np.bfloat16BitsToDouble(0x4049)}');
        {'label': 'bf16(x) − x', 'points': [for (var i = 0; i <= 300; i++) [1 + i / 100, np.bfloat16BitsToDouble(np.doubleToBfloat16Bits(1 + i / 100)) - (1 + i / 100)]]},
      ]})}');
}
Output
0x3f80 = 1.0
0x4049 = 3.140625
parseIndexfunction
List<Object> parseIndex(String spec)

Parses NumPy index syntax: "1:2, None... -1" -> [Slice(1), Slice(null, null, 2), newAxis, ellipsis, -1].

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.parseIndex('1:3, ::2'));
  print(np.parseIndex('..., None, -1'));
  final a = np.NDArray.arange(12).reshape([3, 4]);
  print('a["1:3, ::2"] =\n${a['1:3, ::2']}');
}
Output
[1:3, ::2]
[..., None, -1]
a["1:3, ::2"] =
array([[4, 6],
       [8, 10]])
concatenatefunction
NDArray concatenate(List<NDArray> arrays, {int axis = 0})

Joins arrays along an existing axis; dtypes promote.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0]]);
  final b = np.NDArray.fromList([[3.0, 4.0]]);
  print('concatenate axis 0:\n${np.concatenate([a, b])}');
  print('hstack: ${np.hstack([a, b])}');
  print('vstack shape: ${np.vstack([a, b, a]).shape}');
  print('stack shape:  ${np.stack([a, b]).shape}');
}
Output
concatenate axis 0:
array([[1., 2.],
       [3., 4.]])
hstack: array([[1., 2., 3., 4.]])
vstack shape: [3, 2]
stack shape:  [2, 1, 2]
stackfunction
NDArray stack(List<NDArray> arrays, {int axis = 0})

Joins arrays (same shape) along a new axis.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0]), b = np.NDArray.fromList([4.0, 5.0, 6.0]);
  final s0 = np.stack([a, b]);
  print('stack axis 0: shape ${s0.shape}\n$s0');
  print('stack axis 1: shape ${np.stack([a, b], axis: 1).shape}');
}
Output
stack axis 0: shape [2, 3]
array([[1., 2., 3.],
       [4., 5., 6.]])
stack axis 1: shape [3, 2]
vstackfunction
NDArray vstack(List<NDArray> arrays)

Stacks rows (1-d arrays become rows).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.ones([2, 3]), b = np.NDArray.zeros([1, 3]);
  final v = np.vstack([a, b]);
  print('shape ${v.shape}\n$v');
}
Output
shape [3, 3]
array([[1., 1., 1.],
       [1., 1., 1.],
       [0., 0., 0.]])
hstackfunction
NDArray hstack(List<NDArray> arrays)

Stacks columns (1-d arrays are joined end to end).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.eye(2), b = np.NDArray.full([2, 1], 7.0);
  final h = np.hstack([a, b]);
  print('shape ${h.shape}\n$h');
  print('1-D: ${np.hstack([np.NDArray.arange(2), np.NDArray.arange(3)])}');
}
Output
shape [2, 3]
array([[1., 0., 7.],
       [0., 1., 7.]])
1-D: array([0, 1, 0, 1, 2])
splitfunction
List<NDArray> split(NDArray a, Object sections, {int axis = 0})

Splits a into sections equal parts, or at the given indices, along axis (views).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(9);
  print('3 equal parts: ${np.split(a, 3)}');
  print('at indices [2, 5]: ${np.split(a, [2, 5])}');
  final m = np.NDArray.arange(8).reshape([2, 4]);
  print('columns in 2: ${np.split(m, 2, axis: 1).map((x) => x.shape).toList()}');
}
Output
3 equal parts: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
at indices [2, 5]: [array([0, 1]), array([2, 3, 4]), array([5, 6, 7, 8])]
columns in 2: [[2, 2], [2, 2]]
flipfunction
NDArray flip(NDArray a, {int? axis})

Reverses the order of elements along axis (all axes when null), as a view.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(6).reshape([2, 3]);
  print('flip all:\n${np.flip(a)}');
  print('flip axis 1:\n${np.flip(a, axis: 1)}');
}
Output
flip all:
array([[5, 4, 3],
       [2, 1, 0]])
flip axis 1:
array([[2, 1, 0],
       [5, 4, 3]])
rollfunction
NDArray roll(NDArray a, int shift, {int? axis})

Rolls elements by shift along axis (the flattened array when null).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(6);
  print('roll 2:  ${np.roll(a, 2)}');
  print('roll -1: ${np.roll(a, -1)}');
  final m = np.NDArray.arange(6).reshape([2, 3]);
  print('rows rolled along axis 1:\n${np.roll(m, 1, axis: 1)}');
}
Output
roll 2:  array([4, 5, 0, 1, 2, 3])
roll -1: array([1, 2, 3, 4, 5, 0])
rows rolled along axis 1:
array([[2, 0, 1],
       [5, 3, 4]])
tilefunction
NDArray tile(NDArray a, List<int> reps)

Repeats a reps times along each axis.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]);
  final t = np.tile(a, [2, 3]);
  print('shape ${t.shape}\n$t');
}
Output
shape [4, 6]
array([[1., 2., 1., 2., 1., 2.],
       [3., 4., 3., 4., 3., 4.],
       [1., 2., 1., 2., 1., 2.],
       [3., 4., 3., 4., 3., 4.]])
repeatfunction
NDArray repeat(NDArray a, int repeats, {int? axis})

Repeats each element repeats times along axis (the flattened array when null).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]);
  print('flat: ${np.repeat(a, 2)}');
  print('axis 0:\n${np.repeat(a, 2, axis: 0)}');
  print('axis 1:\n${np.repeat(a, 3, axis: 1)}');
}
Output
flat: array([1., 1., 2., 2., 3., 3., 4., 4.])
axis 0:
array([[1., 2.],
       [1., 2.],
       [3., 4.],
       [3., 4.]])
axis 1:
array([[1., 1., 1., 2., 2., 2.],
       [3., 3., 3., 4., 4., 4.]])
meshgridfunction
List<NDArray> meshgrid(List<NDArray> xs, {String indexing = 'xy'})

Coordinate matrices from coordinate vectors ('xy' indexing like NumPy's default, or 'ij').

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-1, 1, 5), y = np.NDArray.linspace(0, 1, 3);
  final g = np.meshgrid([x, y]);
  print('X shape ${g[0].shape}, Y shape ${g[1].shape}');
  // f(x, y) = x² + y on the grid.
  final f = g[0] * g[0] + g[1];
  print('f =\n$f');
  print('ij indexing: ${np.meshgrid([x, y], indexing: 'ij')[0].shape}');
}
Output
X shape [3, 5], Y shape [3, 5]
f =
array([[1., 0.25, 0., 0.25, 1.],
       [1.5, 0.75, 0.5, 0.75, 1.5],
       [2., 1.25, 1., 1.25, 2.]])
ij indexing: [5, 3]
matmulfunction
NDArray matmul(NDArray a, NDArray b, {NDArray? out})

Matrix product with NumPy matmul semantics: 1-d operands are promoted to a row / column and the added axis is removed afterwards; leading (batch) axes broadcast. Real float64 runs the blocked GEMM; float32/16 accumulate in float32; integers are exact (int64, wrapping).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [1.0, 2.0],
    [3.0, 4.0],
  ]);
  final b = np.NDArray.fromList([
    [5.0, 6.0],
    [7.0, 8.0],
  ]);
  print('a @ b:\n${np.matmul(a, b)}');
  print('a @ [1, 1]: ${np.matmul(a, np.NDArray.fromList([1.0, 1.0]))}');
  print('a @ a.T:\n${np.matmul(a, a.T)}');
}
Output
a @ b:
array([[19., 22.],
       [43., 50.]])
a @ [1, 1]: array([3., 7.])
a @ a.T:
array([[5., 11.],
       [11., 25.]])
dotfunction
NDArray dot(NDArray a, NDArray b)

NumPy dot: inner product of 1-d arrays, matrix product of 2-d ones, and for N-d a sum over the last axis of a and the second-to-last of b.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final u = np.NDArray.fromList([1.0, 2.0, 3.0]);
  final v = np.NDArray.fromList([4.0, 5.0, 6.0]);
  print('dot(u, v):   ${np.dot(u, v)}');
  print('outer(u, v):\n${np.outer(u, v)}');
  print('trace(eye):  ${np.trace(np.NDArray.eye(4))}');
}
Output
dot(u, v):   array(32.)
outer(u, v):
array([[4., 5., 6.],
       [8., 10., 12.],
       [12., 15., 18.]])
trace(eye):  array(4.)
tensordotfunction
NDArray tensordot(NDArray a, NDArray b, {required List<int> axesA, required List<int> axesB})

Sum of products over axesA of a and axesB of b (NumPy tensordot); the result's axes are a's free axes then b's.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(24, null, 1, np.DType.float64).reshape([2, 3, 4]);
  final b = np.NDArray.ones([4, 3]);
  // Contract a's axes (1, 2) with b's (1, 0).
  final c = np.tensordot(a, b, axesA: [1, 2], axesB: [1, 0]);
  print('shape ${c.shape}: $c');
  print('same as sums: ${a.sum(axis: [1, 2])}');
}
Output
shape [2]: array([66., 210.])
same as sums: array([66., 210.])
outerfunction
NDArray outer(NDArray a, NDArray b)

Outer product of two arrays (flattened), NumPy outer.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0]), b = np.NDArray.fromList([1.0, 10.0, 100.0, 1000.0]);
  final o = np.outer(a, b);
  print('shape ${o.shape}\n$o');
}
Output
shape [3, 4]
array([[1., 10., 100., 1000.],
       [2., 20., 200., 2000.],
       [3., 30., 300., 3000.]])
vdotfunction
NDArray vdot(NDArray a, NDArray b)

Inner product of the flattened arrays, conjugating the first (NumPy vdot).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]);
  print('vdot flattens: ${np.vdot(a, a)}');
  final z = np.NDArray.fromList([np.Complex(1, 2), np.Complex(3, -1)]);
  print('complex: vdot(z, z) = ${np.vdot(z, z)}  (conjugates the first)');
}
Output
vdot flattens: array(30.)
complex: vdot(z, z) = array(15.+0.j, dtype=complex128)  (conjugates the first)
tracefunction
NDArray trace(NDArray a, {int k = 0})

Sum of the diagonal k over axes 0 and 1.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [4.0, 1.0, 2.0],
    [1.0, 3.0, 0.0],
    [2.0, 0.0, 5.0],
  ]);
  print('trace = ${np.trace(a)}');
  print('k = 1 (superdiagonal) = ${np.trace(a, k: 1)}');
}
Output
trace = array(12.)
k = 1 (superdiagonal) = array(1.)
einsumfunction
NDArray einsum(String subscripts, List<NDArray> operands)

Einstein summation (NumPy einsum): explicit ('ij,jk->ik') or implicit ('ij,jk': output = the indices that appear once, sorted) subscripts, repeated indices within an operand (diagonals, 'ii->i', 'ii'), ... for broadcast axes, and any number of operands (contracted left to right through matmul).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(6, null, 1, np.DType.float64).reshape([2, 3]);
  final b = np.NDArray.arange(3, null, 1, np.DType.float64);
  print('ij,j->i   (matrix-vector): ${np.einsum('ij,j->i', [a, b])}');
  print('ij->ji    (transpose):\n${np.einsum('ij->ji', [a])}');
  print('ij,ij->   (sum of products): ${np.einsum('ij,ij->', [a, a])}');
  print('i,j->ij   (outer product):\n${np.einsum('i,j->ij', [b, b])}');
}
Output
ij,j->i   (matrix-vector): array([5., 14.])
ij->ji    (transpose):
array([[0., 3.],
       [1., 4.],
       [2., 5.]])
ij,ij->   (sum of products): array(55.)
i,j->ij   (outer product):
array([[0., 0., 0.],
       [0., 1., 2.],
       [0., 2., 4.]])
kronfunction
NDArray kron(NDArray a, NDArray b)

Kronecker product of two 2-d arrays.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]);
  final k = np.kron(a, np.NDArray.eye(2));
  print('shape ${k.shape}\n$k');
}
Output
shape [4, 4]
array([[1., 0., 2., 0.],
       [0., 1., 0., 2.],
       [3., 0., 4., 0.],
       [0., 3., 0., 4.]])
gemmUpdatefunction
void gemmUpdate(NDArray a, NDArray b, NDArray c, double alpha, double beta)

c = \alpha \cdot a @ b + \beta \cdot c on 2-d views; float64 and float32 (all three the same dtype) go straight to the blocked kernels, anything else through a temporary.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]);
  final c = np.NDArray.ones([2, 2]);
  np.gemmUpdate(a, a, c, 2.0, 1.0); // c = 2·a·a + 1·c, in place
  print('c =\n$c');
}
Output
c =
array([[15., 21.],
       [31., 45.]])
List<int> broadcastShapes(List<List<int>> shapes)

The shape two or more shapes broadcast to (NumPy rules); throws when they don't.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.broadcastShapes([[3, 1], [1, 4]]));
  print(np.broadcastShapes([[8, 1, 6, 1], [7, 1, 5]]));
  try {
    np.broadcastShapes([[3], [4]]);
  } catch (e) {
    print('[3] and [4]: ${e.runtimeType}');
  }
}
Output
[3, 4]
[8, 7, 6, 5]
[3] and [4]: ArgumentError
List<NDArray> broadcastArrays(List<NDArray> arrays)

Views of arrays broadcast to their common shape.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final col = np.NDArray.arange(3).reshape([3, 1]), row = np.NDArray.arange(4);
  final b = np.broadcastArrays([col, row]);
  print('shapes ${b[0].shape} and ${b[1].shape}');
  print('${b[0]}');
}
Output
shapes [3, 4] and [3, 4]
array([[0, 0, 0, 0],
       [1, 1, 1, 1],
       [2, 2, 2, 2]])
formatArrayfunction
String formatArray(NDArray a)

NumPy-style printing (summarised with ... past 1000 elements).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.formatArray(np.NDArray.linspace(0, 1, 5)));
  print(np.formatArray(np.NDArray.eye(2)));
}
Output
array([0., 0.25, 0.5, 0.75, 1.])
array([[1., 0.],
       [0., 1.]])
pairwiseSumfunction
double pairwiseSum(List<double> x, int start, int n, int stride)

Pairwise sum of x[start], x[start+stride]... (n terms).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = List<double>.filled(1000000, 0.1);
  var naive = 0.0;
  for (final v in x) {
    naive += v;
  }
  print('naive loop:   $naive');
  print('pairwise sum: ${np.pairwiseSum(x, 0, x.length, 1)}');
  print('every other:  ${np.pairwiseSum(x, 0, 500000, 2)}');
}
Output
naive loop:   100000.00000133288
pairwise sum: 100000.00000000003
every other:  50000.000000000015
expm1function
double expm1(double x)

\exp(x) - 1, accurate near 0 (Kahan's trick).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  print('expm1(1e-10) = ${np.expm1(1e-10)}');
  print('exp(1e-10) − 1 = ${math.exp(1e-10) - 1}  (cancellation)');
  print('expm1(1) = ${np.expm1(1)}');
}
Output
expm1(1e-10) = 1.00000000005e-10
exp(1e-10) − 1 = 1.000000082740371e-10  (cancellation)
expm1(1) = 1.718281828459045
log1pfunction
double log1p(double x)

\log(1 + x), accurate near 0 (Goldberg's trick).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('log1p(1e-12) = ${np.log1p(1e-12)}');
  print('log1p(1) = ${np.log1p(1)}');
  print('log1p(−0.5) = ${np.log1p(-0.5)}');
}
Output
log1p(1e-12) = 9.999999999995e-13
log1p(1) = 0.6931471805599453
log1p(−0.5) = -0.6931471805599453
cbrtfunction
double cbrt(double x)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('cbrt(27) = ${np.cbrt(27)}');
  print('cbrt(−8) = ${np.cbrt(-8)}');
  print('cbrt(2) = ${np.cbrt(2)}');
}
Output
cbrt(27) = 3.0
cbrt(−8) = -2.0
cbrt(2) = 1.2599210498948732
wherefunction
NDArray where(NDArray condition, Object x, Object y)

Elements of x where condition is true, else of y (each broadcast; NumPy where).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([-2.0, -0.5, 0.0, 1.5, 3.0]);
  // ReLU: keep positive values, replace the rest with 0.
  print('relu(x) = ${np.where(x.gt(0), x, 0)}');
  print('sign    = ${x.sign()}');
}
Output
relu(x) = array([0., 0., 0., 1.5, 3.])
sign    = array([-1., -1., 0., 1., 1.])
isClosefunction
NDArray isClose(NDArray a, Object b, {double rtol = 1e-5, double atol = 1e-8, bool equalNan = false})

Elementwise |a - b| <= atol + rtol * |b| (NumPy isclose; NaNs equal when equalNan).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 1.0 + 1e-9, 1.1, double.nan]);
  print(np.isClose(a, 1.0));
  print('NaN equal: ${np.isClose(a, double.nan, equalNan: true)}');
  print('rtol 0.2: ${np.isClose(a, 1.0, rtol: 0.2)}');
}
Output
array([True, True, False, False])
NaN equal: array([False, False, False, True])
rtol 0.2: array([True, True, True, False])
allClosefunction
bool allClose(NDArray a, Object b, {double rtol = 1e-5, double atol = 1e-8, bool equalNan = false})

Whether every element is close (NumPy allclose).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([0.1 + 0.2, 1.0]);
  final b = np.NDArray.fromList([0.3, 1.0]);
  print('exactly equal: ${np.arrayEqual(a, b)}');
  print('allClose:      ${np.allClose(a, b)}');
  print('isClose:       ${np.isClose(a, b)}');
}
Output
exactly equal: false
allClose:      true
isClose:       array([True, True])
arrayEqualfunction
bool arrayEqual(NDArray a, NDArray b)

Same shape and equal elements (NumPy array_equal).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(4);
  print(np.arrayEqual(a, np.NDArray.fromList([0, 1, 2, 3])));
  print(np.arrayEqual(a, a.reshape([2, 2])));
  print(np.arrayEqual(a, a + 0.0));
}
Output
true
false
true
eighfunction
EighResult eigh(NDArray a, {bool computeVectors = true})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [2.0, 1.0],
    [1.0, 2.0],
  ]);
  final e = la.eigh(a);
  print('eigenvalues (ascending): ${[for (final v in e.values.toDoubleList()) v.toStringAsFixed(6)]}');
  // Each column v of the eigenvector matrix satisfies a·v = λ·v.
  final v = e.vectors![':, 1'];
  print('a·v == 3·v: ${np.allClose(np.matmul(a, v), v * 3)}');
}
Output
eigenvalues (ascending): [1.000000, 3.000000]
a·v == 3·v: true
eigvalshfunction
NDArray eigvalsh(NDArray a)

Eigenvalues of a real symmetric matrix, ascending.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [4.0, 1.0, 2.0],
    [1.0, 3.0, 0.0],
    [2.0, 0.0, 5.0],
  ]);
  final w = la.eigvalsh(a);
  print('eigenvalues: ${[for (final v in w.toDoubleList()) v.toStringAsFixed(6)]}');
  print('sum = trace: ${w.sum().toDouble().toStringAsFixed(9)} vs ${np.trace(a)}');
}
Output
eigenvalues: [1.854897, 3.476024, 6.669079]
sum = trace: 12.000000000 vs array(12.)
schurfunction
SchurResult schur(NDArray a, {String output = 'real'})

Real Schur decomposition ('real') or complex Schur decomposition ('complex': T upper triangular, Z unitary), as scipy.linalg.schur.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [4.0, -2.0, 1.0],
    [3.0, 6.0, -4.0],
    [2.0, 1.0, 8.0],
  ]);
  final s = la.schur(a);
  final t = s.t.map((x) => (x * 1e6).roundToDouble() / 1e6);
  print('T (upper quasi-triangular):\n$t');
  print('Z T Zᵀ == a: ${np.allClose(np.matmul(np.matmul(s.z, s.t), s.z.T), a)}');
  print('Z orthogonal: ${np.allClose(np.matmul(s.z.T, s.z), np.NDArray.eye(3))}');
}
Output
T (upper quasi-triangular):
array([[3.525647, -4.368899, -0.683745],
       [2.265497, 6.094414, 2.552899],
       [0., 0., 8.379939]])
Z T Zᵀ == a: true
Z orthogonal: true
eigfunction
EigResult eig(NDArray a, {bool computeVectors = true})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  // A rotation by 90°: eigenvalues ±i.
  final a = np.NDArray.fromList([[0.0, -1.0], [1.0, 0.0]]);
  final e = la.eig(a);
  print('eigenvalues: ${e.values}');
  final b = np.NDArray.fromList([[2.0, 0.0], [1.0, 3.0]]);
  print('real case: ${la.eig(b).values}');
}
Output
eigenvalues: array([0.+1.j, 0.-1.j], dtype=complex128)
real case: array([2., 3.])
eigvalsfunction
NDArray eigvals(NDArray a)

Eigenvalues of a general real matrix.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 2.0]]);
  print('eigvals = ${la.eigvals(a)}');
  print('det = ${la.det(a)} = product of eigenvalues');
}
Output
eigvals = array([-1., 4.])
det = array(-4.) = product of eigenvalues
void luSolveInPlace(Float64List lu, Int64List piv, int n, Float64List x, int nrhs)

Applies the pivots and the two triangular solves to x (n x nrhs, row-major), in place.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final m = Float64List.fromList([4, 3, 6, 3]); // 2 × 2, row-major
  final (piv, singular) = la.getrf(m, 2, 2);
  final x = Float64List.fromList([10, 12]);
  la.luSolveInPlace(m, piv, 2, x, 1);
  print('singular: $singular, x = $x');
}
Output
singular: false, x = [1.0, 2.0]
lufunction
LUDecomposition lu(NDArray a, {GemmBackend? backend})

LU factorization with partial pivoting of a real m \times n matrix (scipy.linalg.lu semantics through the getters). Singular matrices factor fine (LUDecomposition.singular is set); solving with them throws.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [4.0, 1.0, 2.0],
    [1.0, 3.0, 0.0],
    [2.0, 0.0, 5.0],
  ]);
  final f = la.lu(a);
  print('P L U == a: ${np.allClose(np.matmul(np.matmul(f.p, f.l), f.u), a)}');
  print('L =\n${f.l}');
  print('solve a x = (1, 2, 3): ${f.solve(np.NDArray.fromList([1.0, 2.0, 3.0]))}');
}
Output
P L U == a: true
L =
array([[1., 0., 0.],
       [0.25, 1., 0.],
       [0.5, -0.18181818, 1.]])
solve a x = (1, 2, 3): array([-0.30232558, 0.76744186, 0.72093023])
getrffunction
(Int64List, bool) getrf(Float64List a, int m, int n, {GemmBackend? backend})

In-place blocked LU of a row-major m \times n matrix; returns (pivots, singular).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final m = Float64List.fromList([1, 2, 3, 4]);
  final (piv, singular) = la.getrf(m, 2, 2);
  print('packed LU: $m');
  print('pivots: $piv, singular: $singular');
  final (_, s2) = la.getrf(Float64List.fromList([1, 2, 2, 4]), 2, 2);
  print('[[1, 2], [2, 4]] singular: $s2');
}
Output
packed LU: [3.0, 4.0, 0.3333333333333333, 0.6666666666666667]
pivots: [1, 1], singular: false
[[1, 2], [2, 4]] singular: true
solvefunction
NDArray solve(NDArray a, NDArray b, {GemmBackend? backend})

Solves A x = b (b a vector or a matrix of right-hand sides); complex when either is complex.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  // 2x + y = 5, x + 3y = 10
  final a = np.NDArray.fromList([
    [2.0, 1.0],
    [1.0, 3.0],
  ]);
  final b = np.NDArray.fromList([5.0, 10.0]);
  final x = la.solve(a, b);
  print('x = ${[for (final v in x.toDoubleList()) v.toStringAsFixed(6)]}');
  print('check a·x == b: ${np.allClose(np.matmul(a, x), b)}');
}
Output
x = [1.000000, 3.000000]
check a·x == b: true
invfunction
NDArray inv(NDArray a)

The inverse of a square matrix (throws LinAlgError when singular).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [4.0, 7.0],
    [2.0, 6.0],
  ]);
  final ai = la.inv(a);
  print('inv(a) = ${[for (final v in ai.toDoubleList()) v.toStringAsFixed(4)]}');
  print('a · inv(a) is the identity: ${np.allClose(np.matmul(a, ai), np.NDArray.eye(2))}');
}
Output
inv(a) = [0.6000, -0.7000, -0.2000, 0.4000]
a · inv(a) is the identity: true
detfunction
NDArray det(NDArray a)

\det(A) (complex inputs give a Complex-valued 0-d array).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 2.0],
    [0.0, 4.0, 1.0],
    [5.0, 2.0, 0.0],
  ]);
  print('det(a) = ${la.det(a).toDouble().toStringAsFixed(6)}');
  final singular = np.NDArray.fromList([
    [1.0, 2.0],
    [2.0, 4.0],
  ]);
  print('det of a singular matrix is zero: ${la.det(singular).toDouble().abs() < 1e-12}');
  final (sign, logDet) = la.slogdet(a);
  print('slogdet: sign $sign, log|det| ${logDet.toStringAsFixed(6)}');
}
Output
det(a) = -41.000000
det of a singular matrix is zero: true
slogdet: sign -1.0, log|det| 3.713572
slogdetfunction
(double, double) slogdet(NDArray a)

(sign, \log|\det|) of a real square matrix.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.eye(50) * 10;
  final (sign, logdet) = la.slogdet(a);
  print('sign $sign, log|det| = $logdet (det = 1e50)');
  final (s2, l2) = la.slogdet(np.NDArray.fromList([[0.0, 1.0], [1.0, 0.0]]));
  print('swap matrix: sign $s2, log|det| $l2');
}
Output
sign 1.0, log|det| = 115.12925464970236 (det = 1e50)
swap matrix: sign -1.0, log|det| 0.0
choleskyfunction
NDArray cholesky(NDArray a, {bool upper = false, GemmBackend? backend})

Lower-triangular Cholesky factor L of a symmetric positive-definite matrix (A = L L^{T}; only the lower triangle of A is read). Blocked, right-looking; throws LinAlgError when A is not positive definite.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final s = np.NDArray.fromList([
    [4.0, 2.0],
    [2.0, 3.0],
  ]);
  final l = la.cholesky(s);
  print('L = ${[for (final v in l.toDoubleList()) v.toStringAsFixed(6)]}');
  print('L·Lᵀ == S: ${np.allClose(np.matmul(l, l.T), s)}');
}
Output
L = [2.000000, 0.000000, 1.000000, 1.414214]
L·Lᵀ == S: true
potrffunction
void potrf(Float64List a, int n, {GemmBackend? backend})

In-place lower Cholesky of a row-major n \times n matrix (upper triangle zeroed).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final m = Float64List.fromList([4, 2, 2, 3]);
  la.potrf(m, 2);
  print('in place (lower triangle is L): $m');
}
Output
in place (lower triangle is L): [2.0, 0.0, 1.0, 1.4142135623730951]
ldlfunction
LDLDecomposition ldl(NDArray a)

Bunch-Kaufman LDL^T of a symmetric matrix (the lower triangle is read).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [4.0, 2.0, -2.0],
    [2.0, -3.0, 1.0],
    [-2.0, 1.0, 5.0],
  ]);
  final f = la.ldl(a);
  print('D =\n${f.d}');
  print('P L D Lᵀ Pᵀ == a: ${np.allClose(np.matmul(np.matmul(np.matmul(np.matmul(f.p, f.l), f.d), f.l.T), f.p.T), a)}');
  print('solve: ${f.solve(np.NDArray.fromList([1.0, 0.0, 0.0]))}');
}
Output
D =
array([[4., 0., 0.],
       [0., -4., 0.],
       [0., 0., 5.]])
P L D Lᵀ Pᵀ == a: true
solve: array([0.2, 0.15, 0.05])
NDArray solveTriangular(NDArray t, NDArray b, {bool lower = true, bool unitDiagonal = false, bool transpose = false})

Solves T x = b for triangular T (lower or upper, optionally unit diagonal); b a vector or matrix.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final l = np.NDArray.fromList([
    [2.0, 0.0, 0.0],
    [1.0, 1.0, 0.0],
    [3.0, -1.0, 4.0],
  ]);
  final x = la.solveTriangular(l, np.NDArray.fromList([2.0, 3.0, 10.0]));
  print('forward substitution: $x');
  print('L x: ${np.matmul(l, x)}');
  print('with Lᵀ: ${la.solveTriangular(l, np.NDArray.fromList([2.0, 3.0, 10.0]), transpose: true)}');
}
Output
forward substitution: array([1., 2., 2.25])
L x: array([2., 3., 10.])
with Lᵀ: array([-5.5, 5.5, 2.5])
normfunction
NDArray norm(NDArray x, {Object? ord, int? axis, bool keepdims = false})

Vector or matrix norm, as numpy.linalg.norm. ord: for vectors \frac{\operatorname{null}}{2}, 1, any p, inf, -\inf, 0; for matrices null/'fro', 'nuc', 1, -1, 2, -2, inf, -\inf (use double.infinity). axis null: a vector norm of the flattened array for 1-d input, a matrix norm for 2-d input; an int: vector norms along that axis.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final v = np.NDArray.fromList([3.0, 4.0]);
  print('norm(v) = ${la.norm(v).toDouble()}');
  final m = np.NDArray.fromList([
    [1.0, 2.0],
    [3.0, 4.0],
  ]);
  print('Frobenius norm of m = ${la.norm(m).toDouble().toStringAsFixed(6)}');
  print('cond(m) = ${la.cond(m).toStringAsFixed(6)}');
}
Output
norm(v) = 5.0
Frobenius norm of m = 5.477226
cond(m) = 14.933034
condfunction
double cond(NDArray a, {Object? p})

Condition number in norm p (null or 2: sigma_max / sigma_min; inf for singular matrices).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  for (final eps in [1.0, 1e-3, 1e-8]) {
    final a = np.NDArray.fromList([[1.0, 1.0], [1.0, 1.0 + eps]]);
    print('eps $eps: cond = ${la.cond(a).toStringAsExponential(3)}');
  }
}
Output
eps 1.0: cond = 6.854e+0
eps 0.001: cond = 4.002e+3
eps 1e-8: cond = 4.000e+8
matrixRankfunction
int matrixRank(NDArray a, {double? tol})

Numerical rank: singular values above tol (default sigma_max * \max(m, n) \cdot \mathrm{eps}), as numpy.linalg.matrix_rank.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [1.0, 2.0, 3.0],
    [2.0, 4.0, 6.0],
    [1.0, 0.0, 1.0],
  ]);
  print('rank = ${la.matrixRank(a)}');
  print('identity: ${la.matrixRank(np.NDArray.eye(4))}');
  print('outer product: ${la.matrixRank(np.outer(np.NDArray.arange(4), np.NDArray.arange(5)))}');
}
Output
rank = 2
identity: 4
outer product: 1
pinvfunction
NDArray pinv(NDArray a, {double? rtol})

Moore-Penrose pseudo-inverse through the SVD; singular values below rtol * sigma_max are dropped (default rtol \max(m, n) \cdot \mathrm{eps}, as numpy 2).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [1.0, 2.0],
    [3.0, 4.0],
    [5.0, 6.0],
  ]);
  final p = la.pinv(a);
  print('pinv shape ${p.shape}');
  print('A⁺A == I: ${np.allClose(np.matmul(p, a), np.NDArray.eye(2))}');
  print('A A⁺ A == A: ${np.allClose(np.matmul(np.matmul(a, p), a), a)}');
}
Output
pinv shape [2, 3]
A⁺A == I: true
A A⁺ A == A: true
lstsqfunction
(NDArray, NDArray, int, NDArray) lstsq(NDArray a, NDArray b, {double? rcond})

Least-squares solution of A x = b (numpy.linalg.lstsq): x minimises \Vert b - A x\Vert_{2}, with the minimum norm when A is rank deficient. Returns (x, residuals: sums of squared residuals per column when A is full column rank and m > n, else empty; rank; singular values).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  // Fit y = c0 + c1·x to four points.
  final xs = [0.0, 1.0, 2.0, 3.0];
  final ys = [1.0, 3.1, 4.9, 7.0];
  final a = np.NDArray.fromList([for (final x in xs) [1.0, x]]);
  final (coef, residual, rank, _) = la.lstsq(a, np.NDArray.fromList(ys));
  final c = coef.toDoubleList();
  print('intercept ${c[0].toStringAsFixed(4)}, slope ${c[1].toStringAsFixed(4)}, rank $rank');
}
Output
intercept 1.0300, slope 1.9800, rank 2
expmfunction
NDArray expm(NDArray a)

The matrix exponential (real or complex), Higham's scaling and squaring with Pade approximants.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  // exp of a rotation generator is a rotation: [[cos t, -sin t], [sin t, cos t]].
  const t = 0.5;
  final g = np.NDArray.fromList([
    [0.0, -t],
    [t, 0.0],
  ]);
  final r = la.expm(g);
  print('expm(G) = ${[for (final v in r.toDoubleList()) v.toStringAsFixed(6)]}');
}
Output
expm(G) = [0.877583, -0.479426, 0.479426, 0.877583]
sqrtmfunction
NDArray sqrtm(NDArray a)

Principal square root of a square matrix (real result when the input is real and the result's imaginary part is negligible, like scipy.linalg.sqrtm).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[4.0, 1.0], [0.0, 9.0]]);
  final s = la.sqrtm(a);
  print('sqrtm =\n$s');
  print('s·s == a: ${np.allClose(np.matmul(s, s), a)}');
}
Output
sqrtm =
array([[2., 0.2],
       [0., 3.]])
s·s == a: true
logmfunction
NDArray logm(NDArray a)

Principal logarithm of a square matrix (real result when real and negligible imaginary part, like scipy.linalg.logm). Matrices with eigenvalues on the closed negative real axis have no real logarithm; zero eigenvalues give -\inf entries.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = la.expm(np.NDArray.fromList([[0.0, 1.0], [-1.0, 0.0]]));
  final l = la.logm(a);
  print('logm(expm(J)) =\n${l.map((x) => (x * 1e9).roundToDouble() / 1e9)}');
  print('expm(logm(a)) == a: ${np.allClose(la.expm(l), a)}');
}
Output
logm(expm(J)) =
array([[0., 1.],
       [-1., 0.]])
expm(logm(a)) == a: true
solveRefinedfunction
RefinedSolve solveRefined(NDArray a, NDArray b, {GemmBackend backend = const CpuGemmF32(), int maxIterations = 30})

Solves A x = b to float64 accuracy with the LU computed by backend in its precision (float32 on GPUs; the matrix is rounded to float32 first so the factorization is a true float32 one), then iterative refinement with float64 residuals (LAPACK dsgesv). Falls back to a float64 LU when refinement stalls (\operatorname{cond}(A) too close to 1 / eps32).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [4.0, 1.0, 0.0],
    [1.0, 4.0, 1.0],
    [0.0, 1.0, 4.0],
  ]);
  final b = np.NDArray.fromList([1.0, 2.0, 3.0]);
  final r = la.solveRefined(a, b);
  print('x = ${r.x}');
  print('refinement steps ${r.iterations}, fell back: ${r.fellBack}');
  print('matches solve: ${np.allClose(r.x, la.solve(a, b))}');
}
Output
x = array([0.17857143, 0.28571429, 0.67857143])
refinement steps 0, fell back: false
matches solve: true
geqrffunction
Float64List geqrf(Float64List a, int m, int n, {GemmBackend? backend})

In-place blocked QR of a row-major m \times n matrix: R in the upper triangle, the Householder vectors below it. Returns tau (length \min(m, n)).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([3, 1, 4, 2]); // 2 × 2
  final tau = la.geqrf(a, 2, 2);
  print('R in the upper triangle: $a');
  print('Householder tau: $tau');
  final q = la.orgqr(a, 2, 2, tau, 2);
  print('Q = $q');
}
Output
R in the upper triangle: [-5.0, -2.2, 0.5, 0.3999999999999999]
Householder tau: [1.6, 0.0]
Q = [-0.6000000000000001, -0.8, -0.8, 0.6]
orgqrfunction
Float64List orgqr(Float64List a, int m, int n, Float64List tau, int q, {GemmBackend? backend})

Forms the first q columns of Q (m \times q) from a factored matrix (dorgqr, blocked).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 3, 4, 5, 6]); // 3 × 2
  final tau = la.geqrf(a, 3, 2);
  final q = la.orgqr(a, 3, 2, tau, 2);
  final qm = np.NDArray.fromTypedData(q, shape: [3, 2]);
  print('Q =\n$qm');
  print('QᵀQ == I: ${np.allClose(np.matmul(qm.T, qm), np.NDArray.eye(2))}');
}
Output
Q =
array([[-0.16903085, 0.89708523],
       [-0.50709255, 0.27602622],
       [-0.84515425, -0.34503278]])
QᵀQ == I: true
qrfunction
QRDecomposition qr(NDArray a, {String mode = 'reduced', GemmBackend? backend})

Householder QR of a real m \times n matrix. mode: 'reduced' (Q m \times k, R k \times n, k = \min(m, n)), 'complete' (Q m \times m, R m \times n) or 'r' (R only), as numpy.linalg.qr. The diagonal of R may be negative (LAPACK's convention).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [1.0, 2.0],
    [3.0, 4.0],
    [5.0, 6.0],
  ]);
  final f = la.qr(a);
  print('Q shape ${f.q!.shape}, R shape ${f.r.shape}');
  print('Q·R == a:  ${np.allClose(np.matmul(f.q!, f.r), a)}');
  print('QᵀQ == I:  ${np.allClose(np.matmul(f.q!.T, f.q!), np.NDArray.eye(2))}');
  print('R is upper triangular: ${f.r.get2(1, 0).abs() < 1e-12}');
}
Output
Q shape [3, 2], R shape [2, 2]
Q·R == a:  true
QᵀQ == I:  true
R is upper triangular: true
svdfunction
SVDResult svd(NDArray a, {bool fullMatrices = false, bool computeUV = true})

SVD of a real m \times n matrix. fullMatrices gives square U and V^{T} (numpy's default is true; reduced is cheaper); computeUV false returns the singular values only. Complex inputs: singular values only (through the real embedding [[Re, -\operatorname{Im}], [Im, Re]], whose singular values are each of A's twice).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([
    [3.0, 0.0],
    [4.0, 5.0],
  ]);
  final r = la.svd(a);
  print('singular values: ${[for (final s in r.s.toDoubleList()) s.toStringAsFixed(6)]}');
  // Rebuild a from U · diag(s) · Vᵀ.
  final back = np.matmul(np.matmul(r.u!, np.NDArray.diag(r.s)), r.vt!);
  print('U·S·Vᵀ == a: ${np.allClose(back, a)}');
  print('rank: ${la.matrixRank(a)}');
}
Output
singular values: [6.708204, 2.236068]
U·S·Vᵀ == a: true
rank: 2
SVDResult randomizedSvd(NDArray a, int k, {int oversample = 10, int powerIterations = 2, int seed = 1576})

Truncated SVD by randomized range finding (Halko, Martinsson and Tropp, SIAM Review 53(2), 2011, Alg. 4.4 + 5.1): the top k singular triplets of a real m \times n matrix from a sketch A Omega with oversample extra columns and powerIterations re-orthonormalised power iterations. Far cheaper than svd when k < < \min(m, n); accurate when the spectrum decays (error ~ \sigma_{k + 1} times a modest factor; more power iterations for flat spectra). seed makes the Gaussian test matrix reproducible.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  // A rank-2 matrix plus nothing: the top 2 singular values match the full SVD.
  final u = np.NDArray.linspace(0, 1, 30).reshape([30, 1]), v = np.NDArray.linspace(1, 2, 20).reshape([1, 20]);
  final a = np.matmul(u, v) + np.matmul(u * u, v * v) * 0.5;
  final r = la.randomizedSvd(a, 2);
  final full = la.svd(a, computeUV: false);
  print('randomized: ${[for (final s in r.s.toDoubleList()) s.toStringAsFixed(6)]}');
  print('full:       ${[for (final s in full.s.toDoubleList().take(3)) s.toStringAsFixed(6)]}');
}
Output
randomized: [35.550770, 0.375468]
full:       [35.550770, 0.375468, 0.000000]

Constants and variables

newAxisconstant
const NewAxis newAxis = NewAxis._()

Inserts an axis of length 1 (NumPy's None / np.newaxis).

ellipsisconstant
const Ellipsis ellipsis = Ellipsis._()

Stands for as many : as needed (NumPy's ...).

Classes

class

Complex

final class Complex
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4);
  final w = np.Complex(1, -2);
  print('z = $z, w = $w');
  print('z + w = ${z + w}');
  print('z * w = ${z * w}');
  print('z / w = ${z / w}');
  print('|z| = ${z.abs}, conjugate ${z.conjugate}');
  print('i * i = ${np.Complex.i * np.Complex.i}');
}
Output
z = (3.0+4.0j), w = (1.0-2.0j)
z + w = (4.0+2.0j)
z * w = (11.0-2.0j)
z / w = (-1.0+2.0j)
|z| = 5.0, conjugate (3.0-4.0j)
i * i = (-1.0+0.0j)

Constructors

Complexconstructor
const Complex(this.re, [this.im = 0])
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  const z = np.Complex(3, 4);
  print('z = $z, re ${z.re}, im ${z.im}');
  print('real only: ${np.Complex(2.5)}');
  print('|z| = ${z.abs}, arg = ${z.arg.toStringAsFixed(6)}');
}
Output
z = (3.0+4.0j), re 3.0, im 4.0
real only: (2.5+0.0j)
|z| = 5.0, arg = 0.927295
factory Complex.polar(double r, double theta)

r \cdot e^(i theta).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  final z = np.Complex.polar(2, math.pi / 3);
  print('2·e^(iπ/3) = $z');
  print('back: r = ${z.abs}, θ = ${z.arg}');
  final roots = [for (var k = 0; k < 6; k++) np.Complex.polar(1, 2 * math.pi * k / 6)];
}
Output
2·e^(iπ/3) = (1.0000000000000002+1.7320508075688772j)
back: r = 2.0, θ = 1.0471975511965976

Static

zeroconstant
static const Complex zero = Complex(0, 0)
oneconstant
static const Complex one = Complex(1, 0)
iconstant
static const Complex i = Complex(0, 1)

Properties

refield
final double re
imfield
final double im
conjugategetter
Complex get conjugate
absgetter
double get abs
zwithout overflow (hypot).
arggetter
double get arg
isNaNgetter
bool get isNaN
isFinitegetter
bool get isFinite
hashCodegetter
int get hashCode

Methods

scalemethod
Complex scale(double s)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4), w = np.Complex(1, -2);
  print('z·2.5 = ${z.scale(2.5)}');
  print('z·(−1) = ${z.scale(-1)}');
}
Output
z·2.5 = (7.5+10.0j)
z·(−1) = (-3.0-4.0j)
expmethod
Complex exp()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  print('e^(iπ) = ${np.Complex(0, math.pi).exp()}');
  print('e^(1+i) = ${np.Complex(1, 1).exp()}');
  final path = [for (var k = 0; k <= 40; k++) np.Complex(-0.05 * k, 0.3 * k).exp()];
}
Output
e^(iπ) = (-1.0+1.2246467991473532e-16j)
e^(1+i) = (1.4686939399158851+2.2873552871788423j)
logmethod
Complex log()

Principal branch.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('log(−1) = ${np.Complex(-1).log()}');
  print('log(i) = ${np.Complex.i.log()}');
  final z = np.Complex(3, 4);
  print('exp(log z) = ${z.log().exp()}');
}
Output from the Raya VM
log(−1) = (0.0+3.141592653589793j)
log(i) = (0.0+1.5707963267948966j)
exp(log z) = (2.9999999999999996+3.999999999999999j)
sqrtmethod
Complex sqrt()

Principal square root (Kahan's branch cuts: the result has re \ge 0).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('√(−4) = ${np.Complex(-4).sqrt()}');
  print('√i = ${np.Complex.i.sqrt()}');
  final s = np.Complex(3, 4).sqrt();
  print('√(3+4i) = $s, squared ${s * s}');
}
Output
√(−4) = (0.0+2.0j)
√i = (0.7071067811865476+0.7071067811865475j)
√(3+4i) = (2.0+1.0j), squared (3.0+4.0j)
powmethod
Complex pow(Complex w)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('i^i = ${np.Complex.i.pow(np.Complex.i)}');
  print('(1+i)^2 = ${np.Complex(1, 1).pow(np.Complex(2))}');
}
Output
i^i = (0.20787957635076193+0.0j)
(1+i)^2 = (1.2246467991473532e-16+2.0j)
toStringmethod
String toString()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.Complex(1.5, -2));
  print(np.Complex(0, 1));
  print('${np.Complex.zero}');
}
Output
(1.5-2.0j)
(0.0+1.0j)
(0.0+0.0j)

Operators

operator +operator
Complex operator +(Complex o)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4), w = np.Complex(1, -2);
  print('z + w = ${z + w}');
}
Output
z + w = (4.0+2.0j)
operator -operator
Complex operator -(Complex o)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4), w = np.Complex(1, -2);
  print('z - w = ${z - w}');
}
Output
z - w = (2.0+6.0j)
operator *operator
Complex operator *(Complex o)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4), w = np.Complex(1, -2);
  print('z * w = ${z * w}');
}
Output
z * w = (11.0-2.0j)
operator /operator
Complex operator /(Complex o)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4), w = np.Complex(1, -2);
  print('z / w = ${z / w}');
}
Output
z / w = (-1.0+2.0j)
operator -operator
Complex operator -()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.Complex(3, 4), w = np.Complex(1, -2);
  print('−z = ${-z}');
  print('z + (−z) = ${z + -z}');
}
Output
−z = (-3.0-4.0j)
z + (−z) = (0.0+0.0j)
operator ==operator
bool operator ==(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.Complex(1, 2) == np.Complex(1.0, 2.0));
  print(np.Complex(1, 2) == np.Complex(1, -2));
  print(np.Complex.i * np.Complex.i == np.Complex(-1));
}
Output
true
false
true
enum DTypeKind

What a dtype's values are.

Values

booleanvalue
boolean
signedvalue
signed
unsigned
floatvalue
float
complexvalue
complex
enum

DType

enum DType

An NDArray element type. Storage is one typed list per array:

dtypestoragenotes
booleanUint8List0 or 1
int8..int64Int8List..Int64Listwrap on overflow, as NumPy
uint8..uint64Uint8List..Uint64Listuint64 values \ge 2^{63} read back as negative Raya ints
float16, bfloat16Uint16List of IEEE bitscomputed in double, rounded to nearest even on store
float32, float64Float32List, Float64List
complex64, complex128Float32List, Float64Listinterleaved (re, im); strides count elements, not floats

Values

booleanvalue
boolean(DTypeKind.boolean, 1, 'bool')
int8value
int8(DTypeKind.signed, 1, 'int8')
int16value
int16(DTypeKind.signed, 2, 'int16')
int32value
int32(DTypeKind.signed, 4, 'int32')
int64value
int64(DTypeKind.signed, 8, 'int64')
uint8value
uint8(DTypeKind.unsigned, 1, 'uint8')
uint16value
uint16(DTypeKind.unsigned, 2, 'uint16')
uint32value
uint32(DTypeKind.unsigned, 4, 'uint32')
uint64value
uint64(DTypeKind.unsigned, 8, 'uint64')
float16value
float16(DTypeKind.float, 2, 'float16')
bfloat16(DTypeKind.float, 2, 'bfloat16')
float32value
float32(DTypeKind.float, 4, 'float32')
float64value
float64(DTypeKind.float, 8, 'float64')
complex64(DTypeKind.complex, 8, 'complex64')
complex128(DTypeKind.complex, 16, 'complex128')

Constructors

DTypeconstructor
const DType(this.kind, this.itemSize, this.numpyName)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  for (final t in [np.DType.int8, np.DType.float16, np.DType.bfloat16, np.DType.float64, np.DType.complex64]) {
    print('${t.numpyName.padRight(10)} kind ${t.kind.name.padRight(8)} ${t.itemSize} bytes, eps ${t.isInexact ? t.eps : '-'}');
  }
}
Output
int8       kind signed   1 bytes, eps -
float16    kind float    2 bytes, eps 0.0009765625
bfloat16   kind float    2 bytes, eps 0.0078125
float64    kind float    8 bytes, eps 2.220446049250313e-16
complex64  kind complex  8 bytes, eps 1.1920928955078125e-7

Static

ofTypedDatastaticmethod
static DType ofTypedData(TypedData data)

The dtype whose storage data is (float16/bfloat16 and boolean are ambiguous: Uint16List -> uint16, Uint8List -> uint8).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:typed_data';

void main() {
  print(np.DType.ofTypedData(Float32List(3)));
  print(np.DType.ofTypedData(Int16List(3)));
  print(np.DType.ofTypedData(Uint8List(3)));
}
Output
DType.float32
DType.int16
DType.uint8
tryParsestaticmethod
static DType? tryParse(String name)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.DType.tryParse('float32'));
  print(np.DType.tryParse('complex128'));
  print(np.DType.tryParse('float128'));
}
Output
DType.float32
DType.complex128
null
promotestaticmethod
static DType promote(DType a, DType b)

NumPy's result_type for two array dtypes.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final ts = [np.DType.uint8, np.DType.int8, np.DType.int32, np.DType.float16, np.DType.float32, np.DType.complex64];
  print('int8 + uint8 -> ${np.DType.promote(np.DType.int8, np.DType.uint8)}');
  print('int32 + float32 -> ${np.DType.promote(np.DType.int32, np.DType.float32)}');
  print('float32 + complex64 -> ${np.DType.promote(np.DType.float32, np.DType.complex64)}');
        ['', ...ts.map((t) => t.numpyName)],
        for (final a in ts) [a.numpyName, for (final b in ts) np.DType.promote(a, b).numpyName],
      ]})}');
}
Output
int8 + uint8 -> DType.int16
int32 + float32 -> DType.float64
float32 + complex64 -> DType.complex64
promoteScalarstaticmethod
static DType promoteScalar(DType array, Object scalar)

The dtype of array op scalar (NumPy 2 "weak" scalars: a Raya int keeps an integer or inexact array's dtype; a double keeps an inexact array's dtype and makes an integer array float64; a complex scalar makes it complex).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('int32 array + 2 -> ${np.DType.promoteScalar(np.DType.int32, 2)}');
  print('int32 array + 2.5 -> ${np.DType.promoteScalar(np.DType.int32, 2.5)}');
  print('float32 array + 2.5 -> ${np.DType.promoteScalar(np.DType.float32, 2.5)}');
  print('float32 array + Complex -> ${np.DType.promoteScalar(np.DType.float32, np.Complex(1, 1))}');
}
Output
int32 array + 2 -> DType.int32
int32 array + 2.5 -> DType.float64
float32 array + 2.5 -> DType.float32
float32 array + Complex -> DType.complex64

Properties

kindfield
final DTypeKind kind
final int itemSize

Bytes per element (a complex element is two floats).

final String numpyName

The NumPy name (np.dtype(name)), for fixtures and printing.

isBoolgetter
bool get isBool
isIntegergetter
bool get isInteger
isFloatgetter
bool get isFloat
isComplexgetter
bool get isComplex
isInexactgetter
bool get isInexact

Float or complex.

isHalfgetter
bool get isHalf

Stored as raw bits in a Uint16List (float16, bfloat16).

slotsgetter
int get slots

Typed-list slots per element (2 for complex, else 1).

realTypegetter
DType get realType

The real dtype of a complex dtype (complex64 -> float32); itself otherwise.

DType get complexType

The complex dtype that holds this one (float32 -> complex64, others -> complex128).

int get mantissaBits

Bits of mantissa precision (floats; for tolerances).

epsgetter
double get eps

Machine epsilon of the real type (2^(1-p)).

Methods

allocatemethod
TypedData allocate(int length)

A zero-filled typed list for length elements.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final d = np.DType.float32.allocate(4);
  print('${d.runtimeType} of ${d.lengthInBytes} bytes');
  print('complex128 x 3: ${np.DType.complex128.allocate(3).lengthInBytes} bytes');
}
Output
Float32List of 16 bytes
complex128 x 3: 48 bytes
viewmethod
TypedData view(ByteBuffer buffer, int offsetInBytes, int length)

A view of bytes as this dtype's storage (no copy). The offset must be aligned to the slot size.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:typed_data';

void main() {
  final bytes = Uint8List.fromList([0, 0, 128, 63, 0, 0, 0, 64]);
  final f = np.DType.float32.view(bytes.buffer, 0, 2);
  print('the 8 bytes as float32: $f');
  print('as int16: ${np.DType.int16.view(bytes.buffer, 0, 4)}');
}
Output
the 8 bytes as float32: [1.0, 2.0]
as int16: [0, 16256, 0, 16384]
class

Slice

final class Slice

start:stop:step, Python semantics (nulls are the defaults; negatives count from the end).

Constructors

Sliceconstructor
const Slice([this.start, this.stop, this.step])
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(10);
  print('a[1:7:2] = ${a[np.Slice(1, 7, 2)]}');
  print('a[::-1] = ${a[np.Slice(null, null, -1)]}');
  print('a[-3:] = ${a[np.Slice(-3)]}');
}
Output
a[1:7:2] = array([1, 3, 5])
a[::-1] = array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
a[-3:] = array([7, 8, 9])

Static

allconstant
static const Slice all = Slice()

: (every element).

Properties

startfield
final int? start
stopfield
final int? stop
stepfield
final int? step

Methods

resolvemethod
(int, int, int) resolve(int length)

(start, step, count) for an axis of length (Python's slice.indices).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('1:7:2 on length 10 -> ${const np.Slice(1, 7, 2).resolve(10)}');
  print('::-1 on length 5 -> ${const np.Slice(null, null, -1).resolve(5)}');
  print('-100:100 on length 4 -> ${const np.Slice(-100, 100).resolve(4)}');
}
Output
1:7:2 on length 10 -> (1, 2, 3)
::-1 on length 5 -> (4, -1, 5)
-100:100 on length 4 -> (0, 1, 4)
toStringmethod
String toString()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(const np.Slice(1, 7, 2));
  print(const np.Slice(null, -1));
  print(np.Slice.all);
}
Output
1:7:2
:-1
:
class

NewAxis

final class NewAxis

Methods

toStringmethod
String toString()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.newAxis);
  final a = np.NDArray.arange(3);
  print('a[None, :] shape ${a[[np.newAxis, np.Slice.all]].shape}');
  print('a[:, None] shape ${a[[np.Slice.all, np.newAxis]].shape}');
}
Output
None
a[None, :] shape [1, 3]
a[:, None] shape [3, 1]
final class Ellipsis

Methods

toStringmethod
String toString()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.ellipsis);
  final a = np.NDArray.arange(24).reshape([2, 3, 4]);
  print('a[..., 0] =\n${a[[np.ellipsis, 0]]}');
}
Output
...
a[..., 0] =
array([[0, 4, 8],
       [12, 16, 20]])
abstract interface class GemmBackend

Computes c = alpha * a @ b + beta * c for 2-d views (any strides) of float64 or float32 arrays.

Properties

namegetter
String get name

For logs and benchmark tables ("cpu", "metal"...).

minWorkgetter
int get minWork

Products with fewer than this many multiply-adds (m \cdot n \cdot k) stay on the CPU.

DType get computeType

The precision the backend multiplies in (float32 for GPUs; float64 for the CPU). Factorizations that need float64 accuracy from a lower-precision backend refine the result (see solveRefined).

Methods

gemmmethod
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})

Performs the update; returns false when this backend can't (the caller then uses the CPU).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]), b = np.NDArray.eye(2) * 2;
  final c = np.NDArray.ones([2, 2]);
  const np.GemmBackend g = np.CpuGemm();
  final ok = g.gemm(a, b, c, alpha: 1, beta: 1); // c = a·b + c
  print('${g.name}: handled $ok\n$c');
}
Output
cpu: handled true
array([[3., 5.],
       [7., 9.]])
class

CpuGemm

final class CpuGemm implements GemmBackend

The CPU GEMM (blocked, packed; float64 or float32 by the operands' dtype).

Constructors

CpuGemmconstructor
const CpuGemm()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]), b = np.NDArray.eye(2) * 2;
  final c = np.NDArray.ones([2, 2]);
  const g = np.CpuGemm();
  print('name: ${g.name}');
  print('lu with this backend: ${la.lu(a, backend: g).solve(np.NDArray.fromList([1.0, 1.0]))}');
}
Output
name: cpu
lu with this backend: array([-1., 1.])

Properties

namegetter
String get name
minWorkgetter
int get minWork
DType get computeType

Methods

gemmmethod
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0], [3.0, 4.0]]), b = np.NDArray.eye(2) * 2;
  final c = np.NDArray.ones([2, 2]);
  const np.CpuGemm().gemm(a, a, c, alpha: 0.5);
  print('0.5·a·a =\n$c');
}
Output
0.5·a·a =
array([[3.5, 5.],
       [7.5, 11.]])
enum

Order

enum Order

Memory order for new arrays and copies.

Values

cvalue
c
fvalue
f
class

NDArray

final class NDArray

An n-dimensional array: data (one typed list, see DType for each dtype's storage) seen through shape, strides and offset. Strides and offset count elements, not bytes (a complex element is one element); byteStrides gives NumPy's byte strides. Many arrays can share one data: slicing, transposing, reshaping a contiguous array, broadcasting, real and imag are views, never copies. Operations that make new arrays make C-order (row-major) ones.

Constructors

factory NDArray.view(TypedData data, DType dtype, List<int> shape, {List<int>? strides, int offset = 0})

A view over data with explicit geometry (no copy, no checks beyond bounds). The building block of every view.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:typed_data';

void main() {
  final data = Float64List.fromList([0, 1, 2, 3, 4, 5]);
  final m = np.NDArray.view(data, np.DType.float64, [2, 3]);
  final t = np.NDArray.view(data, np.DType.float64, [3, 2], strides: [1, 3]); // the transpose, no copy
  print('m =\n$m');
  print('strided view =\n$t');
  data[0] = 99;
  print('both see the write: ${m.get2(0, 0)}, ${t.get2(0, 0)}');
}
Output
m =
array([[0., 1., 2.],
       [3., 4., 5.]])
strided view =
array([[0., 3.],
       [1., 4.],
       [2., 5.]])
both see the write: 99.0, 99.0
factory NDArray.zeros(List<int> shape, {DType dtype = DType.float64, Order order = Order.c})

A new zero-filled array.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;

void main() {
  print('zeros([2, 3]):\n${np.NDArray.zeros([2, 3])}');
  print('ones([3]):     ${np.NDArray.ones([3])}');
  print('full([2], 7):  ${np.NDArray.full([2], 7)}');
  print('eye(3):\n${np.NDArray.eye(3)}');
}
Output
zeros([2, 3]):
array([[0., 0., 0.],
       [0., 0., 0.]])
ones([3]):     array([1., 1., 1.])
full([2], 7):  array([7, 7])
eye(3):
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
factory NDArray.empty(List<int> shape, {DType dtype = DType.float64})

Same as NDArray.zeros (Raya typed lists are always initialised).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.empty([2, 3]);
  a.fill(1.5); // contents are unspecified until written
  print('$a');
  print('dtype ${np.NDArray.empty([4], dtype: np.DType.int32).dtype}');
}
Output
array([[1.5, 1.5, 1.5],
       [1.5, 1.5, 1.5]])
dtype DType.int32
factory NDArray.ones(List<int> shape, {DType dtype = DType.float64})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.NDArray.ones([2, 3]));
  print(np.NDArray.ones([3], dtype: np.DType.int8));
}
Output
array([[1., 1., 1.],
       [1., 1., 1.]])
array([1, 1, 1], dtype=int8)
factory NDArray.full(List<int> shape, Object value, {DType? dtype})

A new array filled with value (num, bool or Complex); dtype defaults to the value's (int64, float64, boolean, complex128).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.NDArray.full([2, 2], 7));
  print(np.NDArray.full([3], 0.5));
  print(np.NDArray.full([2], np.Complex(1, 1)));
}
Output
array([[7, 7],
       [7, 7]])
array([0.5, 0.5, 0.5])
array([1.+1.j, 1.+1.j], dtype=complex128)
factory NDArray.scalar(Object value, {DType? dtype})

A 0-d array holding value.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final s = np.NDArray.scalar(3.5);
  print('$s, shape ${s.shape}, ndim ${s.ndim}');
  print('broadcasts: ${np.NDArray.arange(3) + s}');
}
Output
array(3.5), shape [], ndim 0
broadcasts: array([3.5, 4.5, 5.5])
factory NDArray.zerosLike(NDArray a, {DType? dtype})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final z = np.NDArray.zerosLike(a);
  print('shape ${z.shape}, dtype ${z.dtype}, sum ${z.sum()}');
  print('as int32: ${np.NDArray.zerosLike(a, dtype: np.DType.int32).dtype}');
}
Output
shape [3, 4], dtype DType.float64, sum array(0.)
as int32: DType.int32
factory NDArray.onesLike(NDArray a, {DType? dtype})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print(np.NDArray.onesLike(a));
}
Output
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
factory NDArray.fullLike(NDArray a, Object value, {DType? dtype})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print(np.NDArray.fullLike(a, -1));
}
Output
array([[-1., -1., -1., -1.],
       [-1., -1., -1., -1.],
       [-1., -1., -1., -1.]])
factory NDArray.fromList(Object values, {DType? dtype})

From nested Raya lists of num, bool or Complex (rectangular). The dtype is inferred like NumPy (bool < int64 < float64 < complex128) unless given.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;

void main() {
  final a = np.NDArray.fromList([
    [1.0, 2.0, 3.0],
    [4.0, 5.0, 6.0],
  ]);
  print(a);
  print('dtype ${a.dtype}, shape ${a.shape}');
  print('as nested lists: ${a.toList()}');
}
Output
array([[1., 2., 3.],
       [4., 5., 6.]])
dtype DType.float64, shape [2, 3]
as nested lists: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
factory NDArray.fromTypedData(TypedData data, {List<int>? shape, DType? dtype, List<int>? strides, int offset = 0})

Wraps data without copying. shape defaults to 1-d over every element; dtype defaults to the typed list's own (pass it for float16/bfloat16 in a Uint16List, booleans in a Uint8List, complex in a Float32/64List).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:typed_data';

void main() {
  final f = Float32List.fromList([1, 2, 3, 4, 5, 6]);
  final a = np.NDArray.fromTypedData(f, shape: [2, 3]);
  print('$a\ndtype ${a.dtype}');
  final ints = np.NDArray.fromTypedData(Int16List.fromList([1, -2, 3]));
  print('${ints.dtype}: $ints');
}
Output
array([[1., 2., 3.],
       [4., 5., 6.]], dtype=float32)
dtype DType.float32
DType.int16: array([1, -2, 3], dtype=int16)
factory NDArray.fromBytes(Uint8List bytes, DType dtype, List<int> shape, {List<int>? byteStrides, int byteOffset = 0})

Wraps raw bytes without copying: byteOffset and byteStrides (default C-contiguous) in bytes, each a multiple of the slot size (the element size; half the element size for complex). The buffer position must be aligned to the slot size, as Raya's typed views require.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:typed_data';

void main() {
  final b = ByteData(16)
    ..setFloat32(0, 1.5, Endian.host)
    ..setFloat32(4, -2, Endian.host)
    ..setFloat32(8, 0.25, Endian.host)
    ..setFloat32(12, 8, Endian.host);
  final a = np.NDArray.fromBytes(b.buffer.asUint8List(), np.DType.float32, [2, 2]);
  print('$a');
}
Output
array([[1.5, -2.],
       [0.25, 8.]], dtype=float32)
factory NDArray.arange(num start, [num? stop, num step = 1, DType? dtype])

Evenly spaced values in [start, stop) (NumPy arange). With one argument it is arange(0, start). The dtype is int64 when every argument is an int, else float64.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print('arange(5):          ${np.NDArray.arange(5)}');
  print('arange(2, 10, 3):   ${np.NDArray.arange(2, 10, 3)}');
  print('as float64:         ${np.NDArray.arange(4, null, 1, np.DType.float64)}');
  print('linspace(0, 1, 5):  ${np.NDArray.linspace(0, 1, 5)}');
}
Output
arange(5):          array([0, 1, 2, 3, 4])
arange(2, 10, 3):   array([2, 5, 8])
as float64:         array([0., 1., 2., 3.])
linspace(0, 1, 5):  array([0., 0.25, 0.5, 0.75, 1.])
factory NDArray.linspace(double start, double stop, int num, {bool endpoint = true, DType dtype = DType.float64})

num values evenly spaced over [start, stop] (NumPy linspace).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  final x = np.NDArray.linspace(0, 1, 5);
  print('linspace(0, 1, 5) = $x');
  print('endpoint: false -> ${np.NDArray.linspace(0, 1, 5, endpoint: false)}');
  final t = np.NDArray.linspace(0, 2 * math.pi, 50);
  final y = t.sin();
}
Output
linspace(0, 1, 5) = array([0., 0.25, 0.5, 0.75, 1.])
endpoint: false -> array([0., 0.2, 0.4, 0.6, 0.8])
factory NDArray.eye(int n, {int? m, int k = 0, DType dtype = DType.float64})

The n \times m identity (ones on diagonal k).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.NDArray.eye(3));
  final r = np.NDArray.eye(3, m: 5, k: 1);
  print('3 × 5, k = 1:\n$r');
}
Output
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
3 × 5, k = 1:
array([[0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.]])
factory NDArray.diag(NDArray v, {int k = 0})

A square matrix with v (1-d) on diagonal k.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final v = np.NDArray.fromList([1.0, 2.0, 3.0]);
  final d = np.NDArray.diag(v);
  print('$d');
  print('above: ${np.NDArray.diag(v, k: 1).shape}');
  print('back to the vector: ${d.diagonal()}');
}
Output
array([[1., 0., 0.],
       [0., 2., 0.],
       [0., 0., 3.]])
above: [4, 4]
back to the vector: array([1., 2., 3.])

Static

fromStructListstaticmethod
static NDArray fromStructList<T extends Object>(StructList<T> list, DType dtype, {required int fields, int fieldOffsetBytes = 0, List<num> Function(T element)? fallback})

A [length, fields] view over a StructList of value-class structs whose first fields fields (from fieldOffsetBytes) all have dtype (e.g. six @pragma('raya:f32') doubles -> float32), with no copy. Needs Raya AOT, where the list has native storage; elsewhere fallback (one row of values per struct) builds a copy, and without it this throws UnsupportedError.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_struct/riptide_struct.ray';

void main() {
  final ps = StructList<Pt>.filled(3, const Pt(0, 0));
  for (var i = 0; i < 3; i++) {
    ps[i] = Pt(i.toDouble(), i * 2.0);
  }
  // Without native storage the fallback copies one row per struct.
  final a = np.NDArray.fromStructList(ps, np.DType.float64, fields: 2, fallback: (p) => [p.x, p.y]);
  print('$a');
}

final class Pt {
  const Pt(this.x, this.y);
  final double x, y;
}
Output
array([[0., 0.],
       [1., 2.],
       [2., 4.]])

Properties

datafield
final TypedData data

The storage. Shared by every view of the same array.

dtypefield
final DType dtype
shapefield
final List<int> shape
stridesfield
final List<int> strides

Element strides (not bytes), one per axis; 0 on broadcast axes.

offsetfield
final int offset

Element offset of index (0... 0) in data.

sizefield
final int size

Number of elements.

ndimgetter
int get ndim
itemSizegetter
int get itemSize
nbytesgetter
int get nbytes
List<int> get byteStrides
bool get isContiguous

Row-major contiguous (NumPy C_CONTIGUOUS).

bool get isFContiguous

Column-major contiguous (NumPy F_CONTIGUOUS).

Tgetter
NDArray get T

The transpose (axes reversed).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(6).reshape([2, 3]);
  print('a:\n$a');
  print('a.T:\n${a.T}');
  print('shape ${a.shape} -> ${a.T.shape}; a view, contiguous: ${a.T.isContiguous}');
}
Output
a:
array([[0, 1, 2],
       [3, 4, 5]])
a.T:
array([[0, 3],
       [1, 4],
       [2, 5]])
shape [2, 3] -> [3, 2]; a view, contiguous: false
Hgetter
NDArray get H

The conjugate transpose of the last two axes (the transpose for real dtypes).

realgetter
NDArray get real

The real part: a view for complex arrays (into the same storage), this array otherwise.

imaggetter
NDArray get imag

The imaginary part: a view for complex arrays, zeros otherwise (a new array).

Methods

offsetOfmethod
int offsetOf(List<int> index)

The element offset in data of index (one int per axis, negatives count from the end).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print('strides ${a.strides}, offsetOf([2, 1]) = ${a.offsetOf([2, 1])}');
  final t = a.T;
  print('transpose strides ${t.strides}, offsetOf([1, 2]) = ${t.offsetOf([1, 2])}');
}
Output
strides [4, 1], offsetOf([2, 1]) = 9
transpose strides [1, 4], offsetOf([1, 2]) = 9
itemmethod
Object item([List<int> index = const <int>[]])

The element at index (empty for a 0-d array) as a Raya value: bool, int, double or Complex.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print('a.item([1, 2]) = ${a.item([1, 2])}');
  print('size-1 array: ${a.sum().item()}');
  print('int array gives int: ${np.NDArray.arange(3).item([2]).runtimeType}');
}
Output
a.item([1, 2]) = 6.0
size-1 array: 66.0
int array gives int: int
getDoublemethod
double getDouble(List<int> index)

The element at index as a double (complex: the real part).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print(a.getDouble([2, 3]));
  print(np.NDArray.arange(4).getDouble([1]));
}
Output
11.0
1.0
get1method
double get1(int i)

1-d and 2-d element reads without an index list (real part for complex).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(0, 1, 5);
  var s = 0.0;
  for (var i = 0; i < x.size; i++) {
    s += x.get1(i);
  }
  print('sum by get1: $s');
}
Output
sum by get1: 2.5
get2method
double get2(int i, int j)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print('a[1, 3] = ${a.get2(1, 3)}');
  print('transpose: ${a.T.get2(3, 1)}');
}
Output
a[1, 3] = 7.0
transpose: 7.0
set1method
void set1(int i, double v)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.zeros([5]);
  for (var i = 0; i < 5; i++) {
    x.set1(i, i * i.toDouble());
  }
  print(x);
}
Output
array([0., 1., 4., 9., 16.])
set2method
void set2(int i, int j, double v)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final m = np.NDArray.zeros([4, 4]);
  for (var i = 0; i < 4; i++) {
    for (var j = 0; j < 4; j++) {
      m.set2(i, j, 1 / (i + j + 1)); // the Hilbert matrix
    }
  }
  print(m);
}
Output
array([[1., 0.5, 0.33333333, 0.25],
       [0.5, 0.33333333, 0.25, 0.2],
       [0.33333333, 0.25, 0.2, 0.16666667],
       [0.25, 0.2, 0.16666667, 0.14285714]])
setItemmethod
void setItem(List<int> index, Object value)

Writes value (num, bool or Complex) at index.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([2, 2], dtype: np.DType.complex128);
  a.setItem([0, 1], np.Complex(1, -1));
  a.setItem([1, 0], 2.5);
  print(a);
}
Output
array([[0.+0.j, 1.-1.j],
       [2.5+0.j, 0.+0.j]], dtype=complex128)
fillmethod
void fill(Object value)

Sets every element to value.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  a.fill(0.5);
  print(a);
  final v = a['1, :'];
  v.fill(9); // a view: fills row 1 of a
  print(a);
}
Output
array([[0.5, 0.5, 0.5, 0.5],
       [0.5, 0.5, 0.5, 0.5],
       [0.5, 0.5, 0.5, 0.5]])
array([[0.5, 0.5, 0.5, 0.5],
       [9., 9., 9., 9.],
       [0.5, 0.5, 0.5, 0.5]])
assignmethod
void assign(Object source)

Copies source (an NDArray, broadcast to this shape, or a scalar) into this array, converting dtypes.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([3, 4]);
  a[':, 1:3'].assign(np.NDArray.fromList([1.0, 2.0])); // broadcast into the view
  a['2, :'].assign(7);
  print(a);
}
Output
array([[0., 1., 2., 0.],
       [0., 1., 2., 0.],
       [7., 7., 7., 7.]])
takemethod
NDArray take(NDArray indices, {int? axis})

The elements at indices (int array, negatives from the end) along axis (null: of the flattened array), as a new array whose axis is replaced by the indices' shape (NumPy take).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final idx = np.NDArray.fromList([2, 0]);
  print('take rows [2, 0]:\n${a.take(idx, axis: 0)}');
  print('flat take: ${a.take(np.NDArray.fromList([0, 5, 11]))}');
}
Output
take rows [2, 0]:
array([[8., 9., 10., 11.],
       [0., 1., 2., 3.]])
flat take: array([0., 5., 11.])
NDArray moveAxisRange(int count, int destination)

Moves the first count axes (an index block) so they start at destination.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([2, 3, 4, 5]);
  print('move first 2 axes to position 2: ${a.moveAxisRange(2, 2).shape}');
  print('one axis to 3: ${a.moveAxisRange(1, 3).shape}');
}
Output
move first 2 axes to position 2: [4, 5, 2, 3]
one axis to 3: [3, 4, 5, 2]
compressmethod
NDArray compress(NDArray mask)

The elements where mask (a bool array of this shape, or broadcastable to it) is true, as a 1-d array.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final big = a.compress(a.gt(6));
  print('elements > 6: $big');
  print('even: ${a.compress((a % 2).eq(0))}');
}
Output
elements > 6: array([7., 8., 9., 10., 11.])
even: array([0., 2., 4., 6., 8., 10.])
reshapemethod
NDArray reshape(List<int> newShape)

Gives this array a new shape with the same elements: a view when the strides allow (always, for contiguous arrays), else a copy. One dimension may be -1 (inferred).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;

void main() {
  final a = np.NDArray.arange(12);
  final m = a.reshape([3, 4]);
  print('reshape([3, 4]):\n$m');
  print('shape ${m.shape}, ndim ${m.ndim}, size ${m.size}');
  print('reshape([2, -1]) infers the -1: ${a.reshape([2, -1]).shape}');
  print('ravel back to 1-D: ${m.ravel()}');
}
Output
reshape([3, 4]):
array([[0, 1, 2, 3],
       [4, 5, 6, 7],
       [8, 9, 10, 11]])
shape [3, 4], ndim 2, size 12
reshape([2, -1]) infers the -1: [2, 6]
ravel back to 1-D: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
ravelmethod
NDArray ravel()

A 1-d view when possible, else a 1-d copy.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print(a.T.ravel());
  print('ravel of a contiguous array is a view: ${a.ravel().shape}');
}
Output
array([0., 4., 8., 1., 5., 9., 2., 6., 10., 3., 7., 11.])
ravel of a contiguous array is a view: [12]
flattenmethod
NDArray flatten()

A 1-d C-order copy.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final f = a.flatten();
  f.set1(0, 100); // a copy: a is unchanged
  print('f[0] = ${f.get1(0)}, a[0, 0] = ${a.get2(0, 0)}');
}
Output
f[0] = 100.0, a[0, 0] = 0.0
transposemethod
NDArray transpose([List<int>? axes])

Permutes the axes (default: reversed), as a view.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(24).reshape([2, 3, 4]);
  print('transpose(): ${a.transpose().shape}');
  print('transpose([1, 0, 2]): ${a.transpose([1, 0, 2]).shape}');
  final m = np.NDArray.arange(6).reshape([2, 3]);
}
Output
transpose(): [4, 3, 2]
transpose([1, 0, 2]): [3, 2, 4]
conjmethod
NDArray conj()

The complex conjugate (a copy; real dtypes return this).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final z = np.NDArray.fromList([np.Complex(1, 2), np.Complex(-3, -1)]);
  print('conj: ${z.conj()}');
  print('real arrays are unchanged: ${np.NDArray.arange(3).conj()}');
}
Output
conj: array([1.-2.j, -3.+1.j], dtype=complex128)
real arrays are unchanged: array([0, 1, 2])
swapAxesmethod
NDArray swapAxes(int a, int b)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([2, 3, 4]);
  print(a.swapAxes(0, 2).shape);
  print(a.swapAxes(-1, -2).shape);
}
Output
[4, 3, 2]
[2, 4, 3]
moveAxismethod
NDArray moveAxis(int source, int destination)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([3, 4, 5]);
  print('moveAxis(0, -1): ${a.moveAxis(0, -1).shape}');
  print('moveAxis(2, 0): ${a.moveAxis(2, 0).shape}');
}
Output
moveAxis(0, -1): [4, 5, 3]
moveAxis(2, 0): [5, 3, 4]
NDArray expandDims(int axis)

Inserts a length-1 axis at axis.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.arange(3);
  print('expandDims(0): ${x.expandDims(0).shape}');
  print('expandDims(1): ${x.expandDims(1).shape}');
  print('outer product by broadcasting:\n${x.expandDims(1) * x.expandDims(0)}');
}
Output
expandDims(0): [1, 3]
expandDims(1): [3, 1]
outer product by broadcasting:
array([[0, 0, 0],
       [0, 1, 2],
       [0, 2, 4]])
squeezemethod
NDArray squeeze([int? axis])

Removes length-1 axes (all, or axis).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([1, 3, 1, 2]);
  print('squeeze(): ${a.squeeze().shape}');
  print('squeeze(2): ${a.squeeze(2).shape}');
}
Output
squeeze(): [3, 2]
squeeze(2): [1, 3, 2]
NDArray broadcastTo(List<int> target)

A read-only-by-convention view of this array broadcast to target (stride 0 on stretched axes).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final row = np.NDArray.fromList([1.0, 2.0, 3.0]);
  final b = row.broadcastTo([4, 3]);
  print('$b');
  print('strides ${b.strides}: no copy, the row repeats');
}
Output
array([[1., 2., 3.],
       [1., 2., 3.],
       [1., 2., 3.],
       [1., 2., 3.]])
strides [0, 1]: no copy, the row repeats
diagonalmethod
NDArray diagonal({int k = 0, int axis1 = 0, int axis2 = 1})

The diagonal of axes axis1, axis2 at offset (k), as a view; the diagonal becomes the last axis.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print('main: ${a.diagonal()}');
  print('k = 1: ${a.diagonal(k: 1)}');
  print('k = −1: ${a.diagonal(k: -1)}');
}
Output
main: array([0., 5., 10.])
k = 1: array([1., 6., 11.])
k = −1: array([4., 9.])
copymethod
NDArray copy({Order order = Order.c})

A new array with the same values in order.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final c = a.copy();
  c.set2(0, 0, -1);
  print('a[0,0] ${a.get2(0, 0)}, copy ${c.get2(0, 0)}');
  print('Fortran order strides: ${a.copy(order: np.Order.f).strides}');
}
Output
a[0,0] 0.0, copy -1.0
Fortran order strides: [1, 3]
astypemethod
NDArray astype(DType type, {bool copy = true})

This array as type (a copy, converting values like NumPy's astype: floats truncate to ints, complex drops the imaginary part to real). With copy false, returns this when the dtype already matches.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([1.7, -2.5, 300.0]);
  print('int32: ${x.astype(np.DType.int32)}');
  print('uint8: ${x.astype(np.DType.uint8)}');
  print('float16: ${x.astype(np.DType.float16)}');
}
Output
int32: array([1, -2, 300], dtype=int32)
uint8: array([1, 254, 44], dtype=uint8)
float16: array([1.7001953, -2.5, 300.], dtype=float16)
NDArray contiguous({DType? dtype})

This array if it is C-contiguous (and dtype matches, when given), else a contiguous copy.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final t = a.T;
  final c = t.contiguous();
  print('T strides ${t.strides} -> contiguous strides ${c.strides}');
  print('as float32: ${a.contiguous(dtype: np.DType.float32).dtype}');
}
Output
T strides [1, 4] -> contiguous strides [3, 1]
as float32: DType.float32
TypedData toTypedData()

The elements in C order as the dtype's typed list: a zero-copy view of data when the array is contiguous (writes go through to the array), else a copy.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:typed_data';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final d = a.toTypedData();
  print('${d is Float64List ? 'Float64List' : d.runtimeType}, ${d.lengthInBytes} bytes');
  print(np.NDArray.arange(3, null, 1, np.DType.int16).toTypedData() is Int16List);
}
Output
Float64List, 96 bytes
true
Float64List toFloat64List()

The elements as a contiguous Float64List (a view when already contiguous float64, else a converted copy; complex arrays give interleaved re, im).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.NDArray.arange(5).toFloat64List());
  print(np.NDArray.eye(2).T.toFloat64List());
}
Output
[0.0, 1.0, 2.0, 3.0, 4.0]
[1.0, 0.0, 0.0, 1.0]
toBytesmethod
Uint8List toBytes()

The raw bytes of a contiguous array (zero-copy view; a copy first when not contiguous), e.g. to upload to the GPU or hand to native code.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final b = np.NDArray.fromList([1.0, -2.0], dtype: np.DType.float32).toBytes();
  print('${b.length} bytes: $b');
}
Output
8 bytes: [0, 0, 128, 63, 0, 0, 0, 192]
toListmethod
Object toList()

Nested Raya lists (bool, int, double or Complex leaves).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  final l = a.toList() as List;
  print(l);
  print('${l.length} rows of ${(l[0] as List).length}');
}
Output
[[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 10.0, 11.0]]
3 rows of 4
List<double> toDoubleList()

Every element (in C order) as doubles (complex: real parts).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(12, null, 1, np.DType.float64).reshape([3, 4]);
  print(a.toDoubleList());
}
Output
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]
toStringmethod
String toString()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  print(np.NDArray.linspace(0, 1, 3));
  print(np.NDArray.eye(2, dtype: np.DType.int32));
  print(np.NDArray.scalar(2.5));
}
Output
array([0., 0.5, 1.])
array([[1, 0],
       [0, 1]], dtype=int32)
array(2.5)

Operators

operator []operator
NDArray operator [](Object index)

NumPy indexing. Basic indexing gives a view: an int (a[2]), a Slice, newAxis, ellipsis, a list of those standing for NumPy's tuple (a[[1, Slice(0, null, 2), newAxis, ellipsis]], so a[[i, j]] is NumPy's a[i, j]), or the string form (a['1:2']). One advanced index, an int or bool NDArray, selects along its axis as a copy (NumPy's a[[1, 3]] is a[NDArray.fromList([1, 3])]); a full-shape bool mask gives the selected elements as 1-d (see take, compress).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;

void main() {
  final a = np.NDArray.arange(20).reshape([4, 5]);
  print('a:\n$a');
  print("a['1']        row 1:      ${a['1']}");
  print("a[':, 2']     column 2:   ${a[':, 2']}");
  print("a['1:3, ::2'] a block:\n${a['1:3, ::2']}");
  print("a['-1, ::-1'] last row reversed: ${a['-1, ::-1']}");
}
Output
a:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
a['1']        row 1:      array([5, 6, 7, 8, 9])
a[':, 2']     column 2:   array([2, 7, 12, 17])
a['1:3, ::2'] a block:
array([[5, 7, 9],
       [10, 12, 14]])
a['-1, ::-1'] last row reversed: array([19, 18, 17, 16, 15])
operator []=operator
void operator []=(Object index, Object value)

Assigns value (an NDArray, broadcast, or a scalar) to this[index].

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.zeros([4, 4]);
  a['1:3, 1:3'] = 1.0;
  a[[0, 0]] = 5.0;
  a['::3, 3'] = np.NDArray.fromList([8.0, 9.0]);
  print(a);
}
Output
array([[5., 0., 0., 8.],
       [0., 1., 1., 0.],
       [0., 1., 1., 0.],
       [0., 0., 0., 9.]])
extension

NDArrayReduce

extension NDArrayReduce on NDArray

Methods

summethod
NDArray sum({Object? axis, bool keepdims = false, DType? dtype})

Sum over axis (an int, a list of ints, or null for all), NumPy sum. Integers sum in int64 (wrapping); floats pairwise in double, stored as the input's float type (or dtype).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(6, null, 1, np.DType.float64).reshape([2, 3]);
  print('a:\n$a');
  print('sum():        ${a.sum()}');
  print('sum(axis: 0): ${a.sum(axis: 0)}');
  print('sum(axis: 1): ${a.sum(axis: 1)}');
  print('mean(axis: 0): ${a.mean(axis: 0)}');
}
Output
a:
array([[0., 1., 2.],
       [3., 4., 5.]])
sum():        array(15.)
sum(axis: 0): array([3., 5., 7.])
sum(axis: 1): array([3., 12.])
mean(axis: 0): array([1.5, 2.5, 3.5])
meanmethod
NDArray mean({Object? axis, bool keepdims = false, DType? dtype})

Arithmetic mean (integers give float64).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('mean: ${a.mean()}');
  print('column means: ${a.mean(axis: 0)}');
  print('row means (keepdims): ${a.mean(axis: 1, keepdims: true).shape}');
}
Output
mean: array(4.3333333)
column means: array([4.3333333, 4.3333333, 3.6666667, 5.])
row means (keepdims): [3, 1]
variancemethod
NDArray variance({Object? axis, int ddof = 0, bool keepdims = false})

Variance with ddof delta degrees of freedom (two-pass: mean, then squared deviations). Complex: of |x - \operatorname{mean}|.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('population variance: ${a.variance()}');
  print('sample (ddof 1): ${a.variance(ddof: 1)}');
  print('per column: ${a.variance(axis: 0)}');
}
Output
population variance: array(5.8888889)
sample (ddof 1): array(6.4242424)
per column: array([0.88888889, 11.555556, 1.5555556, 8.6666667])
stdmethod
NDArray std({Object? axis, int ddof = 0, bool keepdims = false})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
  print('mean:     ${x.mean()}');
  print('variance: ${x.variance()}');
  print('std:      ${x.std()}');
}
Output
mean:     array(5.)
variance: array(4.)
std:      array(2.)
prodmethod
NDArray prod({Object? axis, bool keepdims = false})

Product (integers in int64, floats in double).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(1, 7).reshape([2, 3]);
  print('prod: ${a.prod()}');
  print('axis 0: ${a.prod(axis: 0)}');
  print('axis 1: ${a.prod(axis: 1)}');
}
Output
prod: array(720)
axis 0: array([4, 10, 18])
axis 1: array([6, 120])
maxmethod
NDArray max({Object? axis, bool keepdims = false})

Maximum (NaN propagates, as NumPy max).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('max ${a.max()}, per column ${a.max(axis: 0)}, per row ${a.max(axis: 1)}');
  print('NaN propagates: ${np.NDArray.fromList([1.0, double.nan]).max()}');
}
Output
max array(9.), per column array([5., 9., 5., 8.]), per row array([4., 9., 8.])
NaN propagates: array(nan)
minmethod
NDArray min({Object? axis, bool keepdims = false})

Minimum (NaN propagates).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('min ${a.min()}, per column ${a.min(axis: 0)}, per row ${a.min(axis: 1)}');
}
Output
min array(1.), per column array([3., 1., 2., 1.]), per row array([1., 2., 3.])
anymethod
NDArray any({Object? axis, bool keepdims = false})

True when any element is non-zero.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('any > 8: ${a.gt(8).any()}');
  print('per row: ${a.gt(8).any(axis: 1)}');
}
Output
any > 8: array(True)
per row: array([False, True, False])
allmethod
NDArray all({Object? axis, bool keepdims = false})

True when every element is non-zero.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('all > 0: ${a.gt(0).all()}');
  print('per column all > 2: ${a.gt(2).all(axis: 0)}');
}
Output
all > 0: array(True)
per column all > 2: array([True, False, False, False])
argmaxmethod
NDArray argmax({int? axis, bool keepdims = false})

Index of the maximum along axis (null: of the flattened array); the first one on ties; NaN wins, as NumPy.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final scores = np.NDArray.fromList([
    [0.1, 0.7, 0.2],
    [0.5, 0.3, 0.2],
    [0.2, 0.2, 0.6],
  ]);
  print('best class per row: ${scores.argmax(axis: 1)}');
  print('max per row:        ${scores.max(axis: 1)}');
  print('overall argmax (flat index): ${scores.argmax()}');
}
Output
best class per row: array([1, 0, 2])
max per row:        array([0.7, 0.5, 0.6])
overall argmax (flat index): array(1)
argminmethod
NDArray argmin({int? axis, bool keepdims = false})

Index of the minimum.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('flat argmin: ${a.argmin()}');
  print('per column: ${a.argmin(axis: 0)}');
  print('per row: ${a.argmin(axis: 1)}');
}
Output
flat argmin: array(1)
per column: array([0, 0, 1, 0])
per row: array([1, 2, 1])
cumsummethod
NDArray cumsum({int? axis, DType? dtype})

Cumulative sum along axis (null: of the flattened array).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([3.0, 1.0, 4.0, 1.0, 5.0]);
  print('cumsum:  ${x.cumsum()}');
  print('cumprod: ${x.cumprod()}');
  print('sort:    ${x.sort()}');
  print('argsort: ${x.argsort()}');
}
Output
cumsum:  array([3., 4., 8., 9., 14.])
cumprod: array([3., 3., 12., 12., 60.])
sort:    array([1., 1., 3., 4., 5.])
argsort: array([1, 3, 0, 2, 4])
cumprodmethod
NDArray cumprod({int? axis, DType? dtype})

Cumulative product along axis.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0, 5.0]);
  print('cumprod: ${x.cumprod()}');
  final g = np.NDArray.full([20], 1.05).cumprod();
  print('20 years at 5%: ${g.get1(19).toStringAsFixed(4)}');
}
Output
cumprod: array([1., 2., 6., 24., 120.])
20 years at 5%: 2.6533
sortmethod
NDArray sort({int? axis = -1})

A sorted copy along axis (default last; null sorts the flattened array). NaNs sort last, as NumPy.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  print('sort rows (last axis):\n${a.sort()}');
  print('sort columns:\n${a.sort(axis: 0)}');
  print('flat: ${a.sort(axis: null)}');
}
Output
sort rows (last axis):
array([[1., 1., 3., 4.],
       [2., 5., 6., 9.],
       [3., 5., 5., 8.]])
sort columns:
array([[3., 1., 2., 1.],
       [5., 3., 4., 6.],
       [5., 9., 5., 8.]])
flat: array([1., 1., 2., 3., 3., 4., 5., 5., 5., 6., 8., 9.])
argsortmethod
NDArray argsort({int? axis = -1})

Indices that sort along axis (a stable merge sort; NaNs last).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([3.0, 1.0, 2.0, 1.0]);
  final i = x.argsort();
  print('argsort: $i (stable: the two 1s keep their order)');
  print('x.take(argsort): ${x.take(i)}');
}
Output
argsort: array([1, 3, 2, 0]) (stable: the two 1s keep their order)
x.take(argsort): array([1., 1., 2., 3.])
NDArray takeAlongAxis(NDArray indices, int axis)

Picks values along axis with indices of the same rank (NumPy take_along_axis).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  final idx = a.argsort(axis: 1);
  print('rows sorted via takeAlongAxis:\n${a.takeAlongAxis(idx, 1)}');
  final top = a.argmax(axis: 1, keepdims: true);
  print('row maxima: ${a.takeAlongAxis(top, 1).ravel()}');
}
Output
rows sorted via takeAlongAxis:
array([[1., 1., 3., 4.],
       [2., 5., 6., 9.],
       [3., 5., 5., 8.]])
row maxima: array([4., 9., 8.])
toDoublemethod
double toDouble()

The single value of a size-1 array as a double (complex: the real part).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([
    [3.0, 1.0, 4.0, 1.0],
    [5.0, 9.0, 2.0, 6.0],
    [5.0, 3.0, 5.0, 8.0],
  ]);
  final s = a.sum().toDouble();
  print('sum as a double: $s (${s.runtimeType})');
  print('mean: ${a.mean().toDouble()}');
}
Output
sum as a double: 52.0 (double)
mean: 4.333333333333333
final class BinaryUfunc

A binary elementwise operation. f is the float kernel, i the integer one (null: integers go through f), c the complex one writing (re, im) into o[0], o[1] (null: complex inputs are an error).

Constructors

BinaryUfuncconstructor
const BinaryUfunc(this.name, {this.f, this.i, this.c, this.result = _same, this.compare = false, this.integerOnly = false, FastKernel fast = FastKernel.none})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  // A new elementwise operation from a double function.
  const logaddexp = np.BinaryUfunc('logaddexp', f: _lae);
  final a = np.NDArray.fromList([0.0, 1.0, 100.0]);
  print('${logaddexp.name}: ${logaddexp(a, 0.0)}');
}

double _lae(double x, double y) {
  final m = math.max(x, y);
  return m + math.log(math.exp(x - m) + math.exp(y - m));
}
Output
logaddexp: array([0.69314718, 1.3132617, 100.])

Properties

namefield
final String name
ffield
final double Function(double x, double y)? f
ifield
final int Function(int x, int y)? i
cfield
final void Function(double ar, double ai, double br, double bi, Float64List o)? c
resultfield
final DType Function(DType promoted) result

Result dtype from the promoted input dtype.

comparefield
final bool compare

The result is boolean (comparison).

final bool integerOnly

Methods

callmethod
NDArray call(Object a, Object b, {NDArray? out})

Applies the operation to a and b (NDArray or Raya scalar each), writing into out when given.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(5), b = np.NDArray.fromList([2, 2, 2, 2, 2]);
  print('power: ${np.Ufuncs.power(a, b)}');
  print('arctan2: ${np.Ufuncs.atan2(1.0, np.NDArray.fromList([1.0, -1.0]))}');
  final out = np.NDArray.zeros([5]);
  np.Ufuncs.maximum(a, 2.5, out: out);
  print('maximum into out: $out');
}
Output
power: array([0, 1, 4, 9, 16])
arctan2: array([0.78539816, 2.3561945])
maximum into out: array([2.5, 2.5, 2.5, 3., 4.])
final class UnaryUfunc

A unary elementwise operation.

Constructors

UnaryUfuncconstructor
const UnaryUfunc(this.name, {this.f, this.i, this.c, this.result = _floatResult, this.complexToReal = false})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  const sigmoid = np.UnaryUfunc('sigmoid', f: _sig);
  final x = np.NDArray.linspace(-6, 6, 61);
  final y = sigmoid(x);
  print('${sigmoid.name}(0) = ${sigmoid(0.0)}');
}

double _sig(double x) => 1 / (1 + math.exp(-x));
Output
sigmoid(0) = array(0.5)

Properties

namefield
final String name
ffield
final double Function(double x)? f
ifield
final int Function(int x)? i
cfield
final void Function(double re, double im, Float64List o)? c
resultfield
final DType Function(DType input) result
final bool complexToReal

The complex kernel's result is real (abs, angle): written from o[0].

Methods

callmethod
NDArray call(Object a, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([-2.0, 0.5, 4.0]);
  print('negative: ${np.UnaryUfuncs.negative(x)}');
  final out = np.NDArray.zeros([3]);
  np.UnaryUfuncs.negative(x, out: out);
  print('into out: $out');
}
Output
negative: array([2., -0.5, -4.])
into out: array([2., -0.5, -4.])
class

Ufuncs

abstract final class Ufuncs

The binary ufuncs.

Static

addconstant
static const BinaryUfunc add = BinaryUfunc('add', f: _addF, i: _addI, c: _cadd, fast: FastKernel.add)
subtractconstant
static const BinaryUfunc subtract = BinaryUfunc('subtract', f: _subF, i: _subI, c: _csub, fast: FastKernel.sub)
multiplyconstant
static const BinaryUfunc multiply = BinaryUfunc('multiply', f: _mulF, i: _mulI, c: _cmul, fast: FastKernel.mul)
divideconstant
static const BinaryUfunc divide = BinaryUfunc('divide', f: _divF, c: _cdivK, result: _trueDivResult, fast: FastKernel.div)
floorDivideconstant
static const BinaryUfunc floorDivide = BinaryUfunc('floor_divide', f: _floorDivF, i: _ifloordiv)
modconstant
static const BinaryUfunc mod = BinaryUfunc('mod', f: _fmod, i: _imod)
powerconstant
static const BinaryUfunc power = BinaryUfunc('power', f: _powF, i: _ipow, c: _cpow)
maximumconstant
static const BinaryUfunc maximum = BinaryUfunc('maximum', f: _maxNan, i: math.max, fast: FastKernel.max)
minimumconstant
static const BinaryUfunc minimum = BinaryUfunc('minimum', f: _minNan, i: math.min, fast: FastKernel.min)
fmaxconstant
static const BinaryUfunc fmax = BinaryUfunc('fmax', f: _fmaxF, i: math.max)
fminconstant
static const BinaryUfunc fmin = BinaryUfunc('fmin', f: _fminF, i: math.min)
atan2constant
static const BinaryUfunc atan2 = BinaryUfunc('arctan2', f: math.atan2)
hypotUconstant
static const BinaryUfunc hypotU = BinaryUfunc('hypot', f: hypot)
copysignconstant
static const BinaryUfunc copysign = BinaryUfunc('copysign', f: _copysign)
equalconstant
static const BinaryUfunc equal = BinaryUfunc('equal', f: _eqF, i: _eqI, c: _ceq, compare: true)
notEqualconstant
static const BinaryUfunc notEqual = BinaryUfunc('not_equal', f: _neF, i: _neI, c: _cne, compare: true)
lessconstant
static const BinaryUfunc less = BinaryUfunc('less', f: _ltF, i: _ltI, compare: true)
lessEqualconstant
static const BinaryUfunc lessEqual = BinaryUfunc('less_equal', f: _leF, i: _leI, compare: true)
greaterconstant
static const BinaryUfunc greater = BinaryUfunc('greater', f: _gtF, i: _gtI, compare: true)
greaterEqualconstant
static const BinaryUfunc greaterEqual = BinaryUfunc('greater_equal', f: _geF, i: _geI, compare: true)
logicalAndconstant
static const BinaryUfunc logicalAnd = BinaryUfunc('logical_and', f: _landF, i: _landI, compare: true)
logicalOrconstant
static const BinaryUfunc logicalOr = BinaryUfunc('logical_or', f: _lorF, i: _lorI, compare: true)
logicalXorconstant
static const BinaryUfunc logicalXor = BinaryUfunc('logical_xor', f: _lxorF, i: _lxorI, compare: true)
bitwiseAndconstant
static const BinaryUfunc bitwiseAnd = BinaryUfunc('bitwise_and', i: _bandI, integerOnly: true)
bitwiseOrconstant
static const BinaryUfunc bitwiseOr = BinaryUfunc('bitwise_or', i: _borI, integerOnly: true)
bitwiseXorconstant
static const BinaryUfunc bitwiseXor = BinaryUfunc('bitwise_xor', i: _bxorI, integerOnly: true)
leftShiftconstant
static const BinaryUfunc leftShift = BinaryUfunc('left_shift', i: _shlI, integerOnly: true)
rightShiftconstant
static const BinaryUfunc rightShift = BinaryUfunc('right_shift', i: _shrI, integerOnly: true)
abstract final class UnaryUfuncs

The unary ufuncs.

Static

negativeconstant
static const UnaryUfunc negative = UnaryUfunc('negative', f: _negF, i: _negI, c: _cNeg, result: _keepNumeric)
absoluteconstant
static const UnaryUfunc absolute
signconstant
static const UnaryUfunc sign = UnaryUfunc('sign', f: _sign, i: _signI, result: _keepNumeric)
squareconstant
static const UnaryUfunc square = UnaryUfunc('square', f: _sqF, i: _sqI, c: _cSquare, result: _keepNumeric)
reciprocalconstant
static const UnaryUfunc reciprocal = UnaryUfunc('reciprocal', f: _recipF, c: _cRecip, result: _keep)
sqrtconstant
static const UnaryUfunc sqrt = UnaryUfunc('sqrt', f: math.sqrt, c: _cSqrt)
cbrtUconstant
static const UnaryUfunc cbrtU = UnaryUfunc('cbrt', f: cbrt)
expconstant
static const UnaryUfunc exp = UnaryUfunc('exp', f: math.exp, c: _cExp)
exp2constant
static const UnaryUfunc exp2 = UnaryUfunc('exp2', f: _exp2)
expm1Uconstant
static const UnaryUfunc expm1U = UnaryUfunc('expm1', f: expm1)
logconstant
static const UnaryUfunc log = UnaryUfunc('log', f: math.log, c: _cLog)
log2constant
static const UnaryUfunc log2 = UnaryUfunc('log2', f: _log2)
log10constant
static const UnaryUfunc log10 = UnaryUfunc('log10', f: _log10)
log1pUconstant
static const UnaryUfunc log1pU = UnaryUfunc('log1p', f: log1p)
sinconstant
static const UnaryUfunc sin = UnaryUfunc('sin', f: math.sin, c: _cSin)
cosconstant
static const UnaryUfunc cos = UnaryUfunc('cos', f: math.cos, c: _cCos)
tanconstant
static const UnaryUfunc tan = UnaryUfunc('tan', f: math.tan, c: _cTan)
arcsinconstant
static const UnaryUfunc arcsin = UnaryUfunc('arcsin', f: math.asin)
arccosconstant
static const UnaryUfunc arccos = UnaryUfunc('arccos', f: math.acos)
arctanconstant
static const UnaryUfunc arctan = UnaryUfunc('arctan', f: math.atan)
sinhconstant
static const UnaryUfunc sinh = UnaryUfunc('sinh', f: _sinh, c: _cSinh)
coshconstant
static const UnaryUfunc cosh = UnaryUfunc('cosh', f: _cosh, c: _cCosh)
tanhconstant
static const UnaryUfunc tanh = UnaryUfunc('tanh', f: _tanh, c: _cTanh)
arcsinhconstant
static const UnaryUfunc arcsinh = UnaryUfunc('arcsinh', f: _asinh)
arccoshconstant
static const UnaryUfunc arccosh = UnaryUfunc('arccosh', f: _acosh)
arctanhconstant
static const UnaryUfunc arctanh = UnaryUfunc('arctanh', f: _atanh)
floorconstant
static const UnaryUfunc floor = UnaryUfunc('floor', f: _floorF)
ceilconstant
static const UnaryUfunc ceil = UnaryUfunc('ceil', f: _ceilF)
truncconstant
static const UnaryUfunc trunc = UnaryUfunc('trunc', f: _truncF)
rintconstant
static const UnaryUfunc rint = UnaryUfunc('rint', f: _rint)
deg2radconstant
static const UnaryUfunc deg2rad = UnaryUfunc('deg2rad', f: _d2r)
rad2degconstant
static const UnaryUfunc rad2deg = UnaryUfunc('rad2deg', f: _r2d)
conjugateconstant
static const UnaryUfunc conjugate = UnaryUfunc('conjugate', f: _idF, i: _idI, c: _cConj, result: _keep)
angleconstant
static const UnaryUfunc angle = UnaryUfunc('angle', f: _angleF, c: _cAngle, result: _realOfComplex, complexToReal: true)
isnanconstant
static const UnaryUfunc isnan
isinfconstant
static const UnaryUfunc isinf
isfiniteconstant
static const UnaryUfunc isfinite
logicalNotconstant
static const UnaryUfunc logicalNot = UnaryUfunc('logical_not', f: _lnotF, i: _lnotI, result: _boolResult)
extension

NDArrayUfuncs

extension NDArrayUfuncs on NDArray

Elementwise operations as methods and operators.

Methods

addmethod
NDArray add(Object other, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.add(b);
  print('a.add(b) = $r');
  print('with a scalar: ${a.add(2)}');
}
Output
a.add(b) = array([5., 5., 5., 5.])
with a scalar: array([3., 4., 5., 6.])
subtractmethod
NDArray subtract(Object other, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.subtract(b);
  print('a.subtract(b) = $r');
  print('with a scalar: ${a.subtract(2)}');
}
Output
a.subtract(b) = array([-3., -1., 1., 3.])
with a scalar: array([-1., 0., 1., 2.])
multiplymethod
NDArray multiply(Object other, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.multiply(b);
  print('a.multiply(b) = $r');
  print('with a scalar: ${a.multiply(2)}');
}
Output
a.multiply(b) = array([4., 6., 6., 4.])
with a scalar: array([2., 4., 6., 8.])
dividemethod
NDArray divide(Object other, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.divide(b);
  print('a.divide(b) = $r');
  print('with a scalar: ${a.divide(2)}');
}
Output
a.divide(b) = array([0.25, 0.66666667, 1.5, 4.])
with a scalar: array([0.5, 1., 1.5, 2.])
powmethod
NDArray pow(Object exponent, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(0, 2, 21);
  print('x^2 at 2: ${x.pow(2).get1(20)}');
  print('ints: ${np.NDArray.arange(5).pow(3)}');
}
Output
x^2 at 2: 4.0
ints: array([0, 1, 8, 27, 64])
maximummethod
NDArray maximum(Object other, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.maximum(b);
  print('a.maximum(b) = $r');
  print('with a scalar: ${a.maximum(2)}');
}
Output
a.maximum(b) = array([4., 3., 3., 4.])
with a scalar: array([2., 2., 3., 4.])
minimummethod
NDArray minimum(Object other, {NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.minimum(b);
  print('a.minimum(b) = $r');
  print('with a scalar: ${a.minimum(2)}');
}
Output
a.minimum(b) = array([1., 2., 2., 1.])
with a scalar: array([1., 2., 2., 2.])
eqmethod
NDArray eq(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.eq(b);
  print('a.eq(b) = $r');
  print('count: ${r.astype(np.DType.int64).sum()}');
}
Output
a.eq(b) = array([False, False, False, False])
count: array(0)
nemethod
NDArray ne(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.ne(b);
  print('a.ne(b) = $r');
  print('count: ${r.astype(np.DType.int64).sum()}');
}
Output
a.ne(b) = array([True, True, True, True])
count: array(4)
ltmethod
NDArray lt(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.lt(b);
  print('a.lt(b) = $r');
  print('count: ${r.astype(np.DType.int64).sum()}');
}
Output
a.lt(b) = array([True, True, False, False])
count: array(2)
lemethod
NDArray le(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.le(b);
  print('a.le(b) = $r');
  print('count: ${r.astype(np.DType.int64).sum()}');
}
Output
a.le(b) = array([True, True, False, False])
count: array(2)
gtmethod
NDArray gt(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final t = np.NDArray.fromList([12.0, 31.0, 25.0, 33.0, 18.0]);
  final hot = t.gt(24);
  print('mask:          $hot');
  print('count:         ${hot.sum()}');
  print('selected:      ${t[hot]}');
  print('where hot, 0:  ${np.where(hot, t, 0)}');
}
Output
mask:          array([False, True, True, True, False])
count:         array(3)
selected:      array([31., 25., 33.])
where hot, 0:  array([0., 31., 25., 33., 0.])
gemethod
NDArray ge(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([1.0, 2.0, 3.0, 4.0]), b = np.NDArray.fromList([4.0, 3.0, 2.0, 1.0]);
  final r = a.ge(b);
  print('a.ge(b) = $r');
  print('count: ${r.astype(np.DType.int64).sum()}');
}
Output
a.ge(b) = array([False, False, True, True])
count: array(2)
absmethod
NDArray abs({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.abs();
  print('abs at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
abs at −3, 0, 3: [3.0, 0.0, 3.0]
sqrtmethod
NDArray sqrt({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([1.0, 4.0, 9.0, 16.0]);
  print('sqrt:   ${x.sqrt()}');
  print('square: ${x.square()}');
  print('exp(0..2): ${np.NDArray.arange(3, null, 1, np.DType.float64).exp()}');
  print('clip(2, 10): ${x.clip(2, 10)}');
}
Output
sqrt:   array([1., 2., 3., 4.])
square: array([1., 16., 81., 256.])
exp(0..2): array([1., 2.7182818, 7.3890561])
clip(2, 10): array([2., 4., 9., 10.])
expmethod
NDArray exp({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.exp();
  print('exp at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
exp at −3, 0, 3: [0.049787068367863944, 1.0, 20.085536923187668]
logmethod
NDArray log({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(0.1, 5, 50);
  final y = x.log();
  print('log(e) = ${np.NDArray.scalar(2.718281828459045).log()}');
  print('log(0) = ${np.NDArray.scalar(0.0).log()}, log(−1) = ${np.NDArray.scalar(-1.0).log()}');
}
Output
log(e) = array(1.)
log(0) = array(-inf), log(−1) = array(nan)
sinmethod
NDArray sin({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.sin();
  print('sin at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
sin at −3, 0, 3: [-0.1411200080598672, 0.0, 0.1411200080598672]
cosmethod
NDArray cos({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.cos();
  print('cos at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
cos at −3, 0, 3: [-0.9899924966004454, 1.0, -0.9899924966004454]
tanmethod
NDArray tan({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-1.4, 1.4, 57);
  final y = x.tan();
  print('tan(π/4) ≈ ${np.NDArray.scalar(0.7853981633974483).tan()}');
}
Output
tan(π/4) ≈ array(1.)
tanhmethod
NDArray tanh({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.tanh();
  print('tanh at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
tanh at −3, 0, 3: [-0.9950547536867305, 0.0, 0.9950547536867305]
squaremethod
NDArray square({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.square();
  print('square at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
square at −3, 0, 3: [9.0, 0.0, 9.0]
signmethod
NDArray sign({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.sign();
  print('sign at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
sign at −3, 0, 3: [-1.0, 0.0, 1.0]
floormethod
NDArray floor({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.floor();
  print('floor at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
floor at −3, 0, 3: [-3.0, 0.0, 3.0]
ceilmethod
NDArray ceil({NDArray? out})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.ceil();
  print('ceil at −3, 0, 3: ${[y.get1(0), y.get1(30), y.get1(60)]}');
}
Output
ceil at −3, 0, 3: [-3.0, 0.0, 3.0]
isNaNmethod
NDArray isNaN()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([1.0, double.nan, double.infinity, 0.0 / 0.0]);
  print('isNaN: ${x.isNaN()}');
  print('NaNs: ${x.isNaN().astype(np.DType.int64).sum()}');
}
Output
isNaN: array([False, True, False, True])
NaNs: array(2)
isFinitemethod
NDArray isFinite()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.fromList([1.0, double.nan, double.infinity, -double.infinity, -0.0]);
  print('isFinite: ${x.isFinite()}');
  print('finite values: ${x.compress(x.isFinite())}');
}
Output
isFinite: array([True, False, False, False, True])
finite values: array([1., 0.])
anglemethod
NDArray angle()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'raya:math' as math;

void main() {
  final z = np.NDArray.fromList([for (var k = 0; k < 4; k++) np.Complex.polar(1, k * math.pi / 2)]);
  print('angles: ${z.angle()}');
  print('real negative: ${np.NDArray.fromList([-1.0]).angle()}');
}
Output
angles: array([0., 1.5707963, 3.1415927, -1.5707963])
real negative: array([3.1415927])
clipmethod
NDArray clip(Object? lo, Object? hi)

Elements clipped to [lo, hi] (either may be null).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.clip(-1, 2);
  print('clip(−1, 2) ends: ${y.get1(0)}, ${y.get1(60)}');
  print('one side: ${np.NDArray.arange(5).clip(null, 2)}');
}
Output
clip(−1, 2) ends: -1.0, 2.0
one side: array([0, 1, 2, 2, 2])
mapmethod
NDArray map(double Function(double x) f, {DType dtype = DType.float64})

Applies f to every element (as doubles), returning float64 (or dtype). A slow path for one-off kernels.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final x = np.NDArray.linspace(-3, 3, 61);
  final y = x.map((v) => v * v * v - 3 * v);
  print('f(2) = ${y.get1(50)}');
  print('ints out: ${np.NDArray.arange(4).map((v) => v / 2, dtype: np.DType.float32)}');
}
Output
f(2) = 2.0
ints out: array([0., 0.5, 1., 1.5], dtype=float32)

Operators

operator +operator
NDArray operator +(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  // Broadcasting: a (3, 1) column and a (4,) row combine into a (3, 4) grid.
  final col = np.NDArray.arange(3).reshape([3, 1]) * 10;
  final row = np.NDArray.arange(4);
  print('col + row:\n${col + row}');
  print('row * 2 + 1: ${row * 2 + 1}');
}
Output
col + row:
array([[0, 1, 2, 3],
       [10, 11, 12, 13],
       [20, 21, 22, 23]])
row * 2 + 1: array([1, 3, 5, 7])
operator -operator
NDArray operator -(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([7.0, -7.0, 5.5, 9.0]), b = np.NDArray.fromList([2.0, 2.0, 2.0, -4.0]);
  print('a - b = ${a - b}');
  print('a - 3 = ${a - 3}');
}
Output
a - b = array([5., -9., 3.5, 13.])
a - 3 = array([4., -10., 2.5, 6.])
operator *operator
NDArray operator *(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([7.0, -7.0, 5.5, 9.0]), b = np.NDArray.fromList([2.0, 2.0, 2.0, -4.0]);
  print('a * b = ${a * b}');
  print('a * 3 = ${a * 3}');
}
Output
a * b = array([14., -14., 11., -36.])
a * 3 = array([21., -21., 16.5, 27.])
operator /operator
NDArray operator /(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([7.0, -7.0, 5.5, 9.0]), b = np.NDArray.fromList([2.0, 2.0, 2.0, -4.0]);
  print('a / b = ${a / b}');
  print('a / 3 = ${a / 3}');
}
Output
a / b = array([3.5, -3.5, 2.75, -2.25])
a / 3 = array([2.3333333, -2.3333333, 1.8333333, 3.])
operator %operator
NDArray operator %(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([7.0, -7.0, 5.5, 9.0]), b = np.NDArray.fromList([2.0, 2.0, 2.0, -4.0]);
  print('a % b = ${a % b}');
  print('a % 3 = ${a % 3}');
}
Output
a % b = array([1., 1., 1.5, -3.])
a % 3 = array([1., 2., 2.5, 0.])
operator ~/operator
NDArray operator ~/(Object other)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.fromList([7.0, -7.0, 5.5, 9.0]), b = np.NDArray.fromList([2.0, 2.0, 2.0, -4.0]);
  print('a ~/ b = ${a ~/ b}');
  print('a ~/ 3 = ${a ~/ 3}');
}
Output
a ~/ b = array([3., -4., 2., -3.])
a ~/ 3 = array([2., -3., 1., 3.])
operator -operator
NDArray operator -()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';

void main() {
  final a = np.NDArray.arange(4);
  print('−a = ${-a}');
  print('−(complex) = ${-np.NDArray.fromList([np.Complex(1, -1)])}');
}
Output
−a = array([0, -1, -2, -3])
−(complex) = array([-1.+1.j], dtype=complex128)
class

Blas

abstract final class Blas

Static

dotstaticmethod
static double dot(NDArray x, NDArray y)

x. y

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  print('dot = ${la.Blas.dot(x, y)}');
}
Output
dot = 12.0
axpystaticmethod
static void axpy(double alpha, NDArray x, NDArray y)

y + = \alpha x

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  la.Blas.axpy(2, x, y); // y = 2x + y, in place
  print('y = $y');
}
Output
y = array([6., -1., 12.])
scalstaticmethod
static void scal(double alpha, NDArray x)

x *= alpha

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  la.Blas.scal(-0.5, x);
  print('x = $x');
}
Output
x = array([-0.5, -1., -1.5])
nrm2staticmethod
static double nrm2(NDArray x)
x_2 without overflow.
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  print(la.Blas.nrm2(np.NDArray.fromList([3.0, 4.0])));
  print('no overflow: ${la.Blas.nrm2(np.NDArray.fromList([1e200, 1e200]))}');
}
Output
5.0
no overflow: 1.414213562373095e+200
asumstaticmethod
static double asum(NDArray x)

Sum |x_{i}|

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  print('asum(y) = ${la.Blas.asum(y)}');
}
Output
asum(y) = 15.0
iamaxstaticmethod
static int iamax(NDArray x)

Index of the first element of largest |x_{i}| (-1 for empty).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  print('index of the largest |y_i|: ${la.Blas.iamax(y)}');
}
Output
index of the largest |y_i|: 2
swapstaticmethod
static void swap(NDArray x, NDArray y)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  la.Blas.swap(x, y);
  print('x = $x, y = $y');
}
Output
x = array([4., -5., 6.]), y = array([1., 2., 3.])
copystaticmethod
static void copy(NDArray x, NDArray y)

y = x

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final x = np.NDArray.fromList([1.0, 2.0, 3.0]), y = np.NDArray.fromList([4.0, -5.0, 6.0]);
  la.Blas.copy(x, y);
  print('y = $y');
}
Output
y = array([1., 2., 3.])
rotstaticmethod
static void rot(NDArray x, NDArray y, double c, double s)

Applies the plane rotation (x, y) < - (c x + s y, c y - s x).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:math' as math;

void main() {
  final x = np.NDArray.fromList([1.0, 0.0, -1.0]), y = np.NDArray.fromList([0.0, 1.0, 0.0]);
  final c = math.cos(math.pi / 6), s = math.sin(math.pi / 6);
  la.Blas.rot(x, y, c, s);
  print('x = $x');
  print('y = $y');
}
Output
x = array([0.8660254, 0.5, -0.8660254])
y = array([-0.5, 0.8660254, 0.5])
rotgstaticmethod
static (double, double, double) rotg(double a, double b)

(c, s, r) with [c s; -s c] [a; b] = [r; 0].

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final (c, s, r) = la.Blas.rotg(3, 4);
  print('r = $r, c = $c, s = $s');
  print('rotates (3, 4) to (r, 0): ${c * 3 + s * 4}, ${-s * 3 + c * 4}');
}
Output
r = 5.0, c = 0.6, s = 0.8
rotates (3, 4) to (r, 0): 5.0, -4.440892098500626e-16
gemvstaticmethod
static void gemv(double alpha, NDArray a, NDArray x, double beta, NDArray y, {bool trans = false})

y = \alpha \operatorname{op}(A) x + \beta y, \operatorname{op}(A) = A or A^{T}.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0, 0.0], [0.0, 1.0, 3.0]]);
  final x = np.NDArray.fromList([1.0, 1.0, 1.0]), y = np.NDArray.zeros([2]);
  la.Blas.gemv(1, a, x, 0, y);
  print('A x = $y');
  final z = np.NDArray.zeros([3]);
  la.Blas.gemv(1, a, np.NDArray.fromList([1.0, 2.0]), 0, z, trans: true);
  print('Aᵀ (1, 2) = $z');
}
Output
A x = array([3., 4.])
Aᵀ (1, 2) = array([1., 4., 6.])
gerstaticmethod
static void ger(double alpha, NDArray x, NDArray y, NDArray a)

A + = \alpha x y^{T}

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.zeros([3, 3]);
  la.Blas.ger(1, np.NDArray.fromList([1.0, 2.0, 3.0]), np.NDArray.fromList([1.0, 0.0, -1.0]), a);
  print(a);
}
Output
array([[1., 0., -1.],
       [2., 0., -2.],
       [3., 0., -3.]])
symvstaticmethod
static void symv(double alpha, NDArray a, NDArray x, double beta, NDArray y)

y = \alpha A x + \beta y for symmetric A (the lower triangle is read).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final s = np.NDArray.fromList([[2.0, 1.0], [1.0, 3.0]]);
  final y = np.NDArray.zeros([2]);
  la.Blas.symv(1, s, np.NDArray.fromList([1.0, -1.0]), 0, y);
  print('S x = $y');
}
Output
S x = array([1., -2.])
trsvstaticmethod
static void trsv(NDArray t, NDArray x, {bool lower = true, bool trans = false, bool unit = false})

x < - \operatorname{op}(T)^{-1} x for triangular T (in place).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final t = np.NDArray.fromList([[2.0, 0.0], [1.0, 4.0]]);
  final x = np.NDArray.fromList([2.0, 9.0]);
  la.Blas.trsv(t, x);
  print('solved in place: $x');
}
Output
solved in place: array([1., 2.])
gemmstaticmethod
static void gemm(double alpha, NDArray a, NDArray b, double beta, NDArray c, {bool transA = false, bool transB = false})

C = \alpha \operatorname{op}(A) \operatorname{op}(B) + \beta C (the blocked, packed GEMM; transposes are free).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0, 0.0], [0.0, 1.0, 3.0]]);
  final c = np.NDArray.zeros([2, 2]);
  la.Blas.gemm(1, a, a, 0, c, transB: true);
  print('A Aᵀ =\n$c');
}
Output
A Aᵀ =
array([[5., 2.],
       [2., 10.]])
trsmstaticmethod
static void trsm(NDArray t, NDArray b, {bool lower = true, bool trans = false, bool unit = false, double alpha = 1})

B < - \alpha \operatorname{op}(T)^{-1} B for triangular T (left side), in place; blocked so most of the work is GEMM.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final t = np.NDArray.fromList([[1.0, 0.0], [2.0, 1.0]]);
  final b = np.NDArray.fromList([[1.0, 2.0], [4.0, 6.0]]);
  la.Blas.trsm(t, b);
  print('T⁻¹B =\n$b');
}
Output
T⁻¹B =
array([[1., 2.],
       [2., 2.]])
syrkstaticmethod
static void syrk(double alpha, NDArray a, double beta, NDArray c, {bool trans = false})

C = \alpha A A^{T} + \beta C (trans: A^{T} A); the whole of C is written.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[1.0, 2.0, 0.0], [0.0, 1.0, 3.0]]);
  final c = np.NDArray.zeros([3, 3]);
  la.Blas.syrk(1, a, 0, c, trans: true);
  print('AᵀA =\n$c');
}
Output
AᵀA =
array([[1., 2., 0.],
       [2., 5., 3.],
       [0., 3., 9.]])
symmstaticmethod
static void symm(double alpha, NDArray a, NDArray b, double beta, NDArray c)

C = \alpha A B + \beta C for symmetric A (lower triangle read).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final s = np.NDArray.fromList([[2.0, 1.0], [1.0, 2.0]]), b = np.NDArray.eye(2);
  final c = np.NDArray.zeros([2, 2]);
  la.Blas.symm(3, s, b, 0, c);
  print('3 S I =\n$c');
}
Output
3 S I =
array([[6., 3.],
       [3., 6.]])
class LinAlgError implements Exception

A linear-algebra failure: singular matrix, not positive definite, no convergence (NumPy's LinAlgError).

Constructors

LinAlgErrorconstructor
LinAlgError(this.message)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  try {
    la.inv(np.NDArray.fromList([[1.0, 2.0], [2.0, 4.0]]));
  } on la.LinAlgError catch (e) {
    print('caught: ${e.message}');
  }
  print(la.LinAlgError('custom message'));
}
Output
caught: singular matrix
LinAlgError: custom message

Properties

messagefield
final String message

Methods

toStringmethod
String toString()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  print(la.LinAlgError('matrix is singular'));
}
Output
LinAlgError: matrix is singular
final class EighResult

Eigenvalues (ascending) and, optionally, orthonormal eigenvectors (columns) of a real symmetric matrix (the lower triangle is read, as numpy.linalg.eigh's default).

Properties

valuesfield
final NDArray values
vectorsfield
final NDArray? vectors
final class SchurResult

Real Schur form A = Z T Z^{T}: T quasi upper triangular (1x_{1} blocks for real eigenvalues, 2x_{2} for complex pairs), Z orthogonal.

Properties

tfield
final NDArray t
zfield
final NDArray z
final class EigResult

Eigenvalues and right eigenvectors (unit 2-norm columns) of a general real matrix, as numpy.linalg.eig: real arrays when every eigenvalue is real, complex otherwise (eigenvalues in Schur order, conjugate pairs adjacent).

Properties

valuesfield
final NDArray values
vectorsfield
final NDArray? vectors
final class LUDecomposition

A = P L U for an m \times n matrix: L unit lower (m \times k), U upper (k \times n), k = \min(m, n).

Properties

pivotsfield
final Int64List pivots

LAPACK's pivots: row i was swapped with row pivots[i] (in order).

rowsfield
final int rows
colsfield
final int cols
final bool singular

True when U has an exact zero on its diagonal.

packedgetter
NDArray get packed

L and U packed in one m \times n array (L's unit diagonal not stored), NumPy/SciPy lu_factor layout.

permgetter
List<int> get perm

The row permutation as a list: row i of P^{T} A is row perm[i] of A.

pgetter
NDArray get p

The permutation matrix P (A = P L U).

lgetter
NDArray get l
ugetter
NDArray get u
detgetter
double get det

\det(A) (square only).

slogdetgetter
(double, double) get slogdet

(sign, \log|\det|), robust against overflow.

Methods

solvemethod
NDArray solve(NDArray b)

Solves A x = b for a vector or a matrix of right-hand sides.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[2.0, 1.0], [1.0, 3.0]]);
  final f = la.lu(a); // factor once, solve many times
  for (final b in [[1.0, 0.0], [0.0, 1.0], [3.0, 4.0]]) {
    print('b = $b -> x = ${f.solve(np.NDArray.fromList(b))}');
  }
}
Output
b = [1.0, 0.0] -> x = array([0.6, -0.2])
b = [0.0, 1.0] -> x = array([-0.2, 0.4])
b = [3.0, 4.0] -> x = array([1., 1.])
inversemethod
NDArray inverse()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[4.0, 7.0], [2.0, 6.0]]);
  final inv = la.lu(a).inverse();
  print('$inv');
  print('A·A⁻¹ == I: ${np.allClose(np.matmul(a, inv), np.NDArray.eye(2))}');
}
Output
array([[0.6, -0.7],
       [-0.2, 0.4]])
A·A⁻¹ == I: true
final class LDLDecomposition

P A P^{T} = L D L^{T} for a symmetric (possibly indefinite) matrix, Bunch-Kaufman pivoting (D has 1x_{1} and 2x_{2} blocks).

Properties

permfield
final List<int> perm

Row i of P A P^{T} is row perm[i] of A.

nfield
final int n
lgetter
NDArray get l

Unit lower-triangular L.

dgetter
NDArray get d

Block-diagonal D (1x_{1} and symmetric 2x_{2} blocks).

pgetter
NDArray get p

The permutation matrix P.

Methods

solvemethod
NDArray solve(NDArray b)

Solves A x = b.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[4.0, 2.0], [2.0, -1.0]]); // symmetric, indefinite
  final x = la.ldl(a).solve(np.NDArray.fromList([2.0, 1.0]));
  print('x = $x, A x = ${np.matmul(a, x)}');
}
Output
x = array([0.5, 0.]), A x = array([2., 1.])
final class CpuGemmF32 implements GemmBackend

GEMM in float32 on the CPU (Float32x4 kernels): converts the float64 views, multiplies, adds back. The CPU stand-in for a GPU backend, and a ~2x faster factorization for solveRefined.

Constructors

CpuGemmF32constructor
const CpuGemmF32()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  const g = la.CpuGemmF32();
  print('name: ${g.name}');
  final r = la.solveRefined(a, np.NDArray.fromList([1.0, 2.0]), backend: g);
  print('x = ${r.x}, steps ${r.iterations}');
}
Output
name: cpu-f32
x = array([0.090909091, 0.63636364]), steps 0

Properties

namegetter
String get name
minWorkgetter
int get minWork
DType get computeType

Methods

gemmmethod
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;

void main() {
  final a = np.NDArray.fromList([[0.1, 0.2], [0.3, 0.4]]);
  final c = np.NDArray.zeros([2, 2]);
  const la.CpuGemmF32().gemm(a, a, c);
  print('float32 products: $c');
  print('float64:          ${np.matmul(a, a)}');
}
Output
float32 products: array([[0.07, 0.1],
       [0.15000001, 0.22000001]])
float64:          array([[0.07, 0.1],
       [0.15, 0.22]])
final class RefinedSolve

The result of solveRefined.

Properties

xfield
final NDArray x

The solution, float64.

final int iterations

Refinement steps taken.

final bool fellBack

True when refinement didn't converge and the float64 LU solved it instead.

final double backwardError

\max_{j} \Vert b_{j} - A x_{j}\Vert_{\mathrm{inf}} / (\Vert A\Vert_{\mathrm{inf}} \Vert x_{j}\Vert_{\mathrm{inf}} + \Vert b_{j}\Vert_{\mathrm{inf}}).

final class QRDecomposition

A = Q R.

Properties

qfield
final NDArray? q

Orthonormal columns (m \times k for 'reduced', m \times m for 'complete'; null for mode 'r').

rfield
final NDArray r

Upper triangular (k \times n or m \times n).

final class SVDResult

A = U \operatorname{diag}(S) V^{T} (V^{T} is vt); S descending, non-negative.

Properties

ufield
final NDArray? u

m \times k ('reduced') or m \times m ('full'); null when only values were asked for.

sfield
final NDArray s
vtfield
final NDArray? vt
abstract class NativeLinalg

What a native backend can do. Every method returns null or false when it doesn't handle the case (shape, layout, size); the caller then runs the pure-Raya code. Matrices are row-major Float64Lists unless a stride says otherwise, exactly as the pure-Raya routines take them.

Constructors

NativeLinalgconstructor
const NativeLinalg()
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  const p = Probe();
  print('a custom backend named ${p.name}');
  print('inside using(): ${la.Linalg.using(p, () => la.Linalg.backendName)}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
a custom backend named probe
inside using(): probe

Properties

namegetter
String get name

"accelerate", "raya-native", "raya-native x6" (for logs and benchmark tables).

Methods

allocatemethod
Float64List? allocate(int n)

A zeroed list for a factorization's working matrix, in memory this backend can share with its worker threads (native memory, freed by a finalizer), or null for an ordinary Raya list.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('allocate -> ${p.allocate(16)}  (null: use an ordinary Float64List)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
allocate -> null  (null: use an ordinary Float64List)
solve with the probe installed: array([0.090909091, 0.63636364])
dgemmmethod
bool dgemm(int m, int n, int k, double alpha, Float64List a, int aOff, int aRs, int aCs, Float64List b, int bOff, int bRs, int bCs, double beta, Float64List c, int cOff, int cRs, int cCs)

C = \alpha A B + \beta C on strided views, as dgemm in gemm.ray.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('dgemm -> ${p.dgemm(1, 1, 1, 1, Float64List(1), 0, 1, 1, Float64List(1), 0, 1, 1, 0, Float64List(1), 0, 1, 1)}  (false: the portable kernel runs)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
dgemm -> false  (false: the portable kernel runs)
solve with the probe installed: array([0.090909091, 0.63636364])
sgemmmethod
bool sgemm(int m, int n, int k, double alpha, Float32List a, int aOff, int aRs, int aCs, Float32List b, int bOff, int bRs, int bCs, double beta, Float32List c, int cOff, int cRs, int cCs)

Single precision, as sgemm in gemm.ray.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('sgemm -> ${p.sgemm(1, 1, 1, 1, Float32List(1), 0, 1, 1, Float32List(1), 0, 1, 1, 0, Float32List(1), 0, 1, 1)}  (false: the portable kernel runs)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
sgemm -> false  (false: the portable kernel runs)
solve with the probe installed: array([0.090909091, 0.63636364])
zgemmmethod
bool zgemm(int m, int n, int k, double alpha, Float64List a, int aOff, int aRs, int aCs, Float64List b, int bOff, int bRs, int bCs, double beta, Float64List c, int cOff, int cRs, int cCs)

Complex (interleaved re, im; strides in complex elements), real alpha and beta, as zgemm in gemm.ray.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('zgemm -> ${p.zgemm(1, 1, 1, 1, Float64List(2), 0, 1, 1, Float64List(2), 0, 1, 1, 0, Float64List(2), 0, 1, 1)}  (false: the portable kernel runs)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
zgemm -> false  (false: the portable kernel runs)
solve with the probe installed: array([0.090909091, 0.63636364])
dgemvTmethod
bool dgemvT(int m, int n, double alpha, Float64List a, int aOff, int lda, Float64List x, int xOff, Float64List y, int yOff)

y[0:n] + = \alpha A^{T} x for an m \times n row-major block of A at aOff with row stride lda (for a symmetric A, the symv of the tridiagonal reduction).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('dgemvT -> ${p.dgemvT(1, 1, 1, Float64List(1), 0, 1, Float64List(1), 0, Float64List(1), 0)}  (false)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
dgemvT -> false  (false)
solve with the probe installed: array([0.090909091, 0.63636364])
getrfmethod
(Int64List, bool)? getrf(Float64List a, int m, int n)

In-place LU with partial pivoting of an m \times n matrix (dgetrf); (0-based pivots, singular) or null.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('getrf -> ${p.getrf(Float64List.fromList([1, 2, 3, 4]), 2, 2)}  (null: getrf runs in Raya)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
getrf -> null  (null: getrf runs in Raya)
solve with the probe installed: array([0.090909091, 0.63636364])
sgetrfmethod
(Int64List, bool)? sgetrf(Float64List a, int n)

A true single-precision LU (sgetrf) of n \times n a, whose values are float32 numbers stored as doubles; the factors are written back the same way. For the mixed-precision solve. Null when not handled.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('sgetrf -> ${p.sgetrf(Float64List.fromList([1, 2, 3, 4]), 2)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
sgetrf -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
luSolvemethod
bool luSolve(Float64List lu, int n, Float64List x, int nrhs)

Solves with packed LU factors in place (x is n x nrhs; the pivots are already applied by the caller).

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('luSolve -> ${p.luSolve(Float64List(4), 2, Float64List(2), 1)}  (false)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
luSolve -> false  (false)
solve with the probe installed: array([0.090909091, 0.63636364])
potrfmethod
int? potrf(Float64List a, int n)

In-place lower Cholesky (upper triangle zeroed); the leading minor that is not positive definite (1-based), 0 on success, or null when not handled.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('potrf -> ${p.potrf(Float64List.fromList([4, 2, 2, 3]), 2)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
potrf -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
qrmethod
Float64List? qr(Float64List a, int m, int n, int qCols)

Householder QR: R in the upper triangle of a (m \times n, in place) and Q (m x qCols) returned, or null.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('qr -> ${p.qr(Float64List(4), 2, 2, 2)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
qr -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
syevdmethod
(Float64List, Float64List?)? syevd(Float64List a, int n, bool vectors)

Symmetric eigenproblem of full symmetric storage a (n \times n, destroyed): ascending values, and when vectors the eigenvectors as columns (row-major n \times n). Null when not handled.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('syevd -> ${p.syevd(Float64List(4), 2, true)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
syevd -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
gesddmethod
(Float64List?, Float64List, Float64List?)? gesdd(Float64List a, int m, int n, bool vectors, bool full)

SVD of m \times n a (destroyed): (U m x uCols, S, V^{T} vtRows x n) with uCols = vtRows = \min(m, n) reduced, m and n full; U and V^{T} null when not vectors. Divide and conquer (dgesdd). Null when not handled.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('gesdd -> ${p.gesdd(Float64List(4), 2, 2, true, false)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
gesdd -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
geesmethod
Float64List? gees(Float64List a, int n)

Real Schur form A = Z T Z^{T} in place (T in a), Z returned (row-major), or null.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('gees -> ${p.gees(Float64List(4), 2)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
gees -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
geevmethod
(Float64List, Float64List, Float64List?)? geev(Float64List a, int n, bool vectors)

General eigenproblem (dgeev): (wr, wi, right eigenvectors in LAPACK's real packed form, row-major) or null.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  // A backend that declines every call: the library then uses its own code.
  const p = Probe();
  print('geev -> ${p.geev(Float64List(4), 2, true)}  (null)');
  final a = np.NDArray.fromList([[4.0, 1.0], [1.0, 3.0]]);
  print('solve with the probe installed: ${la.Linalg.using(p, () => la.solve(a, np.NDArray.fromList([1.0, 2.0])))}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
geev -> null  (null)
solve with the probe installed: array([0.090909091, 0.63636364])
class

Linalg

abstract final class Linalg

The backend the linear algebra uses. Set backend to choose one (null: everywhere).

Static

backendstaticgetter
static NativeLinalg? get backend

The active native backend, or null for.

backendstaticsetter
static set backend(NativeLinalg? b)
Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final before = la.Linalg.backend;
  la.Linalg.backend = const Probe();
  print('backend now: ${la.Linalg.backendName}');
  print('det still works: ${la.det(np.NDArray.eye(3) * 2)}');
  la.Linalg.backend = null;
  print('after null: ${la.Linalg.backendName}');
  la.Linalg.backend = before;
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
backend now: probe
det still works: array(8.)
after null: raya
backendNamestaticgetter
static String get backendName

"raya" when no native backend is active.

usingstaticmethod
static T using<T>(NativeLinalg? b, T Function() f)

Runs f with b as the backend (null:), then restores the previous one.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final name = la.Linalg.using(const Probe(), () => la.Linalg.backendName);
  print('inside: $name');
  print('outside again: ${la.Linalg.backendName == name ? 'unchanged' : 'restored'}');
}

final class Probe extends la.NativeLinalg {
  const Probe();
  @override
  String get name => 'probe';
}
Output
inside: probe
outside again: restored
availablestaticmethod
static Map<String, NativeLinalg> available()

The backends available on this platform by name ("accelerate", "native", "native-parallel"), for tests and benchmarks.

Example
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;
import 'raya:convert';
import 'package:riptide_numerics_cpu/linalg.ray' as la;
import 'raya:typed_data';

void main() {
  final avail = la.Linalg.available();
  print('native backends here: ${avail.isEmpty ? 'none (the Raya code runs)' : avail.keys.join(', ')}');
}
Output from the Raya VM
native backends here: accelerate, native, native-parallel