Skip to content

deepbox/ndarray

Sparse, FFT & Advanced Ops

CSRMatrix, einsum, FFTs, convolution and window functions, NaN-aware reductions, unique, advanced indexing, and im2col helpers.

  • Sparse
  • FFT
  • einsum

Overview

  • CSRMatrix stores float64 values in compressed sparse row form. Build one with CSRMatrix.fromDense or CSRMatrix.fromCOO. It supports add, sub, scale, multiply, matvec, matmul with a dense tensor, spmm, transpose and toDense. deepbox/linalg can solve sparse systems.
  • FFT functions return { real, imag } tensors, because tensors cannot hold complex values yet. ifft and irfft take the two parts as separate arguments. norm is "backward" (default), "ortho" or "forward", as in NumPy, and rfft keeps only the non-negative frequencies.
  • einsum supports explicit and implicit subscripts, any number of operands, repeated labels (diagonals and traces) and ... broadcasting. It accumulates in float64. The result is float32 when every operand is float32, int32 when every operand is int32, and float64 otherwise.
  • convolve and correlate take 1-D inputs, follow NumPy and return float64. The nan* reductions skip NaN. unique returns an object with values and, depending on options, indices, inverse and counts.
  • dropoutMask, im2col and col2im are low-level helpers used by the nn layers, and application code rarely needs them.

Types

13

ConvolveMode

type

Boundary handling for convolve and correlate.

type ConvolveMode = "full" | "same" | "valid";

CrossOptions

interface

Options of cross.

  • readonly axis?: Axis

    Axis that holds the three vector components (default: -1).

HistogramOptions

interface

Options of histogram.

  • readonly density?: boolean

    Return the probability density instead of counts (the histogram integrates to 1).

  • readonly weights?: Tensor

    Weight of each sample; must have the same shape as the input.

LikeOptions

interface

Options shared by the *_like creation functions.

  • readonly dtype?: DType

    Result dtype.

PadMode

type

Padding modes accepted by pad.

- "constant": fill with a constant value - "reflect": mirror the tensor without repeating the edge value - "symmetric": mirror the tensor including the edge value - "replicate" (alias "edge"): repeat the edge value - "circular" (alias "wrap"): wrap around to the opposite side

type PadMode = "constant" | "reflect" | "symmetric" | "replicate" | "edge" | "circular" | "wrap";

PadWidth

type

Padding amounts accepted by pad.

type PadWidth = number | readonly [    number,    number] | ReadonlyArray<readonly [    number,    number]>;

UniqueOptions

interface

Options of unique.

  • readonly returnIndex?: boolean

    Also return the index of the first occurrence of each unique value (int32).

  • readonly returnInverse?: boolean

    Also return the indices that rebuild the input from the unique values (int32).

  • readonly returnCounts?: boolean

    Also return how many times each unique value occurs (int32).

  • readonly axis?: Axis

    Find unique sub-tensors along this axis instead of unique elements of the flattened input.

UniqueOutput

type

UniqueResult with the fields requested through the literal options made required.

type UniqueOutput<O extends UniqueOptions> = UniqueResult & (O extends {    readonly returnIndex: true;} ? {    indices: Tensor;} : unknown) & (O extends {    readonly returnInverse: true;} ? {    inverse: Tensor;} : unknown) & (O extends {    readonly returnCounts: true;} ? {    counts: Tensor;} : unknown);

UniqueResult

interface

Result of unique when called with an options object.

  • values: Tensor

    Sorted unique values (or sub-tensors), same dtype as the input.

  • indices?: Tensor

    First-occurrence index of each unique value; present with returnIndex.

  • inverse?: Tensor

    Position of each input element (or sub-tensor) in values; present with returnInverse.

  • counts?: Tensor

    Number of occurrences of each unique value; present with returnCounts.

WindowOptions

type

Options shared by the window functions.

  • readonly periodic?: boolean

    Build the periodic window (length n of an n + 1 point symmetric window with the last point dropped) instead of the symmetric one.

FFTNorm

type

Normalization mode of an FFT, matching NumPy's norm argument.

- "backward" (default): the forward transform is unscaled and the inverse is scaled by 1/n. - "ortho": both directions are scaled by 1/sqrt(n) (unitary transform). - "forward": the forward transform is scaled by 1/n and the inverse is unscaled.

type FFTNorm = "backward" | "ortho" | "forward";

FFTResult

interface

Result of an FFT operation: real and imaginary parts as separate tensors.

  • real: Tensor
  • imag: Tensor

CSRMatrixInit

type

Initialization data for constructing a CSRMatrix.

  • readonly data: Float64Array
  • readonly indices: Int32Array
  • readonly indptr: Int32Array
  • readonly shape: Shape

Classes

1

CSRMatrix

Compressed Sparse Row (CSR) matrix representation.

CSR format stores a sparse matrix using three arrays: - data: Non-zero values in row-major order - indices: Column indices of non-zero values - indptr: Row pointers (indptr[i] to indptr[i+1] gives the range of data/indices for row i)

This format is efficient for: - Row slicing - Matrix-vector products - Arithmetic operations

The constructor stores the arrays it is given without copying. Column indices within a row should be strictly increasing (canonical form, see CSRMatrix.hasCanonicalFormat); all methods also give the right result for unsorted rows or repeated column indices, treating repeated entries as a sum as SciPy does, but get and getCol are faster on canonical input. Results produced by the arithmetic methods are always canonical.

Only entries that are stored take part in matvec, matmul, multiply and spmm, so a NaN or Infinity in the dense operand does not propagate through a structural zero.

