API 指南
The default export is the Matrix class. Named exports include runtime helpers and global configuration.
import Matrix, {
SIMD_REQUIRED,
configure,
createRuntime,
isSimdSupported
} from "wasmatrix";
This page is generated from the TSDoc comments in index.d.ts, which is copied to dist/index.d.ts during the package build.
Runtime Helpers
SIMD_REQUIRED
const SIMD_REQUIRED: true
Whether this package requires WebAssembly SIMD support.
Remarks: This is always true. WASMatrix does not ship a scalar fallback.
isSimdSupported(wasmBytes?)
isSimdSupported(wasmBytes?: WasmBytes): boolean
Checks whether the current JavaScript runtime validates WASMatrix's SIMD WASM.
| Parameter | Type | Description |
|---|---|---|
wasmBytes? | WasmBytes | Optional explicit WASM bytes. When omitted, the default package WASM bytes loaded by the ESM entrypoint are used. |
Returns: true when WebAssembly.validate() accepts the bytes.
createRuntime(wasmBytes?)
createRuntime(wasmBytes?: WasmBytes): unknown
Creates a separate WASM runtime instance.
| Parameter | Type | Description |
|---|---|---|
wasmBytes? | WasmBytes | Optional explicit WASM bytes. When omitted, the default package WASM bytes loaded by the ESM entrypoint are used. |
Remarks: Most users should use the default runtime initialized by the package entrypoint. Separate runtimes are useful only when you intentionally want isolated WASM memories and caches.
Returns: An opaque runtime handle used internally by matrix instances.
Throws: Error if no default WASM bytes are loaded.
Throws: Error if SIMD validation or the ABI probe fails.
configure(options?)
configure(options?: WasmatrixOptions): void
Configures global optimization behavior.
| Parameter | Type | Description |
|---|---|---|
options? | WasmatrixOptions | Partial options to update. |
Remarks: Existing matrices keep their data, but cache sizing changes can evict cached buffers immediately.
Configuration Options
Process-wide optimization and cache options.
| Option | Type | Default | Description |
|---|---|---|---|
cacheLimitBytes | number | 64 * 1024 * 1024 | Maximum WASM heap budget used by reusable caches. The limit covers factorization, transpose, packed operand, reduction, and expression-result caches. Set to 0 to aggressively evict reusable cache entries. |
fastMath | boolean | false | Enables more aggressive algebraic rewrites. Keep this disabled when NaN, Infinity, -0, and strict floating-point rounding behavior are observable in your workflow. |
WasmBytes
type WasmBytes = ArrayBuffer | ArrayBufferView
Raw WebAssembly module bytes accepted by runtime helpers.
Matrix
Dense row-major f32 matrix backed by WASM memory.
Remarks: Most operations return another Matrix. Data stays in WASM memory until you call a readback method such as Matrix.toArray, Matrix.toFloat32Array, Matrix.row, or Matrix.column.
Constructor
new Matrix(rows, cols, data?, options?)
new Matrix(rows: number, cols: number, data?: ArrayLike<number>, options?: { copy?: boolean })
Creates a matrix from row-major values.
| Parameter | Type | Description |
|---|---|---|
rows | number | Positive row count. |
cols | number | Positive column count. |
data? | ArrayLike<number> | Optional row-major values. Omitted values create a zero matrix. |
options? | { copy?: boolean } | Reserved construction options. |
Throws: RangeError if rows, cols, or data.length are invalid.
Properties
| Property | Type | Description |
|---|---|---|
byteOffset | readonly number | Byte offset of the materialized matrix buffer inside WASM memory. Accessing this property can force lazy views or expressions to materialize. |
cols | readonly number | Number of matrix columns. |
data | readonly Float32Array | Snapshot copied from WASM memory when accessed. Mutating the returned typed array does not mutate the matrix. Use Matrix.set for scalar in-place writes. |
length | readonly number | Total number of elements, equal to rows * cols. |
rows | readonly number | Number of matrix rows. |
shape | readonly [number, number] | Matrix shape as [rows, cols]. |
Static Methods
Matrix.configure(options?)
Matrix.configure(options?: WasmatrixOptions): void
Equivalent to the top-level configure helper.
| Parameter | Type | Description |
|---|---|---|
options? | WasmatrixOptions | - |
Matrix.diagonal(values)
Matrix.diagonal(values: Matrix | ArrayLike<number>): Matrix
Creates a dense diagonal matrix from vector values.
| Parameter | Type | Description |
|---|---|---|
values | Matrix | ArrayLike<number> | - |
Remarks: Diagonal structure is tracked for determinant, solve, inverse, and diagonal matrix multiplication shortcuts.
Matrix.from(rows, cols, values)
Matrix.from(rows: number, cols: number, values: ArrayLike<number>): Matrix
Creates a matrix from row-major values.
| Parameter | Type | Description |
|---|---|---|
rows | number | Positive row count. |
cols | number | Positive column count. |
values | ArrayLike<number> | Row-major values with length rows * cols. |
Matrix.identity(size)
Matrix.identity(size: number): Matrix
Creates an identity matrix.
| Parameter | Type | Description |
|---|---|---|
size | number | - |
Remarks: Identity structure is tracked so operations such as I.matmul(A) can use structural shortcuts.
Matrix.matmulChain(...matrices)
Matrix.matmulChain(...matrices: Matrix[]): Matrix
Multiplies a compatible chain of matrices using a shape-based cost model.
| Parameter | Type | Description |
|---|---|---|
matrices | Matrix[] | - |
Remarks: The chain order is chosen by dynamic programming over matrix dimensions. Intermediate products are materialized and disposed where possible.
Matrix.matmulChain(matrices)
Matrix.matmulChain(matrices: Matrix[]): Matrix
Multiplies a compatible chain of matrices using a shape-based cost model.
| Parameter | Type | Description |
|---|---|---|
matrices | Matrix[] | - |
Remarks: Array overload for callers that already hold the chain in a collection.
Matrix.ones(rows, cols)
Matrix.ones(rows: number, cols: number): Matrix
Creates a one-filled matrix.
| Parameter | Type | Description |
|---|---|---|
rows | number | - |
cols | number | - |
Matrix.outer(a, b)
Matrix.outer(a: Matrix | ArrayLike<number>, b: Matrix | ArrayLike<number>): Matrix
Computes the outer product of two vectors.
| Parameter | Type | Description |
|---|---|---|
a | Matrix | ArrayLike<number> | Left vector. |
b | Matrix | ArrayLike<number> | Right vector. |
Returns: A matrix with shape a.length x b.length.
Matrix.random(rows, cols, rng?)
Matrix.random(rows: number, cols: number, rng?: () => number): Matrix
Creates a matrix using a random value generator.
| Parameter | Type | Description |
|---|---|---|
rows | number | Positive row count. |
cols | number | Positive column count. |
rng? | () => number | Function returning each generated element. Defaults to Math.random. |
Matrix.zeros(rows, cols)
Matrix.zeros(rows: number, cols: number): Matrix
Creates a zero-filled matrix.
| Parameter | Type | Description |
|---|---|---|
rows | number | - |
cols | number | - |
Reading And Writing
at(row, col)
at(row: number, col: number): number
Reads one scalar value from row, col.
| Parameter | Type | Description |
|---|---|---|
row | number | - |
col | number | - |
set(row, col, value)
set(row: number, col: number, value: number): this
Writes one scalar value in place.
| Parameter | Type | Description |
|---|---|---|
row | number | - |
col | number | - |
value | number | - |
Remarks: This increments the matrix version and invalidates cached factorizations, reductions, materialized views, and packed operands.
Returns: This matrix.
row(index)
row(index: number): Float32Array
Copies one row into a JavaScript Float32Array.
| Parameter | Type | Description |
|---|---|---|
index | number | - |
column(index)
column(index: number): Float32Array
Copies one column into a JavaScript Float32Array.
| Parameter | Type | Description |
|---|---|---|
index | number | - |
diagonal()
diagonal(): Float32Array
Copies the main diagonal into a JavaScript Float32Array.
Remarks: The diagonal snapshot is cached by matrix version.
reshape(rows, cols)
reshape(rows: number, cols: number): Matrix
Creates a reshaped copy with the same element count.
| Parameter | Type | Description |
|---|---|---|
rows | number | - |
cols | number | - |
Throws: RangeError if rows * cols !== this.length.
toFloat32Array()
toFloat32Array(): Float32Array
Copies matrix contents into a JavaScript Float32Array.
toFlatArray()
toFlatArray(): number[]
Copies matrix contents into a row-major JavaScript number array.
toArray()
toArray(): number[][]
Copies matrix contents into nested JavaScript row arrays.
Elementwise Operations
add(other)
add(other: number | Matrix): Matrix
Adds a scalar, full matrix, row vector, or column vector.
| Parameter | Type | Description |
|---|---|---|
other | number | Matrix | - |
Remarks: Row vectors have shape 1 x cols; column vectors have shape rows x 1. Elementwise chains are represented lazily and fused when materialized.
addScalar(value)
addScalar(value: number): Matrix
Adds a scalar to every element lazily.
| Parameter | Type | Description |
|---|---|---|
value | number | - |
subtract(other)
subtract(other: number | Matrix): Matrix
Subtracts a scalar, full matrix, row vector, or column vector.
| Parameter | Type | Description |
|---|---|---|
other | number | Matrix | - |
Remarks: Scalar subtraction lowers to an affine lazy expression.
scale(value)
scale(value: number): Matrix
Multiplies every element by a scalar lazily.
| Parameter | Type | Description |
|---|---|---|
value | number | - |
multiply(other)
multiply(other: number | Matrix): Matrix
Multiplies by another value.
| Parameter | Type | Description |
|---|---|---|
other | number | Matrix | - |
Remarks: A numeric argument scales elementwise. A broadcast-compatible matrix uses elementwise multiplication. Other matrix arguments use matrix multiplication.
divide(other)
divide(other: number | Matrix): Matrix
Divides by a scalar, full matrix, row vector, or column vector.
| Parameter | Type | Description |
|---|---|---|
other | number | Matrix | - |
Remarks: Division follows JavaScript/WASM floating-point behavior for zero, NaN, and infinities.
hadamard(other)
hadamard(other: Matrix): Matrix
Elementwise matrix multiplication.
| Parameter | Type | Description |
|---|---|---|
other | Matrix | - |
Remarks: Supports full-shape operands and row/column broadcasts.
elementMultiply(other)
elementMultiply(other: Matrix): Matrix
Alias for Matrix.hadamard.
| Parameter | Type | Description |
|---|---|---|
other | Matrix | - |
min(other)
min(other: Matrix): Matrix
Elementwise minimum with a full or broadcast-compatible matrix.
| Parameter | Type | Description |
|---|---|---|
other | Matrix | - |
max(other)
max(other: Matrix): Matrix
Elementwise maximum with a full or broadcast-compatible matrix.
| Parameter | Type | Description |
|---|---|---|
other | Matrix | - |
negate()
negate(): Matrix
Negates every element lazily.
abs()
abs(): Matrix
Applies absolute value lazily.
sqrt()
sqrt(): Matrix
Applies square root lazily.
floor()
floor(): Matrix
Applies floor lazily.
ceil()
ceil(): Matrix
Applies ceiling lazily.
clamp(minValue, maxValue)
clamp(minValue: number, maxValue: number): Matrix
Clamps every element into [minValue, maxValue] lazily.
| Parameter | Type | Description |
|---|---|---|
minValue | number | - |
maxValue | number | - |
Throws: RangeError if minValue > maxValue.
map(fn)
map(fn: (value: number, row: number, col: number) => number): Matrix
Applies a JavaScript callback to every element.
| Parameter | Type | Description |
|---|---|---|
fn | (value: number, row: number, col: number) => number | - |
Remarks: This reads the matrix into JavaScript and writes a new WASM-backed matrix. Prefer built-in elementwise methods when possible.
Matrix Operations
transpose()
transpose(): Matrix
Returns a lazy transpose view.
Remarks: The transposed buffer is materialized only when an operation requires a concrete layout. A.transpose().transpose() collapses back to A.
matmul(other)
matmul(other: Matrix): Matrix
Matrix multiplication.
| Parameter | Type | Description |
|---|---|---|
other | Matrix | - |
Remarks: Transpose-aware kernels, diagonal shortcuts, identity/zero propagation, inverse-view solves, Gram/SPD tags, and packed operand caches may be used according to shape and structure.
matvec(vector)
matvec(vector: Matrix | ArrayLike<number>): Float32Array
Multiplies this matrix by a vector.
| Parameter | Type | Description |
|---|---|---|
vector | Matrix | ArrayLike<number> | Array-like or matrix vector with length equal to cols. |
Returns: A copied JavaScript Float32Array with length rows.
dot(other)
dot(other: Matrix | ArrayLike<number>): number
Computes the dot product with another vector-like value.
| Parameter | Type | Description |
|---|---|---|
other | Matrix | ArrayLike<number> | - |
Remarks: Both operands are flattened row-major and must have the same length.
clone()
clone(): Matrix
Creates a deep copy with its own WASM buffer.
Remarks: Lazy views are materialized before copying.
Reductions
sum()
sum(): number
Sums all elements, cached by matrix version.