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.
| dtype | storage | notes |
|---|---|---|
boolean | Uint8List | |
int8..int64, uint8..uint64 | the matching typed list | wrap on overflow, as NumPy; uint64 \ge 2^{63} reads back negative |
float16, bfloat16 | Uint16List (IEEE bits) | computed in double, rounded to nearest even once on store |
float32, float64 | Float32List, Float64List | |
complex64, complex128 | Float32List, Float64List, interleaved | a complex element is one element for strides |
- Indexing:
a[2],a[Slice(1, null, 2)],a[[i, j]](NumPy's tuplea[i, j]),a[[Slice.all, newAxis, ellipsis]], or the string forma['1:2, None... -1']. One advanced index (an int or boolNDArray) per operation:a[NDArray.fromList([3, 0])]takes rows,a[a.gt(0)]gives the selected elements.a[idx] = valueassigns with broadcasting. - Promotion:
DType.promotematchesnumpy.result_typefor every pair of the 14 dtypes (tested); Raya scalars are NumPy 2 "weak" scalars (int8_array * 3stays int8,float32_array + 1.5stays 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,cumprodover any axis or axes, withkeepdims;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):
| Area | API |
|---|---|
| BLAS 1-3 | la.Blas.dot/axpy/scal/nrm2/asum/iamax/swap/rot/rotg, gemv/ger/symv/trsv, gemm/trsm/syrk/symm (any strides) |
| Factorizations | lu (blocked, partial pivoting; p, l, u, packed, solve, det), cholesky (blocked), ldl (Bunch-Kaufman), qr (blocked Householder; reduced/complete/r) |
| Spectral | svd (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) |
| Solvers | solve (real or complex), solveTriangular, inv, det, slogdet, lstsq (minimum norm), pinv, solveRefined (low-precision LU + float64 refinement) |
| Measures | norm (vector and matrix orders), cond, matrixRank |
| Matrix functions | expm (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
double hypot(double x, double y)\sqrt{x^{2} + y^{2}} without undue overflow or underflow.
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)}');
}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).
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)}');
}
}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.
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)]]},
]})}');
}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).
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)}');
}
}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.
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)]]},
]})}');
}0x3f80 = 1.0 0x4049 = 3.140625
List<Object> parseIndex(String spec)Parses NumPy index syntax: "1:2, None... -1" -> [Slice(1), Slice(null, null, 2), newAxis, ellipsis, -1].
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']}');
}[1:3, ::2]
[..., None, -1]
a["1:3, ::2"] =
array([[4, 6],
[8, 10]])NDArray concatenate(List<NDArray> arrays, {int axis = 0})Joins arrays along an existing axis; dtypes promote.
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}');
}concatenate axis 0:
array([[1., 2.],
[3., 4.]])
hstack: array([[1., 2., 3., 4.]])
vstack shape: [3, 2]
stack shape: [2, 1, 2]NDArray stack(List<NDArray> arrays, {int axis = 0})Joins arrays (same shape) along a new axis.
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}');
}stack axis 0: shape [2, 3]
array([[1., 2., 3.],
[4., 5., 6.]])
stack axis 1: shape [3, 2]NDArray vstack(List<NDArray> arrays)Stacks rows (1-d arrays become rows).
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');
}shape [3, 3]
array([[1., 1., 1.],
[1., 1., 1.],
[0., 0., 0.]])NDArray hstack(List<NDArray> arrays)Stacks columns (1-d arrays are joined end to end).
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)])}');
}shape [2, 3]
array([[1., 0., 7.],
[0., 1., 7.]])
1-D: array([0, 1, 0, 1, 2])List<NDArray> split(NDArray a, Object sections, {int axis = 0})Splits a into sections equal parts, or at the given indices, along axis (views).
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()}');
}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]]
NDArray flip(NDArray a, {int? axis})Reverses the order of elements along axis (all axes when null), as a view.
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)}');
}flip all:
array([[5, 4, 3],
[2, 1, 0]])
flip axis 1:
array([[2, 1, 0],
[5, 4, 3]])NDArray roll(NDArray a, int shift, {int? axis})Rolls elements by shift along axis (the flattened array when null).
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)}');
}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]])NDArray tile(NDArray a, List<int> reps)Repeats a reps times along each axis.
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');
}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.]])NDArray repeat(NDArray a, int repeats, {int? axis})Repeats each element repeats times along axis (the flattened array when null).
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)}');
}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.]])List<NDArray> meshgrid(List<NDArray> xs, {String indexing = 'xy'})Coordinate matrices from coordinate vectors ('xy' indexing like NumPy's default, or 'ij').
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}');
}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]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).
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)}');
}a @ b:
array([[19., 22.],
[43., 50.]])
a @ [1, 1]: array([3., 7.])
a @ a.T:
array([[5., 11.],
[11., 25.]])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.
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))}');
}dot(u, v): array(32.)
outer(u, v):
array([[4., 5., 6.],
[8., 10., 12.],
[12., 15., 18.]])
trace(eye): array(4.)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.
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])}');
}shape [2]: array([66., 210.]) same as sums: array([66., 210.])
NDArray outer(NDArray a, NDArray b)Outer product of two arrays (flattened), NumPy outer.
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');
}shape [3, 4]
array([[1., 10., 100., 1000.],
[2., 20., 200., 2000.],
[3., 30., 300., 3000.]])NDArray vdot(NDArray a, NDArray b)Inner product of the flattened arrays, conjugating the first (NumPy vdot).
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)');
}vdot flattens: array(30.) complex: vdot(z, z) = array(15.+0.j, dtype=complex128) (conjugates the first)
NDArray trace(NDArray a, {int k = 0})Sum of the diagonal k over axes 0 and 1.
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)}');
}trace = array(12.) k = 1 (superdiagonal) = array(1.)
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).
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])}');
}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.]])NDArray kron(NDArray a, NDArray b)Kronecker product of two 2-d arrays.
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');
}shape [4, 4]
array([[1., 0., 2., 0.],
[0., 1., 0., 2.],
[3., 0., 4., 0.],
[0., 3., 0., 4.]])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.
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');
}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.
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}');
}
}[3, 4] [8, 7, 6, 5] [3] and [4]: ArgumentError
List<NDArray> broadcastArrays(List<NDArray> arrays)Views of arrays broadcast to their common shape.
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]}');
}shapes [3, 4] and [3, 4]
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]])String formatArray(NDArray a)NumPy-style printing (summarised with ... past 1000 elements).
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)));
}array([0., 0.25, 0.5, 0.75, 1.])
array([[1., 0.],
[0., 1.]])double pairwiseSum(List<double> x, int start, int n, int stride)Pairwise sum of x[start], x[start+stride]... (n terms).
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)}');
}naive loop: 100000.00000133288 pairwise sum: 100000.00000000003 every other: 50000.000000000015
double expm1(double x)\exp(x) - 1, accurate near 0 (Kahan's trick).
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)}');
}expm1(1e-10) = 1.00000000005e-10 exp(1e-10) − 1 = 1.000000082740371e-10 (cancellation) expm1(1) = 1.718281828459045
double log1p(double x)\log(1 + x), accurate near 0 (Goldberg's trick).
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)}');
}log1p(1e-12) = 9.999999999995e-13 log1p(1) = 0.6931471805599453 log1p(−0.5) = -0.6931471805599453
double cbrt(double x)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)}');
}cbrt(27) = 3.0 cbrt(−8) = -2.0 cbrt(2) = 1.2599210498948732
NDArray where(NDArray condition, Object x, Object y)Elements of x where condition is true, else of y (each broadcast; NumPy where).
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()}');
}relu(x) = array([0., 0., 0., 1.5, 3.]) sign = array([-1., -1., 0., 1., 1.])
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).
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)}');
}array([True, True, False, False]) NaN equal: array([False, False, False, True]) rtol 0.2: array([True, True, True, False])
bool allClose(NDArray a, Object b, {double rtol = 1e-5, double atol = 1e-8, bool equalNan = false})Whether every element is close (NumPy allclose).
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)}');
}exactly equal: false allClose: true isClose: array([True, True])
bool arrayEqual(NDArray a, NDArray b)Same shape and equal elements (NumPy array_equal).
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));
}true false true
EighResult eigh(NDArray a, {bool computeVectors = true})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)}');
}eigenvalues (ascending): [1.000000, 3.000000] a·v == 3·v: true
NDArray eigvalsh(NDArray a)Eigenvalues of a real symmetric matrix, ascending.
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)}');
}eigenvalues: [1.854897, 3.476024, 6.669079] sum = trace: 12.000000000 vs array(12.)
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.
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))}');
}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: trueEigResult eig(NDArray a, {bool computeVectors = true})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}');
}eigenvalues: array([0.+1.j, 0.-1.j], dtype=complex128) real case: array([2., 3.])
NDArray eigvals(NDArray a)Eigenvalues of a general real matrix.
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');
}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.
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');
}singular: false, x = [1.0, 2.0]
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.
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]))}');
}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])(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).
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');
}packed LU: [3.0, 4.0, 0.3333333333333333, 0.6666666666666667] pivots: [1, 1], singular: false [[1, 2], [2, 4]] singular: true
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.
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)}');
}x = [1.000000, 3.000000] check a·x == b: true
NDArray inv(NDArray a)The inverse of a square matrix (throws LinAlgError when singular).
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))}');
}inv(a) = [0.6000, -0.7000, -0.2000, 0.4000] a · inv(a) is the identity: true
NDArray det(NDArray a)\det(A) (complex inputs give a Complex-valued 0-d array).
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)}');
}det(a) = -41.000000 det of a singular matrix is zero: true slogdet: sign -1.0, log|det| 3.713572
(double, double) slogdet(NDArray a)(sign, \log|\det|) of a real square matrix.
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');
}sign 1.0, log|det| = 115.12925464970236 (det = 1e50) swap matrix: sign -1.0, log|det| 0.0
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.
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)}');
}L = [2.000000, 0.000000, 1.000000, 1.414214] L·Lᵀ == S: true
void potrf(Float64List a, int n, {GemmBackend? backend})In-place lower Cholesky of a row-major n \times n matrix (upper triangle zeroed).
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');
}in place (lower triangle is L): [2.0, 0.0, 1.0, 1.4142135623730951]
LDLDecomposition ldl(NDArray a)Bunch-Kaufman LDL^T of a symmetric matrix (the lower triangle is read).
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]))}');
}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.
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)}');
}forward substitution: array([1., 2., 2.25]) L x: array([2., 3., 10.]) with Lᵀ: array([-5.5, 5.5, 2.5])
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.
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)}');
}norm(v) = 5.0 Frobenius norm of m = 5.477226 cond(m) = 14.933034
double cond(NDArray a, {Object? p})Condition number in norm p (null or 2: sigma_max / sigma_min; inf for singular matrices).
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)}');
}
}eps 1.0: cond = 6.854e+0 eps 0.001: cond = 4.002e+3 eps 1e-8: cond = 4.000e+8
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.
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)))}');
}rank = 2 identity: 4 outer product: 1
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).
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)}');
}pinv shape [2, 3] A⁺A == I: true A A⁺ A == A: true
(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).
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');
}intercept 1.0300, slope 1.9800, rank 2
NDArray expm(NDArray a)The matrix exponential (real or complex), Higham's scaling and squaring with Pade approximants.
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)]}');
}expm(G) = [0.877583, -0.479426, 0.479426, 0.877583]
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).
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)}');
}sqrtm =
array([[2., 0.2],
[0., 3.]])
s·s == a: trueNDArray 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.
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)}');
}logm(expm(J)) =
array([[0., 1.],
[-1., 0.]])
expm(logm(a)) == a: trueRefinedSolve 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).
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))}');
}x = array([0.17857143, 0.28571429, 0.67857143]) refinement steps 0, fell back: false matches solve: true
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)).
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');
}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]
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).
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))}');
}Q =
array([[-0.16903085, 0.89708523],
[-0.50709255, 0.27602622],
[-0.84515425, -0.34503278]])
QᵀQ == I: trueQRDecomposition 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).
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}');
}Q shape [3, 2], R shape [2, 2] Q·R == a: true QᵀQ == I: true R is upper triangular: true
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).
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)}');
}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.
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)]}');
}randomized: [35.550770, 0.375468] full: [35.550770, 0.375468, 0.000000]
Constants and variables
const NewAxis newAxis = NewAxis._()Inserts an axis of length 1 (NumPy's None / np.newaxis).
Classes
Complex
final class Complex
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}');
}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
const Complex(this.re, [this.im = 0])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)}');
}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).
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)];
}2·e^(iπ/3) = (1.0000000000000002+1.7320508075688772j) back: r = 2.0, θ = 1.0471975511965976
Static
static const Complex zero = Complex(0, 0)static const Complex one = Complex(1, 0)static const Complex i = Complex(0, 1)Properties
final double refinal double imComplex get conjugatedouble get argbool get isNaNbool get isFiniteint get hashCodeMethods
Complex scale(double s)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)}');
}z·2.5 = (7.5+10.0j) z·(−1) = (-3.0-4.0j)
Complex exp()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()];
}e^(iπ) = (-1.0+1.2246467991473532e-16j) e^(1+i) = (1.4686939399158851+2.2873552871788423j)
Complex log()Principal branch.
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()}');
}log(−1) = (0.0+3.141592653589793j) log(i) = (0.0+1.5707963267948966j) exp(log z) = (2.9999999999999996+3.999999999999999j)
Complex sqrt()Principal square root (Kahan's branch cuts: the result has re \ge 0).
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}');
}√(−4) = (0.0+2.0j) √i = (0.7071067811865476+0.7071067811865475j) √(3+4i) = (2.0+1.0j), squared (3.0+4.0j)
Complex pow(Complex w)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))}');
}i^i = (0.20787957635076193+0.0j) (1+i)^2 = (1.2246467991473532e-16+2.0j)
String toString()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}');
}(1.5-2.0j) (0.0+1.0j) (0.0+0.0j)
Operators
Complex operator +(Complex o)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}');
}z + w = (4.0+2.0j)
Complex operator -(Complex o)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}');
}z - w = (2.0+6.0j)
Complex operator *(Complex o)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}');
}z * w = (11.0-2.0j)
Complex operator /(Complex o)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}');
}z / w = (-1.0+2.0j)
Complex operator -()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}');
}−z = (-3.0-4.0j) z + (−z) = (0.0+0.0j)
bool operator ==(Object other)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));
}true false true
DTypeKind
enum DTypeKind
What a dtype's values are.
Values
booleansignedunsignedfloatcomplexDType
enum DType
An NDArray element type. Storage is one typed list per array:
| dtype | storage | notes |
|---|---|---|
boolean | Uint8List | 0 or 1 |
int8..int64 | Int8List..Int64List | wrap on overflow, as NumPy |
uint8..uint64 | Uint8List..Uint64List | uint64 values \ge 2^{63} read back as negative Raya ints |
float16, bfloat16 | Uint16List of IEEE bits | computed in double, rounded to nearest even on store |
float32, float64 | Float32List, Float64List | |
complex64, complex128 | Float32List, Float64List | interleaved (re, im); strides count elements, not floats |
Values
boolean(DTypeKind.boolean, 1, 'bool')int8(DTypeKind.signed, 1, 'int8')int16(DTypeKind.signed, 2, 'int16')int32(DTypeKind.signed, 4, 'int32')int64(DTypeKind.signed, 8, 'int64')uint8(DTypeKind.unsigned, 1, 'uint8')uint16(DTypeKind.unsigned, 2, 'uint16')uint32(DTypeKind.unsigned, 4, 'uint32')uint64(DTypeKind.unsigned, 8, 'uint64')float16(DTypeKind.float, 2, 'float16')bfloat16(DTypeKind.float, 2, 'bfloat16')float32(DTypeKind.float, 4, 'float32')float64(DTypeKind.float, 8, 'float64')complex64(DTypeKind.complex, 8, 'complex64')complex128(DTypeKind.complex, 16, 'complex128')Constructors
const DType(this.kind, this.itemSize, this.numpyName)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 : '-'}');
}
}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
static DType ofTypedData(TypedData data)The dtype whose storage data is (float16/bfloat16 and boolean are ambiguous: Uint16List -> uint16, Uint8List -> uint8).
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)));
}DType.float32 DType.int16 DType.uint8
static DType? tryParse(String name)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'));
}DType.float32 DType.complex128 null
static DType promote(DType a, DType b)NumPy's result_type for two array dtypes.
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],
]})}');
}int8 + uint8 -> DType.int16 int32 + float32 -> DType.float64 float32 + complex64 -> DType.complex64
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).
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))}');
}int32 array + 2 -> DType.int32 int32 array + 2.5 -> DType.float64 float32 array + 2.5 -> DType.float32 float32 array + Complex -> DType.complex64
Properties
final DTypeKind kindbool get isBoolbool get isIntegerbool get isFloatbool get isComplexDType get realTypeThe real dtype of a complex dtype (complex64 -> float32); itself otherwise.
DType get complexTypeThe complex dtype that holds this one (float32 -> complex64, others -> complex128).
Methods
TypedData allocate(int length)A zero-filled typed list for length elements.
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');
}Float32List of 16 bytes complex128 x 3: 48 bytes
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.
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)}');
}the 8 bytes as float32: [1.0, 2.0] as int16: [0, 16256, 0, 16384]
Slice
final class Slice
start:stop:step, Python semantics (nulls are the defaults; negatives count from the end).
Constructors
const Slice([this.start, this.stop, this.step])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)]}');
}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
Properties
final int? startfinal int? stopfinal int? stepMethods
(int, int, int) resolve(int length)(start, step, count) for an axis of length (Python's slice.indices).
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)}');
}1:7:2 on length 10 -> (1, 2, 3) ::-1 on length 5 -> (4, -1, 5) -100:100 on length 4 -> (0, 1, 4)
String toString()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);
}1:7:2 :-1 :
NewAxis
final class NewAxis
Methods
String toString()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}');
}None a[None, :] shape [1, 3] a[:, None] shape [3, 1]
Ellipsis
final class Ellipsis
Methods
String toString()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]]}');
}...
a[..., 0] =
array([[0, 4, 8],
[12, 16, 20]])GemmBackend
abstract interface class GemmBackend
Computes c = alpha * a @ b + beta * c for 2-d views (any strides) of float64 or float32 arrays.
Properties
int get minWorkProducts with fewer than this many multiply-adds (m \cdot n \cdot k) stay on the CPU.
DType get computeTypeThe 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
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).
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');
}cpu: handled true
array([[3., 5.],
[7., 9.]])CpuGemm
final class CpuGemm implements GemmBackend
The CPU GEMM (blocked, packed; float64 or float32 by the operands' dtype).
Constructors
const CpuGemm()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]))}');
}name: cpu lu with this backend: array([-1., 1.])
Properties
String get nameint get minWorkDType get computeTypeMethods
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})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');
}0.5·a·a =
array([[3.5, 5.],
[7.5, 11.]])Order
enum Order
Memory order for new arrays and copies.
Values
cfNDArray
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.
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)}');
}m =
array([[0., 1., 2.],
[3., 4., 5.]])
strided view =
array([[0., 3.],
[1., 4.],
[2., 5.]])
both see the write: 99.0, 99.0factory NDArray.zeros(List<int> shape, {DType dtype = DType.float64, Order order = Order.c})A new zero-filled array.
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)}');
}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).
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}');
}array([[1.5, 1.5, 1.5],
[1.5, 1.5, 1.5]])
dtype DType.int32factory NDArray.ones(List<int> shape, {DType dtype = DType.float64})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));
}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).
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)));
}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.
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}');
}array(3.5), shape [], ndim 0 broadcasts: array([3.5, 4.5, 5.5])
factory NDArray.zerosLike(NDArray a, {DType? dtype})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}');
}shape [3, 4], dtype DType.float64, sum array(0.) as int32: DType.int32
factory NDArray.onesLike(NDArray a, {DType? dtype})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));
}array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])factory NDArray.fullLike(NDArray a, Object value, {DType? dtype})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));
}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.
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()}');
}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).
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');
}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.
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');
}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.
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)}');
}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).
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();
}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).
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');
}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.
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()}');
}array([[1., 0., 0.],
[0., 2., 0.],
[0., 0., 3.]])
above: [4, 4]
back to the vector: array([1., 2., 3.])Static
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.
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;
}array([[0., 0.],
[1., 2.],
[2., 4.]])Properties
final DType dtypefinal List<int> shapeint get ndimint get itemSizeint get nbytesList<int> get byteStridesNDArray get TThe transpose (axes reversed).
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}');
}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: falseNDArray get realThe real part: a view for complex arrays (into the same storage), this array otherwise.
NDArray get imagThe imaginary part: a view for complex arrays, zeros otherwise (a new array).
Methods
int offsetOf(List<int> index)The element offset in data of index (one int per axis, negatives count from the end).
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])}');
}strides [4, 1], offsetOf([2, 1]) = 9 transpose strides [1, 4], offsetOf([1, 2]) = 9
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.
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}');
}a.item([1, 2]) = 6.0 size-1 array: 66.0 int array gives int: int
double getDouble(List<int> index)The element at index as a double (complex: the real part).
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]));
}11.0 1.0
double get1(int i)1-d and 2-d element reads without an index list (real part for complex).
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');
}sum by get1: 2.5
double get2(int i, int j)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)}');
}a[1, 3] = 7.0 transpose: 7.0
void set1(int i, double v)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);
}array([0., 1., 4., 9., 16.])
void set2(int i, int j, double v)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);
}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]])void setItem(List<int> index, Object value)Writes value (num, bool or Complex) at index.
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);
}array([[0.+0.j, 1.-1.j],
[2.5+0.j, 0.+0.j]], dtype=complex128)void fill(Object value)Sets every element to value.
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);
}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]])void assign(Object source)Copies source (an NDArray, broadcast to this shape, or a scalar) into this array, converting dtypes.
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);
}array([[0., 1., 2., 0.],
[0., 1., 2., 0.],
[7., 7., 7., 7.]])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).
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]))}');
}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.
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}');
}move first 2 axes to position 2: [4, 5, 2, 3] one axis to 3: [3, 4, 5, 2]
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.
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))}');
}elements > 6: array([7., 8., 9., 10., 11.]) even: array([0., 2., 4., 6., 8., 10.])
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).
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()}');
}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])NDArray ravel()A 1-d view when possible, else a 1-d copy.
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}');
}array([0., 4., 8., 1., 5., 9., 2., 6., 10., 3., 7., 11.]) ravel of a contiguous array is a view: [12]
NDArray flatten()A 1-d C-order copy.
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)}');
}f[0] = 100.0, a[0, 0] = 0.0
NDArray transpose([List<int>? axes])Permutes the axes (default: reversed), as a view.
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]);
}transpose(): [4, 3, 2] transpose([1, 0, 2]): [3, 2, 4]
NDArray conj()The complex conjugate (a copy; real dtypes return this).
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()}');
}conj: array([1.-2.j, -3.+1.j], dtype=complex128) real arrays are unchanged: array([0, 1, 2])
NDArray swapAxes(int a, int b)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);
}[4, 3, 2] [2, 4, 3]
NDArray moveAxis(int source, int destination)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}');
}moveAxis(0, -1): [4, 5, 3] moveAxis(2, 0): [5, 3, 4]
NDArray expandDims(int axis)Inserts a length-1 axis at axis.
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)}');
}expandDims(0): [1, 3]
expandDims(1): [3, 1]
outer product by broadcasting:
array([[0, 0, 0],
[0, 1, 2],
[0, 2, 4]])NDArray squeeze([int? axis])Removes length-1 axes (all, or axis).
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}');
}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).
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');
}array([[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.]])
strides [0, 1]: no copy, the row repeatsNDArray 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.
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)}');
}main: array([0., 5., 10.]) k = 1: array([1., 6., 11.]) k = −1: array([4., 9.])
NDArray copy({Order order = Order.c})A new array with the same values in order.
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}');
}a[0,0] 0.0, copy -1.0 Fortran order strides: [1, 3]
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.
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)}');
}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.
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}');
}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.
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);
}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).
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());
}[0.0, 1.0, 2.0, 3.0, 4.0] [1.0, 0.0, 0.0, 1.0]
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.
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');
}8 bytes: [0, 0, 128, 63, 0, 0, 0, 192]
Object toList()Nested Raya lists (bool, int, double or Complex leaves).
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}');
}[[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).
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());
}[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]
String toString()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));
}array([0., 0.5, 1.])
array([[1, 0],
[0, 1]], dtype=int32)
array(2.5)Operators
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).
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']}");
}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])void operator []=(Object index, Object value)Assigns value (an NDArray, broadcast, or a scalar) to this[index].
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);
}array([[5., 0., 0., 8.],
[0., 1., 1., 0.],
[0., 1., 1., 0.],
[0., 0., 0., 9.]])NDArrayReduce
extension NDArrayReduce on NDArray
Methods
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).
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)}');
}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])NDArray mean({Object? axis, bool keepdims = false, DType? dtype})Arithmetic mean (integers give float64).
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}');
}mean: array(4.3333333) column means: array([4.3333333, 4.3333333, 3.6666667, 5.]) row means (keepdims): [3, 1]
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}|.
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)}');
}population variance: array(5.8888889) sample (ddof 1): array(6.4242424) per column: array([0.88888889, 11.555556, 1.5555556, 8.6666667])
NDArray std({Object? axis, int ddof = 0, bool keepdims = false})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()}');
}mean: array(5.) variance: array(4.) std: array(2.)
NDArray prod({Object? axis, bool keepdims = false})Product (integers in int64, floats in double).
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)}');
}prod: array(720) axis 0: array([4, 10, 18]) axis 1: array([6, 120])
NDArray max({Object? axis, bool keepdims = false})Maximum (NaN propagates, as NumPy max).
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()}');
}max array(9.), per column array([5., 9., 5., 8.]), per row array([4., 9., 8.]) NaN propagates: array(nan)
NDArray min({Object? axis, bool keepdims = false})Minimum (NaN propagates).
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)}');
}min array(1.), per column array([3., 1., 2., 1.]), per row array([1., 2., 3.])
NDArray any({Object? axis, bool keepdims = false})True when any element is non-zero.
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)}');
}any > 8: array(True) per row: array([False, True, False])
NDArray all({Object? axis, bool keepdims = false})True when every element is non-zero.
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)}');
}all > 0: array(True) per column all > 2: array([True, False, False, False])
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.
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()}');
}best class per row: array([1, 0, 2]) max per row: array([0.7, 0.5, 0.6]) overall argmax (flat index): array(1)
NDArray argmin({int? axis, bool keepdims = false})Index of the minimum.
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)}');
}flat argmin: array(1) per column: array([0, 0, 1, 0]) per row: array([1, 2, 1])
NDArray cumsum({int? axis, DType? dtype})Cumulative sum along axis (null: of the flattened array).
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()}');
}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])
NDArray cumprod({int? axis, DType? dtype})Cumulative product along axis.
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)}');
}cumprod: array([1., 2., 6., 24., 120.]) 20 years at 5%: 2.6533
NDArray sort({int? axis = -1})A sorted copy along axis (default last; null sorts the flattened array). NaNs sort last, as NumPy.
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)}');
}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.])NDArray argsort({int? axis = -1})Indices that sort along axis (a stable merge sort; NaNs last).
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)}');
}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).
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()}');
}rows sorted via takeAlongAxis:
array([[1., 1., 3., 4.],
[2., 5., 6., 9.],
[3., 5., 5., 8.]])
row maxima: array([4., 9., 8.])double toDouble()The single value of a size-1 array as a double (complex: the real part).
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()}');
}sum as a double: 52.0 (double) mean: 4.333333333333333
BinaryUfunc
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
const BinaryUfunc(this.name, {this.f, this.i, this.c, this.result = _same, this.compare = false, this.integerOnly = false, FastKernel fast = FastKernel.none})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));
}logaddexp: array([0.69314718, 1.3132617, 100.])
Properties
final String namefinal double Function(double x, double y)? ffinal int Function(int x, int y)? ifinal void Function(double ar, double ai, double br, double bi, Float64List o)? cfinal bool integerOnlyMethods
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.
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');
}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.])
UnaryUfunc
final class UnaryUfunc
A unary elementwise operation.
Constructors
const UnaryUfunc(this.name, {this.f, this.i, this.c, this.result = _floatResult, this.complexToReal = false})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));sigmoid(0) = array(0.5)
Properties
final String namefinal double Function(double x)? ffinal int Function(int x)? ifinal void Function(double re, double im, Float64List o)? cfinal DType Function(DType input) resultfinal bool complexToRealThe complex kernel's result is real (abs, angle): written from o[0].
Methods
NDArray call(Object a, {NDArray? out})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');
}negative: array([2., -0.5, -4.]) into out: array([2., -0.5, -4.])
Ufuncs
abstract final class Ufuncs
The binary ufuncs.
Static
static const BinaryUfunc add = BinaryUfunc('add', f: _addF, i: _addI, c: _cadd, fast: FastKernel.add)static const BinaryUfunc subtract = BinaryUfunc('subtract', f: _subF, i: _subI, c: _csub, fast: FastKernel.sub)static const BinaryUfunc multiply = BinaryUfunc('multiply', f: _mulF, i: _mulI, c: _cmul, fast: FastKernel.mul)static const BinaryUfunc divide = BinaryUfunc('divide', f: _divF, c: _cdivK, result: _trueDivResult, fast: FastKernel.div)static const BinaryUfunc floorDivide = BinaryUfunc('floor_divide', f: _floorDivF, i: _ifloordiv)static const BinaryUfunc mod = BinaryUfunc('mod', f: _fmod, i: _imod)static const BinaryUfunc power = BinaryUfunc('power', f: _powF, i: _ipow, c: _cpow)static const BinaryUfunc maximum = BinaryUfunc('maximum', f: _maxNan, i: math.max, fast: FastKernel.max)static const BinaryUfunc minimum = BinaryUfunc('minimum', f: _minNan, i: math.min, fast: FastKernel.min)static const BinaryUfunc fmax = BinaryUfunc('fmax', f: _fmaxF, i: math.max)static const BinaryUfunc fmin = BinaryUfunc('fmin', f: _fminF, i: math.min)static const BinaryUfunc atan2 = BinaryUfunc('arctan2', f: math.atan2)static const BinaryUfunc hypotU = BinaryUfunc('hypot', f: hypot)static const BinaryUfunc copysign = BinaryUfunc('copysign', f: _copysign)static const BinaryUfunc equal = BinaryUfunc('equal', f: _eqF, i: _eqI, c: _ceq, compare: true)static const BinaryUfunc notEqual = BinaryUfunc('not_equal', f: _neF, i: _neI, c: _cne, compare: true)static const BinaryUfunc less = BinaryUfunc('less', f: _ltF, i: _ltI, compare: true)static const BinaryUfunc lessEqual = BinaryUfunc('less_equal', f: _leF, i: _leI, compare: true)static const BinaryUfunc greater = BinaryUfunc('greater', f: _gtF, i: _gtI, compare: true)static const BinaryUfunc greaterEqual = BinaryUfunc('greater_equal', f: _geF, i: _geI, compare: true)static const BinaryUfunc logicalAnd = BinaryUfunc('logical_and', f: _landF, i: _landI, compare: true)static const BinaryUfunc logicalOr = BinaryUfunc('logical_or', f: _lorF, i: _lorI, compare: true)static const BinaryUfunc logicalXor = BinaryUfunc('logical_xor', f: _lxorF, i: _lxorI, compare: true)static const BinaryUfunc bitwiseAnd = BinaryUfunc('bitwise_and', i: _bandI, integerOnly: true)static const BinaryUfunc bitwiseOr = BinaryUfunc('bitwise_or', i: _borI, integerOnly: true)static const BinaryUfunc bitwiseXor = BinaryUfunc('bitwise_xor', i: _bxorI, integerOnly: true)static const BinaryUfunc leftShift = BinaryUfunc('left_shift', i: _shlI, integerOnly: true)static const BinaryUfunc rightShift = BinaryUfunc('right_shift', i: _shrI, integerOnly: true)UnaryUfuncs
abstract final class UnaryUfuncs
The unary ufuncs.
Static
static const UnaryUfunc negative = UnaryUfunc('negative', f: _negF, i: _negI, c: _cNeg, result: _keepNumeric)static const UnaryUfunc absolutestatic const UnaryUfunc sign = UnaryUfunc('sign', f: _sign, i: _signI, result: _keepNumeric)static const UnaryUfunc square = UnaryUfunc('square', f: _sqF, i: _sqI, c: _cSquare, result: _keepNumeric)static const UnaryUfunc reciprocal = UnaryUfunc('reciprocal', f: _recipF, c: _cRecip, result: _keep)static const UnaryUfunc sqrt = UnaryUfunc('sqrt', f: math.sqrt, c: _cSqrt)static const UnaryUfunc cbrtU = UnaryUfunc('cbrt', f: cbrt)static const UnaryUfunc exp = UnaryUfunc('exp', f: math.exp, c: _cExp)static const UnaryUfunc exp2 = UnaryUfunc('exp2', f: _exp2)static const UnaryUfunc expm1U = UnaryUfunc('expm1', f: expm1)static const UnaryUfunc log = UnaryUfunc('log', f: math.log, c: _cLog)static const UnaryUfunc log2 = UnaryUfunc('log2', f: _log2)static const UnaryUfunc log10 = UnaryUfunc('log10', f: _log10)static const UnaryUfunc log1pU = UnaryUfunc('log1p', f: log1p)static const UnaryUfunc sin = UnaryUfunc('sin', f: math.sin, c: _cSin)static const UnaryUfunc cos = UnaryUfunc('cos', f: math.cos, c: _cCos)static const UnaryUfunc tan = UnaryUfunc('tan', f: math.tan, c: _cTan)static const UnaryUfunc arcsin = UnaryUfunc('arcsin', f: math.asin)static const UnaryUfunc arccos = UnaryUfunc('arccos', f: math.acos)static const UnaryUfunc arctan = UnaryUfunc('arctan', f: math.atan)static const UnaryUfunc sinh = UnaryUfunc('sinh', f: _sinh, c: _cSinh)static const UnaryUfunc cosh = UnaryUfunc('cosh', f: _cosh, c: _cCosh)static const UnaryUfunc tanh = UnaryUfunc('tanh', f: _tanh, c: _cTanh)static const UnaryUfunc arcsinh = UnaryUfunc('arcsinh', f: _asinh)static const UnaryUfunc arccosh = UnaryUfunc('arccosh', f: _acosh)static const UnaryUfunc arctanh = UnaryUfunc('arctanh', f: _atanh)static const UnaryUfunc floor = UnaryUfunc('floor', f: _floorF)static const UnaryUfunc ceil = UnaryUfunc('ceil', f: _ceilF)static const UnaryUfunc trunc = UnaryUfunc('trunc', f: _truncF)static const UnaryUfunc rint = UnaryUfunc('rint', f: _rint)static const UnaryUfunc deg2rad = UnaryUfunc('deg2rad', f: _d2r)static const UnaryUfunc rad2deg = UnaryUfunc('rad2deg', f: _r2d)static const UnaryUfunc conjugate = UnaryUfunc('conjugate', f: _idF, i: _idI, c: _cConj, result: _keep)static const UnaryUfunc angle = UnaryUfunc('angle', f: _angleF, c: _cAngle, result: _realOfComplex, complexToReal: true)static const UnaryUfunc isnanstatic const UnaryUfunc isinfstatic const UnaryUfunc isfinitestatic const UnaryUfunc logicalNot = UnaryUfunc('logical_not', f: _lnotF, i: _lnotI, result: _boolResult)NDArrayUfuncs
extension NDArrayUfuncs on NDArray
Elementwise operations as methods and operators.
Methods
NDArray add(Object other, {NDArray? out})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)}');
}a.add(b) = array([5., 5., 5., 5.]) with a scalar: array([3., 4., 5., 6.])
NDArray subtract(Object other, {NDArray? out})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)}');
}a.subtract(b) = array([-3., -1., 1., 3.]) with a scalar: array([-1., 0., 1., 2.])
NDArray multiply(Object other, {NDArray? out})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)}');
}a.multiply(b) = array([4., 6., 6., 4.]) with a scalar: array([2., 4., 6., 8.])
NDArray divide(Object other, {NDArray? out})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)}');
}a.divide(b) = array([0.25, 0.66666667, 1.5, 4.]) with a scalar: array([0.5, 1., 1.5, 2.])
NDArray pow(Object exponent, {NDArray? out})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)}');
}x^2 at 2: 4.0 ints: array([0, 1, 8, 27, 64])
NDArray maximum(Object other, {NDArray? out})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)}');
}a.maximum(b) = array([4., 3., 3., 4.]) with a scalar: array([2., 2., 3., 4.])
NDArray minimum(Object other, {NDArray? out})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)}');
}a.minimum(b) = array([1., 2., 2., 1.]) with a scalar: array([1., 2., 2., 2.])
NDArray eq(Object other)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()}');
}a.eq(b) = array([False, False, False, False]) count: array(0)
NDArray ne(Object other)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()}');
}a.ne(b) = array([True, True, True, True]) count: array(4)
NDArray lt(Object other)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()}');
}a.lt(b) = array([True, True, False, False]) count: array(2)
NDArray le(Object other)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()}');
}a.le(b) = array([True, True, False, False]) count: array(2)
NDArray gt(Object other)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)}');
}mask: array([False, True, True, True, False]) count: array(3) selected: array([31., 25., 33.]) where hot, 0: array([0., 31., 25., 33., 0.])
NDArray ge(Object other)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()}');
}a.ge(b) = array([False, False, True, True]) count: array(2)
NDArray abs({NDArray? out})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)]}');
}abs at −3, 0, 3: [3.0, 0.0, 3.0]
NDArray sqrt({NDArray? out})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)}');
}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.])
NDArray exp({NDArray? out})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)]}');
}exp at −3, 0, 3: [0.049787068367863944, 1.0, 20.085536923187668]
NDArray log({NDArray? out})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()}');
}log(e) = array(1.) log(0) = array(-inf), log(−1) = array(nan)
NDArray sin({NDArray? out})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)]}');
}sin at −3, 0, 3: [-0.1411200080598672, 0.0, 0.1411200080598672]
NDArray cos({NDArray? out})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)]}');
}cos at −3, 0, 3: [-0.9899924966004454, 1.0, -0.9899924966004454]
NDArray tan({NDArray? out})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()}');
}tan(π/4) ≈ array(1.)
NDArray tanh({NDArray? out})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)]}');
}tanh at −3, 0, 3: [-0.9950547536867305, 0.0, 0.9950547536867305]
NDArray square({NDArray? out})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)]}');
}square at −3, 0, 3: [9.0, 0.0, 9.0]
NDArray sign({NDArray? out})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)]}');
}sign at −3, 0, 3: [-1.0, 0.0, 1.0]
NDArray floor({NDArray? out})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)]}');
}floor at −3, 0, 3: [-3.0, 0.0, 3.0]
NDArray ceil({NDArray? out})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)]}');
}ceil at −3, 0, 3: [-3.0, 0.0, 3.0]
NDArray isNaN()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()}');
}isNaN: array([False, True, False, True]) NaNs: array(2)
NDArray isFinite()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())}');
}isFinite: array([True, False, False, False, True]) finite values: array([1., 0.])
NDArray angle()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()}');
}angles: array([0., 1.5707963, 3.1415927, -1.5707963]) real negative: array([3.1415927])
NDArray clip(Object? lo, Object? hi)Elements clipped to [lo, hi] (either may be null).
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)}');
}clip(−1, 2) ends: -1.0, 2.0 one side: array([0, 1, 2, 2, 2])
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.
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)}');
}f(2) = 2.0 ints out: array([0., 0.5, 1., 1.5], dtype=float32)
Operators
NDArray operator +(Object other)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}');
}col + row:
array([[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]])
row * 2 + 1: array([1, 3, 5, 7])NDArray operator -(Object other)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}');
}a - b = array([5., -9., 3.5, 13.]) a - 3 = array([4., -10., 2.5, 6.])
NDArray operator *(Object other)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}');
}a * b = array([14., -14., 11., -36.]) a * 3 = array([21., -21., 16.5, 27.])
NDArray operator /(Object other)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}');
}a / b = array([3.5, -3.5, 2.75, -2.25]) a / 3 = array([2.3333333, -2.3333333, 1.8333333, 3.])
NDArray operator %(Object other)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}');
}a % b = array([1., 1., 1.5, -3.]) a % 3 = array([1., 2., 2.5, 0.])
NDArray operator ~/(Object other)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}');
}a ~/ b = array([3., -4., 2., -3.]) a ~/ 3 = array([2., -3., 1., 3.])
NDArray operator -()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)])}');
}−a = array([0, -1, -2, -3]) −(complex) = array([-1.+1.j], dtype=complex128)
Blas
abstract final class Blas
Static
static double dot(NDArray x, NDArray y)x. y
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)}');
}dot = 12.0
static void axpy(double alpha, NDArray x, NDArray y)y + = \alpha x
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');
}y = array([6., -1., 12.])
static void scal(double alpha, NDArray x)x *= alpha
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');
}x = array([-0.5, -1., -1.5])
static double nrm2(NDArray x)| x | _2 without overflow. |
|---|
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]))}');
}5.0 no overflow: 1.414213562373095e+200
static double asum(NDArray x)Sum |x_{i}|
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)}');
}asum(y) = 15.0
static int iamax(NDArray x)Index of the first element of largest |x_{i}| (-1 for empty).
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)}');
}index of the largest |y_i|: 2
static void swap(NDArray x, NDArray y)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');
}x = array([4., -5., 6.]), y = array([1., 2., 3.])
static void copy(NDArray x, NDArray y)y = x
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');
}y = array([1., 2., 3.])
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).
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');
}x = array([0.8660254, 0.5, -0.8660254]) y = array([-0.5, 0.8660254, 0.5])
static (double, double, double) rotg(double a, double b)(c, s, r) with [c s; -s c] [a; b] = [r; 0].
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}');
}r = 5.0, c = 0.6, s = 0.8 rotates (3, 4) to (r, 0): 5.0, -4.440892098500626e-16
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}.
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');
}A x = array([3., 4.]) Aᵀ (1, 2) = array([1., 4., 6.])
static void ger(double alpha, NDArray x, NDArray y, NDArray a)A + = \alpha x y^{T}
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);
}array([[1., 0., -1.],
[2., 0., -2.],
[3., 0., -3.]])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).
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');
}S x = array([1., -2.])
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).
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');
}solved in place: array([1., 2.])
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).
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');
}A Aᵀ =
array([[5., 2.],
[2., 10.]])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.
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');
}T⁻¹B =
array([[1., 2.],
[2., 2.]])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.
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');
}AᵀA =
array([[1., 2., 0.],
[2., 5., 3.],
[0., 3., 9.]])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).
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');
}3 S I =
array([[6., 3.],
[3., 6.]])LinAlgError
class LinAlgError implements Exception
A linear-algebra failure: singular matrix, not positive definite, no convergence (NumPy's LinAlgError).
Constructors
LinAlgError(this.message)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'));
}caught: singular matrix LinAlgError: custom message
Properties
final String messageMethods
String toString()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'));
}LinAlgError: matrix is singular
EighResult
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
final NDArray valuesfinal NDArray? vectorsSchurResult
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
final NDArray tfinal NDArray zEigResult
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
final NDArray valuesfinal NDArray? vectorsLUDecomposition
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
final int rowsfinal int colsNDArray get packedL and U packed in one m \times n array (L's unit diagonal not stored), NumPy/SciPy lu_factor layout.
NDArray get lNDArray get uMethods
NDArray solve(NDArray b)Solves A x = b for a vector or a matrix of right-hand sides.
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))}');
}
}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.])
NDArray inverse()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))}');
}array([[0.6, -0.7],
[-0.2, 0.4]])
A·A⁻¹ == I: trueLDLDecomposition
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
final int nMethods
NDArray solve(NDArray b)Solves A x = b.
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)}');
}x = array([0.5, 0.]), A x = array([2., 1.])
CpuGemmF32
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
const CpuGemmF32()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}');
}name: cpu-f32 x = array([0.090909091, 0.63636364]), steps 0
Properties
String get nameint get minWorkDType get computeTypeMethods
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})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)}');
}float32 products: array([[0.07, 0.1],
[0.15000001, 0.22000001]])
float64: array([[0.07, 0.1],
[0.15, 0.22]])RefinedSolve
final class RefinedSolve
The result of solveRefined.
Properties
final bool fellBackTrue 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}}).
QRDecomposition
final class QRDecomposition
A = Q R.
Properties
final NDArray? qOrthonormal columns (m \times k for 'reduced', m \times m for 'complete'; null for mode 'r').
SVDResult
final class SVDResult
A = U \operatorname{diag}(S) V^{T} (V^{T} is vt); S descending, non-negative.
Properties
final NDArray? um \times k ('reduced') or m \times m ('full'); null when only values were asked for.
final NDArray sfinal NDArray? vtNativeLinalg
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
const NativeLinalg()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';
}a custom backend named probe inside using(): probe
Properties
String get name"accelerate", "raya-native", "raya-native x6" (for logs and benchmark tables).
Methods
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.
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';
}allocate -> null (null: use an ordinary Float64List) solve with the probe installed: array([0.090909091, 0.63636364])
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.
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';
}dgemm -> false (false: the portable kernel runs) solve with the probe installed: array([0.090909091, 0.63636364])
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.
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';
}sgemm -> false (false: the portable kernel runs) solve with the probe installed: array([0.090909091, 0.63636364])
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.
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';
}zgemm -> false (false: the portable kernel runs) solve with the probe installed: array([0.090909091, 0.63636364])
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).
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';
}dgemvT -> false (false) solve with the probe installed: array([0.090909091, 0.63636364])
(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.
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';
}getrf -> null (null: getrf runs in Raya) solve with the probe installed: array([0.090909091, 0.63636364])
(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.
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';
}sgetrf -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
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).
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';
}luSolve -> false (false) solve with the probe installed: array([0.090909091, 0.63636364])
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.
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';
}potrf -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
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.
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';
}qr -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
(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.
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';
}syevd -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
(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.
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';
}gesdd -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
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.
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';
}gees -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
(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.
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';
}geev -> null (null) solve with the probe installed: array([0.090909091, 0.63636364])
Linalg
abstract final class Linalg
The backend the linear algebra uses. Set backend to choose one (null: everywhere).
Static
static set backend(NativeLinalg? b)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';
}backend now: probe det still works: array(8.) after null: raya
static T using<T>(NativeLinalg? b, T Function() f)Runs f with b as the backend (null:), then restores the previous one.
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';
}inside: probe outside again: restored
static Map<String, NativeLinalg> available()The backends available on this platform by name ("accelerate", "native", "native-parallel"), for tests and benchmarks.
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(', ')}');
}native backends here: accelerate, native, native-parallel