Metadata-Version: 2.2
Name: jdai
Version: 0.1.0
Summary: Fast JSON, BJData, UBJSON and MessagePack I/O with JData annotations (numpy arrays, compression)
Author: Qianqian Fang
License: BSD-3-Clause OR GPL-3.0-or-later
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: BSD License
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Requires-Python: >=3.8
Requires-Dist: numpy
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Description-Content-Type: text/markdown

# jdai for Python

Fast reading and writing of JSON, BJData (Binary JData, Draft 4), UBJSON and MessagePack, with
[JData](https://neurojson.org/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 jdai library), with the GIL released and up to 8 threads.

```python
import numpy as np
import jdai

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

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

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

ann = jdai.encode(obj, compression="zlib")       # the JData-annotated form (dicts)
obj = jdai.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`             |
| `jdai.Extension(type, data)`    | BJData extension (`E`)                                  | `jdai.Extension`               |

Arrays read from a file share jdai'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.
- `jdai.threads()`, `jdai.set_threads(n)`: the number of threads (default: up to 8).

Errors in the input raise `jdai.JdaiError`, a `ValueError`.

## JSON-Mmap: reading and updating one member

A file can carry a [JSON-Mmap](https://neurojson.org/jsonmmap/draft1) table, the byte locators of its
values, before the document. jdai 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.

```python
jdai.save({"meta": {...}, "image": big_array, "n": 7}, "scan.pmat")   # with a table
jdai.load("scan.pmat", keys="n")              # 7: only those bytes are parsed
jdai.load("scan.pmat", keys=["meta", "n"])    # a dict of the members asked for
jdai.load("scan.pmat", keys="$.meta.date")    # a JSON-Mmap path
jdai.update("scan.pmat", "n", 8)              # in place (moved to the end of the file when it does not fit)
jdai.mmap("scan.pmat")                        # the table: [[name, value], ..., [path, [start, length, before, after]]]
jdai.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. `jdai.load` of a file with a table returns the
document after it, with values moved by updates put back.

## Building

```sh
pip install .                                   # scikit-build-core, from the top of the repository
# or with CMake:
cmake -S . -B build -DJDAI_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.
