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 letsload_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:
dictwithstrkeys (any characters, including/; keys are escaped into valid HDF5 names and restored on load),listandtuple;numpy arrays and numpy scalars, JAX arrays (of any shape, including 0-d, with numeric or bool dtype);
Python
bool,int,float,complex,strandNone;brainunit.Quantity(the mantissa is the dataset; the unit is stored as attributes);braintools.spike.SpikeTrains(a group with the datasetstimes,counts,t_start,t_stopandoverflow, and the time unit as attributes).
overwrite (
bool) – Whether to replace an existing file atpath.
- Raises:
FileExistsError – If
pathexists andoverwriteis False.TypeError – If the tree contains an unsupported value (for example a non-
strdict key, an object or string array, abfloat16array, or a JAX tracer).OverflowError – If a Python
intlies outside[-2**63, 2**64 - 1].ImportError – If
h5pyis not installed (pip install braintools[hdf5]).
- Return type:
See also
load_hdf5Read the file back.
msgpack_saveCheckpoint brainstate model states.
Notes
This is a host-side I/O function: call it on concrete values, not inside
jax.jitorjax.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 withbrainunit.parse_unitand falls back to the exact definition, so even units without a display name round-trip exactly.None.
Noneis stored as an empty dataset and loaded asNone.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}