diff --git a/source/User-Manual/Data-formats/NWB-format.rst b/source/User-Manual/Data-formats/NWB-format.rst index c3dcdede..ee3447f5 100644 --- a/source/User-Manual/Data-formats/NWB-format.rst +++ b/source/User-Manual/Data-formats/NWB-format.rst @@ -13,39 +13,51 @@ NWB Format "*Platforms*", "Windows, Linux, macOS" "*Built in?*", "No" - "*Key Developers*", "Aarón Cuevas López, Pavel Kulik, Josh Siegle" + "*Key Developers*", "Aarón Cuevas López, Pavel Kulik, Josh Siegle, Stephanie Prince, Oliver Rübel" "*Source Code*", "https://github.com/open-ephys-plugins/nwb-format" +This page describes the files written by version 2.0 and later of the NWB Format plugin, which uses `AqNWB `__ to write NWB 2.11 files. The differences to files written by earlier versions are listed under :ref:`nwbearlierversions`. **Advantages** -* NWB is a widely used format for sharing data among neuroscience labs. +* NWB is a widely used format for sharing data among neuroscience labs, and the standard format of the `DANDI Archive `__. * Data is stored in a single HDF5 file with self-documenting internal structure. -* Files can be read using the `pynwb `__ or `matnwb `__ libraries, or with the growing number of high-level tools that support the NWB format. +* Files can be read using the `PyNWB `__ or `MatNWB `__ libraries, or with the growing number of high-level tools that support the NWB format. + +* Files are written in HDF5 SWMR (single-writer, multiple-reader) mode, which keeps the file consistent at any time, so a crash doesn't leave a damaged file. Other programs can read the file during a recording by opening it as an SWMR reader. + +* Files are flushed every 10 s during a recording and when a recording stops, so data up to the last flush remains readable if the GUI crashes (see :ref:`nwbaftercrash`). **Limitations** -* HDF5 files must be closed gracefully, so data may be irrecoverable if the GUI crashes during acquisition. +* Data written since the last flush (at most about 10 s) is lost if the GUI crashes during a recording. * The HDF5 C++ library is not thread-safe, so you cannot write to the NWB format from multiple Record Nodes simultaneously. +* Sorted spike units (e.g., from the Spike Sorter) are not stored yet. + File organization #################### -Within a Record Node directory, data for each **experiment** (stop/start acquisition) is contained in a separate NWB file. Individual **recordings** are appended to datasets stored inside the "acquisition" group. +Within a Record Node directory, data for each **experiment** (stop/start acquisition) is contained in a separate NWB file, :code:`experiment.nwb`. Individual **recordings** (start/stop recording) within an experiment are appended to the same datasets; the start and stop time of each recording are stored in the :code:`epochs` table. + +If the recording directory is changed between recordings, the next recording starts a new file in the new directory. Existing files are never changed: if the new directory already contains :code:`experiment.nwb` (e.g., after changing the directory and back), the new file is named after the experiment and its first recording, e.g. :code:`experiment1_recording3.nwb`. .. image:: ../../_static/images/recordingdata/nwb/organization.png :alt: NWB data file structure :width: 300 +The objects are named after the processor, its id, the data stream and (for spikes) the electrode, e.g., :code:`File Reader-100.example_data` (shown as :code:`processor1.stream1` in the figures). :code:`/general` also contains the devices, the subject (if provided, see below) and the versions of the GUI and the plugin (:code:`was_generated_by`). + Each NWB file also contains the following information: -* :code:`/file_create_date`: date + time in ISO format (text array) -* :code:`/identifier`: string identifier for this file (text array) -* :code:`/nwb_version`: '2.4.0' (text attribute) -* :code:`/session_start_time`: date + time in ISO format (text array) +* :code:`/nwb_version`: :code:`2.11.0` (text attribute) +* :code:`/identifier`: unique identifier for this file (text) +* :code:`/session_start_time` and :code:`/timestamps_reference_time`: date and time of timestamp 0 of the GUI in ISO 8601 format (see :ref:`nwbtimestamps`) +* :code:`/file_create_date`: date and time in ISO 8601 format (text array) +* :code:`/session_description`: description of the session (text) Format details ################ @@ -57,64 +69,198 @@ Continuous data is grouped by stream (a block of synchronously sampled channels) .. image:: ../../_static/images/recordingdata/nwb/continuous.png :alt: NWB data continuous format - :width: 300 + :width: 214 -Each **continuous** group is an NWB *ElectricalSeries* containing the following datasets: +Each **continuous** group in :code:`/acquisition` is an NWB *ElectricalSeries* containing the following datasets: -* :code:`data`: *N* channels x *M* samples of 16-bit integers. The :code:`channel_conversion` dataset stores the "bitVolts" value required to convert these values into volts. +* :code:`data`: *M* samples x *N* channels of 16-bit integers. The :code:`channel_conversion` dataset stores the "bitVolts" value of each channel, converted to volts, i.e., :code:`data * channel_conversion` is the signal in volts. The :code:`channel_conversion` of auxiliary and ADC channels converts the values to volts as well. -* :code:`timestamps`: *M* 64-bit floats representing the timestamps (in seconds) for each sample. +* :code:`timestamps`: *M* 64-bit floats representing the timestamps (in seconds) of each sample. +* :code:`sync/sample_numbers`: *M* 64-bit integers representing the sample number of each sample since the start of acquisition, counted on the clock of the data stream. +* :code:`electrodes`: the rows of the electrodes table (see :ref:`nwbelectrodes`) that correspond to the *N* channels. + +.. note:: :code:`sync/sample_numbers` is not yet part of the NWB specification. The :code:`sync` group of a *TimeSeries* has no specified contents; a standard location for sample numbers is being discussed in `nwb-schema#712 `__. Events ------- -Event data is organized by stream and event channel (eusually named :code:`TTL`). Each event channel can contain data for multiple TTL lines. +TTL events are stored in :code:`/events`, with one NWB *EventsTable* per event channel, named after the processor, its id and the data stream, e.g., :code:`Phase Detector-104.example_data.TTL` (:code:`TTL_1`, :code:`TTL_2`, ... for further event channels of the same processor and stream, as for the event folders of the :ref:`binaryformat`). Each event channel can contain data for multiple TTL lines. .. image:: ../../_static/images/recordingdata/nwb/events.png :alt: NWB data events format - :width: 300 + :width: 204 -Each **events** group is an NWB *TimeSeries* containing the following datasets: +Each row of the table is one event, with the following columns: -* :code:`timestamps`: *N* 64-bit float representing the timestamps (in seconds) for each event +* :code:`timestamp`: timestamp (in seconds) of the event, 64-bit float -* :code:`data`: *N* event codes indicating ON (+CH_number) and OFF (-CH_number) states +* :code:`line`: TTL line (0-based) that changed state, 8-bit unsigned integer -* :code:`full_words`: *N* 64-bit integers representing the state of the first 64 TTL lines when each event occurred. +* :code:`state`: new state of the TTL line (1 = on, 0 = off), 8-bit unsigned integer +* :code:`full_word`: state of the first 64 TTL lines when the event occurred, 64-bit unsigned integer + +* :code:`sample_number`: sample number of the event since the start of acquisition, 64-bit integer + +.. note:: All event tables are created when the file is created, since objects can't be added to an HDF5 file in SWMR mode. An event channel without any events therefore results in an empty table. The `NWB Inspector `__ reports empty tables with :code:`check_empty_table`; use :code:`nwbinspector --ignore check_empty_table` to skip this check. Spikes -------- -Spike data is organized by stream and electrode. +Spike data is organized by stream and electrode: .. image:: ../../_static/images/recordingdata/nwb/spikes.png :alt: NWB data spikes format - :width: 300 + :width: 251 + +Each **spikes** group in :code:`/acquisition` is an NWB *SpikeEventSeries* containing the following datasets: + +* :code:`data`: array with dimensions *S* spikes x *N* channels x *M* samples of 16-bit integers containing the spike waveforms. The :code:`conversion` attribute of :code:`data` stores the "bitVolts" value, converted to volts, i.e., :code:`data * data.conversion` is the waveform in volts. + +* :code:`timestamps`: *S* 64-bit floats containing the timestamps (in seconds) of the peak of each spike. + +* :code:`sync/sample_numbers`: *S* 64-bit integers containing the sample number of the peak of each spike since the start of acquisition. + +* :code:`electrodes`: the rows of the electrodes table (see :ref:`nwbelectrodes`) that correspond to the *N* channels. + +Messages +--------- + +Text messages (e.g., from the Message Center) are stored in the *EventsTable* :code:`/events/messages`, with the columns :code:`timestamp` (in seconds), :code:`annotation` (the text) and :code:`sample_number` (counted on the clock of the main sync stream of the Record Node). + +Sync messages +-------------- + +The *EventsTable* :code:`/events/sync_messages` stores the start of each recording for each data stream, with the columns :code:`timestamp` (the first timestamp of the stream in the recording, in seconds), :code:`annotation` (the text of the sync message, e.g., :code:`Start Time for File Reader (100) - example_data @ 40000 Hz`), :code:`stream_id` (the id of the data stream) and :code:`sample_number` (the first sample number of the stream in the recording). For the :code:`Software Time` message, :code:`stream_id` is 0 and :code:`sample_number` is the system time in milliseconds since midnight Jan 1st 1970 UTC. + +Epochs +------- + +The *TimeIntervals* table :code:`/intervals/epochs` contains one row per recording, with the columns :code:`start_time` and :code:`stop_time` (in seconds) and :code:`tags` (e.g., :code:`recording1`). + +.. _nwbelectrodes: + +Electrodes +----------- + +The electrodes table :code:`/general/extracellular_ephys/electrodes` contains one row per channel, with the columns :code:`location`, :code:`group_name`, :code:`group` (a reference to the *ElectrodeGroup* of the data stream) and :code:`channel_type` (0 = headstage, 1 = auxiliary, 2 = ADC). + +.. _nwbtimestamps: + +Timestamps +########### + +Timestamps are the GUI's synchronized timestamps, as in the :ref:`binaryformat`: seconds since timestamp 0 of the GUI (sample 0 of the main sync stream, normally the start of acquisition). :code:`timestamps_reference_time` and :code:`session_start_time` are set to the date and time of timestamp 0. They are computed from the system time when the first recording of the file starts (the :code:`Software Time` sync message) minus the first recorded timestamp, so they are accurate to about one processing block. -Each **spikes** group is an NWB *SpikeEventSeries* containing the following datasets: +Session and subject metadata +############################# -* :code:`data`: array with dimensions *S* spikes x *N* channels x *M* samples containing the spike waveforms. The :code:`channel_conversion` attribute stores the "bitVolts" value required to convert these values into microvolts (headstage channels) or volts (ADC channels). +NWB files should describe the session and the subject; for example, the `DANDI Archive `__ requires a subject with :code:`subject_id`, :code:`species`, :code:`sex` and :code:`age` or :code:`date_of_birth`. There are three ways to add this metadata. The first two are applied when an NWB file is created (at the first recording of each experiment), so changes apply to the next experiment. -* :code:`timestamps`: *S* 64-bit floats containing the timestamps (in seconds) corresponding to the peak time of each spike. +1. **The Record Node's NWB2 options (before recording).** With NWB2 selected as the recording format, the gear button next to the format selector of the Record Node opens the format's options: + .. image:: ../../_static/images/recordingdata/nwb/nwb2-options.png + :alt: The NWB2 options of the Record Node + + The options are the Identifier Text, Session description, Experimenter(s) (separated by :code:`;`), Institution, Lab, the subject's ID, species, sex, age, date of birth, genotype, strain, weight and description, and a metadata file (see 2.). The date of birth must include the time and time zone, e.g., :code:`2026-01-15T00:00:00Z`. The options are saved with the signal chain and can be set with the :ref:`HTTP API ` while acquisition is stopped (parameters :code:`engine_NWB2_` of the Record Node; the IDs are listed in the `plugin's README `__). Options that are set override the corresponding values in the metadata file; empty options don't. If the subject fields that DANDI requires are missing when an NWB file is created, the plugin logs a warning. + +2. **A metadata file (before recording).** A JSON file can provide more fields than the options, e.g., when a script creates the metadata for each session. The plugin reads the file set in the :code:`Metadata file (JSON)` option (an absolute path) or, if that option is empty, a file named :code:`nwb_metadata.json` in the Record Node directory, the recording directory, or the directory selected for recordings in the GUI (searched in this order). The file uses the same structure as `NeuroConv `__ metadata: + + .. code-block:: json + + { + "NWBFile": { + "session_description": "Recording in V1 during visual stimulation", + "experimenter": ["Last, First"], + "institution": "...", + "lab": "...", + "keywords": ["V1", "Neuropixels"] + }, + "Subject": { + "subject_id": "mouse01", + "species": "Mus musculus", + "sex": "M", + "age": "P90D" + } + } + + The supported fields are listed in the `plugin's README `__. The GUI log reports which metadata file was used, and any unsupported fields. + +3. **After recording.** NWB files can be edited once they are closed (when the next experiment starts or the GUI quits), e.g., with `PyNWB `__ or `NWB GUIDE `__: + + .. code-block:: python + + from pynwb import NWBHDF5IO + from pynwb.file import Subject + + with NWBHDF5IO("experiment1.nwb", "a") as io: + nwbfile = io.read() + nwbfile.subject = Subject(subject_id="mouse01", species="Mus musculus", sex="M", age="P90D") + io.write(nwbfile) + +The plugin also writes :code:`/general/was_generated_by` (the versions of the GUI and of the plugin) and :code:`/general/data_collection` (the GUI version). Reading data in Python ####################### * Create a :code:`Session` object using the `open-ephys-python-tools `__ package. The data format will be automatically detected. -* Alternatively, you can use the `PyNWB `__ package. +* Alternatively, you can use the `PyNWB `__ package (version 4.2 or later, which supports NWB 2.11), e.g.: + + .. code-block:: python + + from pynwb import NWBHDF5IO + with NWBHDF5IO("experiment1.nwb", "r") as io: + nwbfile = io.read() + series = nwbfile.acquisition["File Reader-100.example_data"] + volts = series.data[:1000, :] * series.channel_conversion[:] + ttl_events = nwbfile.events["Phase Detector-104.example_data.TTL"].to_dataframe() Reading data in Matlab ####################### -* Use the `open-ephys-matlab-tools `__ library. +* Use the `MatNWB `__ library. + +* The `open-ephys-matlab-tools `__ library currently reads only files written by earlier versions of the plugin (see :ref:`nwbearlierversions`). + +.. _nwbaftercrash: + +Opening a file after a crash +############################# + +If the GUI crashes during a recording, HDF5 still marks the file as open for writing, and opening it normally (e.g., with PyNWB) fails with "file is already open for write (may use to clear file consistency flags)". The data up to the last flush are in the file. To open it, either: + +* reset the flags once with :code:`h5clear -s experiment1.nwb`, after which PyNWB and other tools can read the file. :code:`h5clear` only resets these flags; it is part of the HDF5 command-line tools (e.g., :code:`conda install -c conda-forge hdf5`), not of the h5py package; + +* or open the file as an SWMR reader, e.g., :code:`h5py.File("experiment1.nwb", "r", swmr=True)`. + +Playing back NWB files +####################### + +The :code:`NWB File` file source of the File Reader can play back NWB files written by this plugin, by earlier versions of this plugin, and by other tools (e.g., PyNWB). + +.. _nwbearlierversions: + +Files written by earlier versions +################################## + +Files written by versions of the NWB Format plugin before 2.0 (NWB 2.4 or 2.5) differ as follows: + +* Sample numbers are stored in a :code:`sync` dataset of each series instead of :code:`sync/sample_numbers`. + +* TTL events are stored as a *TimeSeries* in :code:`/acquisition` (e.g., :code:`/acquisition/Phase Detector-104.example_data.TTL`), with the datasets :code:`data` (event codes indicating ON (+CH_number) and OFF (-CH_number) states), :code:`timestamps`, :code:`full_word` and :code:`sync`. + +* Text messages and sync messages are stored as *AnnotationSeries* in :code:`/acquisition` (:code:`messages` and :code:`sync_messages`), which NWB 2.11 deprecated. + +* The scaling factor of continuous data and spikes is stored both in :code:`data.conversion` and in :code:`channel_conversion`, so NWB readers that apply both scale the data twice. Use only :code:`channel_conversion`. + +* :code:`session_start_time` is the time when the file was created, so all times are offset by the time between the start of acquisition and the start of recording. -.. note:: NWB files written by the Open Ephys GUI are not currently compatible with the :code:`MatNWB` library. We are working on a fix! +* There is no :code:`channel_type` column in the electrodes table, and no :code:`epochs` table. +The open-ephys-python-tools package and the :code:`NWB File` file source read both layouts. | diff --git a/source/_static/images/recordingdata/nwb/continuous.png b/source/_static/images/recordingdata/nwb/continuous.png index 68f5ed91..9885c37c 100644 Binary files a/source/_static/images/recordingdata/nwb/continuous.png and b/source/_static/images/recordingdata/nwb/continuous.png differ diff --git a/source/_static/images/recordingdata/nwb/events.png b/source/_static/images/recordingdata/nwb/events.png index 370da507..24aea306 100644 Binary files a/source/_static/images/recordingdata/nwb/events.png and b/source/_static/images/recordingdata/nwb/events.png differ diff --git a/source/_static/images/recordingdata/nwb/nwb2-options.png b/source/_static/images/recordingdata/nwb/nwb2-options.png new file mode 100644 index 00000000..cfa4159b Binary files /dev/null and b/source/_static/images/recordingdata/nwb/nwb2-options.png differ diff --git a/source/_static/images/recordingdata/nwb/organization.png b/source/_static/images/recordingdata/nwb/organization.png index 1b736969..192439ab 100644 Binary files a/source/_static/images/recordingdata/nwb/organization.png and b/source/_static/images/recordingdata/nwb/organization.png differ diff --git a/source/_static/images/recordingdata/nwb/spikes.png b/source/_static/images/recordingdata/nwb/spikes.png index f565b983..b12c87c7 100644 Binary files a/source/_static/images/recordingdata/nwb/spikes.png and b/source/_static/images/recordingdata/nwb/spikes.png differ