Skip to content
NeuroJSONPublic

About

JData encoder and decoder for JavaScript

Resources

Code of conduct

Stars

4 stars

Watchers

1 watching

Forks

Latest commit

 

History

27 Commits

Folders and files

Repository files navigation

jda

jda: JData annotations for JavaScript, in web browsers and Node.js: typed, N-D, complex, sparse and compressed arrays in JSON and BJData

npm jsDelivr

Table of Contents

What's New

jda 1.0.0

  • A complete rewrite in TypeScript, with no runtime dependencies (atob, btoa, pako and numjs need not be installed). One source builds an ES module, a CommonJS module, a browser <script> file (plain and minified) and TypeScript declarations.
  • All of the JData specification: N-D arrays of every type and memory order, complex and sparse arrays, the special matrices of _ArrayShape_, compressed, byte-shuffled and chunked arrays, maps, tables, enumerations and byte streams.
  • Codecs built in: zlib and gzip (Node.js's own zlib, or a bundled pako in browsers), lz4 and lz4hc (raw LZ4 blocks, as zmat and jsonlab write them), base64, and, for label arrays (segmentations, atlases, masks), the experimental labelac and slabelac (the bytes jdai, zmat, jsonlab and pyjdata write; slabelac skips 4×4×4 blocks of one label); any other codec (lzma, zstd, blosc2 ...) plugs in with registerCodec.
  • Its own NDArray, or numjs arrays when numjs is loaded, as NeuroJSON.io's viewer uses them.
  • Multi-threaded zlib (zlibmt): stringifyAsync, parseAsync, savebjAsync, loadbjAsync (and encodeAsync, decodeAsync) compress and decompress zlib and gzip arrays on several threads: Node's zlib thread pool, or Web Workers in browsers. zlib arrays are written in the block-parallel zlibmt layout of zmat and jdai, which is still a standard zlib stream: 3 to 6 times faster to write, about twice as fast to read.
  • BJData files with bjd 1.0.
  • Checked against jsonlab and pyjdata in both directions.

Introduction

JData is a language-independent data annotation standard of the NeuroJSON project. It stores what plain JSON cannot (strongly-typed binary N-D arrays, complex and sparse arrays, compressed arrays, tables, maps, NaN and infinities) as lightweight name: value pairs in JSON, or in its binary form, BJData, so that MATLAB/Octave (jsonlab), Python (pyjdata, jdai) and JavaScript exchange them without loss. The neuroimaging formats of NeuroJSON (JNIfTI .jnii/.bnii, JMesh .jmsh/.bmsh, JSNIRF) are JData documents.

A uint8 3-D array of size 3x2x4 is stored as

{"_ArrayType_": "uint8", "_ArraySize_": [3, 2, 4],
 "_ArrayData_": [1, 7, 13, 19, 4, 10, 16, 22, 2, 8, 14, 20, 5, 11, 17, 23, 3, 9, 15, 21, 6, 12, 18, 24]}

or, compressed with zlib and stored as base64 text,

{"_ArrayType_": "uint8", "_ArraySize_": [3, 2, 4], "_ArrayZipType_": "zlib", "_ArrayZipSize_": [1, 24],
 "_ArrayZipData_": "eJxjZOcVZuESEGPi4BNh5RYUZ+bkF2XjEZIAAA1CAS0="}

jda turns either into a JavaScript value (here, an NDArray of shape [3, 2, 4] over a Uint8Array), and JavaScript values (typed arrays, N-D arrays, Map, NaN, BigInt ...) into such annotations. Together with JSON.parse, or with bjd for BJData, it reads the JData files written by jsonlab, pyjdata and jdai, in a web page or in Node.js.

Installation

For Node.js and bundlers

npm install jda
npm install bjd          # only to read and write BJData (.bjd, .bnii, .bmsh, .jdb) files

jda runs on Node.js 12 or newer, and has no dependencies (bjd is an optional peer). The package holds:

file for
dist/jdata.cjs require('jda') (CommonJS)
dist/jdata.mjs import ... from 'jda' (ES module, also for webpack, Vite, Rollup, esbuild)
dist/jdata.js, dist/jdata.min.js a <script> tag: defines the global jdata
dist/types/ TypeScript declarations (found by TypeScript by themselves)

For a web page

No installation is needed. Load the minified build from a CDN, which defines the global jdata; add bjd first to read BJData (the global bjdata):

<script src="https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.min.js"></script>   <!-- optional: BJData -->
<script src="https://cdn.jsdelivr.net/npm/jda@1/dist/jdata.min.js"></script>

(or the same paths on https://unpkg.com/), or import the ES modules:

<script type="module">
  import jd from 'https://cdn.jsdelivr.net/npm/jda@1/dist/jdata.mjs';
  import * as bjd from 'https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.mjs';
</script>

To serve it yourself, copy dist/jdata.min.js (89 kB, 30 kB gzipped, pako included) next to your page, from the npm package or from a build of this repository (see Building and testing).

Using jda in Node.js

const jd = require('jda');               // CommonJS
// import jd from 'jda';                 // ES module (or: import { parse, stringify } from 'jda')
const fs = require('fs');

// JavaScript values to JSON text with JData annotations
const vol = new jd.NDArray(new Float32Array(64 * 64 * 32).fill(1), [64, 64, 32]);
const text = jd.stringify({
    subject: 's01',
    vol,                                                  // an N-D array of floats
    labels: new Map([[1, 'gray matter'], [2, 'white matter']]),
    missing: NaN,                                         // "_NaN_" in the JSON text
}, { compression: 'zlib' });                              // arrays compressed, as base64 text
fs.writeFileSync('scan.json', text);

// and back
const data = jd.parse(fs.readFileSync('scan.json', 'utf8'));
data.vol.shape;            // [64, 64, 32]
data.vol.dtype;            // 'single'
data.vol.get(0, 0, 0);     // 1
data.labels.get(2);        // 'white matter'
data.missing;              // NaN

jd.parse(text) is jd.decode(JSON.parse(text)): decode takes a document that is already parsed, for example by a web framework. The same works for any JData file written by jsonlab, pyjdata or jdai (.json, .jdt, .jnii, .jmsh, ...).

BJData files need bjd (npm install bjd):

const bytes = jd.savebj({ vol, note: 'binary' }, { compression: 'lz4' });   // a Uint8Array
fs.writeFileSync('scan.bjd', bytes);

const scan = jd.loadbj(fs.readFileSync('scan.bjd'));     // scan.vol: an NDArray again

In TypeScript, the functions, the options and the classes are typed:

import jd, { parse, stringify, NDArray, EncodeOptions } from 'jda';

const opts: EncodeOptions = { compression: 'lz4', shuffle: true };
const text: string = stringify({ vol: new NDArray(new Float32Array(8), [2, 2, 2]) }, opts);
const vol: NDArray = parse(text).vol;

Using jda in a web page

With <script> tags, the functions are members of the global jdata (which is also the jda 0.x class):

<!DOCTYPE html>
<html>
<body>
  <script src="https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jda@1/dist/jdata.min.js"></script>
  <script>
    // a JSON file with JData annotations
    fetch('data/scan.json')
      .then((r) => r.json())
      .then((doc) => {
        const data = jdata.decode(doc);
        console.log(data.subject, data.vol.shape, data.vol.data);   // s01 [64, 64, 32] Float32Array
      });

    // a BJData file (with bjd loaded above)
    fetch('data/scan.bjd')
      .then((r) => r.arrayBuffer())
      .then((buf) => console.log(jdata.loadbj(buf).vol.shape));

    // JSON text to save or send
    const text = jdata.stringify({ m: new jdata.NDArray(new Float32Array([1, 2, 3, 4]), [2, 2]) },
                                 { compression: 'zlib' });
  </script>
</body>
</html>

When numjs is loaded (the global nj), arrays are decoded as numjs NdArrays instead, as NeuroJSON.io's viewer expects:

<script src="https://cdnjs.cloudflare.com/ajax/libs/numjs/0.16.0/numjs.min.js"></script>
<script>
  // jdata.decode(doc).vol is now an nj.NdArray: vol.shape, vol.get(i, j, k), vol.tolist()
</script>

(the ndarray option chooses the form either way: 'ndarray', 'numjs', 'nested', 'typed').

As ES modules, in a page or in an application built with a bundler, give bjd as an option:

<script type="module">
  import jd from 'https://cdn.jsdelivr.net/npm/jda@1/dist/jdata.mjs';
  import * as bjd from 'https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.mjs';

  const r = await fetch('data/scan.bjd');
  const scan = jd.loadbj(await r.arrayBuffer(), { bjd });
</script>
// in an application bundled by webpack, Vite, Rollup or esbuild (after npm install jda bjd)
import jd from 'jda';
import * as bjd from 'bjd';
const scan = jd.loadbj(bytes, { bjd });

More examples

N-D arrays

NDArray holds a typed array data in row-major order, a shape and a JData type dtype:

const m = jd.NDArray.from([[1, 2, 3], [4, 5, 6]]);      // double, 2x3 (or NDArray.from(list, 'int32'))
m.shape;                 // [2, 3]
m.get(1, 2);             // 6
m.set(1, 2, 60);         // m.get(1, 2) is now 60
m.transpose().tolist();  // [[1, 4], [2, 5], [3, 60]]
m.reshape(3, 2).tolist();// [[1, 2], [3, 4], [5, 60]]

new jd.NDArray(new Int16Array(24), [2, 3, 4]);          // over an existing typed array

Plain typed arrays, numjs NdArrays and scijs ndarrays are encoded as annotated arrays too. Column-major arrays (_ArrayOrder_: "c", as MATLAB stores them) are reordered on reading.

Complex, sparse and special matrices

const z = new jd.NDArray(new Float64Array([1, 2]), [2], 'double', new Float64Array([3, -4]));
jd.stringify({ z });
// {"z":{"_ArrayType_":"double","_ArraySize_":[2],"_ArrayIsComplex_":true,"_ArrayData_":[[1,2],[3,-4]]}}
jd.parse(jd.stringify({ z })).z.tolist();               // [{re: 1, im: 3}, {re: 2, im: -4}]

// a 3x3 sparse matrix: 1-based row and column indices, then the values
const s = jd.decode({ _ArrayType_: 'double', _ArraySize_: [3, 3], _ArrayIsSparse_: true,
                      _ArrayData_: [[1, 3], [1, 2], [5.5, 7]] });
s.nnz;                   // 2
s.toDense().tolist();    // [[5.5, 0, 0], [0, 0, 0], [0, 7, 0]]

jd.decode({ _ArrayType_: 'double', _ArraySize_: [3, 3], _ArrayShape_: 'diag',
            _ArrayData_: [1, 2, 3] }).tolist();          // [[1, 0, 0], [0, 2, 0], [0, 0, 3]]

Compression

jd.stringify(value, { compression: 'zlib' });                   // or 'gzip', 'lz4', 'lz4hc', 'base64'
jd.stringify(value, { compression: 'lz4', shuffle: true });     // byte-shuffled: floats compress better
jd.stringify({ seg }, { compression: 'slabelac' });              // label arrays (or 'labelac')
jd.stringify(value, { compression: 'zlib', compressArraySize: 100 });   // leave small arrays alone

Codecs that are not built in are registered once, with a function that decompresses (and optionally one that compresses), for example zstd with the fzstd package:

const { decompress } = require('fzstd');
jd.registerCodec('zstd', { decode: (bytes) => decompress(bytes) });
const doc = jd.parse(text);          // _ArrayZipType_ "zstd" arrays now decode

Without a codec, decoding such an array fails with an error that names it.

Multi-threaded zlib (zlibmt)

The Async functions take the same options as the others, and return promises. They compress or decompress every zlib and gzip array of the document at the same time, and split large zlib arrays into blocks, so several threads work on one array:

const text = await jd.stringifyAsync({ vol }, { compression: 'zlib' });   // threads: all of them
const doc = await jd.parseAsync(text, { threads: 4 });
const bytes = await jd.savebjAsync({ vol }, { compression: 'zlib' });     // BJData, with bjd
const back = await jd.loadbjAsync(bytes);
  • The format: a zlib array is deflated in independent blocks (1/16 of the array, from 256 KiB to 4 MiB), each ended by a full flush, behind one zlib header and with the Adler-32 of the whole array. This is zlibmt, the layout zmat and jdai write. It is an ordinary zlib stream, so jsonlab, pyjdata, Python's zlib and any other zlib reader decode it, and it is only 0.02% (level 1) to 0.2% (level 6) larger. The blocks depend on the array alone, so the output is the same for any number of threads. encode, stringify and savebj write it too with zlibmt: true.
  • Reading splits a zlib stream at its full-flush marks, inflates the pieces on threads, and keeps the result when the lengths and the Adler-32 agree. Any zlib stream decodes correctly. A stream with no such marks, as zmat writes without zlibmt and as stringify writes by default, is inflated whole, still off the main thread, alongside the other arrays.
  • Node.js uses its zlib thread pool, 4 threads unless UV_THREADPOOL_SIZE (set before Node starts) says otherwise. No worker files are needed.
  • Browsers start Web Workers that load the same jdata.js, jdata.min.js or jdata.mjs the page loaded, from a CDN as well. The workers stay for later calls; jd.closeWorkers() stops them. When jda is bundled into your own script, pass the URL of a jdata.min.js as workerURL (or a jdata.mjs, with workerModule: true). Without workers (no URL, or a page whose CSP does not allow blob: workers) the work runs on the main thread, with the same results.
  • Other codecs (lz4, base64, registered ones) run as they do in the synchronous functions.

jd.zlibmt.deflate(bytes, {level, threads}) and jd.zlibmt.inflate(bytes, {size, threads}) do the same for bytes of your own.

Tables, byte streams and other values

jd.decode({ _TableCols_: ['name', 'age'], _TableRows_: [], _TableRecords_: [['Ann', 31], ['Bob', 42]] });
// { name: ['Ann', 'Bob'], age: [31, 42] }     (table: 'records' gives an array of objects)

jd.stringify({ when: new Date(0), n: BigInt(5), raw: new Uint8Array([1, 2]).buffer });
// {"when":"1970-01-01T00:00:00.000Z","n":5,"raw":{"_ByteStream_":"AQI="}}

The jda 0.x class

Code written for jda 0.x keeps working:

const jdata = require('jda');        // or the jdata global in a page
const json = new jdata({ v: new Float64Array([1, 2, 3]) }, { compression: 'zlib' }).encode().tojson();
const back = new jdata(JSON.parse(json)).decode().data;   // back.v: an NDArray (or a numjs array)

API reference

Function
decode(value, options?) the JavaScript values of the JData annotations in a parsed document
encode(value, options?) the JData-annotated form of a value (target: 'bjdata' for BJData)
parse(text, options?) decode(JSON.parse(text))
stringify(value, options?, space?) JSON text of encode(value)
loadbj(bytes, options?), savebj(value, options?) BJData with bjd (installed, the bjdata global, or options.bjd; options.bjdOptions go to bjd)
parseAsync, stringifyAsync, loadbjAsync, savebjAsync, decodeAsync, encodeAsync the same, returning promises, with zlib and gzip arrays on several threads (zlibmt)
zlibmt.deflate(bytes, options?), zlibmt.inflate(bytes, options?) zlibmt streams of bytes, on threads; closeWorkers() stops the browser workers
registerCodec(name, {decode, encode?}), codecNames() add a compression codec; the codecs known
base64ToBytes(text), bytesToBase64(bytes) base64 (also the URL alphabet, with line breaks)
new jdata(data, options) the jda 0.x class: .encode(), .decode(), .tojson(), .data

Classes: NDArray (data, shape, dtype, imag for complex arrays; get, set, reshape, transpose, tolist, NDArray.from(nested, dtype?)) and SparseArray (shape, 0-based indices per dimension, values, nnz; toDense()).

Decoded values

JData JavaScript
annotated array NDArray, or a numjs NdArray when numjs is loaded (option ndarray)
complex array NDArray with imag ({re, im} values in the other forms)
sparse array SparseArray (sparse: 'dense': a dense array)
_ArrayShape_ matrix the full matrix; a range of several dimensions: one axis per dimension
_MapData_ Map
table an object of columns (table: 'records': an array of objects)
enumeration the array of its values
_ByteStream_ Uint8Array
"_NaN_", "_Inf_", "-_Inf_" NaN, Infinity, -Infinity

Decoder options

Option Default
ndarray 'auto' 'auto': numjs NdArray when numjs is loaded (the nj global) or given (nj), else NDArray; 'ndarray'; 'numjs'; 'nested' (nested arrays); 'typed' (the flat typed array); 'jdata' (a {_ArrayType_, _ArraySize_, _ArrayData_} object); or (data, shape, dtype) => value
nj the numjs module
sparse 'sparse' 'dense': sparse arrays as dense ones
table 'columns' 'records': tables as arrays of objects
codecs {name: {decode, encode}} codecs for this call
base64 true false: _ArrayZipData_ text is a binary string, not base64
threads all the Async functions: the most threads (Node.js: at most UV_THREADPOOL_SIZE, default 4)
workerURL, workerModule this script browsers: the jdata.min.js (or, with workerModule, jdata.mjs) the workers load

Encoder options

Option Default
compression 'zlib', 'gzip', 'lz4', 'lz4hc', 'base64', 'labelac', 'slabelac', or a registered codec
compressArraySize 1 the fewest elements an array needs to be compressed
shuffle false shuffle the bytes of the elements before compressing (true: by element size)
level the compression level
target 'json' 'bjdata': raw payloads, IEEE numbers and typed arrays for a BJData writer
base64 _ArrayZipData_ as base64 text (default: for JSON); false in JSON: a list of byte values
zlibmt false zlib arrays in zlibmt blocks (true in the Async functions)
threads, workerURL, workerModule the Async functions, as for decoding

JavaScript values are written as: typed arrays, NDArray, numjs and scijs ndarrays as annotated arrays; SparseArray as sparse arrays; NaN and infinities as "_NaN_", "_Inf_", "-_Inf_" (in JSON); BigInt as a number when exact, else a compressed 64-bit array (JSON numbers cannot hold it); Map as _MapData_; ArrayBuffer as _ByteStream_; Date as ISO 8601 text; Set as an array.

Performance

Node.js 12, one thread, best of 3, a 64×128×128 float32 volume (4 MiB) as {vol: NDArray}:

stringify parse
uncompressed 174 ms 71 ms
zlib 127 ms 21 ms
lz4 13 ms 8 ms
base64 8 ms 11 ms

Uncompressed JSON is the cost of JSON.stringify and JSON.parse of a million numbers, and zlib is Node's own deflate (117 ms of the 127). base64 uses Node's codec when it can and a table-driven loop in browsers; lz4 is built in, and skips ahead through data that does not compress, as LZ4 itself does. For the fastest loading of large arrays, store them as BJData: loadbj of the same volume, uncompressed, takes under a millisecond.

With threads, a 4000×4000 float32 array (64 MiB), zlib level 6, best of 3; Node.js 12 on a 16-core machine (threads set by UV_THREADPOOL_SIZE), and Chrome on the same machine for a 32 MiB array (one run, warm workers):

one thread 4 threads 8 threads
Node.js savebj / savebjAsync 1863 ms 519 ms 316 ms
Node.js loadbj / loadbjAsync 161 ms 93 ms 72 ms
Node.js stringify / stringifyAsync 1918 ms 569 ms 368 ms
Node.js parse / parseAsync 200 ms 129 ms 116 ms
Chrome stringify / stringifyAsync (32 MiB) 1670 ms 236 ms (16 workers)
Chrome parse / parseAsync (32 MiB) 162 ms 81 ms (16 workers)

Deflating scales with the threads. Inflating is fast already, and the main thread's share (the Adler-32 check, copying the pieces together, base64 and JSON) limits the gain to about two times.

Upgrading from jda 0.x

  • new jdata(data, options).encode()/.decode()/.tojson() work as before; require('jda') and the jdata global are still the class, and require('jda/jdata.js') still works.
  • No more dependencies: atob, btoa, pako and numjs need not be installed (Node.js uses its own zlib). numjs is still used when it is loaded or passed as {nj}; else arrays are NDArrays.
  • Uncompressed annotated arrays are now N-D arrays as compressed ones are (0.x returned their _ArrayData_ as it was), and column-major ones are reordered.
  • _ByteStream_ gives a Uint8Array (0.x: a Blob; bytestream: 'blob' in browsers).
  • _ArrayZipData_ text or bytes are told apart by type: base64: false is rarely needed.

Building and testing

git clone https://github.com/NeuroJSON/jsdata.git
cd jsdata
npm install            # TypeScript, esbuild and pako, to build
npm run build          # dist/: jdata.mjs, jdata.cjs, jdata.js, jdata.min.js, types/
npm test               # unit tests, with the examples of the specification

The sources are in src/ (decode.ts, encode.ts, codecs.ts, ndarray.ts). test/interop/ checks jda against jsonlab (Octave or MATLAB) and pyjdata in both directions (sh test/interop/run.sh), and test/browser.html, served over HTTP from the parent folder of jsdata and js-bjdata, runs the browser builds.

Contribution and Feedback

jda is an open-source project. You can not only use it and modify it as you wish, but also contribute your changes back so that everyone else can enjoy the improvement. To contribute, download the source code from its repository:

git clone https://github.com/NeuroJSON/jsdata.git

or browse the github site at https://github.com/NeuroJSON/jsdata

Once you are satisfied with your changes, and ready to share them with others, please submit them as a "pull request" on github. The project maintainer, Dr. Qianqian Fang, will review the changes and choose to accept the patch.

We appreciate any suggestions and feedback from you. Please use the NeuroJSON forum to report any questions you may have regarding jda:

NeuroJSON forum

Acknowledgement

jda's decoders and encoders, its lz4, base64, labelac and slabelac codecs are its own. Its browser builds bundle the below open-source library, unmodified (in Node.js, jda uses Node's own zlib instead):

  1. pako: https://github.com/nodeca/pako (version 2.1.0)
    • Copyright (C) 2014-2017 by Vitaly Puzrin and Andrei Tuputcyn
    • License: MIT License, and the zlib License for the parts ported from zlib
    • Used for: the zlib and gzip codecs

About

JData encoder and decoder for JavaScript

Resources

Code of conduct

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages