/*
* Chalkboard v3.1.0 Ricci - Tensor Namespace
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
///
namespace Chalkboard {
/**
* The tensor namespace.
* @namespace
*/
export namespace tens {
/** @ignore */
const $broadcast = (tens1: ChalkboardTensor, shape1: number[], tens2: ChalkboardTensor, shape2: number[], callback: (a: number, b: number) => number, caller: string): ChalkboardTensor => {
const n = Math.max(shape1.length, shape2.length), shape: number[] = [], pad1: number[] = [], pad2: number[] = [];
for (let k = 0; k < n; k++) {
const a = shape1[shape1.length - n + k] ?? 1, b = shape2[shape2.length - n + k] ?? 1;
if (a !== b && a !== 1 && b !== 1) throw new Error(`Chalkboard.tens.${caller}: Parameters "tens1" and "tens2" must have broadcastable shapes.`);
shape.push(a === 1 ? b : a);
pad1.push(a);
pad2.push(b);
}
const walk = (arr1: ChalkboardTensor[], arr2: ChalkboardTensor[], depth: number): ChalkboardTensor[] => {
const result: ChalkboardTensor[] = [];
if (depth === n - 1) {
if (pad1[depth] === 1) {
const a = arr1[0] as number;
for (let i = 0; i < shape[depth]; i++) result[i] = callback(a, (pad2[depth] === 1 ? arr2[0] : arr2[i]) as number);
} else if (pad2[depth] === 1) {
const b = arr2[0] as number;
for (let i = 0; i < shape[depth]; i++) result[i] = callback(arr1[i] as number, b);
} else {
for (let i = 0; i < shape[depth]; i++) result[i] = callback(arr1[i] as number, arr2[i] as number);
}
} else for (let i = 0; i < shape[depth]; i++) result[i] = walk((pad1[depth] === 1 ? arr1[0] : arr1[i]) as ChalkboardTensor[], (pad2[depth] === 1 ? arr2[0] : arr2[i]) as ChalkboardTensor[], depth + 1);
return result;
};
let wrap1 = tens1, wrap2 = tens2;
for (let i = shape1.length; i < n; i++) wrap1 = [wrap1];
for (let i = shape2.length; i < n; i++) wrap2 = [wrap2];
return walk(wrap1 as ChalkboardTensor[], wrap2 as ChalkboardTensor[], 0);
};
/** @ignore */
const $contract = (tens: ChalkboardTensor, shape: number[], axis1: number, axis2: number): ChalkboardTensor | number => {
const flat = $flatten(tens), n = shape.length, stride: number[] = new Array(n);
stride[n - 1] = 1;
for (let k = n - 2; k >= 0; k--) stride[k] = stride[k + 1] * shape[k + 1];
const keep: number[] = [];
for (let k = 0; k < n; k++) if (k !== axis1 && k !== axis2) keep.push(k);
const diag = stride[axis1] + stride[axis2], m = shape[axis1];
const sum = (offset: number): number => {
let result = 0;
for (let i = 0; i < m; i++) result += flat[offset + i * diag];
return result;
};
if (keep.length === 0) return sum(0);
const build = (depth: number, offset: number): ChalkboardTensor[] => {
const result: ChalkboardTensor[] = [], axis = keep[depth];
for (let j = 0; j < shape[axis]; j++) result[j] = depth === keep.length - 1 ? sum(offset + j * stride[axis]) : build(depth + 1, offset + j * stride[axis]);
return result;
};
return build(0, 0);
};
/** @ignore */
const $copy = (tens: ChalkboardTensor): ChalkboardTensor => {
if (!Array.isArray(tens)) return tens;
if (!Array.isArray(tens[0])) return tens.slice();
const result: ChalkboardTensor[] = [];
for (let i = 0; i < tens.length; i++) result[i] = $copy(tens[i]);
return result;
};
/** @ignore */
const $flatten = (tens: ChalkboardTensor): number[] => {
if (!Array.isArray(tens)) return [tens];
const result: number[] = [];
const flatten = (tens: ChalkboardTensor[]): void => {
for (let i = 0; i < tens.length; i++) {
const t = tens[i];
if (Array.isArray(t)) flatten(t);
else result.push(t);
}
};
flatten(tens);
return result;
};
/** @ignore */
const $isApproxEqual = (tens1: ChalkboardTensor, tens2: ChalkboardTensor, precision: number, numeric: boolean, caller: string): boolean => {
const shape = $shape(tens1, numeric, caller, "tens1");
let result = true;
const walk = (arr1: ChalkboardTensor[], arr2: ChalkboardTensor, depth: number): boolean => {
if (!Array.isArray(arr2) || arr2.length !== shape[depth]) return false;
if (depth === shape.length - 1) {
for (let i = 0; i < arr2.length; i++) {
const a = arr1[i] as number, b = arr2[i] as number;
if (typeof b !== "number" && (numeric || b !== null)) return false;
if (result && a !== b && !(Math.abs(a - b) < precision)) result = false;
}
} else for (let i = 0; i < arr2.length; i++) if (!walk(arr1[i] as ChalkboardTensor[], arr2[i], depth + 1)) return false;
return true;
};
if (shape.length === 0) {
const a = tens1 as number, b = tens2 as number;
return $shape(tens2, numeric, caller, "tens2").length === 0 && (a === b || Math.abs(a - b) < precision);
}
if (walk(tens1 as ChalkboardTensor[], tens2, 0)) return result;
$shape(tens2, numeric, caller, "tens2");
return false;
};
/** @ignore */
const $isShapeEqual = (shape1: number[], shape2: number[]): boolean => {
return shape1.length === shape2.length && shape1.every((n, i) => n === shape2[i]);
};
/** @ignore */
const $map = (tens: ChalkboardTensor, callback: (x: number) => number): ChalkboardTensor => {
if (!Array.isArray(tens)) return callback(tens);
const result: ChalkboardTensor[] = [];
if (Array.isArray(tens[0])) for (let i = 0; i < tens.length; i++) result[i] = $map(tens[i], callback);
else for (let i = 0; i < tens.length; i++) result[i] = callback(tens[i] as number);
return result;
};
/** @ignore */
const $outer = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): ChalkboardTensor => {
if (!Array.isArray(tens1)) return $map(tens2, (b) => tens1 * b);
const result: ChalkboardTensor[] = [];
for (let i = 0; i < tens1.length; i++) result[i] = $outer(tens1[i], tens2);
return result;
};
/** @ignore */
const $permute = (tens: ChalkboardTensor, shape: number[], axes: number[]): ChalkboardTensor => {
const n = shape.length;
if (n === 0) return tens;
const flat = $flatten(tens), stride: number[] = new Array(n);
stride[n - 1] = 1;
for (let k = n - 2; k >= 0; k--) stride[k] = stride[k + 1] * shape[k + 1];
const outShape = axes.map((a) => shape[a]), outStride = axes.map((a) => stride[a]);
const build = (depth: number, offset: number): ChalkboardTensor[] => {
const result: ChalkboardTensor[] = [];
for (let j = 0; j < outShape[depth]; j++) result[j] = depth === n - 1 ? flat[offset + j * outStride[depth]] : build(depth + 1, offset + j * outStride[depth]);
return result;
};
return build(0, 0);
};
/** @ignore */
const $resize = (tens: ChalkboardTensor, shape: number[]): ChalkboardTensor => {
if (shape.length === 0) return 0;
const entries = $flatten(tens);
let index = 0;
const refill = (depth: number): ChalkboardTensor[] => {
const result: ChalkboardTensor[] = [];
for (let i = 0; i < shape[depth]; i++) {
if (depth === shape.length - 1) result[i] = index < entries.length ? entries[index++] : 0;
else result[i] = refill(depth + 1);
}
return result;
};
return refill(0);
};
/** @ignore */
const $shape = (tens: ChalkboardTensor, numeric: boolean, caller: string, name: string): number[] => {
if (typeof tens === "number") return [];
if (!Array.isArray(tens)) throw new Error(`Chalkboard.tens.${caller}: Parameter "${name}" must be a tensor.`);
const shape: number[] = [];
const seen = new Set();
for (let t: ChalkboardTensor = tens; Array.isArray(t); t = t[0]) {
if (seen.has(t)) throw new Error(`Chalkboard.tens.${caller}: Parameter "${name}" must be a tensor.`);
seen.add(t);
shape.push(t.length);
}
const walk =(t: ChalkboardTensor, depth: number): void => {
if (!Array.isArray(t) || t.length !== shape[depth]) throw new Error(`Chalkboard.tens.${caller}: Parameter "${name}" must be a rectangular tensor.`);
if (depth === shape.length - 1) {
for (let i = 0; i < t.length; i++) if (typeof t[i] !== "number" && (numeric || t[i] !== null)) throw new Error(`Chalkboard.tens.${caller}: Parameter "${name}" must be a tensor whose leaves are ${numeric ? "numbers" : "numbers or null"}.`);
} else for (let i = 0; i < t.length; i++) walk(t[i], depth + 1);
};
walk(tens, 0);
return shape;
};
/** @ignore */
const $shapeArgs = (shape: number[], caller: string): number[] => {
shape = Array.isArray(shape[0]) ? shape[0] : shape;
for (let i = 0; i < shape.length; i++) if (!Number.isInteger(shape[i]) || shape[i] < 0) throw new Error(`Chalkboard.tens.${caller}: Parameter "shape" must contain only non-negative integers.`);
return shape;
};
/** @ignore */
const $string = (tens: ChalkboardTensor, indentation: number): string => {
if (typeof tens === "number") {
return "\t".repeat(indentation) + String(tens) + "\n";
} else if (Array.isArray(tens[0])) {
let result = "\t".repeat(indentation) + "[\n";
for (let i = 0; i < tens.length; i++) result += $string(tens[i], indentation + 1);
result += "\t".repeat(indentation) + "]\n";
return result;
} else {
let result = "\t".repeat(indentation) + "[ ";
for (let i = 0; i < tens.length; i++) result += String(tens[i]) + " ";
result += "]\n";
return result;
}
};
/** @ignore */
const $zip = (tens1: ChalkboardTensor, tens2: ChalkboardTensor, callback: (a: number, b: number) => number): ChalkboardTensor => {
if (Array.isArray(tens1)) {
const result: ChalkboardTensor[] = [];
for (let i = 0; i < tens1.length; i++) {
const a = tens1[i], b = Array.isArray(tens2) ? tens2[i] : tens2;
result[i] = Array.isArray(a) ? $zip(a, b, callback) : callback(a, b as number);
}
return result;
} else if (Array.isArray(tens2)) {
const result: ChalkboardTensor[] = [];
for (let i = 0; i < tens2.length; i++) {
const b = tens2[i];
result[i] = Array.isArray(b) ? $zip(tens1, b, callback) : callback(tens1, b);
}
return result;
} else return callback(tens1, tens2);
};
/**
* Calculates the absolute value of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.absolute([[-1, 2], [-3, 4]]); // Returns [[1, 2], [3, 4]]
*/
export const absolute = (tens: ChalkboardTensor): ChalkboardTensor => {
$shape(tens, true, "absolute", "tens");
return $map(tens, (x) => Math.abs(x));
};
/**
* Calculates the addition of two tensors, which are broadcast together as in NumPy (their shapes are aligned from the right, and axes of length 1 or missing axes are stretched).
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.add([[1, 2], [3, 4]], [[4, 3], [2, 1]]); // Returns [[5, 5], [5, 5]]
* const broadcast = Chalkboard.tens.add([[1, 2, 3], [4, 5, 6]], [10, 20, 30]); // Returns [[11, 22, 33], [14, 25, 36]]
*/
export const add = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): ChalkboardTensor => {
const shape1 = $shape(tens1, true, "add", "tens1"), shape2 = $shape(tens2, true, "add", "tens2");
if (Array.isArray(tens1) && Array.isArray(tens2) && !$isShapeEqual(shape1, shape2)) return $broadcast(tens1, shape1, tens2, shape2, (a, b) => a + b, "add");
return $zip(tens1, tens2, (a, b) => a + b);
};
/**
* Calculates the antisymmetric part of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} axes - Distinct 0-based axes, as a sequence or one array, while an empty list selects all axes
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.antisymmetrize([[1, 2], [4, 3]]); // Returns [[0, -1], [1, 0]]
*/
export const antisymmetrize = (tens: ChalkboardTensor, ...axes: number[]): ChalkboardTensor => {
const shape = $shape(tens, true, "antisymmetrize", "tens");
axes = Array.isArray(axes[0]) ? axes[0] : axes;
if (axes.length === 0) axes = shape.map((_, i) => i);
if (new Set(axes).size !== axes.length || Array.from(axes).some((a) => !Number.isInteger(a) || a < 0 || a >= shape.length)) throw new Error(`Chalkboard.tens.antisymmetrize: Parameter "axes" must contain distinct non-negative integers less than the tensor rank.`);
if (axes.some((a) => shape[a] !== shape[axes[0]])) throw new Error(`Chalkboard.tens.antisymmetrize: Parameter "axes" must contain axes of equal length.`);
if (axes.length < 2) return $copy(tens);
const result = new Array($flatten(tens).length).fill(0);
const permutation = axes.slice();
let count = 0;
const walk = (depth: number, sign: number): void => {
if (depth === permutation.length) {
const order = shape.map((_, i) => i);
for (let i = 0; i < axes.length; i++) order[axes[i]] = permutation[i];
const flat = $flatten($permute(tens, shape, order));
for (let i = 0; i < flat.length; i++) result[i] += sign * flat[i];
count++;
return;
}
for (let i = depth; i < permutation.length; i++) {
[permutation[depth], permutation[i]] = [permutation[i], permutation[depth]];
walk(depth + 1, i === depth ? sign : -sign);
[permutation[depth], permutation[i]] = [permutation[i], permutation[depth]];
}
};
walk(0, 1);
for (let i = 0; i < result.length; i++) result[i] /= count;
return $resize(result, shape);
};
/**
* Calculates the concatenation of two tensors.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @param {number} [axis=0] - The axis to concatenate along, starting from 0 for the outermost axis
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.concat([[1, 2]], [[3, 4]], 1); // Returns [[1, 2, 3, 4]]
*/
export const concat = (tens1: ChalkboardTensor, tens2: ChalkboardTensor, axis: number = 0): ChalkboardTensor => {
const shape1 = $shape(tens1, false, "concat", "tens1"), shape2 = $shape(tens2, false, "concat", "tens2");
if (!Number.isInteger(axis) || axis < 0 || axis >= Math.min(shape1.length, shape2.length)) throw new Error(`Chalkboard.tens.concat: Parameter "axis" must be a non-negative integer less than both tensor ranks.`);
if (shape1.length !== shape2.length || shape1.some((n, i) => i !== axis && n !== shape2[i])) throw new Error(`Chalkboard.tens.concat: Parameters "tens1" and "tens2" must have equal shapes except along the concatenated axis.`);
const concatAtAxis = (arr1: ChalkboardTensor, arr2: ChalkboardTensor, currentAxis: number): ChalkboardTensor => {
if (currentAxis === axis) return $copy((arr1 as ChalkboardTensor[]).concat(arr2));
return (arr1 as ChalkboardTensor[]).map((element, index) => concatAtAxis(element, (arr2 as ChalkboardTensor[])[index], currentAxis + 1));
};
return concatAtAxis(tens1, tens2, 0);
};
/**
* Calculates a tensor constrained within a range.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} [range=[0, 1]] - The range
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.constrain([[-1, 0.5], [2, 1]], [0, 1]); // Returns [[0, 0.5], [1, 1]]
*/
export const constrain = (tens: ChalkboardTensor, range: [number, number] = [0, 1]): ChalkboardTensor => {
$shape(tens, true, "constrain", "tens");
if (!Array.isArray(range) || range.length !== 2 || !Number.isFinite(range[0]) || !Number.isFinite(range[1]) || range[0] > range[1]) throw new Error(`Chalkboard.tens.constrain: Parameter "range" must be an array of two finite numbers whose first element is less than or equal to its second element.`);
return $map(tens, (x) => Math.max(Math.min(x, range[1]), range[0]));
};
/**
* Calculates the contraction of a tensor over two of its axes, which sums the entries whose indices along both axes are equal and removes those axes (as in NumPy's trace with axis arguments).
* @param {ChalkboardTensor} tens - The tensor
* @param {number} [axis1=0] - The first axis
* @param {number} [axis2=1] - The second axis, which must have the same length as the first axis
* @returns {ChalkboardTensor | number}
* @example
* const result = Chalkboard.tens.contract([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]], 0, 2); // Returns [9, 13, 17]
*/
export const contract = (tens: ChalkboardTensor, axis1: number = 0, axis2: number = 1): ChalkboardTensor | number => {
const shape = $shape(tens, true, "contract", "tens");
if (shape.length < 2) throw new Error(`Chalkboard.tens.contract: Parameter "tens" must have a rank of at least two.`);
if (!Number.isInteger(axis1) || axis1 < 0 || axis1 >= shape.length) throw new Error(`Chalkboard.tens.contract: Parameter "axis1" must be a non-negative integer less than the tensor rank.`);
if (!Number.isInteger(axis2) || axis2 < 0 || axis2 >= shape.length) throw new Error(`Chalkboard.tens.contract: Parameter "axis2" must be a non-negative integer less than the tensor rank.`);
if (axis1 === axis2) throw new Error(`Chalkboard.tens.contract: Parameters "axis1" and "axis2" must be different axes.`);
if (shape[axis1] !== shape[axis2]) throw new Error(`Chalkboard.tens.contract: Parameters "axis1" and "axis2" must be axes of equal length.`);
return $contract(tens, shape, axis1, axis2);
};
/**
* Copies a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.copy([[[1, 2]], [[3, 4]]]); // Returns an independent copy
*/
export const copy = (tens: ChalkboardTensor): ChalkboardTensor => {
$shape(tens, false, "copy", "tens");
return $copy(tens);
};
/**
* Calculates the dot product (the Frobenius inner product) of two tensors.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {number}
* @example
* const result = Chalkboard.tens.dot([[1, 2], [3, 4]], [[1, 2], [3, 4]]); // Returns 30
*/
export const dot = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): number => {
const shape1 = $shape(tens1, true, "dot", "tens1");
const shape2 = $shape(tens2, true, "dot", "tens2");
if (!$isShapeEqual(shape1, shape2)) throw new Error(`Chalkboard.tens.dot: Parameters "tens1" and "tens2" must have equal shapes.`);
const a = $flatten(tens1);
const b = $flatten(tens2);
let result = 0;
for (let i = 0; i < a.length; i++) result += a[i] * b[i];
return result;
};
/**
* Calculates Einstein summation using case-sensitive axis letters, commas, and an optional -> output, ignoring whitespace. Repeated letters select diagonals or contractions, but without an explicit output, letters occurring exactly once are kept in character-code order. Ellipses and broadcasting are not supported.
* @param {string} subscripts - One term per tensor, with one letter per axis and equal lengths for equal letters, and explicit output letters must be distinct and occur in an input
* @param {ChalkboardTensor[]} tensors - The numeric tensors, with an empty term for a number
* @returns {ChalkboardTensor}
* @example
* const multi = Chalkboard.tens.einsum("ij,jk->ik", [[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns [[19, 22], [43, 50]]
* const trace = Chalkboard.tens.einsum("ii", [[1, 2], [3, 4]]); // Returns 5
* const cross = Chalkboard.tens.einsum("ijk,j,k->i", Chalkboard.tens.LeviCivita(3), [1, 2, 3], [4, 5, 6]); // Returns [-3, 6, -3]
*/
export const einsum = (subscripts: string, ...tensors: ChalkboardTensor[]): ChalkboardTensor => {
const shapes = tensors.map((t) => $shape(t, true, "einsum", "tensors"));
if (typeof subscripts !== "string" || !/^[a-zA-Z]*(,[a-zA-Z]*)*(->[a-zA-Z]*)?$/.test(subscripts.replace(/\s/g, ""))) throw new Error(`Chalkboard.tens.einsum: Parameter "subscripts" must be comma-separated axis letters, optionally followed by "->" and the output axis letters.`);
const parts = subscripts.replace(/\s/g, "").split("->");
const terms = parts[0].split(",");
if (tensors.length === 0 || terms.length !== tensors.length) throw new Error(`Chalkboard.tens.einsum: Parameter "subscripts" must have one term for each tensor.`);
const lengths = new Map();
const counts = new Map();
const strides = shapes.map((shape) => {
const result: number[] = new Array(shape.length);
let stride = 1;
for (let i = shape.length - 1; i >= 0; i--) { result[i] = stride; stride *= shape[i]; }
return result;
});
const letterStrides = new Map();
for (let t = 0; t < tensors.length; t++) {
if (terms[t].length !== shapes[t].length) throw new Error(`Chalkboard.tens.einsum: Parameter "subscripts" must have as many letters in each term as the rank of the corresponding tensor.`);
for (let a = 0; a < terms[t].length; a++) {
const letter = terms[t][a];
const length = shapes[t][a];
if (lengths.has(letter) && lengths.get(letter) !== length) throw new Error(`Chalkboard.tens.einsum: Parameter "subscripts" must label axes of equal length with the same letter.`);
lengths.set(letter, length);
counts.set(letter, (counts.get(letter) ?? 0) + 1);
if (!letterStrides.has(letter)) letterStrides.set(letter, new Array(tensors.length).fill(0));
letterStrides.get(letter)![t] += strides[t][a];
}
}
const output = parts.length === 2 ? parts[1].split("") : Array.from(counts.keys()).filter((l) => counts.get(l) === 1).sort();
if (new Set(output).size !== output.length || output.some((l) => !lengths.has(l))) throw new Error(`Chalkboard.tens.einsum: Parameter "subscripts" must have distinct output letters that each appear in an input term.`);
const letters = output.concat(Array.from(lengths.keys()).filter((l) => !output.includes(l)));
const steps = letters.map((l) => letterStrides.get(l)!);
const limits = letters.map((l) => lengths.get(l)!);
const flat = tensors.map((t) => $flatten(t));
const offsets = new Array(tensors.length).fill(0);
const result: number[] = [];
const walk = (depth: number): number => {
if (depth === letters.length) {
let product = 1;
for (let t = 0; t < flat.length; t++) product *= flat[t][offsets[t]];
return product;
}
let sum = 0;
const step = steps[depth];
for (let i = 0; i < limits[depth]; i++) {
const value = walk(depth + 1);
if (depth === output.length - 1) result.push(0 + value);
else sum += value;
for (let t = 0; t < offsets.length; t++) offsets[t] += step[t];
}
for (let t = 0; t < offsets.length; t++) offsets[t] -= limits[depth] * step[t];
return sum;
};
const scalar = walk(0);
return output.length === 0 ? 0 + scalar : $resize(result, output.map((l) => lengths.get(l)!));
};
/**
* Initializes an empty tensor.
* @param {number[]} shape - The shape
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.empty(2, 2, 2); // Returns [[[null, null], [null, null]], [[null, null], [null, null]]]
*/
export const empty = (...shape: number[]): ChalkboardTensor => {
shape = $shapeArgs(shape, "empty");
const newNDArray = (shape: number[]): ChalkboardTensor | null => {
if (shape.length === 0) return null;
const curr = shape[0];
const rest = shape.slice(1);
const result: ChalkboardTensor = [];
for (let i = 0; i < curr; i++) result[i] = newNDArray(rest) as ChalkboardTensor;
return result;
};
return newNDArray(shape) as ChalkboardTensor;
};
/**
* Initializes a tensor filled with one number.
* @param {number} element - The number to fill the elements with, which may be NaN or infinite
* @param {number[]} shape - The shape
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.fill(1, 2, 2, 2); // Returns [[[1, 1], [1, 1]], [[1, 1], [1, 1]]]
*/
export const fill = (element: number, ...shape: number[]): ChalkboardTensor => {
if (typeof element !== "number") throw new Error(`Chalkboard.tens.fill: Parameter "element" must be a number.`);
shape = $shapeArgs(shape, "fill");
const newNDArray = (shape: number[]): ChalkboardTensor => {
if (shape.length === 0) return element;
const curr = shape[0];
const rest = shape.slice(1);
const result = [];
for (let i = 0; i < curr; i++) result[i] = newNDArray(rest);
return result;
};
return newNDArray(shape);
};
/**
* Returns a fresh copy of an indexed subtensor, or its number or null leaf when every axis is indexed.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} index - At most one non-negative in-bounds index per axis, as a sequence or one array, while an empty index copies the whole tensor
* @returns {ChalkboardTensor | null}
* @example
* const result = Chalkboard.tens.get([[1, 2, 3], [4, 5, 6]], 1, 2); // Returns 6
*/
export const get = (tens: ChalkboardTensor, ...index: number[]): ChalkboardTensor | null => {
const shape = $shape(tens, false, "get", "tens");
index = Array.isArray(index[0]) ? index[0] : index;
if (index.length > shape.length || Array.from(index).some((i, a) => !Number.isInteger(i) || i < 0 || i >= shape[a])) throw new Error(`Chalkboard.tens.get: Parameter "index" must contain at most as many integers as the tensor rank, each within its axis bounds.`);
for (let a = 0; a < index.length; a++) tens = (tens as ChalkboardTensor[])[index[a]];
return $copy(tens);
};
/**
* Initializes the identity tensor, with all axes of the given dimension and entries of one where all indices are equal, zero elsewhere.
* @param {number} dimension - The length of every axis
* @param {number} [rank=2] - The number of axes
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.identity(2, 3); // Returns [[[1, 0], [0, 0]], [[0, 0], [0, 1]]]
*/
export const identity = (dimension: number, rank: number = 2): ChalkboardTensor => {
if (!Number.isInteger(dimension) || dimension < 0) throw new Error(`Chalkboard.tens.identity: Parameter "dimension" must be a non-negative integer.`);
if (!Number.isInteger(rank) || rank < 0) throw new Error(`Chalkboard.tens.identity: Parameter "rank" must be a non-negative integer.`);
const build = (depth: number, first: number, equal: boolean): ChalkboardTensor => {
if (depth === rank) return equal ? 1 : 0;
const result: ChalkboardTensor[] = [];
for (let i = 0; i < dimension; i++) result[i] = build(depth + 1, depth === 0 ? i : first, equal && (depth === 0 || i === first));
return result;
};
return build(0, 0, true);
};
/**
* Initializes a new tensor.
* @param {ChalkboardTensor[]} tensor - The n-dimensional array either as a sequence of arrays or one array
* @returns {ChalkboardTensor}
* @example
* // Defines a 2x2x2 tensor [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
* let A = Chalkboard.tens.init([[1, 2], [3, 4]],
* [[5, 6], [7, 8]]);
* let B = Chalkboard.tens.init([[[1, 2], [3, 4]],
* [[5, 6], [7, 8]]]);
*/
export const init = (...tensor: ChalkboardTensor[]): ChalkboardTensor => {
if (tensor.length === 0) {
return [];
} else if (tensor.length === 1 && Array.isArray(tensor[0])) {
tensor = tensor[0];
}
$shape(tensor, false, "init", "tensor");
return $copy(tensor);
};
/**
* Checks if a tensor is antisymmetric under swaps of the chosen axes.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} axes - Distinct 0-based axes, as a sequence or one array, while an empty list selects all axes
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isAntisymmetric(Chalkboard.tens.LeviCivita(3)); // Returns true
*/
export const isAntisymmetric = (tens: ChalkboardTensor, ...axes: number[]): boolean => {
const shape = $shape(tens, true, "isAntisymmetric", "tens");
axes = Array.isArray(axes[0]) ? axes[0] : axes;
if (axes.length === 0) axes = shape.map((_, i) => i);
if (new Set(axes).size !== axes.length || Array.from(axes).some((a) => !Number.isInteger(a) || a < 0 || a >= shape.length)) throw new Error(`Chalkboard.tens.isAntisymmetric: Parameter "axes" must contain distinct non-negative integers less than the tensor rank.`);
if (axes.some((a) => shape[a] !== shape[axes[0]])) return false;
if (axes.length < 2) return true;
const flat = $flatten(tens);
for (let k = 1; k < axes.length; k++) {
const order = shape.map((_, i) => i);
order[axes[k - 1]] = axes[k];
order[axes[k]] = axes[k - 1];
const swapped = $flatten($permute(tens, shape, order));
for (let i = 0; i < flat.length; i++) if (flat[i] !== -swapped[i]) return false;
}
return true;
};
/**
* Checks if two tensors are approximately equal within a particular precision. Infinities of the same sign are approximately equal, while NaN is never approximately equal to anything.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @param {number} [precision=0.000001] - The precision to check
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isApproxEqual([[1, 2]], [[1, 2.0000001]]); // Returns true
*/
export const isApproxEqual = (tens1: ChalkboardTensor, tens2: ChalkboardTensor, precision: number = 0.000001): boolean => {
if (!Number.isFinite(precision) || precision <= 0) throw new Error(`Chalkboard.tens.isApproxEqual: Parameter "precision" must be a positive finite number.`);
return $isApproxEqual(tens1, tens2, precision, true, "isApproxEqual");
};
/**
* Checks if two tensors are equal.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isEqual([[1, 2]], [[1, 2]]); // Returns true
*/
export const isEqual = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): boolean => {
return $isApproxEqual(tens1, tens2, 0, false, "isEqual");
};
/**
* Checks if two tensors have equal ranks.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isRankEqual([[1, 2]], [[3, 4], [5, 6]]); // Returns true
*/
export const isRankEqual = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): boolean => {
return $shape(tens1, false, "isRankEqual", "tens1").length === $shape(tens2, false, "isRankEqual", "tens2").length;
};
/**
* Checks if a tensor is of a particular rank.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} rank - The rank
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isRankOf([[[1]]], 3); // Returns true
*/
export const isRankOf = (tens: ChalkboardTensor, rank: number): boolean => {
const shape = $shape(tens, false, "isRankOf", "tens");
if (!Number.isInteger(rank) || rank < 0) throw new Error(`Chalkboard.tens.isRankOf: Parameter "rank" must be a non-negative integer.`);
return shape.length === rank;
};
/**
* Checks if two tensors have equal shapes.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isShapeEqual([[1, 2]], [[3, 4]]); // Returns true
*/
export const isShapeEqual = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): boolean => {
return $isShapeEqual($shape(tens1, false, "isShapeEqual", "tens1"), $shape(tens2, false, "isShapeEqual", "tens2"));
};
/**
* Checks if a tensor is of a particular shape.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} shape - The shape
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isShapeOf([[[1, 2]], [[3, 4]]], 2, 1, 2); // Returns true
*/
export const isShapeOf = (tens: ChalkboardTensor, ...shape: number[]): boolean => {
return $isShapeEqual($shape(tens, false, "isShapeOf", "tens"), $shapeArgs(shape, "isShapeOf"));
};
/**
* Checks if a tensor has a uniform shape, in which every axis has the same length (analogous to checking if a matrix is square).
* @param {ChalkboardTensor} tens - The tensor
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isShapeUniform([[1, 2], [3, 4]]); // Returns true
*/
export const isShapeUniform = (tens: ChalkboardTensor): boolean => {
const shape = $shape(tens, false, "isShapeUniform", "tens");
return shape.every((n) => n === shape[0]);
};
/**
* Checks if a tensor is symmetric under swaps of the chosen axes.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} axes - Distinct 0-based axes, as a sequence or one array, while an empty list selects all axes
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isSymmetric([[1, 2], [2, 1]]); // Returns true
*/
export const isSymmetric = (tens: ChalkboardTensor, ...axes: number[]): boolean => {
const shape = $shape(tens, true, "isSymmetric", "tens");
axes = Array.isArray(axes[0]) ? axes[0] : axes;
if (axes.length === 0) axes = shape.map((_, i) => i);
if (new Set(axes).size !== axes.length || Array.from(axes).some((a) => !Number.isInteger(a) || a < 0 || a >= shape.length)) throw new Error(`Chalkboard.tens.isSymmetric: Parameter "axes" must contain distinct non-negative integers less than the tensor rank.`);
if (axes.some((a) => shape[a] !== shape[axes[0]])) return false;
if (axes.length < 2) return true;
const flat = $flatten(tens);
for (let k = 1; k < axes.length; k++) {
const order = shape.map((_, i) => i);
order[axes[k - 1]] = axes[k];
order[axes[k]] = axes[k - 1];
const swapped = $flatten($permute(tens, shape, order));
for (let i = 0; i < flat.length; i++) if (flat[i] !== swapped[i]) return false;
}
return true;
};
/**
* Checks if a tensor is a zero tensor. Elements that are NaN or infinite are never zero.
* @param {ChalkboardTensor} tens - The tensor
* @returns {boolean}
* @example
* const result = Chalkboard.tens.isZero([[0, 0], [0, 0]]); // Returns true
*/
export const isZero = (tens: ChalkboardTensor): boolean => {
$shape(tens, true, "isZero", "tens");
const check = (tens: ChalkboardTensor): boolean => {
if (!Array.isArray(tens)) return Math.abs(tens) < 0.000001;
for (let i = 0; i < tens.length; i++) {
const t = tens[i];
if (Array.isArray(t) ? !check(t) : !(Math.abs(t) < 0.000001)) return false;
}
return true;
};
return check(tens);
};
/**
* Initializes the Levi-Civita tensor.
* @param {number} dimension - The length of every axis
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.LeviCivita(2); // Returns [[0, 1], [-1, 0]]
*/
export const LeviCivita = (dimension: number): ChalkboardTensor => {
if (!Number.isInteger(dimension) || dimension < 0) throw new Error(`Chalkboard.tens.LeviCivita: Parameter "dimension" must be a non-negative integer.`);
if (dimension === 0) return 1;
const result = $resize([], new Array(dimension).fill(dimension));
const order = Array.from({ length: dimension }, (_, i) => i);
const walk = (depth: number, sign: number): void => {
if (depth === dimension) {
let target = result as ChalkboardTensor[];
for (let i = 0; i < dimension - 1; i++) target = target[order[i]] as ChalkboardTensor[];
target[order[dimension - 1]] = sign;
return;
}
for (let i = depth; i < dimension; i++) {
[order[depth], order[i]] = [order[i], order[depth]];
walk(depth + 1, i === depth ? sign : -sign);
[order[depth], order[i]] = [order[i], order[depth]];
}
};
walk(0, 1);
return result;
};
/**
* Calculates the maximum of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} [axis] - An axis less than the rank, removed from the result, while omitting it reduces all entries to a number
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.max([[1, 2, 3], [4, 5, 6]], 1); // Returns [3, 6]
*/
export const max = (tens: ChalkboardTensor, axis?: number): ChalkboardTensor => {
const shape = $shape(tens, true, "max", "tens");
if (axis !== undefined && (!Number.isInteger(axis) || axis < 0 || axis >= shape.length)) throw new Error(`Chalkboard.tens.max: Parameter "axis" must be a non-negative integer less than the tensor rank.`);
const flat = new Array(shape.reduce((a, b) => a * b, 1));
let index = 0;
const flatten = (t: ChalkboardTensor): void => {
if (!Array.isArray(t)) flat[index++] = t;
else if (Array.isArray(t[0])) for (let i = 0; i < t.length; i++) flatten(t[i]);
else for (let i = 0; i < t.length; i++) flat[index++] = t[i] as number;
};
flatten(tens);
const count = axis === undefined ? flat.length : shape[axis];
if (count === 0) throw new Error(`Chalkboard.tens.max: Parameter "tens" must have at least one entry to reduce.`);
const stride = axis === undefined ? 1 : shape.slice(axis + 1).reduce((a, b) => a * b, 1);
const reduce = (offset: number): number => {
let result = -Infinity;
for (let j = 0; j < count; j++) {
const x = flat[offset + j * stride];
result = Math.max(result, x);
}
return result;
};
if (axis === undefined) return reduce(0);
const outShape = shape.filter((_, i) => i !== axis);
const result: number[] = [];
const outer = shape.slice(0, axis).reduce((a, b) => a * b, 1);
for (let i = 0; i < outer; i++) for (let j = 0; j < stride; j++) result.push(reduce(i * count * stride + j));
return outShape.length === 0 ? result[0] : $resize(result, outShape);
};
/**
* Calculates the mean of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} [axis] - An axis less than the rank, removed from the result, while omitting it reduces all entries to a number
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.mean([[1, 2, 3], [4, 5, 6]], 1); // Returns [2, 5]
*/
export const mean = (tens: ChalkboardTensor, axis?: number): ChalkboardTensor => {
const shape = $shape(tens, true, "mean", "tens");
if (axis !== undefined && (!Number.isInteger(axis) || axis < 0 || axis >= shape.length)) throw new Error(`Chalkboard.tens.mean: Parameter "axis" must be a non-negative integer less than the tensor rank.`);
const flat = new Array(shape.reduce((a, b) => a * b, 1));
let index = 0;
const flatten = (t: ChalkboardTensor): void => {
if (!Array.isArray(t)) flat[index++] = t;
else if (Array.isArray(t[0])) for (let i = 0; i < t.length; i++) flatten(t[i]);
else for (let i = 0; i < t.length; i++) flat[index++] = t[i] as number;
};
flatten(tens);
const count = axis === undefined ? flat.length : shape[axis];
if (count === 0) throw new Error(`Chalkboard.tens.mean: Parameter "tens" must have at least one entry to reduce.`);
const stride = axis === undefined ? 1 : shape.slice(axis + 1).reduce((a, b) => a * b, 1);
const reduce = (offset: number): number => {
let result = 0;
for (let j = 0; j < count; j++) {
const x = flat[offset + j * stride];
result += x;
}
return result / count;
};
if (axis === undefined) return reduce(0);
const outShape = shape.filter((_, i) => i !== axis);
const result: number[] = [];
const outer = shape.slice(0, axis).reduce((a, b) => a * b, 1);
for (let i = 0; i < outer; i++) for (let j = 0; j < stride; j++) result.push(reduce(i * count * stride + j));
return outShape.length === 0 ? result[0] : $resize(result, outShape);
};
/**
* Calculates the minimum of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} [axis] - An axis less than the rank, removed from the result, while omitting it reduces all entries to a number
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.min([[1, 2, 3], [4, 5, 6]], 0); // Returns [1, 2, 3]
*/
export const min = (tens: ChalkboardTensor, axis?: number): ChalkboardTensor => {
const shape = $shape(tens, true, "min", "tens");
if (axis !== undefined && (!Number.isInteger(axis) || axis < 0 || axis >= shape.length)) throw new Error(`Chalkboard.tens.min: Parameter "axis" must be a non-negative integer less than the tensor rank.`);
const flat = new Array(shape.reduce((a, b) => a * b, 1));
let index = 0;
const flatten = (t: ChalkboardTensor): void => {
if (!Array.isArray(t)) flat[index++] = t;
else if (Array.isArray(t[0])) for (let i = 0; i < t.length; i++) flatten(t[i]);
else for (let i = 0; i < t.length; i++) flat[index++] = t[i] as number;
};
flatten(tens);
const count = axis === undefined ? flat.length : shape[axis];
if (count === 0) throw new Error(`Chalkboard.tens.min: Parameter "tens" must have at least one entry to reduce.`);
const stride = axis === undefined ? 1 : shape.slice(axis + 1).reduce((a, b) => a * b, 1);
const reduce = (offset: number): number => {
let result = Infinity;
for (let j = 0; j < count; j++) {
const x = flat[offset + j * stride];
result = Math.min(result, x);
}
return result;
};
if (axis === undefined) return reduce(0);
const outShape = shape.filter((_, i) => i !== axis);
const result: number[] = [];
const outer = shape.slice(0, axis).reduce((a, b) => a * b, 1);
for (let i = 0; i < outer; i++) for (let j = 0; j < stride; j++) result.push(reduce(i * count * stride + j));
return outShape.length === 0 ? result[0] : $resize(result, outShape);
};
/**
* Calculates the tensor (outer) product of two tensors, whose axes are the axes of the first tensor followed by the axes of the second tensor, so that the entry at index (i, ..., j, ...) is the product of the entries at (i, ...) and (j, ...); a number operand multiplies every entry of the other operand.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.mul([1, 2], [3, 4]); // Returns [[3, 4], [6, 8]]
*/
export const mul = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): ChalkboardTensor => {
$shape(tens1, true, "mul", "tens1");
$shape(tens2, true, "mul", "tens2");
return $outer(tens1, tens2);
};
/**
* Calculates the contraction between paired axes of two tensors. Remaining axes of the first tensor precede those of the second, while two empty axis lists give the outer product.
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @param {number | number[]} [axes1] - Distinct 0-based axes of the first tensor, defaulting to its last axis
* @param {number | number[]} [axes2=0] - Distinct 0-based axes of the second tensor, paired with equal-length axes in axes1
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.mulContract([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns [[19, 22], [43, 50]]
*/
export const mulContract = (tens1: ChalkboardTensor, tens2: ChalkboardTensor, axes1?: number | number[], axes2: number | number[] = [0]): ChalkboardTensor => {
const shape1 = $shape(tens1, true, "mulContract", "tens1");
const shape2 = $shape(tens2, true, "mulContract", "tens2");
axes1 = axes1 === undefined ? [shape1.length - 1] : Array.isArray(axes1) ? axes1 : [axes1];
axes2 = Array.isArray(axes2) ? axes2 : [axes2];
if (new Set(axes1).size !== axes1.length || Array.from(axes1).some((a) => !Number.isInteger(a) || a < 0 || a >= shape1.length)) throw new Error(`Chalkboard.tens.mulContract: Parameter "axes1" must contain distinct non-negative integers less than the rank of "tens1".`);
if (new Set(axes2).size !== axes2.length || Array.from(axes2).some((a) => !Number.isInteger(a) || a < 0 || a >= shape2.length)) throw new Error(`Chalkboard.tens.mulContract: Parameter "axes2" must contain distinct non-negative integers less than the rank of "tens2".`);
if (axes1.length !== axes2.length || axes1.some((a, i) => shape1[a] !== shape2[(axes2 as number[])[i]])) throw new Error(`Chalkboard.tens.mulContract: Parameters "axes1" and "axes2" must contain the same number of axes, pairing axes of equal length.`);
const keep1 = shape1.map((_, i) => i).filter((i) => !(axes1 as number[]).includes(i));
const keep2 = shape2.map((_, i) => i).filter((i) => !(axes2 as number[]).includes(i));
const a = $flatten($permute(tens1, shape1, keep1.concat(axes1)));
const b = $flatten($permute(tens2, shape2, axes2.concat(keep2)));
const m = keep1.reduce((p, i) => p * shape1[i], 1);
const n = keep2.reduce((p, i) => p * shape2[i], 1);
const k = axes1.reduce((p, i) => p * shape1[i], 1);
const result = new Array(m * n).fill(0);
for (let i = 0; i < m; i++) {
for (let p = 0; p < k; p++) {
const value = a[i * k + p];
for (let j = 0; j < n; j++) result[i * n + j] += value * b[p * n + j];
}
}
const outShape = keep1.map((i) => shape1[i]).concat(keep2.map((i) => shape2[i]));
return outShape.length === 0 ? result[0] : $resize(result, outShape);
};
/**
* Calculates the Hadamard (elementwise) product of two tensors, which are broadcast together as in NumPy (their shapes are aligned from the right, and axes of length 1 or missing axes are stretched).
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.mulHadamard([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns [[5, 12], [21, 32]]
* const broadcast = Chalkboard.tens.mulHadamard([[1, 2], [3, 4]], [10, 100]); // Returns [[10, 200], [30, 400]]
*/
export const mulHadamard = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): ChalkboardTensor => {
const shape1 = $shape(tens1, true, "mulHadamard", "tens1"), shape2 = $shape(tens2, true, "mulHadamard", "tens2");
if (Array.isArray(tens1) && Array.isArray(tens2) && !$isShapeEqual(shape1, shape2)) return $broadcast(tens1, shape1, tens2, shape2, (a, b) => a * b, "mulHadamard");
return $zip(tens1, tens2, (a, b) => a * b);
};
/**
* Calculates the negation of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.negate([[1, -2], [3, -4]]); // Returns [[-1, 2], [-3, 4]]
*/
export const negate = (tens: ChalkboardTensor): ChalkboardTensor => {
$shape(tens, true, "negate", "tens");
return $map(tens, (x) => -x);
};
/**
* Calculates the norm of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {"L0" | "L1" | "L2" | "LInfinity"} [type="L2"] - The type of norm, which can be "L0", "L1", "L2", or "LInfinity"
* @returns {number}
* @example
* const result = Chalkboard.tens.norm([[3, 4]]); // Returns 5
*/
export const norm = (tens: ChalkboardTensor, type: "L0" | "L1" | "L2" | "LInfinity" = "L2"): number => {
$shape(tens, true, "norm", "tens");
if (type !== "L0" && type !== "L1" && type !== "L2" && type !== "LInfinity") throw new Error(`Chalkboard.tens.norm: Parameter "type" must be L0, L1, L2, or LInfinity.`);
const flat = $flatten(tens);
let result = 0;
for (let i = 0; i < flat.length; i++) {
const x = flat[i];
if (type === "L0") result += x !== 0 ? 1 : 0;
else if (type === "L1") result += Math.abs(x);
else if (type === "L2") result += x * x;
else result = Math.max(result, Math.abs(x));
}
return type === "L2" ? Math.sqrt(result) : result;
};
/**
* Calculates the normalization of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {"L0" | "L1" | "L2" | "LInfinity"} [type="L2"] - The type of norm, which can be "L0", "L1", "L2", or "LInfinity"
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.normalize([3, 4]); // Returns [0.6, 0.8]
*/
export const normalize = (tens: ChalkboardTensor, type: "L0" | "L1" | "L2" | "LInfinity" = "L2"): ChalkboardTensor => {
$shape(tens, true, "normalize", "tens");
if (type !== "L0" && type !== "L1" && type !== "L2" && type !== "LInfinity") throw new Error(`Chalkboard.tens.normalize: Parameter "type" must be L0, L1, L2, or LInfinity.`);
const flat = $flatten(tens);
let result = 0;
for (let i = 0; i < flat.length; i++) {
const x = flat[i];
if (type === "L0") result += x !== 0 ? 1 : 0;
else if (type === "L1") result += Math.abs(x);
else if (type === "L2") result += x * x;
else result = Math.max(result, Math.abs(x));
}
const norm = type === "L2" ? Math.sqrt(result) : result;
return $map(tens, (x) => x / norm);
};
/**
* Calculates the norm squared of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {"L0" | "L1" | "L2" | "LInfinity"} [type="L2"] - The type of norm, which can be "L0", "L1", "L2", or "LInfinity"
* @returns {number}
* @example
* const result = Chalkboard.tens.normsq([[3, 4]]); // Returns 25
*/
export const normsq = (tens: ChalkboardTensor, type: "L0" | "L1" | "L2" | "LInfinity" = "L2"): number => {
$shape(tens, true, "normsq", "tens");
if (type !== "L0" && type !== "L1" && type !== "L2" && type !== "LInfinity") throw new Error(`Chalkboard.tens.normsq: Parameter "type" must be L0, L1, L2, or LInfinity.`);
const flat = $flatten(tens);
let result = 0;
for (let i = 0; i < flat.length; i++) {
const x = flat[i];
if (type === "L0") result += x !== 0 ? 1 : 0;
else if (type === "L1") result += Math.abs(x);
else if (type === "L2") result += x * x;
else result = Math.max(result, Math.abs(x));
}
return type === "L2" ? result : result * result;
};
/**
* Calculates the permutation of the axes of a tensor, so that axis k of the result is axis axes[k] of the tensor (as in NumPy's transpose with an axes argument).
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} axes - The order of the axes, as a permutation of the integers from 0 to the tensor rank minus one, either as a sequence of arguments or one array
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.permute([[[1, 2, 3]], [[4, 5, 6]]], 2, 0, 1); // Returns [[[1], [4]], [[2], [5]], [[3], [6]]]
*/
export const permute = (tens: ChalkboardTensor, ...axes: number[]): ChalkboardTensor => {
const shape = $shape(tens, false, "permute", "tens");
axes = Array.isArray(axes[0]) ? axes[0] : axes;
if (axes.length !== shape.length || new Set(axes).size !== shape.length || Array.from(axes).some((a) => !Number.isInteger(a) || a < 0 || a >= shape.length)) throw new Error(`Chalkboard.tens.permute: Parameter "axes" must be a permutation of the integers from 0 to the tensor rank minus one.`);
return $permute(tens, shape, axes);
};
/**
* Prints a tensor in the console.
* @param {ChalkboardTensor} tens - The tensor
* @returns {void}
* @example
* Chalkboard.tens.print([[[1, 2]], [[3, 4]]]); // Prints the tensor
*/
export const print = (tens: ChalkboardTensor): void => {
$shape(tens, false, "print", "tens");
console.log($string(tens, 0));
};
/**
* Returns a tensor with elements in an axis removed (pulled out).
* @param {ChalkboardTensor} tens - The tensor
* @param {number} axis - The axis, starting from 0 for the outermost axis
* @param {number} index - The index of the elements to pull
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.pull([[[1, 2]], [[3, 4]]], 1, 0); // Removes the first outer slice
*/
export const pull = (tens: ChalkboardTensor, axis: number, index: number): ChalkboardTensor => {
const shape = $shape(tens, false, "pull", "tens");
if (!Number.isInteger(axis) || axis < 0 || axis >= shape.length) throw new Error(`Chalkboard.tens.pull: Parameter "axis" must be a non-negative integer less than the tensor rank.`);
if (!Number.isInteger(index) || index < 0 || index >= shape[axis]) throw new Error(`Chalkboard.tens.pull: Parameter "index" must be an integer within the selected axis bounds.`);
const remove = (tensor: ChalkboardTensor[], currentAxis: number): void => {
if (currentAxis === 0) {
tensor.splice(index, 1);
} else {
for (let i = 0; i < tensor.length; i++) remove(tensor[i] as ChalkboardTensor[], currentAxis - 1);
}
};
remove(tens as ChalkboardTensor[], axis);
return tens;
};
/**
* Returns a tensor with elements in an axis added (pushed in).
* @param {ChalkboardTensor} tens - The tensor
* @param {number} axis - The axis, starting from 0 for the outermost axis
* @param {number} index - The index at which to insert the elements
* @param {ChalkboardTensor} elements - The elements to push
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.push([[[1, 2]]], 1, 1, [[3, 4]]); // Returns [[[1, 2], [3, 4]]]
*/
export const push = (tens: ChalkboardTensor, axis: number, index: number, elements: ChalkboardTensor): ChalkboardTensor => {
const shape = $shape(tens, false, "push", "tens");
if (!Number.isInteger(axis) || axis < 0 || axis >= shape.length) throw new Error(`Chalkboard.tens.push: Parameter "axis" must be a non-negative integer less than the tensor rank.`);
if (!Number.isInteger(index) || index < 0 || index > shape[axis]) throw new Error(`Chalkboard.tens.push: Parameter "index" must be an integer within the selected axis insertion bounds.`);
if (!$isShapeEqual($shape(elements, false, "push", "elements"), shape.slice(0, axis).concat(shape.slice(axis + 1)))) throw new Error(`Chalkboard.tens.push: Parameter "elements" must be a tensor whose shape equals the shape of "tens" without the selected axis.`);
const insert = (tensor: ChalkboardTensor[], currentAxis: number, currentElements: ChalkboardTensor): ChalkboardTensor[] => {
if (currentAxis === 0) {
tensor.splice(index, 0, currentElements);
} else {
for (let i = 0; i < tensor.length; i++) insert(tensor[i] as ChalkboardTensor[], currentAxis - 1, (currentElements as ChalkboardTensor[])[i]);
}
return tensor;
};
return insert(tens as ChalkboardTensor[], axis, elements);
};
/**
* Initializes a random tensor.
* @param {number} inf - The lower bound
* @param {number} sup - The upper bound
* @param {number[]} shape - The shape
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.random(-1, 1, 2, 2, 2); // Returns a random 2x2x2 tensor
*/
export const random = (inf: number, sup: number, ...shape: number[]): ChalkboardTensor => {
if (!Number.isFinite(inf)) throw new Error(`Chalkboard.tens.random: Parameter "inf" must be a finite number.`);
if (!Number.isFinite(sup)) throw new Error(`Chalkboard.tens.random: Parameter "sup" must be a finite number.`);
shape = $shapeArgs(shape, "random");
const newNDArray = (shape: number[]): ChalkboardTensor => {
if (shape.length === 0) return Chalkboard.numb.random(inf, sup);
const curr = shape[0];
const rest = shape.slice(1);
const result = [];
for (let i = 0; i < curr; i++) result[i] = newNDArray(rest);
return result;
};
return newNDArray(shape);
};
/**
* Calculates the rank of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @returns {number}
* @example
* const result = Chalkboard.tens.rank([[[1, 2]], [[3, 4]]]); // Returns 3
*/
export const rank = (tens: ChalkboardTensor): number => {
return $shape(tens, false, "rank", "tens").length;
};
/**
* Calculates the reciprocal of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.reciprocate([[1, 2], [4, 8]]); // Returns [[1, 0.5], [0.25, 0.125]]
*/
export const reciprocate = (tens: ChalkboardTensor): ChalkboardTensor => {
$shape(tens, true, "reciprocate", "tens");
return $map(tens, (x) => 1 / x);
};
/**
* Returns a tensor with the same entries in row-major order but a different shape, which must have the same size (unlike resize, which truncates or pads with zeros).
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} shape - The shape to change to, either as a sequence of arguments or one array
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.reshape([1, 2, 3, 4, 5, 6], 2, 3); // Returns [[1, 2, 3], [4, 5, 6]]
*/
export const reshape = (tens: ChalkboardTensor, ...shape: number[]): ChalkboardTensor => {
const current = $shape(tens, false, "reshape", "tens");
shape = $shapeArgs(shape, "reshape");
if (shape.reduce((a, b) => a * b, 1) !== current.reduce((a, b) => a * b, 1)) throw new Error(`Chalkboard.tens.reshape: Parameter "shape" must have a product equal to the size of "tens".`);
if (shape.length === 0) return $flatten(tens)[0];
return $resize(tens, shape);
};
/**
* Returns a tensor with its shape changed.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} shape - The shape to change to
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.resize([[1, 2], [3, 4]], 4); // Returns [1, 2, 3, 4]
*/
export const resize = (tens: ChalkboardTensor, ...shape: number[]): ChalkboardTensor => {
$shape(tens, false, "resize", "tens");
return $resize(tens, $shapeArgs(shape, "resize"));
};
/**
* Calculates the rounding of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.round([[1.2, 2.7], [-3.5, 4.4]]); // Returns [[1, 3], [-3, 4]]
*/
export const round = (tens: ChalkboardTensor): ChalkboardTensor => {
$shape(tens, true, "round", "tens");
return $map(tens, (x) => Math.round(x));
};
/**
* Calculates the scalar multiplication of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} num - The number, which may be NaN or infinite
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.scl([[1, 2], [3, 4]], 2); // Returns [[2, 4], [6, 8]]
*/
export const scl = (tens: ChalkboardTensor, num: number): ChalkboardTensor => {
$shape(tens, true, "scl", "tens");
if (typeof num !== "number") throw new Error(`Chalkboard.tens.scl: Parameter "num" must be a number.`);
return $map(tens, (x) => x * num);
};
/**
* Returns a tensor with a value set at a specific index.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} index - Between one and rank, in-bounds indices
* @param {ChalkboardTensor | null} value - A tensor matching the shape after the indexed axes, or a number or null at a full index
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.set([[1, 2], [3, 4]], [0, 1], 9); // Returns [[1, 9], [3, 4]]
*/
export const set = (tens: ChalkboardTensor, index: number[], value: ChalkboardTensor | null): ChalkboardTensor => {
const shape = $shape(tens, false, "set", "tens");
if (!Array.isArray(index) || index.length === 0 || index.length > shape.length || Array.from(index).some((i, a) => !Number.isInteger(i) || i < 0 || i >= shape[a])) throw new Error(`Chalkboard.tens.set: Parameter "index" must contain between one and as many integers as the tensor rank, each within its axis bounds.`);
const valueShape = value === null ? [] : $shape(value, false, "set", "value");
if (!$isShapeEqual(valueShape, shape.slice(index.length))) throw new Error(`Chalkboard.tens.set: Parameter "value" must be a tensor whose shape equals the shape of "tens" after the indexed axes.`);
let target = tens as ChalkboardTensor[];
for (let a = 0; a < index.length - 1; a++) target = target[index[a]] as ChalkboardTensor[];
target[index[index.length - 1]] = $copy(value as ChalkboardTensor);
return tens;
};
/**
* Returns the shape of a tensor, which is the array of its axis lengths.
* @param {ChalkboardTensor} tens - The tensor
* @returns {number[]}
* @example
* const result = Chalkboard.tens.shape([[[1, 2]], [[3, 4]]]); // Returns [2, 1, 2]
*/
export const shape = (tens: ChalkboardTensor): number[] => {
return $shape(tens, false, "shape", "tens");
};
/**
* Calculates the size of a tensor, which is its number of entries.
* @param {ChalkboardTensor} tens - The tensor
* @returns {number}
* @example
* const result = Chalkboard.tens.size([[[1, 2]], [[3, 4]]]); // Returns 4
*/
export const size = (tens: ChalkboardTensor): number => {
return $shape(tens, false, "size", "tens").reduce((a, b) => a * b, 1);
};
/**
* Returns a tensor sliced along leading axes.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[][]} ranges - At most rank [start, end] pairs, as a sequence or one array of pairs, with non-negative integer bounds and an exclusive end
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.slice([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [1, 3], [0, 2]); // Returns [[5, 6], [9, 10]]
*/
export const slice = (tens: ChalkboardTensor, ...ranges: [number, number][]): ChalkboardTensor => {
if (ranges.length === 1 && Array.isArray(ranges[0]) && ((ranges[0] as number[]).length === 0 || Array.isArray(ranges[0][0]))) ranges = ranges[0] as unknown as [number, number][];
const shape = $shape(tens, false, "slice", "tens");
if (ranges.length > shape.length || Array.from(ranges).some((r, a) => !Array.isArray(r) || r.length !== 2 || !Number.isInteger(r[0]) || !Number.isInteger(r[1]) || r[0] < 0 || r[0] > r[1] || r[1] > shape[a])) throw new Error(`Chalkboard.tens.slice: Parameter "ranges" must contain at most as many [start, end] pairs as the tensor rank, with integers such that 0 <= start <= end <= the axis length.`);
const walk = (t: ChalkboardTensor, depth: number): ChalkboardTensor => {
if (depth === ranges.length) return $copy(t);
const result: ChalkboardTensor[] = [];
const range = ranges[depth];
for (let i = range[0]; i < range[1]; i++) result.push(walk((t as ChalkboardTensor[])[i], depth + 1));
return result;
};
return walk(tens, 0);
};
/**
* Returns a tensor with a new axis inserted.
* @param {ChalkboardTensor[]} tensors - An array of tensors of equal shape
* @param {number} [axis=0] - The integer insertion axis, from 0 through the common rank inclusive
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.stack([[1, 2], [3, 4]], 1); // Returns [[1, 3], [2, 4]]
*/
export const stack = (tensors: ChalkboardTensor[], axis: number = 0): ChalkboardTensor => {
if (!Array.isArray(tensors) || tensors.length === 0) throw new Error(`Chalkboard.tens.stack: Parameter "tensors" must be a non-empty array of tensors with equal shapes.`);
const shapes = Array.from(tensors, (t) => $shape(t, false, "stack", "tensors"));
const shape = shapes[0];
if (shapes.some((s) => !$isShapeEqual(s, shape))) throw new Error(`Chalkboard.tens.stack: Parameter "tensors" must be a non-empty array of tensors with equal shapes.`);
if (!Number.isInteger(axis) || axis < 0 || axis > shape.length) throw new Error(`Chalkboard.tens.stack: Parameter "axis" must be a non-negative integer less than or equal to the rank of the tensors.`);
const order = shape.map((_, i) => i + 1);
order.splice(axis, 0, 0);
return $permute(tensors.map((t) => $copy(t)), [tensors.length].concat(shape), order);
};
/**
* Calculates the subtraction of two tensors, which are broadcast together as in NumPy (their shapes are aligned from the right, and axes of length 1 or missing axes are stretched).
* @param {ChalkboardTensor} tens1 - The first tensor
* @param {ChalkboardTensor} tens2 - The second tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.sub([[5, 8], [13, 21]], [[2, 3], [5, 8]]); // Returns [[3, 5], [8, 13]]
* const broadcast = Chalkboard.tens.sub([10], [[1], [2]]); // Returns [[9], [8]]
*/
export const sub = (tens1: ChalkboardTensor, tens2: ChalkboardTensor): ChalkboardTensor => {
const shape1 = $shape(tens1, true, "sub", "tens1"), shape2 = $shape(tens2, true, "sub", "tens2");
if (Array.isArray(tens1) && Array.isArray(tens2) && !$isShapeEqual(shape1, shape2)) return $broadcast(tens1, shape1, tens2, shape2, (a, b) => a - b, "sub");
return $zip(tens1, tens2, (a, b) => a - b);
};
/**
* Calculates the sum of a tensor along a given axis, or all entries if no axis is specified.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} [axis] - An axis less than the rank, removed from the result, while omitting it reduces all entries to a number
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.sum([[1, 2, 3], [4, 5, 6]], 0); // Returns [5, 7, 9]
*/
export const sum = (tens: ChalkboardTensor, axis?: number): ChalkboardTensor => {
const shape = $shape(tens, true, "sum", "tens");
if (axis !== undefined && (!Number.isInteger(axis) || axis < 0 || axis >= shape.length)) throw new Error(`Chalkboard.tens.sum: Parameter "axis" must be a non-negative integer less than the tensor rank.`);
const flat = new Array(shape.reduce((a, b) => a * b, 1));
let index = 0;
const flatten = (t: ChalkboardTensor): void => {
if (!Array.isArray(t)) flat[index++] = t;
else if (Array.isArray(t[0])) for (let i = 0; i < t.length; i++) flatten(t[i]);
else for (let i = 0; i < t.length; i++) flat[index++] = t[i] as number;
};
flatten(tens);
const count = axis === undefined ? flat.length : shape[axis];
const stride = axis === undefined ? 1 : shape.slice(axis + 1).reduce((a, b) => a * b, 1);
const reduce = (offset: number): number => {
let result = 0;
for (let j = 0; j < count; j++) {
const x = flat[offset + j * stride];
result += x;
}
return result;
};
if (axis === undefined) return reduce(0);
const outShape = shape.filter((_, i) => i !== axis);
const result: number[] = [];
const outer = shape.slice(0, axis).reduce((a, b) => a * b, 1);
for (let i = 0; i < outer; i++) for (let j = 0; j < stride; j++) result.push(reduce(i * count * stride + j));
return outShape.length === 0 ? result[0] : $resize(result, outShape);
};
/**
* Calculates the symmetric part of a tensor.
* @param {ChalkboardTensor} tens - The tensor
* @param {number[]} axes - Distinct 0-based axes, as a sequence or one array, while an empty list selects all axes
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.symmetrize([[1, 2], [4, 3]]); // Returns [[1, 3], [3, 3]]
*/
export const symmetrize = (tens: ChalkboardTensor, ...axes: number[]): ChalkboardTensor => {
const shape = $shape(tens, true, "symmetrize", "tens");
axes = Array.isArray(axes[0]) ? axes[0] : axes;
if (axes.length === 0) axes = shape.map((_, i) => i);
if (new Set(axes).size !== axes.length || Array.from(axes).some((a) => !Number.isInteger(a) || a < 0 || a >= shape.length)) throw new Error(`Chalkboard.tens.symmetrize: Parameter "axes" must contain distinct non-negative integers less than the tensor rank.`);
if (axes.some((a) => shape[a] !== shape[axes[0]])) throw new Error(`Chalkboard.tens.symmetrize: Parameter "axes" must contain axes of equal length.`);
if (axes.length < 2) return $copy(tens);
const result = new Array($flatten(tens).length).fill(0), permutation = axes.slice();
let count = 0;
const walk = (depth: number): void => {
if (depth === permutation.length) {
const order = shape.map((_, i) => i);
for (let i = 0; i < axes.length; i++) order[axes[i]] = permutation[i];
const flat = $flatten($permute(tens, shape, order));
for (let i = 0; i < flat.length; i++) result[i] += flat[i];
count++;
return;
}
for (let i = depth; i < permutation.length; i++) {
[permutation[depth], permutation[i]] = [permutation[i], permutation[depth]];
walk(depth + 1);
[permutation[depth], permutation[i]] = [permutation[i], permutation[depth]];
}
};
walk(0);
for (let i = 0; i < result.length; i++) result[i] /= count;
return $resize(result, shape);
};
/**
* Converts a tensor to an array.
* @param {ChalkboardTensor} tens - The tensor
* @returns {number[]}
* @example
* const result = Chalkboard.tens.toArray([[[1, 2]], [[3, 4]]]); // Returns [1, 2, 3, 4]
*/
export const toArray = (tens: ChalkboardTensor): number[] => {
$shape(tens, false, "toArray", "tens");
return $flatten(tens);
};
/**
* Converts a tensor to a matrix.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardMatrix}
* @example
* const result = Chalkboard.tens.toMatrix([[[1, 2]], [[3, 4]]]); // Returns a matrix containing the tensor values
*/
export const toMatrix = (tens: ChalkboardTensor): ChalkboardMatrix => {
$shape(tens, false, "toMatrix", "tens");
const result = Chalkboard.matr.init();
const arr = $flatten(tens);
const rows = (tens as ChalkboardTensor[]).length || 1;
for (let j = 0; j < rows; j++) {
result.push(arr.slice((j * arr.length) / rows, ((j + 1) * arr.length) / rows));
}
return result;
};
/**
* Converts a tensor to an object.
* @param {ChalkboardTensor} tens - The tensor
* @returns {object}
* @example
* const result = Chalkboard.tens.toObject([[1, 2], [3, 4]]); // Returns a nested object
*/
export const toObject = (tens: ChalkboardTensor): object | number => {
$shape(tens, false, "toObject", "tens");
const objectify = (tens: ChalkboardTensor): object | number => {
if (Array.isArray(tens)) {
const result: { [key: string]: number | object } = {};
for (let i = 0; i < tens.length; i++) {
result["_" + (i + 1)] = objectify(tens[i]);
}
return result;
} else {
return tens;
}
};
return objectify(tens);
};
/**
* Converts a tensor to a set.
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardSet}
* @example
* const result = Chalkboard.tens.toSet([[1, 1], [2, 3]]); // Returns the set {1, 2, 3}
*/
export const toSet = (tens: ChalkboardTensor): ChalkboardSet => {
$shape(tens, true, "toSet", "tens");
return Chalkboard.abal.set($flatten(tens));
};
/**
* Converts a tensor to a string.
* @param {ChalkboardTensor} tens - The tensor
* @returns {string}
* @example
* const result = Chalkboard.tens.toString([[[1, 2]], [[3, 4]]], 2); // Returns an indented tensor string
*/
export const toString = (tens: ChalkboardTensor, indentation: number = 0): string => {
$shape(tens, false, "toString", "tens");
if (!Number.isInteger(indentation) || indentation < 0) throw new Error(`Chalkboard.tens.toString: Parameter "indentation" must be a non-negative integer.`);
return $string(tens, indentation);
};
/**
* Converts a tensor to a typed array.
* @param {ChalkboardTensor} tens - The tensor
* @param {"int8" | "int16" | "int32" | "float32" | "float64" | "bigint64"} [type="float32"] - The type of the typed array, which can be "int8", "int16", "int32", "float32", "float64", or "bigint64" (optional, defaults to "float32")
* @returns {Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | BigInt64Array}
* @example
* const result = Chalkboard.tens.toTypedArray([[1, 2], [3, 4]], "float64"); // Returns a Float64Array
*/
export const toTypedArray = (tens: ChalkboardTensor, type: "int8" | "int16" | "int32" | "float32" | "float64" | "bigint64" = "float32"): Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | BigInt64Array => {
$shape(tens, true, "toTypedArray", "tens");
const arr = $flatten(tens);
if (type === "int8") {
return new Int8Array(arr);
} else if (type === "int16") {
return new Int16Array(arr);
} else if (type === "int32") {
return new Int32Array(arr);
} else if (type === "float32") {
return new Float32Array(arr);
} else if (type === "float64") {
return new Float64Array(arr);
} else if (type === "bigint64") {
return new BigInt64Array(arr.map((n) => BigInt(Math.floor(n))));
}
throw new Error(`Chalkboard.tens.toTypedArray: Parameter "type" must be int8, int16, int32, float32, float64, or bigint64.`);
};
/**
* Converts a tensor to a vector.
* @param {ChalkboardTensor} tens - The tensor
* @param {number} dimension - The dimension of the vector, which can be 2, 3, or 4
* @param {number} [index=0] - The index to start from
* @returns {ChalkboardVector}
* @example
* const result = Chalkboard.tens.toVector([[3, 4], [5, 12]], 2, 1); // Returns the second two-dimensional vector
*/
export const toVector = (tens: ChalkboardTensor, dimension: number, index: number = 0): ChalkboardVector => {
$shape(tens, true, "toVector", "tens");
if (dimension !== 2 && dimension !== 3 && dimension !== 4) throw new Error(`Chalkboard.tens.toVector: Parameter "dimension" must be 2, 3, or 4.`);
const arr = $flatten(tens);
if (!Number.isInteger(index) || index < 0 || index + dimension > arr.length) throw new Error(`Chalkboard.tens.toVector: Parameter "index" and parameter "dimension" must fit within the flattened tensor bounds.`);
if (dimension === 2) {
return Chalkboard.vect.init(arr[index], arr[index + 1]);
} else if (dimension === 3) {
return Chalkboard.vect.init(arr[index], arr[index + 1], arr[index + 2]);
} else if (dimension === 4) {
return Chalkboard.vect.init(arr[index], arr[index + 1], arr[index + 2], arr[index + 3]);
} else {
throw new Error(`Chalkboard.tens.toVector: Parameter "dimension" must be 2, 3, or 4.`);
}
};
/**
* Calculates the transpose of a tensor by reversing the order of its axes, so that the entry at index (i, j, ..., k) moves to (k, ..., j, i).
* @param {ChalkboardTensor} tens - The tensor
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.transpose([[1, 2, 3], [4, 5, 6]]); // Returns [[1, 4], [2, 5], [3, 6]]
*/
export const transpose = (tens: ChalkboardTensor): ChalkboardTensor => {
const shape = $shape(tens, false, "transpose", "tens");
return $permute(tens, shape, shape.map((_, k) => shape.length - 1 - k));
};
/**
* Initializes a zero tensor.
* @param {number[]} shape - The shape
* @returns {ChalkboardTensor}
* @example
* const result = Chalkboard.tens.zero(2, 2, 2); // Returns [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
*/
export const zero = (...shape: number[]): ChalkboardTensor => {
shape = $shapeArgs(shape, "zero");
const newNDArray = (shape: number[]): ChalkboardTensor => {
if (shape.length === 0) return 0;
const curr = shape[0];
const rest = shape.slice(1);
const result = [];
for (let i = 0; i < curr; i++) result[i] = newNDArray(rest);
return result;
};
return newNDArray(shape);
};
}
}