@thi.ng/tensors
Version:
0D/1D/2D/3D/4D tensors with extensible polymorphic operations and customizable storage
38 lines (37 loc) • 1.08 kB
JavaScript
import { isNumber } from "@thi.ng/checks/is-number";
import { floatFixedWidth } from "@thi.ng/strings/float";
import { padLeft } from "@thi.ng/strings/pad-left";
import { truncate } from "@thi.ng/strings/truncate";
import { dot } from "@thi.ng/vectors/dot";
let formatNumber;
let pad;
let trunc;
const format = (x) => isNumber(x) ? formatNumber(x) : trunc(pad(x.toString()));
const setFormat = (width, prec) => {
formatNumber = floatFixedWidth(width, prec);
pad = padLeft(width);
trunc = truncate(width);
};
setFormat(9, 4);
const debug = ({ data, shape, stride, offset }) => {
let dim = shape.length;
const state = new Array(dim).fill(0);
dim--;
while (true) {
const idx = dot(state, stride) + offset;
console.log(state, idx, data[idx]);
if (++state[dim] >= shape[dim]) {
for (; dim-- > 0; ) if (++state[dim] < shape[dim]) break;
if (state[0] >= shape[0]) return;
state.fill(0, dim + 1);
dim = shape.length - 1;
}
}
};
const print = (a) => console.log(a.toString(), "\n");
export {
debug,
format,
print,
setFormat
};