Example
import { CSRMatrix } from 'deepbox/ndarray'; // Create a 3x3 sparse matrix with values at (0,0)=1, (1,2)=2, (2,1)=3const sparse = CSRMatrix.fromCOO({  rows: 3, cols: 3,  rowIndices: new Int32Array([0, 1, 2]),  colIndices: new Int32Array([0, 2, 1]),  values: new Float64Array([1, 2, 3])}); // Convert to dense for operationsconst dense = sparse.toDense();
Members (28)
  • constructor(init: CSRMatrixInit)
  • readonly data: Float64Array
  • readonly indices: Int32Array
  • readonly indptr: Int32Array
  • readonly shape: Shape
  • nnz: number

    Number of stored entries (explicitly stored zeros included).

  • rows: number

    Number of rows in the matrix

  • cols: number

    Number of columns in the matrix

  • hasCanonicalFormat: boolean

    Whether column indices are strictly increasing within every row (sorted, no repeated entries).

  • toDense(): Tensor

    Convert the sparse matrix to a dense Tensor.

  • static fromDense(dense: Tensor): CSRMatrix

    Create a CSR matrix from a dense 2D tensor, storing every entry that is not exactly zero.

  • canonicalize(): CSRMatrix

    Return an equivalent matrix in canonical form: columns sorted within each row and repeated entries summed.

  • add(other: CSRMatrix): CSRMatrix

    Add two sparse matrices element-wise.

  • sub(other: CSRMatrix): CSRMatrix

    Subtract another sparse matrix element-wise.

  • scale(scalar: number): CSRMatrix

    Multiply all elements by a scalar value.

  • multiply(other: CSRMatrix): CSRMatrix

    Element-wise multiplication (Hadamard product) with another sparse matrix.

  • matvec(vector: Tensor | Float64Array): Tensor

    Matrix multiplication with a dense vector.

  • matmul(dense: Tensor): Tensor

    Matrix multiplication with a dense matrix.

  • transpose(): CSRMatrix

    Transpose the sparse matrix.

  • get(row: number, col: number): number

    Get a specific element from the matrix.

  • copy(): CSRMatrix

    Create a copy of this matrix.

  • spmm(other: CSRMatrix): CSRMatrix

    Sparse-sparse matrix multiplication.

  • sliceRows(start: number, end: number): CSRMatrix

    Extract a contiguous range of rows as a new CSRMatrix.

  • getRow(row: number): Float64Array

    Extract a single row as a 1D dense Float64Array.

  • getCol(col: number): Float64Array

    Extract a single column as a 1D dense Float64Array.

  • static eye(n: number): CSRMatrix

    Create a sparse identity matrix.

  • static diag(values: Float64Array): CSRMatrix

    Create a sparse diagonal matrix from values.

  • static fromCOO(args: { readonly rows: number; readonly cols: number; readonly rowIndices: Int32Array; readonly colIndices: Int32Array; readonly values: Float64Array; readonly sort?: boolean; }): CSRMatrix

    Create a sparse matrix from COO (Coordinate List) format.

Functions

68

col2im

function col2im(cols: Tensor, inputShape: Shape, kernelSize: [ number, number ], stride: [ number, number ], padding: [ number, number ]): Tensor;

Column to Image operation (col2im).

Rearranges columns back into image blocks, summing values where windows overlap. This is the adjoint of im2col and is used for gradients. The output keeps the dtype of cols.

Parameters

cols
Tensor
Column tensor of shape (batch, outH * outW, channels * kH * kW)
inputShape
Shape
Shape of the original image (batch, channels, height, width)
kernelSize
[ number, number ]
Size of the kernel [kH, kW]
stride
[ number, number ]
Stride [sH, sW]
padding
[ number, number ]
Padding [pH, pW]

Returns

TensorGradient tensor of shape inputShape

Throws

  • ShapeErrorIf cols is not 3-D, inputShape does not have 4 entries, or the column shape does not match the geometry
  • DTypeErrorIf cols has string dtype
  • InvalidParameterErrorIf a parameter is invalid or the kernel does not fit the image

im2col

function im2col(input: Tensor, kernelSize: [ number, number ], stride: [ number, number ], padding: [ number, number ]): Tensor;

Image to Column operation (im2col).

Rearranges image blocks into columns. Positions that fall in the padding are zero. The output keeps the input dtype.

Parameters

input
Tensor
Input tensor of shape (batch, channels, height, width)
kernelSize
[ number, number ]
Size of the kernel [kH, kW]
stride
[ number, number ]
Stride [sH, sW]
padding
[ number, number ]
Padding [pH, pW]

Returns

TensorOutput tensor of shape (batch, outH * outW, channels * kH * kW)

Throws

  • ShapeErrorIf input is not 4-D
  • DTypeErrorIf input has string dtype
  • InvalidParameterErrorIf a parameter is invalid or the kernel does not fit the input
Example
const x = tensor([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]);   // (1, 1, 3, 3)im2col(x, [2, 2], [1, 1], [0, 0]).shape;                    // [1, 4, 4]

einsum

function einsum(subscripts: string, ...tensors: Tensor[]): Tensor;

Einstein summation convention.

Details

Supports explicit ("ij,jk->ik") and implicit ("ij,jk") subscripts, any number of operands, repeated labels within one operand (diagonals and traces), and ... for broadcast dimensions. Dimensions of size 1 broadcast against larger dimensions that share their label, as in NumPy.

Common patterns: - "ij,jk->ik" (matrix multiply) - "ii->i" (diagonal) - "ii->" (trace) - "ij->ji" (transpose) - "i,i->" (dot product) - "ij,j->i" (matrix-vector multiply) - "...ij,...jk->...ik" (batched matrix multiply)

In implicit mode the output holds the labels that appear exactly once, in alphabetical order (uppercase before lowercase), preceded by any ellipsis dimensions.

The result is float32 when every operand is float32, int32 when every operand is int32, and float64 otherwise. Products are accumulated in float64. int64 operands are converted to doubles (exact up to 2^53).

Parameters

subscripts
string
Subscript string in Einstein notation
tensors
Tensor[]
Input tensors

Returns

TensorResult tensor

Throws

  • InvalidParameterErrorIf the subscripts are malformed or do not match the operand count
  • ShapeErrorIf an operand's rank does not match its subscript or label sizes conflict
  • DTypeErrorIf an operand has string dtype
Example
const a = tensor([[1, 2], [3, 4]]);einsum("ij,jk->ik", a, a);  // [[7, 10], [15, 22]]einsum("ii->", a);          // 5

argwhere

function argwhere(t: Tensor): Tensor;

Indices of the nonzero elements as one int32 matrix (like np.argwhere). Row i holds the coordinates of the i-th nonzero element in row-major order. NaN counts as nonzero. A 0-d tensor gives shape [1, 0] when it is nonzero and [0, 0] otherwise.

Parameters

t
Tensor
Input tensor

Returns

Tensorint32 tensor of shape [count, t.ndim]

Throws

  • DTypeErrorIf t has string dtype
Example
argwhere(tensor([[0, 2], [3, 0]])); // [[0, 1], [1, 0]]

atleast1d

function atleast1d(t: Tensor): Tensor;

Ensure the input is at least 1-D. Scalars become shape [1]; higher-dimensional tensors pass through unchanged (the same tensor is returned).

Parameters

t
Tensor

Returns

Tensor

atleast2d

function atleast2d(t: Tensor): Tensor;

Ensure the input is at least 2-D. Scalars become shape [1,1]; 1-D tensors become shape [1,n]; others pass through unchanged (the same tensor is returned).

Parameters

t
Tensor

Returns

Tensor

bartlettWindow

function bartlettWindow(n: number, options?: WindowOptions): Tensor;

Bartlett (triangular) window with zero end points.

Matches np.bartlett(n).

Parameters

n
number
Number of points; a positive integer
optionsoptional
WindowOptions
{ periodic: true } for the periodic form

Returns

Tensorfloat64 tensor of shape [n]

Throws

  • InvalidParameterErrorIf n is not a positive integer
Example
bartlettWindow(5); // [0, 0.5, 1, 0.5, 0]

bincount

function bincount(t: Tensor, minlength?: number, weights?: Tensor): Tensor;

