Skip to content

Latest commit

 

History

History
110 lines (86 loc) · 6.49 KB

README.md

File metadata and controls

110 lines (86 loc) · 6.49 KB

jdi for Python

Fast reading and writing of JSON, BJData (Binary JData, Draft 4), UBJSON and MessagePack, with JData annotations: numpy arrays of any element type, shape and memory order, complex and compressed arrays (zlib, gzip, zstd, lz4, lzma, lzip, xz), structure-of-arrays records. The work is done in C++ (the jdi library), with the GIL released and up to 8 threads.

import numpy as np
import jdi

obj = {"name": "scan", "image": np.zeros((256, 256, 64), np.uint16), "tags": ["a", "b"]}

jdi.save(obj, "scan.bjd", compression="zstd")   # format from the file name: .bjd/.jdb, .json/.jdt, .ubj, .msgpack
back = jdi.load("scan.bjd")                     # numpy arrays come back with their dtype and shape

b = jdi.dumps(obj)                              # BJData bytes
t = jdi.dumps(obj, format="json", indent=2)     # JSON text (arrays as JData annotations)
obj = jdi.loads(b)                              # bytes; a str is read as JSON

ann = jdi.encode(obj, compression="zlib")       # the JData-annotated form (dicts)
obj = jdi.decode(ann)

load and save also take file objects (binary or text) and os.PathLike paths.

Values

Python stored as read back as
None, bool, str null, true/false, UTF-8 string the same
int the smallest integer type that holds it; beyond 64 bits a high-precision number int
float double (JSON: always with a decimal point) float
list, tuple array list
dict object (keys: str; int/float/bool/None keys as json writes them) dict
numpy.ndarray typed N-D array (BJData), or a JData annotation numpy.ndarray, no copy
numpy scalars a number of that type int/float/bool
bytes, bytearray BJData byte array (B) bytes (JSON etc.: uint8 array)
decimal.Decimal high-precision number (H) decimal.Decimal
jdi.Extension(type, data) BJData extension (E) jdi.Extension

Arrays read from a file share jdi's memory (no copy). Column-major data keeps its layout and gets Fortran strides (order="C" or "F" on load asks for one layout). Text that is not valid UTF-8 is kept with surrogate escapes and written back unchanged.

Options

load(path, format="auto", decode=True, order="keep", soa="records")

save(obj, path, format="auto", encode=True, compression=None, level=0, compress_min=300, annotate=False, shuffle=0, chunks=None, indent=None, float_digits=0, nonfinite="jdata", soa="col", soa_threshold=0.5, compact=False)

  • compression, level: the codec and its level (0: the codec's default). compress_min: only arrays with more elements are compressed (0: all). shuffle: byte-shuffle before compressing. chunks: compress in chunks: a number (1-D chunks of this many elements), a shape (N-D tiles, which load_region and update_region read and write one tile at a time), or "auto": N-D tiles of about 256 KiB (arrays up to 64 MiB) or 1 MiB (larger ones) for arrays of 2 or more dimensions and at least 2 MiB, one payload for the rest. A dict {"shape": "auto" or [...], "index": True, "slack": 16} also writes a chunk index with spare bytes after each chunk, for in-place updates.
  • annotate: write every array as a JData annotation, also in BJData.
  • JSON: indent (a number of spaces or a string), float_digits (0: the shortest text that reads back exactly), nonfinite ("jdata": "_NaN_"/"_Inf_"; "null"; "literal": NaN, not JSON).
  • BJData: soa stores a list of dicts with the same keys and scalar values as a structure-of-arrays ("col" or "row"; None turns it off); compact stores whole-valued numbers and arrays (also floating-point ones) in the smallest integer type, as jsonlab's savebj does: smaller files, but the element type is not kept.
  • enum (default on): a list of 16 or more strings with at most half as many distinct ones is stored as a JData enumeration (_EnumKey_: each distinct string once; _EnumValue_: 1-based integer codes, 0 for None), much smaller and faster to read; it loads back as the same list.
  • jdi.threads(), jdi.set_threads(n): the number of threads (default: up to 8).

Errors in the input raise jdi.JdiError, a ValueError.

JSON-Mmap: reading and updating one member

A file can carry a JSON-Mmap table, the byte locators of its values, before the document. jdi writes one by default for .pmat, .jmat, .bmmap and .jmmap files (mmap=True for any JSON or BJData file, mmap=False for none), and reads tables written by jsonlab (inline or embedded) and mimagen.

jdi.save({"meta": {...}, "image": big_array, "n": 7}, "scan.pmat")   # with a table
jdi.load("scan.pmat", keys="n")              # 7: only those bytes are parsed
jdi.load("scan.pmat", keys=["meta", "n"])    # a dict of the members asked for
jdi.load("scan.pmat", keys="$.meta.date")    # a JSON-Mmap path
jdi.update("scan.pmat", "n", 8)              # in place (moved to the end of the file when it does not fit)
jdi.mmap("scan.pmat")                        # the table: [[name, value], ..., [path, [start, length, before, after]]]
jdi.mmap("data.json", scan=True)             # a table made from any file's content

A table that no longer matches its file (its ReferenceFileBytes or a value's position) is not trusted: the file is parsed as a whole instead. jdi.load of a file with a table returns the document after it, with values moved by updates put back.

Building

pip install .                                   # scikit-build-core, from the top of the repository
# or with CMake:
cmake -S . -B build -DJDI_BUILD_PYTHON=ON && cmake --build build
PYTHONPATH=build/bindings/python python -m pytest tests/python

Requires a C++11 compiler, pybind11 and numpy.

License

BSD-3-Clause or GPL-3.0-or-later, at your choice.