Public
Edited
Feb 19, 2020
Importers
3 stars
Insert cell
Insert cell
Insert cell
// adapted from https://github.com/jhuapl-boss/npyjs
class npyjs {
constructor(opts) {
if (opts) {
throw [
"No arguments accepted to npyjs constructor.",
"For usage, go to https://github.com/jhuapl-boss/npyjs."
].join(" ");
}

this.dtypes = {
"<u1": {
name: "uint8",
size: 8,
arrayConstructor: Uint8Array
},
"|u1": {
name: "uint8",
size: 8,
arrayConstructor: Uint8Array
},
"|i1": {
name: "int8",
size: 8,
arrayConstructor: Int8Array
},
"<u4": {
name: "uint32",
size: 32,
arrayConstructor: Int32Array
},
"<i4": {
name: "int32",
size: 32,
arrayConstructor: Int32Array
},
"<u8": {
name: "uint64",
size: 64,
arrayConstructor: BigUint64Array
},
"<i8": {
name: "int64",
size: 64,
arrayConstructor: BigInt64Array
},
"<f4": {
name: "float32",
size: 32,
arrayConstructor: Float32Array
},
"<f8": {
name: "float64",
size: 64,
arrayConstructor: Float64Array
}
};
}

parse(arrayBufferContents) {
// const version = arrayBufferContents.slice(6, 8); // Uint8-encoded
const headerLength = new DataView(
arrayBufferContents.slice(8, 10)
).getUint8(0);
const offsetBytes = 10 + headerLength;

const hcontents = new TextDecoder("utf-8").decode(
new Uint8Array(arrayBufferContents.slice(10, 10 + headerLength))
);
const header = JSON.parse(
hcontents
.replace(/'/g, '"')
.replace("False", "false")
.replace("(", "[")
.replace(/,*\),*/g, "]")
);
const shape = header.shape;

const dtype = this.dtypes[header.descr];

const nums = new dtype["arrayConstructor"](
arrayBufferContents,
offsetBytes
);

return {
dtype: dtype.name,
data: nums,
shape
};
}
}
Insert cell
Insert cell
Insert cell
FileAttachment("10-float32.npy")
.arrayBuffer()
.then(d => new npyjs().parse(d))
Insert cell
Insert cell
import { file } from "@jashkenas/inputs"
Insert cell
viewof f = file()
Insert cell
f.arrayBuffer().then(d => new npyjs().parse(d))
Insert cell
Insert cell
fetch(
"https://rawcdn.githack.com/aplbrain/npyjs/ba60a3a529f3210dd07d2ed05ab628939e18b6a7/test/data/4x4x4x4x4-float32.npy"
)
.then(d => d.arrayBuffer())
.then(d => new npyjs().parse(d))
Insert cell
// aplbrain/npyjs is licensed under the Apache License 2.0
LICENSE = "apache-2.0"
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more