Count the occurrences of each value in a tensor of non-negative integers (flattened). The result is a float64 tensor of length max(max(t) + 1, minlength), or the sum of weights per value when given.

Parameters

t
Tensor
Input tensor of non-negative integers
minlengthoptional
number
Minimum output length (default: 0)
weightsoptional
Tensor
Optional weight per element, same number of elements as t

Returns

TensorTensor of counts

Throws

  • InvalidParameterErrorIf t has a negative or non-integer value, or minlength is invalid
  • ShapeErrorIf weights does not have the same size as t

blackmanWindow

function blackmanWindow(n: number, options?: WindowOptions): Tensor;

Blackman window.

w[i] = 0.42 - 0.5 * cos(2 * pi * i / (n - 1)) + 0.08 * cos(4 * pi * i / (n - 1)). Matches np.blackman(n).

Parameters

n
number
Number of points; a positive integer
optionsoptional
WindowOptions
{ periodic: true } for the periodic form

Returns

Tensorfloat64 tensor of shape [n]

Throws

  • InvalidParameterErrorIf n is not a positive integer
Example
blackmanWindow(5); // [-1.4e-17, 0.34, 1, 0.34, -1.4e-17]

booleanIndex

function booleanIndex(t: Tensor, mask: Tensor): Tensor;

Select elements from a tensor using a boolean mask. Returns a 1-D tensor of elements where the mask is true (nonzero, NaN included).

The mask is matched to t element by element in row-major order, so it must have the same number of elements as t (normally the same shape).

Parameters

t
Tensor
Input tensor
mask
Tensor
Boolean mask tensor (same shape as t)

Returns

Tensor1-D tensor of selected elements, in row-major order

Throws

  • ShapeErrorIf t and mask have a different number of elements
Example
const a = tensor([1, 2, 3, 4, 5]);const m = tensor([1, 0, 1, 0, 1], { dtype: 'bool' });booleanIndex(a, m); // [1, 3, 5]

broadcastTo

function broadcastTo(t: Tensor, shape: Shape): Tensor;

Broadcast a tensor to a target shape.

