save_hdf5

Contents

save_hdf5#

class braintools.file.save_hdf5(path, tree, *, overwrite=False)#

Save a nested tree of arrays, Quantities and spike trains to an HDF5 file.

Containers become HDF5 groups and leaves become datasets, so the file can also be browsed with standard HDF5 tools (h5ls, HDFView, h5py). Every object carries a small type attribute that lets load_hdf5() rebuild exactly the Python types that were saved.

Parameters:
  • path (str | PathLike) – Target file. The file is written to a temporary file next to it and moved into place only when writing succeeded.

  • tree (Any) –

    The data to save. Supported values, nested arbitrarily:

    • dict with str keys (any characters, including /; keys are escaped into valid HDF5 names and restored on load), list and tuple;

    • numpy arrays and numpy scalars, JAX arrays (of any shape, including 0-d, with numeric or bool dtype);

    • Python bool, int, float, complex, str and None;

    • brainunit.Quantity (the mantissa is the dataset; the unit is stored as attributes);

    • braintools.spike.SpikeTrains (a group with the datasets times, counts, t_start, t_stop and overflow, and the time unit as attributes).

  • overwrite (bool) – Whether to replace an existing file at path.

Raises:
  • FileExistsError – If path exists and overwrite is False.

  • TypeError – If the tree contains an unsupported value (for example a non-str dict key, an object or string array, a bfloat16 array, or a JAX tracer).

  • OverflowError – If a Python int lies outside [-2**63, 2**64 - 1].

  • ImportError – If h5py is not installed (pip install braintools[hdf5]).

Return type:

None

See also

load_hdf5

Read the file back.

msgpack_save

Checkpoint brainstate model states.

Notes

This is a host-side I/O function: call it on concrete values, not inside jax.jit or jax.vmap.

Type fidelity. dtypes and shapes are kept, and so are the container types, the dict key order, whether an array was a numpy or a JAX array, and whether a Quantity mantissa was a numpy or a JAX array. Named tuples are saved as their fields and loaded as plain tuples.

Units. A unit is stored both as its display string (for example "mV / ms") and as its exact definition (SI dimension exponents, scale, base and factor). Loading parses the string with brainunit.parse_unit and falls back to the exact definition, so even units without a display name round-trip exactly.

None. None is stored as an empty dataset and loaded as None.

Examples

>>> import os, tempfile
>>> import brainunit as u
>>> import numpy as np
>>> from braintools.file._hdf5 import save_hdf5, load_hdf5
>>> path = os.path.join(tempfile.mkdtemp(), 'run.h5')
>>> tree = {'v/soma': np.zeros(3) * u.mV, 'meta': {'seed': 42, 'tag': None}}
>>> save_hdf5(path, tree)
>>> out = load_hdf5(path)
>>> out['v/soma']
Quantity([0. 0. 0.], "mV")
>>> out['meta']
{'seed': 42, 'tag': None}