/** * N-D arrays without dependencies: NDArray (a typed array and a shape, row-major, optionally * complex) and SparseArray (coordinates and values); conversions from and to numjs, scijs * ndarray, nested arrays and JData N-D objects. * * Copyright (c) 2019-2026 Qianqian Fang . BSD 3-clause license. */ export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; /** The canonical JData type name (_ArrayType_) of an alias, or null. */ export function canonicalType(t: any): string | null { const s = String(t).toLowerCase(); switch (s) { case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32': case 'int64': case 'uint64': case 'half': case 'single': case 'double': return s; case 'float16': return 'half'; case 'float32': return 'single'; case 'float64': return 'double'; case 'byte': case 'char': return 'uint8'; case 'logical': case 'bool': case 'boolean': return 'logical'; } return null; } export const ELEM_BYTES: { [t: string]: number } = { int8: 1, uint8: 1, logical: 1, int16: 2, uint16: 2, half: 2, int32: 4, uint32: 4, single: 4, int64: 8, uint64: 8, double: 8 }; /** The typed-array constructor holding a JData type (half: Float32Array). */ export function typedArrayFor(t: string): any { switch (t) { case 'int8': return Int8Array; case 'uint8': case 'logical': return Uint8Array; case 'int16': return Int16Array; case 'uint16': return Uint16Array; case 'int32': return Int32Array; case 'uint32': return Uint32Array; case 'int64': return typeof BigInt64Array !== 'undefined' ? BigInt64Array : Float64Array; case 'uint64': return typeof BigUint64Array !== 'undefined' ? BigUint64Array : Float64Array; case 'half': case 'single': return Float32Array; case 'double': return Float64Array; } throw new Error('jdata: unknown array type ' + t); } /** The JData type of a typed array (by name, so that other realms count), or null. */ export function typeOfTypedArray(a: any): string | null { switch (Object.prototype.toString.call(a).slice(8, -1)) { case 'Int8Array': return 'int8'; case 'Uint8Array': case 'Uint8ClampedArray': return 'uint8'; case 'Int16Array': return 'int16'; case 'Uint16Array': return 'uint16'; case 'Int32Array': return 'int32'; case 'Uint32Array': return 'uint32'; case 'BigInt64Array': return 'int64'; case 'BigUint64Array': return 'uint64'; case 'Float16Array': return 'half'; case 'Float32Array': return 'single'; case 'Float64Array': return 'double'; } return null; } export function isTypedArray(a: any): boolean { return ArrayBuffer.isView(a) && !(a instanceof DataView); } export function product(shape: ArrayLike): number { let n = 1; for (let k = 0; k < shape.length; k++) { n *= shape[k]; } return n; } /** Row-major strides of a shape. */ function strides(shape: number[]): number[] { const s = new Array(shape.length); let x = 1; for (let k = shape.length - 1; k >= 0; k--) { s[k] = x; x *= shape[k]; } return s; } /** Nested arrays of shape from row-major flat data. */ export function nest(data: ArrayLike, shape: number[]): any { if (!shape.length) { return data[0]; } const st = strides(shape); const build = (k: number, at: number): any[] => { const out = new Array(shape[k]); if (k === shape.length - 1) { for (let i = 0; i < shape[k]; i++) { out[i] = data[at + i]; } } else { for (let i = 0; i < shape[k]; i++) { out[i] = build(k + 1, at + i * st[k]); } } return out; }; return build(0, 0); } /** Row-major data of column-major data of a shape (or the reverse, with reverse = true). */ export function reorder(data: any, shape: number[], reverse: boolean = false): any { const nd = shape.length; const n = data.length; if (nd < 2 || n < 2) { return data; } const out = new (data.constructor as any)(n); const cs = new Array(nd); // column-major strides let x = 1; for (let k = 0; k < nd; k++) { cs[k] = x; x *= shape[k]; } const idx = new Array(nd).fill(0); let f = 0; for (let c = 0; c < n; c++) { if (reverse) { out[f] = data[c]; } else { out[c] = data[f]; } for (let k = nd - 1; k >= 0; k--) { idx[k]++; f += cs[k]; if (idx[k] < shape[k]) { break; } f -= cs[k] * shape[k]; idx[k] = 0; } } return out; } /** * An N-D array: row-major `data` (a typed array) of `shape` and JData type `dtype`; `imag` holds * the imaginary parts of a complex array; `attrs` the _ArrayLabel_, _ArrayCoords_, _ArrayUnits_ * annotations it was stored with. */ export class NDArray { data: any; shape: number[]; dtype: string; imag?: any; attrs?: { [name: string]: any }; constructor(data: any, shape?: number[], dtype?: string, imag?: any) { this.data = data; this.shape = shape ? shape.slice() : [data.length]; this.dtype = dtype || typeOfTypedArray(data) || 'double'; if (imag !== undefined) { this.imag = imag; } if (product(this.shape) !== data.length) { throw new Error('jdata: ' + data.length + ' values for an array of shape [' + this.shape + ']'); } } get size(): number { return this.data.length; } get ndim(): number { return this.shape.length; } get iscomplex(): boolean { return this.imag !== undefined; } /** The flat (row-major) position of an index. */ offset(...idx: number[]): number { let p = 0; for (let k = 0; k < this.shape.length; k++) { const i = idx[k] || 0; if (i < 0 || i >= this.shape[k]) { throw new RangeError('jdata: index ' + i + ' out of range for dimension ' + k); } p = p * this.shape[k] + i; } return p; } get(...idx: number[]): any { const p = this.offset(...idx); return this.imag !== undefined ? { re: this.data[p], im: this.imag[p] } : this.data[p]; } set(...args: any[]): void { const v = args.pop(); const p = this.offset(...args); if (this.imag !== undefined && typeof v === 'object') { this.data[p] = v.re; this.imag[p] = v.im; } else { this.data[p] = v; } } /** The same data in another shape. */ reshape(...shape: any[]): NDArray { const s: number[] = Array.isArray(shape[0]) ? shape[0] : shape; const r = new NDArray(this.data, s, this.dtype, this.imag); r.attrs = this.attrs; return r; } /** A copy with the dimensions reversed (the transpose of a matrix). */ transpose(): NDArray { const rev = this.shape.slice().reverse(); return new NDArray(reorder(this.data, rev), rev, this.dtype, this.imag !== undefined ? reorder(this.imag, rev) : undefined); } /** Nested arrays ({re, im} elements when complex; numbers for 64-bit integers when exact). */ tolist(): any { let d: any = this.data; if (this.imag !== undefined) { const im = this.imag; d = Array.from(d, (x: any, k: number) => ({ re: x, im: im[k] })); } else if (typeof BigInt64Array !== 'undefined' && (d instanceof BigInt64Array || d instanceof BigUint64Array)) { d = Array.from(d as any, (x: any) => (x >= -9007199254740991 && x <= 9007199254740991 ? Number(x) : x)); } return nest(d, this.shape); } toJSON(): any { return this.tolist(); } /** An NDArray of nested arrays of numbers. */ static from(nested: any, dtype: string = 'double'): NDArray { const shape: number[] = []; let x = nested; while (Array.isArray(x)) { shape.push(x.length); x = x[0]; } const flat: any[] = []; const walk = (y: any, k: number) => { if (k === shape.length) { flat.push(y); return; } if (!Array.isArray(y) || y.length !== shape[k]) { throw new Error('jdata: not a rectangular array'); } for (const e of y) { walk(e, k + 1); } }; walk(nested, 0); return new NDArray(toTyped(flat, dtype), shape, dtype); } } /** A sparse N-D array: 0-based coordinates (one Int32Array per dimension) and values. */ export class SparseArray { shape: number[]; indices: Int32Array[]; values: any; imag?: any; dtype: string; constructor(shape: number[], indices: Int32Array[], values: any, dtype: string, imag?: any) { this.shape = shape; this.indices = indices; this.values = values; this.dtype = dtype; if (imag !== undefined) { this.imag = imag; } } get nnz(): number { return this.values.length; } toDense(): NDArray { const Ctor = typedArrayFor(this.dtype); const n = product(this.shape); const d = new Ctor(n); const im = this.imag !== undefined ? new Ctor(n) : undefined; const st = strides(this.shape); for (let k = 0; k < this.values.length; k++) { let p = 0; for (let j = 0; j < this.shape.length; j++) { p += this.indices[j][k] * st[j]; } d[p] = this.values[k]; if (im) { im[p] = this.imag[k]; } } return new NDArray(d, this.shape, this.dtype, im); } toJSON(): any { return { shape: this.shape, indices: this.indices.map((a) => Array.from(a)), values: Array.from(this.values) }; } } /** A typed array of JData type t holding values (numbers, BigInts, NaN strings ...). */ export function toTyped(values: ArrayLike, t: string): any { const Ctor = typedArrayFor(t); const n = values.length; if (values instanceof Ctor) { return values; } const out = new Ctor(n); const big = typeof BigInt64Array !== 'undefined' && (out instanceof BigInt64Array || out instanceof BigUint64Array); const isInt = t !== 'half' && t !== 'single' && t !== 'double'; for (let k = 0; k < n; k++) { let x: any = values[k]; if (typeof x === 'string' || x === null) { x = specialNumber(x); } else if (typeof x === 'boolean') { x = x ? 1 : 0; } if (big) { out[k] = typeof x === 'bigint' ? x : BigInt(Math.round(Number(x)) || 0); } else { out[k] = typeof x === 'bigint' ? Number(x) : isInt ? Math.round(x) : x; } } return out; } /** The number of a JData special-constant string ("_NaN_", "_Inf_", "-_Inf_"), or of null: NaN. */ export function specialNumber(x: any): number { if (x === '_Inf_' || x === '+_Inf_') { return Infinity; } if (x === '-_Inf_') { return -Infinity; } if (x === null || x === '_NaN_') { return NaN; } const v = Number(x); return v; } /** Shape and row-major flat values of a numjs NdArray, scijs ndarray, NDArray, JData N-D object, * typed array or (nested) array; null for anything else. */ export function arrayOf(x: any): { data: any; shape: number[]; dtype: string | null } | null { if (x instanceof NDArray) { return { data: x.data, shape: x.shape, dtype: x.dtype }; } if (isTypedArray(x)) { return { data: x, shape: [x.length], dtype: typeOfTypedArray(x) }; } if (x && typeof x === 'object') { // numjs NdArray if (x.selection && Array.isArray(x.shape) && typeof x.flatten === 'function') { const d = x.flatten().selection.data; return { data: d, shape: x.shape.slice(), dtype: typeOfTypedArray(d) }; } // scijs ndarray if (isTypedArray(x.data) && Array.isArray(x.shape) && Array.isArray(x.stride) && typeof x.offset === 'number') { const n = product(x.shape); const Ctor = x.data.constructor; const d = new Ctor(n); const idx = new Array(x.shape.length).fill(0); for (let c = 0; c < n; c++) { let p = x.offset; for (let k = 0; k < idx.length; k++) { p += idx[k] * x.stride[k]; } d[c] = x.data[p]; for (let k = idx.length - 1; k >= 0; k--) { if (++idx[k] < x.shape[k]) { break; } idx[k] = 0; } } return { data: d, shape: x.shape.slice(), dtype: typeOfTypedArray(d) }; } } return null; }