Passa al contenuto principale

Guida 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.

ParameterTypeDescription
wasmBytes?WasmBytesOptional 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.

ParameterTypeDescription
wasmBytes?WasmBytesOptional 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.

ParameterTypeDescription
options?WasmatrixOptionsPartial 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.

OptionTypeDefaultDescription
cacheLimitBytesnumber64 * 1024 * 1024Maximum 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.
fastMathbooleanfalseEnables 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.

ParameterTypeDescription
rowsnumberPositive row count.
colsnumberPositive 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

PropertyTypeDescription
byteOffsetreadonly numberByte offset of the materialized matrix buffer inside WASM memory. Accessing this property can force lazy views or expressions to materialize.
colsreadonly numberNumber of matrix columns.
datareadonly Float32ArraySnapshot copied from WASM memory when accessed. Mutating the returned typed array does not mutate the matrix. Use Matrix.set for scalar in-place writes.
lengthreadonly numberTotal number of elements, equal to rows * cols.
rowsreadonly numberNumber of matrix rows.
shapereadonly [number, number]Matrix shape as [rows, cols].

Static Methods

Matrix.configure(options?)

Matrix.configure(options?: WasmatrixOptions): void

Equivalent to the top-level configure helper.

ParameterTypeDescription
options?WasmatrixOptions-

Matrix.diagonal(values)

Matrix.diagonal(values: Matrix | ArrayLike<number>): Matrix

Creates a dense diagonal matrix from vector values.

ParameterTypeDescription
valuesMatrix | 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.

ParameterTypeDescription
rowsnumberPositive row count.
colsnumberPositive column count.
valuesArrayLike<number>Row-major values with length rows * cols.

Matrix.identity(size)

Matrix.identity(size: number): Matrix

Creates an identity matrix.

ParameterTypeDescription
sizenumber-

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.

ParameterTypeDescription
matricesMatrix[]-

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.

ParameterTypeDescription
matricesMatrix[]-

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.

ParameterTypeDescription
rowsnumber-
colsnumber-

Matrix.outer(a, b)

Matrix.outer(a: Matrix | ArrayLike<number>, b: Matrix | ArrayLike<number>): Matrix

Computes the outer product of two vectors.

ParameterTypeDescription
aMatrix | ArrayLike<number>Left vector.
bMatrix | 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.

ParameterTypeDescription
rowsnumberPositive row count.
colsnumberPositive column count.
rng?() => numberFunction returning each generated element. Defaults to Math.random.

Matrix.zeros(rows, cols)

Matrix.zeros(rows: number, cols: number): Matrix

Creates a zero-filled matrix.

ParameterTypeDescription
rowsnumber-
colsnumber-

Reading And Writing

at(row, col)

at(row: number, col: number): number

Reads one scalar value from row, col.

ParameterTypeDescription
rownumber-
colnumber-

set(row, col, value)

set(row: number, col: number, value: number): this

Writes one scalar value in place.

ParameterTypeDescription
rownumber-
colnumber-
valuenumber-

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.

ParameterTypeDescription
indexnumber-

column(index)

column(index: number): Float32Array

Copies one column into a JavaScript Float32Array.

ParameterTypeDescription
indexnumber-

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.

ParameterTypeDescription
rowsnumber-
colsnumber-

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.

ParameterTypeDescription
othernumber | 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.

ParameterTypeDescription
valuenumber-

subtract(other)

subtract(other: number | Matrix): Matrix

Subtracts a scalar, full matrix, row vector, or column vector.

ParameterTypeDescription
othernumber | Matrix-

Remarks: Scalar subtraction lowers to an affine lazy expression.

scale(value)

scale(value: number): Matrix

Multiplies every element by a scalar lazily.

ParameterTypeDescription
valuenumber-

multiply(other)

multiply(other: number | Matrix): Matrix

Multiplies by another value.

ParameterTypeDescription
othernumber | 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.

ParameterTypeDescription
othernumber | Matrix-

