Skip to content

Write NWB 2.11 files with AqNWB and read NWB files with AqNWB in the NWB File Source - #6

Open
oruebel wants to merge 88 commits into
open-ephys-plugins:mainfrom
NeurodataWithoutBorders:add-aqnwb-v0.4
Open

oruebel wants to merge 88 commits into
open-ephys-plugins:mainfrom
NeurodataWithoutBorders:add-aqnwb-v0.4

Conversation

@oruebel

@oruebel oruebel commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Context

@jsiegle I had prioritized several needed updates in AqNWB but am now starting to look at updating the nwb-format plugin for OpenEphys to use AqNWB and bring the plugin up-to-date with the latest version of NWB. This PR is currently in draft mode because it depends on several changes/fixes in AqNWB that are in pending PRs, so we should hold off with merging until after I have made an AqNWB release with the required changes. However, I figured it would be useful to start the review of this in parallel so we can test and refine the changes. AqNWB with the necessary changes for this PR was released on 11/03/2026 (0.5.0). The PR now points to the AqNWB 0.5.1 release (11/21/2026), which also makes small writes faster.

Because this PR updates to the latest version of NWB, I'll also need to create created a follow-up PR on the OpenEphys Python tools repo open-ephys/open-ephys-python-tools#51. That PR is in draft mode for now to wait for the release here first in case there are additional changes here. While working on this PR, I also ran into a few issues in the OpenEphys-GUI, however, none of those are blocking issues so I filed those as issues for now.

Summary

This PR replaces the NWB writer of the plugin (NWBFormat.h/.cpp) with AqNWB 0.5 and rewrites the NWB File file source on top of AqNWB's read API. It supersedes #4 (it builds on the commits of #4).

The files are valid NWB 2.11 and pass the NWB Inspector at BEST_PRACTICE_VIOLATION (except check_empty_table, see below). The goal was to stay schema compliant without custom extensions or workarounds, and to update the readers (python-tools, NWB File Source) as necessary to correctly work with the updated format.

File layout