The result is a zero-copy view: broadcast axes get stride 0, so all elements along them alias the same buffer entry (like NumPy's broadcast_to). Call clone to get independent memory.

Parameters

t
Tensor
Input tensor
shape
Shape
Target shape

Returns

TensorBroadcast view of the tensor

Throws

  • ShapeErrorIf the target has fewer dimensions or an axis cannot be broadcast
  • InvalidParameterErrorIf the target shape has a negative or non-integer entry

clone

function clone(t: Tensor): Tensor;

Create a deep copy of a tensor with its own data buffer.

The returned tensor shares no data with the original and is always contiguous with offset 0, even when the input is a strided view.

Parameters

t
Tensor
Input tensor

Returns

TensorDeep copy of the tensor

Example
const a = tensor([1, 2, 3]);const b = clone(a);

contiguous

function contiguous(t: Tensor): Tensor;

Return a contiguous tensor. A tensor that is already contiguous and starts at offset 0 is returned as is (no copy); any other tensor is materialized into a new contiguous copy.

Parameters

t
Tensor
Input tensor

Returns

TensorContiguous tensor

convolve

function convolve(a: Tensor, v: Tensor, mode?: ConvolveMode): Tensor;

Discrete linear convolution of two 1-D tensors.

Matches np.convolve(a, v, mode). The result is a float64 tensor.

- "full" (default): every overlap, length a.size + v.size - 1 - "same": length max(a.size, v.size), centered with respect to "full" - "valid": only complete overlaps, length max(a.size, v.size) - min(a.size, v.size) + 1

Parameters

a
Tensor
First 1-D input
v
Tensor
Second 1-D input
modeoptional
ConvolveMode
Output size, default "full"

Returns

Tensorfloat64 tensor

Throws

  • InvalidParameterErrorIf an input is not a non-empty 1-D numeric tensor or mode is unknown
Example
convolve(tensor([1, 2, 3]), tensor([0, 1, 0.5])); // [0, 1, 2.5, 4, 1.5]

copy

function copy(t: Tensor): Tensor;

Create an explicit deep copy of a tensor (alias for clone).

Parameters

t
Tensor
Input tensor

Returns

TensorDeep copy of the tensor

correlate

function correlate(a: Tensor, v: Tensor, mode?: ConvolveMode): Tensor;

Cross-correlation of two 1-D tensors.

Matches np.correlate(a, v, mode): c[k] = sum_n a[n + k] * v[n], which is convolve(a, reversed(v), mode). The result is a float64 tensor.

Parameters

a
Tensor
First 1-D input
v
Tensor
Second 1-D input
modeoptional
ConvolveMode
Output size, default "full" (see convolve)

Returns

Tensorfloat64 tensor

Throws

  • InvalidParameterErrorIf an input is not a non-empty 1-D numeric tensor or mode is unknown
Example
correlate(tensor([1, 2, 3]), tensor([0, 1, 0.5])); // [0.5, 2, 3.5, 3, 0]

countNonzero

function countNonzero(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;

Count the nonzero elements (like np.count_nonzero). NaN counts as nonzero.

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis or axes to count along (default: all axes)
keepdimsoptional
boolean
Keep the counted axes as size-1 dimensions

Returns

Tensorint32 tensor of counts; 0-d when every axis is counted without keepdims

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or repeated
Example
const a = tensor([[1, 0, 3], [0, 0, 5]]);countNonzero(a); // 3countNonzero(a, 0); // [1, 0, 2]

cross

function cross(a: Tensor, b: Tensor, options?: CrossOptions | Axis): Tensor;

Compute the cross product of 3-element vectors (like np.cross).

Details

The vectors lie along axis (default: the last axis), which must have length 3 in both inputs. All other axes are batch axes that broadcast against each other under NumPy rules, so [N, 3] with [3] or [N, 1, 3] with [M, 3] work. The result has the broadcast batch shape and the vectors along the same axis position.

The result dtype is the promoted dtype of the inputs: float32 inputs give float32, float64 gives float64 (float16 with bfloat16 gives float32). Integer inputs give integer results (uint8, int32, or int64) that wrap on overflow, as in NumPy; bool counts as int32.

Parameters

a
Tensor
First tensor with a.shape[axis] === 3
b
Tensor
Second tensor with b.shape[axis] === 3
optionsoptional
CrossOptions | Axis
{ axis }, or the axis number itself (default: -1)

Returns

TensorCross product a x b

Throws

  • ShapeErrorIf an input is 0-d, the cross axis does not have length 3, or the batch axes do not broadcast
  • InvalidParameterErrorIf axis is out of range
  • DTypeErrorIf an input has string dtype
Example
cross(tensor([1, 0, 0]), tensor([0, 1, 0])); // [0, 0, 1] // Batched: every row of `a` crossed with the same vector.cross(tensor([[1, 0, 0], [0, 1, 0]]), tensor([0, 0, 1])); // [[0, -1, 0], [1, 0, 0]] // Vectors stored along axis 0.cross(tensor([[1, 0], [0, 1], [0, 0]]), tensor([[0, 0], [0, 0], [1, 1]]), { axis: 0 });

detach

function detach(t: Tensor): Tensor;

Create a copy of a tensor detached from any computation graph. Equivalent to clone: plain tensors carry no graph.

Parameters

t
Tensor
Input tensor

Returns

TensorDetached copy of the tensor

diag

function diag(t: Tensor, k?: number): Tensor;

Extract a diagonal or construct a diagonal matrix.

- If input is 1-D, returns a 2-D square matrix with the input on the k-th diagonal. - If input is 2-D, returns a copy of the k-th diagonal as a 1-D tensor.

Parameters

t
Tensor
Input tensor (1-D or 2-D)
koptional
number
Diagonal offset (0 = main, positive = above, negative = below)

Returns

TensorDiagonal tensor

Throws

  • ShapeErrorIf the input is not 1-D or 2-D
  • InvalidParameterErrorIf k is not an integer
Example
diag(tensor([1, 2, 3]));     // [[1, 0, 0], [0, 2, 0], [0, 0, 3]]diag(tensor([[1, 2], [3, 4]])); // [1, 4]

diagonal

function diagonal(t: Tensor, k?: number): Tensor;

Extract the k-th diagonal from a 2-D tensor. The result is a copy.

Parameters

t
Tensor
Input 2-D tensor
koptional
number
Diagonal offset (0 = main, positive = above, negative = below)

Returns

Tensor1-D tensor of diagonal elements (empty if |k| exceeds the matrix size)

Throws

  • ShapeErrorIf the input is not 2-D
  • InvalidParameterErrorIf k is not an integer

emptyLike

function emptyLike(t: Tensor, options?: LikeOptions): Tensor;

Create a zero-filled tensor with the same shape as the input tensor. JavaScript typed arrays are always zero-initialized, so unlike NumPy's empty_like the contents are well defined.

Parameters

t
Tensor
Reference tensor
optionsoptional
LikeOptions
dtype overrides the result dtype (default: the dtype of t)

Returns

TensorNew tensor (zero-initialized)

fancyIndex

function fancyIndex(t: Tensor, indices: Tensor, axis?: Axis): Tensor;

Select elements from a tensor using integer index arrays (like np.take).

The result has the shape of t with axis replaced by the shape of indices. A 0-d indices tensor selects a single entry and keeps the axis with size 1. Negative indices count from the end of the axis.

Parameters

t
Tensor
Input tensor
indices
Tensor
Integer-valued index tensor (bool tensors are rejected; use booleanIndex)
axisoptional
Axis
Axis along which to index (default: 0)

Returns

TensorTensor with selected elements, same dtype as t

Throws

  • IndexErrorIf an index is out of bounds for axis
  • InvalidParameterErrorIf an index is not an integer
  • DTypeErrorIf indices has bool dtype

fft

function fft(t: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;

Compute the one-dimensional discrete Fourier transform along one axis.

Parameters

t
Tensor
Real-valued input tensor.
noptional
number
Length of the transformed axis. A shorter input is zero-padded and a longer one is cropped. Default: the input length along axis.
axisoptional
number
Axis to transform (negative values count from the end). Default: -1.
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real and imag tensors; the transformed axis has length n.

Throws

  • DTypeErrorIf t has string dtype.
  • ShapeErrorIf t is 0-D.
  • InvalidParameterErrorIf n is not a positive integer or axis is invalid.
Example
import { fft, tensor } from "deepbox/ndarray"; const { real, imag } = fft(tensor([1, 0, 0, 0]));// real = [1, 1, 1, 1], imag = [0, 0, 0, 0]

fft2

function fft2(t: Tensor, axes?: readonly [ number, number ], norm?: FFTNorm): FFTResult;

Compute the 2-dimensional discrete Fourier transform.

Parameters

t
Tensor
Real-valued input with at least 2 dimensions.
axesoptional
readonly [ number, number ]
The two axes to transform. Default: the last two, [-2, -1].
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real and imag tensors of the same shape as t.

Example
const { real, imag } = fft2(tensor([[1, 0], [0, 0]]));// real = [[1, 1], [1, 1]], imag = zeros

fftfreq

function fftfreq(n: number, d?: number): Tensor;

Sample frequencies of an n-point FFT: [0, 1, ..., ceil(n/2) - 1, -floor(n/2), ..., -1] / (n * d).

Parameters

n
number
Window length (positive integer).
doptional
number
Sample spacing (non-zero). Default: 1.

Returns

Tensor1-D float64 tensor of length n.

Example
fftfreq(4);  // [0, 0.25, -0.5, -0.25]

fftn

function fftn(t: Tensor, axes?: number[], norm?: FFTNorm): FFTResult;

Compute the n-dimensional discrete Fourier transform.

The 1-D transform is applied along each listed axis in turn. If axes is omitted, every axis is transformed.

Parameters

t
Tensor
Real-valued input tensor.
axesoptional
number[]
Axes to transform (negative values count from the end). Default: all axes.
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real and imag tensors of the same shape as t.

Example
const { real } = fftn(tensor([[1, 0], [0, 0]]));

fftshift

function fftshift(t: Tensor, axes?: number[]): Tensor;

Shift the zero-frequency component to the center of the spectrum.

Parameters

t
Tensor
Input tensor (for example one half of an fft result).
axesoptional
number[]
Axes to shift. Default: all axes.

Returns

TensorShifted copy of t.

Example
fftshift(fftfreq(4));  // [-0.5, -0.25, 0, 0.25]

flip

function flip(t: Tensor, axes?: Axis | readonly Axis[]): Tensor;

Reverse the order of elements along the given axes. The result is a copy.

Parameters

t
Tensor
Input tensor
axesoptional
Axis | readonly Axis[]
Axis or axes along which to flip. If undefined, flip all axes.

Returns

TensorFlipped tensor

Throws

  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
flip(tensor([1, 2, 3]));     // [3, 2, 1]flip(tensor([[1, 2], [3, 4]]), [1]); // [[2, 1], [4, 3]]

flipLr

function flipLr(t: Tensor): Tensor;

Flip a tensor left-right (reverse the order of columns, axis 1).

Parameters

t
Tensor
Input tensor with at least 2 dimensions

Returns

TensorHorizontally flipped tensor

Throws

  • ShapeErrorIf the input has fewer than 2 dimensions

flipUd

function flipUd(t: Tensor): Tensor;

Flip a tensor up-down (reverse the order of rows, axis 0).

Parameters

t
Tensor
Input tensor with at least 1 dimension

Returns

TensorVertically flipped tensor

Throws

  • ShapeErrorIf the input is a scalar

fullLike

function fullLike(t: Tensor, fillValue: number | bigint, options?: LikeOptions): Tensor;

Create a tensor filled with a specified value, matching the shape of the input.

The value is converted to the result dtype: bool stores 1 for any non-zero value (NaN included), integer dtypes truncate toward zero and reject NaN and infinities, and int64 stores a BigInt.

Parameters

t
Tensor
Reference tensor
fillValue
number | bigint
Value to fill the tensor with
optionsoptional
LikeOptions
dtype overrides the result dtype (default: the dtype of t)

Returns

TensorNew tensor filled with the specified value

Throws

  • DTypeErrorIf the resulting dtype is string
  • InvalidParameterErrorIf a non-finite value is stored in an integer dtype
Example
const a = tensor([[1, 2], [3, 4]]);const f = fullLike(a, 7); // [[7, 7], [7, 7]]

hammingWindow

function hammingWindow(n: number, options?: WindowOptions): Tensor;

Hamming window.

w[i] = 0.54 - 0.46 * cos(2 * pi * i / (n - 1)). Matches np.hamming(n).

Parameters

n
number
Number of points; a positive integer
optionsoptional
WindowOptions
{ periodic: true } for the periodic form

Returns

Tensorfloat64 tensor of shape [n]

Throws

  • InvalidParameterErrorIf n is not a positive integer
Example
hammingWindow(5); // [0.08, 0.54, 1, 0.54, 0.08]

hannWindow

function hannWindow(n: number, options?: WindowOptions): Tensor;

Hann window (raised cosine).

w[i] = 0.5 - 0.5 * cos(2 * pi * i / (n - 1)). Matches np.hanning(n).

Parameters

n
number
Number of points; a positive integer
optionsoptional
WindowOptions
{ periodic: true } for the periodic form

Returns

Tensorfloat64 tensor of shape [n]

Throws

  • InvalidParameterErrorIf n is not a positive integer
Example
hannWindow(5); // [0, 0.5, 1, 0.5, 0]

histogram

function histogram(t: Tensor, bins?: number | readonly number[], range?: readonly [ number, number ], options?: HistogramOptions): { counts: Tensor; binEdges: Tensor; };

Compute the histogram of a tensor (flattened).

Bins are half-open [left, right) except the last one, which also includes its right edge. NaN samples and samples outside the range are ignored. When no range is given the bins span the data minimum to maximum (0 to 1 for empty data); a range with equal ends is widened by 0.5 on each side.

Parameters

t
Tensor
Input tensor
binsoptional
number | readonly number[]
Number of equal-width bins (default: 10), or a non-decreasing list of bin edges
rangeoptional
readonly [ number, number ]
[min, max] range for equal-width bins (ignored when bins is a list of edges)
optionsoptional
HistogramOptions
density and weights

Returns

{ counts: Tensor; binEdges: Tensor; }Object with float64 counts (or densities) and binEdges tensors

Throws

  • InvalidParameterErrorIf bins or range is invalid, or the data range is not finite
  • ShapeErrorIf weights does not match the shape of t
Example
const { counts, binEdges } = histogram(tensor([1, 2, 2, 3, 10]), 3, [0, 12]);// counts: [4, 0, 1], binEdges: [0, 4, 8, 12]

ifft

function ifft(real: Tensor, imag: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;

Compute the one-dimensional inverse discrete Fourier transform along one axis.

Parameters

real
Tensor
Real part of the input spectrum.
imag
Tensor
Imaginary part of the input spectrum (same shape as real).
noptional
number
Length of the transformed axis. Default: the input length along axis.
axisoptional
number
Axis to transform. Default: -1.
normoptional
FFTNorm
Normalization mode. Default: "backward" (the inverse is scaled by 1/n).

Returns

FFTResultObject with real and imag tensors.

Throws

  • DTypeErrorIf an input has string dtype.
  • ShapeErrorIf an input is 0-D or the two parts differ in shape.
Example
const spectrum = fft(tensor([1, 2, 3, 4]));const { real } = ifft(spectrum.real, spectrum.imag);// real is approximately [1, 2, 3, 4]

ifft2

function ifft2(real: Tensor, imag: Tensor, axes?: readonly [ number, number ], norm?: FFTNorm): FFTResult;

Compute the 2-dimensional inverse discrete Fourier transform.

Parameters

real
Tensor
Real part of the 2-D spectrum (at least 2 dimensions).
imag
Tensor
Imaginary part of the 2-D spectrum (same shape as real).
axesoptional
readonly [ number, number ]
The two axes to transform. Default: [-2, -1].
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real and imag tensors of the same shape as the input.

ifftn

function ifftn(real: Tensor, imag: Tensor, axes?: number[], norm?: FFTNorm): FFTResult;

Compute the n-dimensional inverse discrete Fourier transform.

Parameters

real
Tensor
Real part of the n-D spectrum.
imag
Tensor
Imaginary part of the n-D spectrum (same shape as real).
axesoptional
number[]
Axes to transform. Default: all axes.
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real and imag tensors of the same shape as the input.

ifftshift

function ifftshift(t: Tensor, axes?: number[]): Tensor;

Inverse of fftshift.

Parameters

t
Tensor
Input tensor.
axesoptional
number[]
Axes to shift. Default: all axes.

Returns

TensorShifted copy of t.

indexSelect

function indexSelect(input: Tensor, dim: Axis, index: Tensor): Tensor;

Select elements along a dimension using an index tensor.

Returns a new tensor that indexes the input tensor along dimension dim using the entries in index (a 1-D integer tensor). The result keeps the dtype of input. Negative indices are not accepted.

Equivalent to PyTorch's torch.index_select(input, dim, index).

Parameters

input
Tensor
The input tensor
dim
Axis
The dimension to index along
index
Tensor
1-D tensor of indices to select

Returns

TensorA new tensor with the selected elements

Throws

  • ShapeErrorIf index is not 1-D
  • IndexErrorIf an index is outside [0, size) for dim
  • InvalidParameterErrorIf dim is out of range or an index is not an integer
Example
const x = tensor([[1, 2, 3], [4, 5, 6]]);const idx = tensor([0, 2], { dtype: 'int32' });const result = indexSelect(x, 1, idx); // [[1, 3], [4, 6]]

irfft

function irfft(real: Tensor, imag: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;

Compute the inverse of rfft: a real signal from a one-sided spectrum.

The imaginary parts of the DC term and, for even n, the Nyquist term are ignored, as in NumPy. The returned imag tensor is all zeros; it is kept so the result has the same { real, imag } form as the other transforms.

Parameters

real
Tensor
Real part of the one-sided spectrum (length floor(n/2) + 1 along axis).
imag
Tensor
Imaginary part of the one-sided spectrum (same shape as real).
noptional
number
Length of the output axis. Default: 2 * (m - 1) for an input length m.
axisoptional
number
Axis to transform. Default: -1.
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real (the signal) and a zero imag tensor of shape [..., n].

Example
const { real, imag } = rfft(tensor([1, 2, 3, 4]));irfft(real, imag).real;  // [1, 2, 3, 4]

isin

function isin(a: Tensor, values: Tensor | readonly number[] | readonly string[], invert?: boolean): Tensor;

Test whether each element of a is in values.

Returns a boolean tensor of the same shape as a. NaN is never a member (NaN never equals NaN, as in NumPy). String tensors can be tested against a string tensor or a list of strings; int64 values are compared exactly.

Parameters

a
Tensor
Input tensor
values
Tensor | readonly number[] | readonly string[]
Values to test against (a tensor or an array)
invertoptional
boolean
If true, return the negation (a not in values)

Returns

TensorBoolean tensor with the shape of a

Throws

  • DTypeErrorIf string and numeric inputs are mixed
Example
isin(tensor([1, 2, 3, 4]), [2, 4]); // [0, 1, 0, 1]

kaiserWindow

function kaiserWindow(n: number, beta?: number, options?: WindowOptions): Tensor;

Kaiser window.

w[i] = I0(beta * sqrt(1 - r^2)) / I0(beta) with r = 2 * i / (n - 1) - 1, where I0 is the modified Bessel function of order zero. Matches np.kaiser(n, beta). Larger beta gives a narrower main lobe and lower side lobes; beta = 0 is the rectangular window.

Parameters

n
number
Number of points; a positive integer
betaoptional
number
Shape parameter; a finite number (default 12)
optionsoptional
WindowOptions
{ periodic: true } for the periodic form

Returns

Tensorfloat64 tensor of shape [n]

Throws

  • InvalidParameterErrorIf n is not a positive integer or beta is not finite
Example
kaiserWindow(8, 5); // [0.0367, 0.2707, 0.6517, 0.9552, 0.9552, 0.6517, 0.2707, 0.0367]

meshgrid

function meshgrid(...args: [ ...Tensor[], ...[ { readonly indexing?: "xy" | "ij"; } ] ] | Tensor[]): Tensor[];

Return coordinate matrices from coordinate vectors.

Details

Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2, ..., xn. Each output keeps the dtype of its input vector.

Supports "xy" (default, Cartesian) and "ij" (matrix) indexing. With "xy" the first two output axes are swapped: the outputs have shape [len(x2), len(x1), len(x3), ...].

Parameters

args
[ ...Tensor[], ...[ { readonly indexing?: "xy" | "ij"; } ] ] | Tensor[]
1-D coordinate tensors, optionally followed by { indexing }

Returns

Tensor[]Array of N-D tensors, one for each input

Throws

  • ShapeErrorIf an input is not 1-D
  • InvalidParameterErrorIf indexing is neither "xy" nor "ij"
Example
const x = tensor([1, 2, 3]);const y = tensor([4, 5]);const [X, Y] = meshgrid(x, y);// X shape: [2, 3], Y shape: [2, 3]

moveaxis

function moveaxis(t: Tensor, source: number | readonly number[], destination: number | readonly number[]): Tensor;

Move axes of a tensor to new positions. Other axes keep their relative order. The result is a zero-copy view that shares the input's buffer.

Parameters

t
Tensor
Input tensor
source
number | readonly number[]
Original positions of axes to move
destination
number | readonly number[]
Destination positions for each axis

Returns

TensorTensor view with moved axes

Throws

  • InvalidParameterErrorIf the lists differ in length, an axis is out of range, or an axis is repeated in source or in destination
Example
moveaxis(zeros([2, 3, 4]), 0, -1).shape; // [3, 4, 2]

nanmax

function nanmax(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;

Maximum of elements, ignoring NaN. A slice without non-NaN values (including an empty slice) gives NaN. The result is always float64.

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis or axes to reduce (default: all)
keepdimsoptional
boolean
Keep reduced axes as size-1 dimensions

Returns

Tensorfloat64 tensor of maxima

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or repeated

nanmean

function nanmean(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;

Mean of elements, ignoring NaN. A slice without non-NaN values gives NaN. The result is always float64.

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis or axes to reduce (default: all)
keepdimsoptional
boolean
Keep reduced axes as size-1 dimensions

Returns

Tensorfloat64 tensor of means

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or repeated

nanmin

function nanmin(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;

Minimum of elements, ignoring NaN. A slice without non-NaN values (including an empty slice) gives NaN. The result is always float64.

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis or axes to reduce (default: all)
keepdimsoptional
boolean
Keep reduced axes as size-1 dimensions

Returns

Tensorfloat64 tensor of minima

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or repeated

nanstd

function nanstd(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean, ddof?: number): Tensor;

Standard deviation of elements, ignoring NaN. Computed in two passes, so it does not suffer from the cancellation of E[x^2] - mean^2. A slice with count - ddof <= 0 non-NaN values gives NaN. The result is always float64.

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis or axes to reduce (default: all)
keepdimsoptional
boolean
Keep reduced axes as size-1 dimensions
ddofoptional
number
Delta degrees of freedom; the divisor is count - ddof (default: 0, population standard deviation, like NumPy)

Returns

Tensorfloat64 tensor of standard deviations

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or repeated, or ddof is negative or not finite

nansum

function nansum(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;

Sum of elements, treating NaN as zero. The sum of an empty or all-NaN slice is 0. Uses compensated summation. The result is always float64.

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis or axes to reduce (default: all)
keepdimsoptional
boolean
Keep reduced axes as size-1 dimensions

Returns

Tensorfloat64 tensor of sums

Throws

  • DTypeErrorIf t has string dtype
  • InvalidParameterErrorIf an axis is out of range or repeated

nonzero

function nonzero(t: Tensor): Tensor[];

Indices of the nonzero elements, one int32 tensor per dimension (like np.nonzero). NaN counts as nonzero. The indices are in row-major order, so nonzero(t) can be used directly to index t element by element.

Parameters

t
Tensor
Input tensor

Returns

Tensor[]Array with t.ndim int32 tensors of shape [count]; entry d holds the index along axis d of every nonzero element

Throws

  • ShapeErrorIf t is 0-d (use argwhere or reshape to 1-D first)
  • DTypeErrorIf t has string dtype
Example
const [rows, cols] = nonzero(tensor([[0, 2], [3, 0]]));// rows: [0, 1], cols: [1, 0]

onesLike

function onesLike(t: Tensor, options?: LikeOptions): Tensor;

Create a tensor of ones with the same shape as the input tensor.

Parameters

t
Tensor
Reference tensor
optionsoptional
LikeOptions
dtype overrides the result dtype (default: the dtype of t)

Returns

TensorNew tensor filled with ones

Throws

  • DTypeErrorIf the resulting dtype is string
Example
const a = tensor([[1, 2], [3, 4]]);const o = onesLike(a); // [[1, 1], [1, 1]]

pad

function pad(t: Tensor, padWidth: PadWidth, mode?: PadMode, constantValue?: number | bigint): Tensor;

Pad a tensor.

Parameters

t
Tensor
Input tensor
padWidth
PadWidth
Padding as [[before0, after0], [before1, after1], ...] with one pair per axis. A single pair, or a single-element list of pairs, applies to every axis, and a number pads every side of every axis by that amount.
modeoptional
PadMode
Padding mode: 'constant', 'reflect', 'symmetric', 'replicate' (alias 'edge') or 'circular' (alias 'wrap')
constantValueoptional
number | bigint
Fill value for constant mode (default: 0). Converted to the dtype of t (booleans store 1 for any non-zero value)

Returns

TensorPadded tensor

Throws

  • InvalidParameterErrorIf the mode is unknown, a pad width is negative or not an integer, or a non-constant mode would extend an empty axis
Example
pad(tensor([1, 2, 3]), [[2, 1]]); // [0, 0, 1, 2, 3, 0]

putAlongAxis

function putAlongAxis(arr: Tensor, indices: Tensor, values: Tensor | number | bigint, axis?: Axis | null): Tensor;

Put values into a copy of arr along an axis at the positions given by indices (like np.put_along_axis, with the same index and broadcasting rules as takeAlongAxis).

Details

Unlike NumPy, which modifies arr in place and returns nothing, this function leaves arr unchanged and returns the updated copy, as scatter does. values broadcasts to the broadcast shape of the indices; a plain number or bigint is accepted and converted to the dtype of arr. When an index repeats, the last value written wins (row-major order).

With axis = null, arr is flattened for the operation, indices must be 1-D, and the result has the shape of arr.

Parameters

arr
Tensor
Tensor to update (not modified)
indices
Tensor
Integer positions along axis (same number of dimensions as arr)
values
Tensor | number | bigint
Values to write: a tensor broadcastable to the index shape, or a scalar
axisoptional
Axis | null
Axis to index along (default: -1), or null to use the flattened arr

Returns

TensorNew tensor with the shape and dtype of arr

Throws

  • ShapeErrorIf the dimensions differ, the other axes do not broadcast, or values does not broadcast to the index shape
  • IndexErrorIf an index is out of bounds for axis
  • InvalidParameterErrorIf an index is not an integer or axis is out of range
  • DTypeErrorIf a tensor has string dtype, or indices has bool dtype
Example
const a = tensor([[10, 30, 20], [60, 40, 50]]);const idx = tensor([[0], [2]]);putAlongAxis(a, idx, 99, 1); // [[99, 30, 20], [60, 40, 99]]

rfft

function rfft(t: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;

Compute the one-dimensional FFT of real input, keeping only the non-negative frequencies.

The spectrum of a real signal is Hermitian-symmetric, so the transformed axis has length floor(n / 2) + 1.

Parameters

t
Tensor
Real-valued input tensor.
noptional
number
Length of the underlying FFT. Default: the input length along axis.
axisoptional
number
Axis to transform. Default: -1.
normoptional
FFTNorm
Normalization mode. Default: "backward".

Returns

FFTResultObject with real and imag tensors of shape [..., floor(n/2) + 1] (along axis).

Example
const { real, imag } = rfft(tensor([1, 2, 3, 4]));// real = [10, -2, -2], imag = [0, 2, 0]

rfftfreq

function rfftfreq(n: number, d?: number): Tensor;

Sample frequencies of an n-point rfft: [0, 1, ..., floor(n/2)] / (n * d).

Parameters

n
number
Window length (positive integer).
doptional
number
Sample spacing (non-zero). Default: 1.

Returns

Tensor1-D float64 tensor of length floor(n / 2) + 1.

roll

function roll(t: Tensor, shift: number | readonly number[], axis?: Axis | readonly Axis[]): Tensor;

Roll tensor elements along the given axis. Elements that roll beyond the last position are re-introduced at the first. The result is a copy.

With several axes, shift is either one number applied to every axis or a list with one shift per axis (NumPy semantics). Without axis the tensor is rolled as if flattened and keeps its shape.

Parameters

t
Tensor
Input tensor
shift
number | readonly number[]
Number of places to shift (positive = toward end)
axisoptional
Axis | readonly Axis[]
Axis or axes along which to roll (default: roll the flattened tensor)

Returns

TensorRolled tensor

Throws

  • InvalidParameterErrorIf a shift is not an integer, or shift and axis lengths disagree
Example
roll(tensor([1, 2, 3, 4, 5]), 2);  // [4, 5, 1, 2, 3]

rot90

function rot90(t: Tensor, k?: number): Tensor;

Rotate a 2-D tensor by 90 degrees counter-clockwise, k times.

Parameters

t
Tensor
Input 2-D tensor
koptional
number
Number of 90° rotations (default 1). Negative values rotate clockwise.

Returns

TensorRotated copy of the tensor

Throws

  • ShapeErrorIf the input is not 2-D
  • InvalidParameterErrorIf k is not an integer

scatter

function scatter(t: Tensor, dim: Axis, index: Tensor, src: Tensor): Tensor;

Scatter values into a copy of a tensor at specified indices along an axis. This is the inverse of gather: for a 3-D tensor and dim = 0 the result satisfies out[index[i][j][k]][j][k] = src[i][j][k].

t, index and src must have the same number of dimensions, index must not be larger than src along any axis, and not larger than t along every axis except dim. Negative indices count from the end of the axis. When an index repeats, the last write wins. Values of src are converted to the dtype of t.

Parameters

t
Tensor
Input tensor (left unchanged)
dim
Axis
Dimension along which to scatter
index
Tensor
Integer-valued index tensor
src
Tensor
Source values tensor

Returns

TensorNew tensor with scattered values

Throws

  • ShapeErrorIf the shapes are inconsistent
  • IndexErrorIf an index is out of bounds for dim
  • InvalidParameterErrorIf an index is not an integer

searchsorted

function searchsorted(sortedArr: Tensor, values: Tensor, side?: "left" | "right"): Tensor;

Find indices where elements should be inserted to maintain order.

NaN sorts after every other value (NumPy convention), so searching for NaN returns the length of the array unless the array itself ends in NaNs. The array is not checked for being sorted. The indices are returned as int32.

Parameters

sortedArr
Tensor
1-D sorted tensor
values
Tensor
Values to insert (any shape)
sideoptional
"left" | "right"
'left' (default): first suitable index, 'right': last suitable index

Returns

Tensorint32 tensor of insertion indices with the shape of values

Throws

  • ShapeErrorIf sortedArr is not 1-D
  • InvalidParameterErrorIf side is not 'left' or 'right'

swapaxes

function swapaxes(t: Tensor, axis1: number, axis2: number): Tensor;

Swap two axes of a tensor. The result is a zero-copy view that shares the input's buffer.

Parameters

t
Tensor
Input tensor
axis1
number
First axis
axis2
number
Second axis

Returns

TensorTensor view with swapped axes

Throws

  • InvalidParameterErrorIf an axis is out of range

takeAlongAxis

function takeAlongAxis(arr: Tensor, indices: Tensor, axis?: Axis | null): Tensor;

Take values from arr along an axis at the positions given by indices (like np.take_along_axis). It is the companion of argsort, argmax and similar functions that return per-axis positions.

Details

arr and indices must have the same number of dimensions. Every axis except axis broadcasts between the two (a size-1 axis stretches), and the result has the length of indices along axis: out[i][j][k] = arr[i][indices[i][j][k]][k] for axis = 1. Negative indices count from the end of the axis. Integer-valued float indices are accepted.

With axis = null, arr is flattened first and indices must be 1-D.

Parameters

arr
Tensor
Source tensor
indices
Tensor
Integer positions along axis (same number of dimensions as arr)
axisoptional
Axis | null
Axis to index along (default: -1), or null to use the flattened arr

Returns

TensorNew tensor with the dtype of arr and the broadcast shape described above

Throws

  • ShapeErrorIf the dimensions differ or the other axes do not broadcast
  • IndexErrorIf an index is out of bounds for axis
  • InvalidParameterErrorIf an index is not an integer or axis is out of range
  • DTypeErrorIf arr or indices has string dtype, or indices has bool dtype
Example
const a = tensor([[10, 30, 20], [60, 40, 50]]);const order = argsort(a, 1); // [[0, 2, 1], [1, 2, 0]]takeAlongAxis(a, order, 1); // [[10, 20, 30], [40, 50, 60]]

tril

function tril(t: Tensor, k?: number): Tensor;

Return the lower triangular part of a tensor, with elements above the k-th diagonal zeroed. For tensors with more than two axes the last two axes are treated as the matrix and the leading axes as a batch.

Parameters

t
Tensor
Input tensor with at least 2 dimensions
koptional
number
Diagonal offset (0 = main diagonal)

Returns

TensorLower triangular tensor

Throws

  • ShapeErrorIf the input has fewer than 2 dimensions
  • InvalidParameterErrorIf k is not an integer
Example
tril(tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]));// [[1, 0, 0], [4, 5, 0], [7, 8, 9]]

triu

function triu(t: Tensor, k?: number): Tensor;

Return the upper triangular part of a tensor, with elements below the k-th diagonal zeroed. For tensors with more than two axes the last two axes are treated as the matrix and the leading axes as a batch.

Parameters

t
Tensor
Input tensor with at least 2 dimensions
koptional
number
Diagonal offset (0 = main diagonal)

Returns

TensorUpper triangular tensor

Throws

  • ShapeErrorIf the input has fewer than 2 dimensions
  • InvalidParameterErrorIf k is not an integer
Example
triu(tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]));// [[1, 2, 3], [0, 5, 6], [0, 0, 9]]

unique

function unique<const O extends UniqueOptions>(t: Tensor, options: O): UniqueOutput<O>;

Parameters

t
Tensor
options
O

Returns

UniqueOutput<O>

where

function where(condition: Tensor, x: Tensor, y: Tensor): Tensor;

Conditional element selection: returns elements from x where condition is true, and from y where condition is false.

All three tensors must be broadcastable to a common shape. The condition is evaluated as boolean: 0 is false, every other value (including NaN) is true. x and y must have the same dtype.

Complexity: O(n) where n is the number of elements in the output

Parameters

condition
Tensor
Boolean condition tensor
x
Tensor
Values where condition is true
y
Tensor
Values where condition is false

Returns

TensorTensor with selected elements

Throws

  • DTypeErrorIf any input has string dtype, or x and y differ in dtype
  • ShapeErrorIf the shapes cannot be broadcast together
Example
const cond = tensor([1, 0, 1, 0], { dtype: 'bool' });const x = tensor([10, 20, 30, 40]);const y = tensor([1, 2, 3, 4]);const result = where(cond, x, y); // [10, 2, 30, 4]

zerosLike

function zerosLike(t: Tensor, options?: LikeOptions): Tensor;

Create a tensor of zeros with the same shape as the input tensor.

Parameters

t
Tensor
Reference tensor
optionsoptional
LikeOptions
dtype overrides the result dtype (default: the dtype of t)

Returns

TensorNew tensor filled with zeros (empty strings for string dtype)

Example
const a = tensor([[1, 2], [3, 4]]);const z = zerosLike(a); // [[0, 0], [0, 0]]

dropoutMask

function dropoutMask(shape: Shape, p: number, scale: number, dtype: NumericDType, device: Device): Tensor;

Generate a tensor of Bernoulli samples scaled by a constant.

Details

Each element is independently drawn: it equals scale with probability (1 - p) and 0 with probability p. This is the mask used by inverted dropout: non-dropped elements are pre-scaled by 1 / (1 - p).

Draws come from the library's shared random stream, so setSeed makes the mask reproducible. For integer dtypes scale is converted like astype does (truncated toward zero); bool masks hold 1 where scale is non-zero.

Parameters

shape
Shape
Output tensor shape
p
number
Probability of an element being zero (drop probability), in [0, 1)
scale
number
Value assigned to kept elements (typically 1 / (1 - p)), must be finite
dtype
NumericDType
Numeric dtype for the output tensor
device
Device
Target device

Returns

TensorTensor of the given shape filled with 0 or scale

Throws

  • InvalidParameterErrorIf p is outside [0, 1) or scale is not finite

Deprecated names

10

These older spellings still work in 1.x. New code should use the names above.

  • atleast_1dPrefer atleast1d.
  • atleast_2dPrefer atleast2d.
  • broadcast_toPrefer broadcastTo.
  • empty_likePrefer emptyLike.
  • fliplrPrefer flipLr.
  • flipudPrefer flipUd.
  • full_likePrefer fullLike.
  • index_selectPrefer indexSelect.
  • ones_likePrefer onesLike.
  • zeros_likePrefer zerosLike.
ndarray-sparse.ts
import {  CSRMatrix,  convolve,  einsum,  fft,  ifft,  nanmean,  tensor,  unique,} from "deepbox/ndarray"; const dense = tensor([  [1, 0, 0],  [0, 2, 3],]);const sparse = CSRMatrix.fromDense(dense);console.log(sparse.nnz, sparse.matvec(tensor([1, 1, 1])).toString());console.log(sparse.toDense().toString()); console.log(einsum("ij,jk->ik", dense, tensor([[1], [2], [3]])).toString()); const signal = tensor([1, 2, 3, 4]);const spectrum = fft(signal); // { real, imag }console.log(spectrum.real.toString(), spectrum.imag.toString());console.log(ifft(spectrum.real, spectrum.imag).real.toString()); console.log(convolve(tensor([1, 2, 3]), tensor([0, 1, 0.5])).toString());console.log(nanmean(tensor([1, Number.NaN, 3])).toString());console.log(unique(tensor([3, 1, 1, 2]), { returnCounts: true }).counts?.toString());