Remarks: Division follows JavaScript/WASM floating-point behavior for zero, NaN, and infinities.

hadamard(other)

hadamard(other: Matrix): Matrix

Elementwise matrix multiplication.

ParameterTypeDescription
otherMatrix-

Remarks: Supports full-shape operands and row/column broadcasts.

elementMultiply(other)

elementMultiply(other: Matrix): Matrix

Alias for Matrix.hadamard.

ParameterTypeDescription
otherMatrix-

min(other)

min(other: Matrix): Matrix

Elementwise minimum with a full or broadcast-compatible matrix.

ParameterTypeDescription
otherMatrix-

max(other)

max(other: Matrix): Matrix

Elementwise maximum with a full or broadcast-compatible matrix.

ParameterTypeDescription
otherMatrix-

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.

ParameterTypeDescription
minValuenumber-
maxValuenumber-

Throws: RangeError if minValue > maxValue.

map(fn)

map(fn: (value: number, row: number, col: number) => number): Matrix

Applies a JavaScript callback to every element.

ParameterTypeDescription
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.

ParameterTypeDescription
otherMatrix-

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.

ParameterTypeDescription
vectorMatrix | 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.

ParameterTypeDescription
otherMatrix | 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.

minValue()

minValue(): number

Returns the minimum element, cached by matrix version.

maxValue()

maxValue(): number

Returns the maximum element, cached by matrix version.

trace()

trace(): number

Returns the trace of the matrix.

Remarks: For some lazy products, the trace can be computed without materializing the full dense product.

frobeniusNorm()

frobeniusNorm(): number

Returns the Frobenius norm, cached by matrix version.

Linear Algebra

determinant()

determinant(): number

Computes the determinant of a square matrix.

Remarks: Uses structural shortcuts, Cholesky for SPD-tagged matrices when available, and LU factorization otherwise. Results are cached by matrix version.

Throws: RangeError if the matrix is not square.

logDet()

logDet(): number

Computes the natural log of a positive determinant.

Remarks: Returns NaN when the available path determines that the determinant is not positive.

inverse()

inverse(): Matrix

Returns an inverse view where possible.

Remarks: The dense inverse is avoided until required. Expressions such as A.inverse().matmul(B) lower to A.solve(B).

solve(rhs)

solve(rhs: Matrix | ArrayLike<number>): Matrix

Solves this * X = rhs.

ParameterTypeDescription
rhsMatrix | ArrayLike<number>-

Remarks: Square systems use diagonal, Cholesky, or LU paths depending on structure. Factorizations are cached by matrix version and reused across compatible determinant, solve, and inverse operations.

Throws: RangeError if the matrix is not square, the RHS shape is invalid, or the system is singular.

leastSquares(rhs)

leastSquares(rhs: Matrix | ArrayLike<number>): Matrix

Solves a least-squares system for tall or square matrices.

ParameterTypeDescription
rhsMatrix | ArrayLike<number>-

Remarks: Uses QR factorization and shares the QR cache with Matrix.rank.

Throws: RangeError if rows < cols, the RHS shape is invalid, or the matrix is rank deficient.

rank(epsilon?)

rank(epsilon?: number): number

Estimates matrix rank with a QR factorization.

ParameterTypeDescription
epsilon?numberAbsolute threshold for nonzero diagonal entries of R.

Memory Management

dispose()

dispose(): void

Releases WASM memory and cached resources owned by this matrix.

Remarks: Calling dispose() more than once is safe. Do not use the matrix after it has been disposed.

[Symbol.dispose]()

[Symbol.dispose](): void

Integrates with runtimes that support explicit resource management.

Utilities

equalsApprox(other, epsilon?)

equalsApprox(other: Matrix, epsilon?: number): boolean

Compares matrices with an absolute tolerance.

ParameterTypeDescription
otherMatrixMatrix with the same shape.
epsilon?numberAbsolute tolerance. Defaults to 1e-6.

toString()

toString(): string

Formats the matrix as tab-separated rows.