As before, each experiment (start/stop of acquisition) is written to a separate file experiment<N>.nwb, and the recordings within an experiment are appended to the same datasets. Existing files are never changed: if the data directory is changed between recordings, the next recording starts a new file in the new directory, named experiment<N>_recording<M>.nwb if that directory already contains experiment<N>.nwb (python-tools support in open-ephys/open-ephys-python-tools#51).

Data Location Change from the previous plugin
Continuous data (one per stream) /acquisition/<source>-<id>.<stream> (ElectricalSeries) sample numbers moved from sync to sync/sample_numbers to improve format compliance; store scaling only in channel_conversion (the previous plugin stored the factor in both data.conversion and channel_conversion, so the data was scaled twice by NWB readers)
Spikes (one per electrode) /acquisition/<source>-<id>.<stream>.<electrode> (SpikeEventSeries) sample numbers in sync/sample_numbers; scaling in data.conversion (one factor per waveform); chunked by whole waveforms
TTL events (one per event channel) /events/<processor>-<id>.<stream>.TTL (TTL_1, TTL_2, ... for further channels; named as the Binary event folders) EventsTable (new in NWB 2.11) with line, state, full_word, sample_number, instead of a .TTL TimeSeries in /acquisition
Text messages /events/messages EventsTable with annotation, sample_number, instead of a TimeSeries of strings
Sync messages (recording start) /events/sync_messages EventsTable
Start/stop of each recording /intervals/epochs new, now stored in a TimeIntervalsTable
Electrodes /general/extracellular_ephys/electrodes new channel_type column

Note: Whilesync/sample_numbers is not yet part of the NWB schema, it is explicitly being ignored so it doesn't raise error during validation. TimeSeries/sync is a group without a specification for its contents. We are discussing a standard location for sample numbers in NeurodataWithoutBorders/nwb-schema#712. I think for now, the TimeSeries/sync group is a good place. Previously, the plugin used a dataset TimeSeries/sync instead, which was not schema compliant.

Robustness and performance

  • The file is written in HDF5 SWMR mode. It is flushed when a recording stops and every 10 s during a recording, and sync messages are written immediately. To confirm that files are not corrupted by a crash, I tested killing the GUI (SIGKILL) during recording and confirmed that the data up to the last flush was readable.
  • The HDF5 chunk cache is sized to the number of recorded channels (and is never set below the HDF5 default).

Preliminary performance tests

Setup: Apple M4 (10 cores, 32 GB RAM), internal SSD, macOS 15.7.2, Open Ephys GUI v1.1.0 and the plugin built in Debug mode (Release builds are expected to be faster; not measured yet), HDF5 1.14.3.

Method: A File Reader plays back a synthetic Binary dataset (int16, 30 kHz, 5 s of noise plus a 7 Hz sine, looped) with 64 to 3072 channels into a Record Node, which records with either the Binary or the NWB2 engine to the internal SSD. Each run starts acquisition, records for 30 s, and stops via the HTTP API. I then count the samples written to the file. When the record buffer is 90% full, the GUI stops the recording (the buffer holds 300 blocks of 1024 samples, about 10 s at 30 kHz, so it stops at about 9 s of backlog). A recording that is still running after 30 s and has all samples therefore kept up with the data rate. The scripts are make_stress_dataset.py and stress_test.sh (I can add them to the repo if useful).

Channels Data rate Binary NWB2 (this PR)
384 23 MB/s complete complete
1536 92 MB/s complete complete
2304 138 MB/s complete complete
3072 184 MB/s 29.9 / 30.1 / 30.9 s of ~30.9 s written (3 runs) 25.6 / 28.8 / 20.0 s of ~30.9 s written (3 runs)

"Complete" means that the recording kept running and all samples were written (about 30.9 s per run, since the recording runs slightly longer than the 30 s between the API calls). NWB2 and Binary files have the same size (e.g., 2.89 vs 2.87 GB at 1536 channels).

Up to 2304 channels, both engines keep up with the data rate, so this test can't tell which one writes faster, but it only shows that both are fast enough. At 3072 channels, neither Binary nor NWB completed, but Binary appeared to be a slightly faster. However, these are Debug builds, and the File Reader reads the source data from the same SSD at the same rate, so the absolute limits are only indicative.

None of the 3072-channel recordings was stopped, since the backlog after 30 s stayed below the 9 s limit. However, the samples still in the buffer when recording stops are discarded without a warning (the record thread writes at most one block of 4096 samples after it is stopped; open-ephys/plugin-GUI#713), which is why these recordings are short.

Note on the chunk cache and batch writes: The GUI only uses batch writes (writeContinuousDataBatch) for the built-in Binary engine. Other engines receive each block one channel at a time. For NWB, each per-channel call writes one column of the (samples x channels) array and touches every chunk that overlaps the block. If the chunks of all channels don't fit in the HDF5 chunk cache, HDF5 reads and rewrites a whole chunk for every channel. With the HDF5 default cache (1 MiB in HDF5 1.14), this is already the case at 384 channels (a chunk of 2048 samples x 384 channels x int16 is 1.5 MiB): in the same test, a 384-channel recording was stopped after 1.5 s because the record buffer filled up, while 64 channels still kept up. Sizing the cache to the channel count (this PR, using AqNWB's new ChunkCacheConfig) fixes this, at the cost of memory (4 chunks per stream, e.g. 6 MiB at 384 and 24 MiB at 1536 channels).

A more efficient alternative would be to write all channels of a block at once (one HDF5 write per block instead of one per channel), which would make the write independent of the cache size. This needs the GUI to call writeContinuousDataBatch for plugin engines too, e.g. via an opt-in such as RecordEngine::supportsBatchWrites() (open-ephys/plugin-GUI#711), and the plugin to implement writeContinuousDataBatch (not done yet, since the GUI doesn't call it for plugin engines).

Timestamp handling

Timestamps are the GUI's synchronized timestamps, as in the Binary format: seconds since timestamp 0 of the GUI (sample 0 of the main stream, normally the start of acquisition). timestamps_reference_time and session_start_time are set to the time of timestamp 0: the system time when the first recording of the file starts (the "Software Time" sync message) minus the first recorded timestamp. The previous plugin used the time the file was created, so all times were offset by the time between the start of acquisition and the start of recording.

Session and subject metadata

Record engine parameters are currently not applied by the GUI (see open-ephys/plugin-GUI#710), so metadata can't be entered in the GUI. Instead, the plugin reads an optional nwb_metadata.json file (same structure as NeuroConv metadata) from the Record Node directory, the recording directory, or the recording path, and writes the session, subject and /general fields (experimenter, institution, keywords, ...) to each new file with AqNWB's GeneralMetadataSpec. was_generated_by records the GUI and plugin versions. The README also shows how to add metadata after recording with PyNWB or NWB GUIDE.

NWB File Source

The NWB File file source now reads with AqNWB, with lazy reads instead of loading whole datasets. It plays back files written by this plugin, by the previous plugin (tested with a GUI v0.6.7 file), and by other tools such as PyNWB, including TTL events and messages. Playback is bit-exact (compared with a Binary recording of the played-back data).

Known limitations

Dependencies

Build and CI

  • AqNWB is included as a git submodule (sparse checkout) and compiled with the plugin; the CI workflows check out the submodule.
  • CI builds against the main branch of the Open Ephys GUI on all platforms. The plugin's record engine inherits the virtual function RecordEngine::writeContinuousDataBatch (its vtable references it, although the plugin doesn't call or override it), which was added in v1.1.0 without a plugin API version change, so the v1.0.0 import library (open-ephys-lib-v1.0.0.zip) doesn't contain it (Record Node: allow plugin record engines to opt in to batch writes (writeContinuousDataBatch) open-ephys/plugin-GUI#711); the Windows workflow therefore builds the GUI's open-ephys target to get the import library.
  • The plugin version is bumped to 2.0.0, since the file layout changed (the version is also stored in /general/was_generated_by). The version stays a literal in OpenEphysLib.cpp, since the deploy steps of the CI workflows read it from the info->libVersion line.
  • Windows CI runs on windows-2022, as the GUI does (windows-latest no longer has Visual Studio 2022).

Testing

  • Recorded from the File Reader with spikes, TTL events (Phase Detector) and messages, over multiple recordings per file; checked with PyNWB, the NWB Inspector, python-tools and playback in the NWB File Source.
  • Performance tests with 384 to 3072 channels at 30 kHz (see Preliminary performance tests above).
  • CI passes on Linux, macOS and Windows.

GUI issues found

AI usage declaration

🤖 Generated with the help of Claude Code

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread Source/FileSource/NWBFileSource.cpp Resolved
Comment thread Source/RecordEngine/NWBRecording.cpp Resolved
Comment thread Source/FileSource/NWBFileSource.cpp Resolved
Comment thread Source/FileSource/NWBFileSource.cpp Resolved
Comment thread Source/FileSource/NWBFileSource.cpp Resolved
Comment thread Source/RecordEngine/NWBRecording.cpp Resolved
Comment thread Source/RecordEngine/NWBRecording.cpp Resolved
Comment thread Source/RecordEngine/NWBRecording.cpp Resolved
…t events

- Catch HDF5 exceptions (which do not derive from std::exception) when
  opening a file in the NWB File Source and in the record engine, so that
  a non-HDF5 file or an unwritable destination does not terminate the GUI
- Take the epoch of a recording from the minimum and maximum timestamps of
  all written continuous data, events, and spikes, and flush periodically
  for events and spikes too, so that recordings without continuous
  channels get an epoch, a reference time, and periodic flushes
- Play back the text events of the "<processor>-<id>.<stream>.TEXT"
  tables in the NWB File Source

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@anjaldoshi anjaldoshi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for all the work you’ve put into this. I’ve pushed the related GUI fixes to development, so those are now available for testing alongside this PR:

  • Engine parameters: 3c513e8 exposes engine options as per-Record Node parameters, configurable through a gear button or the HTTP API and saved with the node’s settings. The existing “Identifier Text” option is accessible as engine_NWB2_0. This provides the GUI-side path for the session and subject metadata follow-up; the plugin still needs to declare and write those fields.

  • Batch writes: 5a16ccf enables batching for NWB2 libraries reporting version 2.0 or newer, which matches this PR’s version. Your batch implementation won’t need a new supportsBatchWrites() override. Until it lands, this PR can use the inherited implementation, which delegates to per-channel writes. The version guard avoids calling the new virtual method on older plugin binaries.

  • File Reader: 7e6782c preserves the exact file endpoint, splits event queries at every loop boundary, and keeps acquisition and TTL sample numbers continuous across loops and seeks. File sources receive file-relative [start, stop) ranges, where stop may equal the file length. The NWB source’s current implementation appears compatible with those bounded ranges, but please include events at sample zero and immediately before EOF in the playback comparison.

  • Recording shutdown: 4d14692 and 7f44157 drain all queued continuous data, events, and spikes before finalization completes. The GUI remains responsive, and overflow warnings are logged in both GUI and headless modes.

I’ve also published open-ephys-lib-v1.1.0.zip with the updated ABI, so Windows CI can use that with the matching headers instead of building the GUI just to obtain the import library.

Keeping batching and metadata exposure as follow-up PRs still makes sense. We can stack those PRs on top of this one and merge them all together. For the next validation run, please use the GUI’s development branch; these changes aren’t on main yet. The HTTP stress test should wait for finalizing to become false before inspecting files. It would also be useful to report buffer growth and finalization time separately: now that shutdown drains the backlog, a complete sample count alone won’t show whether the writer sustained the incoming data rate.

Let me know if you need any further help.

Comment thread CMakeLists.txt Resolved
Comment thread .github/workflows/windows.yml Resolved
Comment thread .github/workflows/linux.yml Resolved
oruebel and others added 6 commits November 9, 2026 21:27
With AqNWB, the plugin no longer uses the OpenEphysHDF5 common library.
Remove the link to it, and install the HDF5 1.14.3 runtime libraries in
libs/<platform>/bin into the GUI's shared directory (shared-api10 on
macOS) instead, as suggested in the review.

CI: remove the OpenEphysHDF5Lib build steps, use the published
open-ephys-lib-v1.1.0.zip import library on Windows instead of building
the GUI, and add the HDF5 runtime libraries (signed on macOS) to the
deployed packages, as zmq-interface does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…essEventData

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Streams that are not synchronized have timestamps of -1. Since the epoch
start is the minimum timestamp of all written data, a recording with
such a stream got an epoch start of -1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rd Node

Add record engine parameters (IDs 1-13; ID 0 remains the identifier) for
the session description, experimenter(s), institution, lab, and the
subject's ID, species, sex, age, date of birth, genotype, strain, weight
and description. GUI development (open-ephys/plugin-GUI#710, 3c513e8)
shows them in the Record Node's format options, saves them with the
signal chain and exposes them in the HTTP API (engine_NWB2_<id>).
Options that are set override the values in nwb_metadata.json; empty
options don't. Log a warning if the subject fields that DANDI requires
are missing when an NWB file is created.

Fixes open-ephys-plugins#7

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…taBatch)

Implement RecordEngine::writeContinuousDataBatch: the GUI passes all
recorded channels of a data stream (one ElectricalSeries) for a block;
convert them to int16, interleave them into the [sample][channel] layout
of the dataset (in 64 x 64 tiles), and write the data and timestamps with
a single ElectricalSeries::writeAllChannels call instead of one HDF5
write per channel. Any other combination of channels is written channel
by channel. The sample numbers, the time range of the recording
(dataWritten) and the stream start times are shared with
writeContinuousData (writeBlockSampleNumbers, finishContinuousWrite).

GUI development (open-ephys/plugin-GUI#711, 5a16ccf) calls
writeContinuousDataBatch for the NWB2 engine if the plugin's library
version is 2.0 or newer; GUI v1.1.0 keeps calling writeContinuousData.

Tested on GUI development: data identical to the source for one and two
streams (Merger), with spikes, events and messages, several recordings,
and recordings across the File Reader loop; complete, gap-free sample
numbers for 20 s recordings with 3072 and 4608 channels. Record Thread time spent writing at
384/1536/3072 channels (Release): 3.1/12.9/23.8% (one write per channel:
8.6/35.0/71.8%).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- New NWB2 option 14, "Metadata file (JSON)": the absolute path of the
  metadata file. If it is empty, nwb_metadata.json is searched next to the
  recording as before. A missing file or a relative path is logged as an error.
- AqNWB only writes date_of_birth as an ISO 8601 date and time with time zone
  and reports other values on stderr only. The plugin now logs an error in the
  GUI log and leaves the field out.
- Shorter age and date-of-birth labels, which didn't fit the options dialog.
- README: the options first, with a screenshot of the dialog, then the
  metadata file; both are applied when an NWB file is created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@oruebel

oruebel commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the fixes and the review! I retested everything on development (e6008f0); the results are in the GUI issues (open-ephys/plugin-GUI#710, open-ephys/plugin-GUI#711, open-ephys/plugin-GUI#712, open-ephys/plugin-GUI#713).

Changes in this PR:

  • 3a28355: your three inline comments.
    • The plugin no longer links the OpenEphysHDF5 library.
    • It installs the bundled HDF5 1.14.3 runtime from libs/<platform>/bin instead.
    • CI no longer builds OpenEphysHDF5Lib, and Windows uses open-ephys-lib-v1.1.0.zip.
    • I also added the HDF5 libraries to the deployed packages, signed on macOS, as zmq-interface does. Otherwise a plugin installed through the Plugin Installer wouldn't find them. Please check that this matches how you package plugins with shared libraries.
  • fe8db8e: a comment in NWBFileSource::processEventData.
    • The implementation already handles the bounded [start, stop) ranges of development and the ranges of v1.1.0.
    • The playback test with events at the first and last sample of the file passes.
  • 2c51913: the epochs ignore the timestamps of unsynchronized streams (-1). Since the Copilot fixes, the epoch start is the minimum timestamp of all written data, so a recording with an unsynchronized stream (e.g., two File Readers and a Merger) got an epoch start of -1.

Follow-up PRs, on the fork, targeting this PR's branch and each other:

Once you've reviewed them, I'll merge them into this PR's branch, so they can be merged together, as you suggested. Device metadata (NWB 2.11 DeviceModel) will come later, after the next AqNWB release (#13).

Tested on development (macOS, Debug):

  • the plugin loads and records without libOpenEphysHDF5.dylib;
  • data is identical to the source (one and two streams, across the File Reader loop);
  • the HTTP tests wait for finalizing to be false.

oruebel and others added 5 commits November 20, 2026 09:23
Write all channels of a stream with one HDF5 write (writeContinuousDataBatch)
Set session and subject metadata through the NWB2 options of the Record Node
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace JUCE's FloatVectorOperations::copyWithMultiply and
AudioDataConverters::convertFloatToInt16LE (a scalar loop in double
precision) with one loop that the compiler vectorizes. It uses the same
arithmetic, including JUCE's rounding (adding 1.5 * 2^52 as
juce::roundToInt), so the written values are unchanged. The float
buffer for the scaled samples is no longer needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Convert samples to int16 in one vectorizable loop
@oruebel

oruebel commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@jsiegle @anjaldoshi this PR is ready for the final review. It was great seeing you at SfN. As we had discussed, I've now merged the follow-up PRs from the fork into this PR's branch, and I've updated the PR description.

Merged into this PR (head 936deb6):

Tested on macOS (Debug) with the latest development (d90de30, v1.2.0) and with v1.1.0:

  • Smoke test: 2 recordings with spikes. On development, the data is identical to the source, including across the File Reader loop, with continuous sample numbers and monotonic timestamps. On v1.1.0, only the rows at the loop points differ (File Reader: loop end is rounded down to whole milliseconds, and events near the loop point are lost or misplaced open-ephys/plugin-GUI#712).
  • Playback of the recorded file in the NWB File Source: exact on both GUI versions.
  • Two streams through a Merger: both streams identical to the source on development.
  • Metadata: set through the HTTP API, with options only, the metadata file only, both, neither, and invalid input (9 cases). Checked with PyNWB and the NWB Inspector.
  • CI passes on Linux, macOS and Windows.

Still needed from your side for the release:

  1. Review and merge this PR.
  2. Packaging check on main. The deploy steps now package the HDF5 runtime libraries in shared/ next to the plugin. They only run on main, so please check the first packages, in particular that the Plugin Installer installs shared/ the way it does for zmq-interface. I'm happy to help test them.
  3. GUI v1.2.0 release. The plugin also works with v1.1.0. There, the NWB2 options are shown but not applied, so the metadata can only come from a nwb_metadata.json file next to the recording. The NWB2 options, batch writes and draining the record buffer at stop need v1.2.0. I'll name v1.2.0 as the recommended version in the README and docs.
  4. Docs and tools updates. Once this PR is merged, we can take Update the NWB format page for version 2.0 of the NWB Format plugin open-ephys/gui-docs#112 and Read the NWB layout of the AqNWB-based NWB Format plugin open-ephys/open-ephys-python-tools#51 out of draft mode and review.

Future items:

Thanks again for the quick fixes in the GUI and for the review!

oruebel and others added 4 commits November 20, 2026 22:13
Events are collected per event table and written with one addRows call
when 256 are pending, before each periodic flush, and when recording
stops. One addRow per event cost ~22 us; at 30000 TTL events/s that
was two thirds of the Record Thread's time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AqNWB 0.5.1 makes small writes faster (NeurodataWithoutBorders/aqnwb#366,
NeurodataWithoutBorders/aqnwb#367), e.g. one EventsTable row ~5x and one
channel of a block ~2.5x.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…a file after a crash

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants