save_nwb_units

Contents

save_nwb_units#

class braintools.file.save_nwb_units(path, trains, *, session_description, identifier, session_start_time=None, unit_ids=None, overwrite=False)#

Write a SpikeTrains to the Units table of a new NWB file.

Each neuron becomes one row of the NWB units table. Its spike_times are stored in seconds (the NWB convention), converted from the trains’ time unit, and its obs_intervals is [[t_start, t_stop]] in seconds. The recording bounds are also written as the single row of a TimeIntervals table braintools_recording in the file’s intervals group, so they round-trip even for zero neurons.

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

  • trains (SpikeTrains) – Unbatched spike trains whose times carry a brainunit time unit.

  • session_description (str) – Description of the recording session (required by NWB).

  • identifier (str) – Unique identifier of the file (required by NWB).

  • session_start_time (datetime | None) – Start of the session; NWB requires a timezone-aware value. Defaults to the current UTC time.

  • unit_ids (Sequence[int] | None) – Unique ids of the n_neurons rows. Defaults to 0, ..., N-1.

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

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

  • TypeError – If trains is not a SpikeTrains, is traced, or has no time unit (NWB stores seconds, so unitless times are rejected rather than assumed to be in some unit).

  • ValueError – If trains is batched, or unit_ids has the wrong length or repeated ids.

  • ImportError – If pynwb is not installed (pip install braintools[nwb]).

Return type:

None

See also

load_nwb_units

Read the Units table back.

save_nwb_timeseries

Write a regularly sampled signal.

Notes

Host-only (not under jax.jit/jax.vmap). Times are converted to float64 seconds before writing. If trains.overflow is set, a boolean column braintools_overflow (True in every row) is added so that load_nwb_units() restores the flag; otherwise the file contains only standard NWB columns. A population with zero neurons is written as an empty Units table.

Examples

>>> import os, tempfile
>>> import brainunit as u
>>> import numpy as np
>>> from braintools.file._nwb import save_nwb_units, load_nwb_units
>>> from braintools.spike import SpikeTrains
>>> st = SpikeTrains.from_list([np.array([1.5, 4.]) * u.ms, np.array([]) * u.ms],
...                            t_start=0. * u.ms, t_stop=5. * u.ms)
>>> path = os.path.join(tempfile.mkdtemp(), 'units.nwb')
>>> save_nwb_units(path, st, session_description='demo', identifier='demo-1')
>>> back = load_nwb_units(path)
>>> back.counts
Array([2, 0], dtype=int32)
>>> back.t_stop
Quantity(0.005, "s")