From a9f6332b5c2c15d3dbfa3cf7d13c8e4a75c3a86e Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Wed, 17 Jul 2024 17:41:54 -0700 Subject: [PATCH 01/13] Return can_read as False if no nwbfile version is found (#1934) * add can_read catch if no nwb_version found * add tests for can_read method * fix comment in test description * fix test name * update CHANGELOG.md * add warnings for can_read conditions --- CHANGELOG.md | 3 +++ src/pynwb/__init__.py | 11 ++++++++- tests/integration/hdf5/test_io.py | 38 +++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c72e78f58..9762bf20d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ### Documentation and tutorial enhancements - Added pre-release pull request instructions to release process documentation @stephprince [#1928](https://github.com/NeurodataWithoutBorders/pynwb/pull/1928) +### Bug fixes +- Fixed `can_read` method to return False if no nwbfile version can be found @stephprince [#1934](https://github.com/NeurodataWithoutBorders/pynwb/pull/1934) + ## PyNWB 2.8.1 (July 3, 2024) ### Documentation and tutorial enhancements diff --git a/src/pynwb/__init__.py b/src/pynwb/__init__.py index 50db92dcc..278e48948 100644 --- a/src/pynwb/__init__.py +++ b/src/pynwb/__init__.py @@ -4,6 +4,7 @@ import os.path from pathlib import Path from copy import deepcopy +from warnings import warn import h5py from hdmf.spec import NamespaceCatalog @@ -269,7 +270,15 @@ def can_read(path: str): return False try: with h5py.File(path, "r") as file: # path is HDF5 file - return get_nwbfile_version(file)[1][0] >= 2 # Major version of NWB >= 2 + version_info = get_nwbfile_version(file) + if version_info[0] is None: + warn("Cannot read because missing NWB version in the HDF5 file. The file is not a valid NWB file.") + return False + elif version_info[1][0] < 2: # Major versions of NWB < 2 not supported + warn("Cannot read because PyNWB supports NWB files version 2 and above.") + return False + else: + return True except IOError: return False diff --git a/tests/integration/hdf5/test_io.py b/tests/integration/hdf5/test_io.py index d68334c89..e1ce4269b 100644 --- a/tests/integration/hdf5/test_io.py +++ b/tests/integration/hdf5/test_io.py @@ -531,3 +531,41 @@ def test_round_trip_with_pathlib_path(self): with NWBHDF5IO(pathlib_path, 'r') as io: read_file = io.read() self.assertContainerEqual(read_file, self.nwbfile) + + def test_can_read_current_nwb_file(self): + with NWBHDF5IO(self.path, 'w') as io: + io.write(self.nwbfile) + self.assertTrue(NWBHDF5IO.can_read(self.path)) + + def test_can_read_file_does_not_exits(self): + self.assertFalse(NWBHDF5IO.can_read('not_a_file.nwb')) + + def test_can_read_file_no_version(self): + # write the example file + with NWBHDF5IO(self.path, 'w') as io: + io.write(self.nwbfile) + # remove the version attribute + with File(self.path, mode='a') as io: + del io.attrs['nwb_version'] + + # assert can_read returns False and warning raised + warn_msg = "Cannot read because missing NWB version in the HDF5 file. The file is not a valid NWB file." + with self.assertWarnsWith(UserWarning, warn_msg): + self.assertFalse(NWBHDF5IO.can_read(self.path)) + + def test_can_read_file_old_version(self): + # write the example file + with NWBHDF5IO(self.path, 'w') as io: + io.write(self.nwbfile) + # set the version attribute <2.0 + with File(self.path, mode='a') as io: + io.attrs['nwb_version'] = "1.0.5" + + # assert can_read returns False and warning raised + warn_msg = "Cannot read because PyNWB supports NWB files version 2 and above." + with self.assertWarnsWith(UserWarning, warn_msg): + self.assertFalse(NWBHDF5IO.can_read(self.path)) + + def test_can_read_file_invalid_hdf5_file(self): + # current file is not an HDF5 file + self.assertFalse(NWBHDF5IO.can_read(__file__)) From fcd7008f0b065a5856c0a838c2aa844c20736bd0 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Thu, 18 Jul 2024 13:59:42 -0700 Subject: [PATCH 02/13] Change epoch tags to property (#1935) * make epoch_tags a property * remove epoch tags from fields dict * remove epoch_tags from print assertion * add test for single string tags * add test for no epochs table * update CHANGELOG.md --- CHANGELOG.md | 1 + src/pynwb/file.py | 11 ++++------- tests/unit/test_core.py | 4 ---- tests/unit/test_file.py | 12 ++++++++++++ 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9762bf20d..3d3dae88c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ### Bug fixes - Fixed `can_read` method to return False if no nwbfile version can be found @stephprince [#1934](https://github.com/NeurodataWithoutBorders/pynwb/pull/1934) +- Changed `epoch_tags` to be a NWBFile property instead of constructor argument. @stephprince [#1935](https://github.com/NeurodataWithoutBorders/pynwb/pull/1935) ## PyNWB 2.8.1 (July 3, 2024) diff --git a/src/pynwb/file.py b/src/pynwb/file.py index 0b294e873..7621df2ac 100644 --- a/src/pynwb/file.py +++ b/src/pynwb/file.py @@ -273,7 +273,6 @@ class NWBFile(MultiContainerInterface, HERDManager): {'name': 'subject', 'child': True, 'required_name': 'subject'}, {'name': 'sweep_table', 'child': True, 'required_name': 'sweep_table'}, {'name': 'invalid_times', 'child': True, 'required_name': 'invalid_times'}, - 'epoch_tags', # icephys_filtering is temporary. /intracellular_ephys/filtering dataset will be deprecated {'name': 'icephys_filtering', 'settable': False}, {'name': 'intracellular_recordings', 'child': True, @@ -362,8 +361,6 @@ class NWBFile(MultiContainerInterface, HERDManager): 'doc': 'Stimulus template TimeSeries objects belonging to this NWBFile', 'default': None}, {'name': 'epochs', 'type': TimeIntervals, 'doc': 'Epoch objects belonging to this NWBFile', 'default': None}, - {'name': 'epoch_tags', 'type': (tuple, list, set), - 'doc': 'A sorted list of tags used across all epochs', 'default': set()}, {'name': 'trials', 'type': TimeIntervals, 'doc': 'A table containing trial data', 'default': None}, {'name': 'invalid_times', 'type': TimeIntervals, @@ -426,7 +423,6 @@ def __init__(self, **kwargs): 'stimulus_template', 'keywords', 'processing', - 'epoch_tags', 'electrodes', 'electrode_groups', 'devices', @@ -555,6 +551,10 @@ def modules(self): warn("NWBFile.modules has been replaced by NWBFile.processing.", DeprecationWarning) return self.processing + @property + def epoch_tags(self): + return set(self.epochs.tags[:]) if self.epochs is not None else set() + @property def ec_electrode_groups(self): warn("NWBFile.ec_electrode_groups has been replaced by NWBFile.electrode_groups.", DeprecationWarning) @@ -616,7 +616,6 @@ def add_epoch_column(self, **kwargs): See :py:meth:`~hdmf.common.table.DynamicTable.add_column` for more details """ self.__check_epochs() - self.epoch_tags.update(kwargs.pop('tags', list())) self.epochs.add_column(**kwargs) def add_epoch_metadata_column(self, *args, **kwargs): @@ -638,8 +637,6 @@ def add_epoch(self, **kwargs): enclosure versus sleeping between explorations) """ self.__check_epochs() - if kwargs['tags'] is not None: - self.epoch_tags.update(kwargs['tags']) self.epochs.add_interval(**kwargs) def __check_electrodes(self): diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py index e2a060d20..5a564f975 100644 --- a/tests/unit/test_core.py +++ b/tests/unit/test_core.py @@ -135,10 +135,6 @@ def test_print_file(self): name1 , name2 } - epoch_tags: { - tag1, - tag2 - } epochs: epochs file_create_date: \[datetime.datetime\(.*\)\] identifier: identifier diff --git a/tests/unit/test_file.py b/tests/unit/test_file.py index 98446fa46..8cb3415d9 100644 --- a/tests/unit/test_file.py +++ b/tests/unit/test_file.py @@ -142,6 +142,18 @@ def test_epoch_tags(self): tags = self.nwbfile.epoch_tags self.assertEqual(set(expected_tags), set(tags)) + def test_epoch_tags_single_string(self): + tags1 = 't1' + tags2 = 't2' + expected_tags = set([tags1, tags2]) + self.nwbfile.add_epoch(0.0, 1.0, tags=tags1) + self.nwbfile.add_epoch(1.0, 2.0, tags=tags2) + tags = self.nwbfile.epoch_tags + self.assertEqual(expected_tags, tags) + + def test_epoch_tags_no_table(self): + self.assertEqual(set(), self.nwbfile.epoch_tags) + def test_add_acquisition(self): self.nwbfile.add_acquisition(TimeSeries('test_ts', [0, 1, 2, 3, 4, 5], 'grams', timestamps=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5])) From d453804744c9b6c0fe8dfc599e319f38ecc3b22d Mon Sep 17 00:00:00 2001 From: Ben Dichter Date: Wed, 24 Jul 2024 12:18:28 -0400 Subject: [PATCH 03/13] add AbstractFeatureSeries (#1942) * add AbstractFeatureSeries * fix location of AbstractFeatureSeries * fix location of AbstractFeatureSeries * add AbstractFeatureSeries to intro text --- docs/gallery/domain/images.py | 48 +++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/docs/gallery/domain/images.py b/docs/gallery/domain/images.py index d6eef24b3..4e9214784 100644 --- a/docs/gallery/domain/images.py +++ b/docs/gallery/domain/images.py @@ -11,7 +11,8 @@ about the subject, the environment, the presented stimuli, or other parts related to the experiment. This tutorial focuses in particular on the usage of: -* :py:class:`~pynwb.image.OpticalSeries` for series of images that were presented as stimulus +* :py:class:`~pynwb.image.OpticalSeries` and :py:class:`~pynwb.misc.AbstractFeatureSeries` for series of images that + were presented as stimulus * :py:class:`~pynwb.image.ImageSeries`, for series of images (movie segments); * :py:class:`~pynwb.image.GrayscaleImage`, :py:class:`~pynwb.image.RGBImage`, :py:class:`~pynwb.image.RGBAImage`, for static images; @@ -19,23 +20,22 @@ The following examples will reference variables that may not be defined within the block they are used in. For clarity, we define them here: """ -# Define file paths used in the tutorial - -import os # sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_image_data.png' from datetime import datetime +import os from uuid import uuid4 import numpy as np from dateutil import tz -from dateutil.tz import tzlocal from PIL import Image from pynwb import NWBHDF5IO, NWBFile from pynwb.base import Images from pynwb.image import GrayscaleImage, ImageSeries, OpticalSeries, RGBAImage, RGBImage +from pynwb.misc import AbstractFeatureSeries +# Define file paths used in the tutorial nwbfile_path = os.path.abspath("images_tutorial.nwb") moviefiles_path = [ os.path.abspath("image/file_1.tiff"), @@ -55,7 +55,7 @@ nwbfile = NWBFile( session_description="my first synthetic recording", identifier=str(uuid4()), - session_start_time=datetime.now(tzlocal()), + session_start_time=session_start_time, experimenter=[ "Baggins, Bilbo", ], @@ -109,6 +109,35 @@ nwbfile.add_stimulus(stimulus=optical_series) #################### +# AbstractFeatureSeries: Storing features of visual stimuli +# --------------------------------------------------------- +# +# While it is usually recommended to store the entire image data as an :py:class:`~pynwb.image.OpticalSeries`, sometimes +# it is useful to store features of the visual stimuli instead of or in addition to the raw image data. For example, +# you may want to store the mean luminance of the image, the contrast, or the spatial frequency. This can be done using +# an instance of :py:class:`~pynwb.misc.AbstractFeatureSeries`. This class is a general container for storing time +# series of features that are derived from the raw image data. + +# Create some fake feature data +feature_data = np.random.rand(200, 3) # 200 time points, 3 features + +# Create an AbstractFeatureSeries object +abstract_feature_series = AbstractFeatureSeries( + name="StimulusFeatures", + data=feature_data, + timestamps=np.linspace(0, 1, 200), + description="Features of the visual stimuli", + features=["luminance", "contrast", "spatial frequency"], + feature_units=["n.a.", "n.a.", "cycles/degree"], +) + +# Add the AbstractFeatureSeries to the NWBFile +nwbfile.add_stimulus(abstract_feature_series) + +#################### +# Like all :py:class:`~pynwb.base.TimeSeries`, :py:class:`~pynwb.misc.AbstractFeatureSeries` specify timing using +# either the ``rate`` and ``starting_time`` attributes or the ``timestamps`` attribute. +# # ImageSeries: Storing series of images as acquisition # ---------------------------------------------------- # @@ -118,7 +147,6 @@ # # We can add raw data to the :py:class:`~pynwb.file.NWBFile` object as *acquisition* using # the :py:meth:`~pynwb.file.NWBFile.add_acquisition` method. -# image_data = np.random.randint(low=0, high=255, size=(200, 50, 50, 3), dtype=np.uint8) behavior_images = ImageSeries( @@ -138,13 +166,13 @@ # ^^^^^^^^^^^^^^ # # External files (e.g. video files of the behaving animal) can be added to the :py:class:`~pynwb.file.NWBFile` -# by creating an :py:class:`~pynwb.image.ImageSeries` object using the +# by creating an :py:class:`~pynwb.image.ImageSeries` object using the # :py:attr:`~pynwb.image.ImageSeries.external_file` attribute that specifies # the path to the external file(s) on disk. # The file(s) path must be relative to the path of the NWB file. # Either ``external_file`` or ``data`` must be specified, but not both. # -# If the sampling rate is constant, use :py:attr:`~pynwb.base.TimeSeries.rate` and +# If the sampling rate is constant, use :py:attr:`~pynwb.base.TimeSeries.rate` and # :py:attr:`~pynwb.base.TimeSeries.starting_time` to specify time. # For irregularly sampled recordings, use :py:attr:`~pynwb.base.TimeSeries.timestamps` to specify time for each sample # image. @@ -152,7 +180,7 @@ # Each external image may contain one or more consecutive frames of the full :py:class:`~pynwb.image.ImageSeries`. # The :py:attr:`~pynwb.image.ImageSeries.starting_frame` attribute serves as an index to indicate which frame # each file contains. -# For example, if the ``external_file`` dataset has three paths to files and the first and the second file have 2 +# For example, if the ``external_file`` dataset has three paths to files and the first and the second file have 2 # frames, and the third file has 3 frames, then this attribute will have values `[0, 2, 4]`. external_file = [ From 379213673cdb4064d5565326622d0dc1ca31d50c Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 25 Jul 2024 15:47:34 -0700 Subject: [PATCH 04/13] Add note about writing table with custom col and no rows (#1943) --- docs/gallery/general/plot_timeintervals.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/gallery/general/plot_timeintervals.py b/docs/gallery/general/plot_timeintervals.py index 4069fd4a4..905b3213c 100644 --- a/docs/gallery/general/plot_timeintervals.py +++ b/docs/gallery/general/plot_timeintervals.py @@ -92,7 +92,8 @@ # Additional columns can be added using :py:meth:`~pynwb.file.NWBFile.add_trial_column`. This method takes a name # for the column and a description of what the column stores. You do not need to supply data # type, as this will inferred. Once all columns have been added, trial data can be populated using -# :py:meth:`~pynwb.file.NWBFile.add_trial`. +# :py:meth:`~pynwb.file.NWBFile.add_trial`. Note that if you add a custom column, you must +# add at least one row to write the table to a file. # # Lets add an additional column and some trial data with tags and timeseries references. From 12598ea9b85fd10f510f808ce8384b2169566fd8 Mon Sep 17 00:00:00 2001 From: Oliver Ruebel Date: Tue, 20 Aug 2024 12:05:57 -0700 Subject: [PATCH 05/13] Add docs for using the family file driver with PyNWB (#1949) * Fix #1948 Add docs for using the family file driver with PyNWB --------- Co-authored-by: Steph Prince <40640337+stephprince@users.noreply.github.com> Co-authored-by: Ben Dichter Co-authored-by: Steph Prince <40640337+stephprince@users.noreply.github.com> --- CHANGELOG.md | 1 + .../advanced_io/plot_iterative_write.py | 2 + .../{linking_data.py => plot_linking_data.py} | 151 ++++++++++++++++-- 3 files changed, 140 insertions(+), 14 deletions(-) rename docs/gallery/advanced_io/{linking_data.py => plot_linking_data.py} (60%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d3dae88c..82370cff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Documentation and tutorial enhancements - Added pre-release pull request instructions to release process documentation @stephprince [#1928](https://github.com/NeurodataWithoutBorders/pynwb/pull/1928) +- Added section on how to use the `family` driver in `h5py` for splitting data across multiple files @oruebel [#1949](https://github.com/NeurodataWithoutBorders/pynwb/pull/1949) ### Bug fixes - Fixed `can_read` method to return False if no nwbfile version can be found @stephprince [#1934](https://github.com/NeurodataWithoutBorders/pynwb/pull/1934) diff --git a/docs/gallery/advanced_io/plot_iterative_write.py b/docs/gallery/advanced_io/plot_iterative_write.py index 958981a0b..bb629e14d 100644 --- a/docs/gallery/advanced_io/plot_iterative_write.py +++ b/docs/gallery/advanced_io/plot_iterative_write.py @@ -1,4 +1,6 @@ """ +.. _iterative_write: + Iterative Data Write ==================== diff --git a/docs/gallery/advanced_io/linking_data.py b/docs/gallery/advanced_io/plot_linking_data.py similarity index 60% rename from docs/gallery/advanced_io/linking_data.py rename to docs/gallery/advanced_io/plot_linking_data.py index 2f79d1488..88ba7e10f 100644 --- a/docs/gallery/advanced_io/linking_data.py +++ b/docs/gallery/advanced_io/plot_linking_data.py @@ -13,7 +13,7 @@ HDF5 files with NWB data files via external links. To make things more concrete, let's look at the following use case. We want to simultaneously record multiple data streams during data acquisition. Using the concept of external links allows us to save each data stream to an external HDF5 files during data acquisition and to -afterwards link the data into a single NWB file. In this case, each recording becomes represented by a +afterward link the data into a single NWB file. In this case, each recording becomes represented by a separate file-system object that can be set as read-only once the experiment is done. In the following we are using :py:meth:`~pynwb.base.TimeSeries` as an example, but the same approach works for other NWBContainers as well. @@ -42,7 +42,7 @@ Creating test data ---------------------------- +^^^^^^^^^^^^^^^^^^ In the following we are creating two :py:meth:`~pynwb.base.TimeSeries` each written to a separate file. We then show how we can integrate these files into a single NWBFile. @@ -61,7 +61,7 @@ # Create the base data start_time = datetime(2017, 4, 3, 11, tzinfo=tzlocal()) data = np.arange(1000).reshape((100, 10)) -timestamps = np.arange(100) +timestamps = np.arange(100, dtype=float) filename1 = "external1_example.nwb" filename2 = "external2_example.nwb" filename3 = "external_linkcontainer_example.nwb" @@ -105,12 +105,12 @@ ##################### # Linking to select datasets -# -------------------------- +# ^^^^^^^^^^^^^^^^^^^^^^^^^^ # #################### # Step 1: Create the new NWBFile -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create the first file nwbfile4 = NWBFile( @@ -122,7 +122,7 @@ #################### # Step 2: Get the dataset you want to link to -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Now let's open our test files and retrieve our timeseries. # @@ -134,7 +134,7 @@ #################### # Step 3: Create the object you want to link to the data -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # To link to the dataset we can simply assign the data object (here `` timeseries_1.data``) to a new ``TimeSeries`` @@ -167,7 +167,7 @@ #################### # Step 4: Write the data -# ^^^^^^^^^^^^^^^^^^^^^^^ +# ~~~~~~~~~~~~~~~~~~~~~~~~ # with NWBHDF5IO(filename4, "w") as io4: # Use link_data=True to specify default behavior to link rather than copy data @@ -185,7 +185,7 @@ #################### # Linking to whole Containers -# --------------------------- +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # Appending to files and linking is made possible by passing around the same # :py:class:`~hdmf.build.manager.BuildManager`. You can get a manager to pass around @@ -203,7 +203,7 @@ #################### # Step 1: Get the container object you want to link to -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Now let's open our test files and retrieve our timeseries. # @@ -219,7 +219,7 @@ #################### # Step 2: Add the container to another NWBFile -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # To integrate both :py:meth:`~pynwb.base.TimeSeries` into a single file we simply create a new # :py:meth:`~pynwb.file.NWBFile` and add our existing :py:meth:`~pynwb.base.TimeSeries` to it. PyNWB's # :py:class:`~pynwb.NWBHDF5IO` backend then automatically detects that the TimeSeries have already @@ -247,7 +247,7 @@ # ------------------------------ # # Using the :py:func:`~pynwb.file.NWBFile.copy` method allows us to easily create a shallow copy -# of a whole NWB:N file with links to all data in the original file. For example, we may want to +# of a whole NWB file with links to all data in the original file. For example, we may want to # store processed data in a new file separate from the raw data, while still being able to access # the raw data. See the :ref:`scratch` tutorial for a detailed example. # @@ -259,5 +259,128 @@ # External links are convenient but to share data we may want to hand a single file with all the # data to our collaborator rather than having to collect all relevant files. To do this, # :py:class:`~hdmf.backends.hdf5.h5tools.HDF5IO` (and in turn :py:class:`~pynwb.NWBHDF5IO`) -# provide the convenience function :py:meth:`~hdmf.backends.hdf5.h5tools.HDF5IO.copy_file`, -# which copies an HDF5 file and resolves all external links. +# provide the convenience function :py:meth:`~hdmf.backends.hdf5.h5tools.HDF5IO.export`, +# which can copy the file and resolves all external links. + + +#################### +# Automatically splitting large data across multiple HDF5 files +# ------------------------------------------------------------------- +# +# For extremely large datasets it can be useful to split data across multiple files, e.g., in cases where +# the file stystem does not allow for large files. While we can +# achieve this by writing different components (e.g., :py:meth:`~pynwb.base.TimeSeries`) to different files as described above, +# this option does not allow splitting data from single datasets. An alternative option is to use the +# ``family`` driver in ``h5py`` to automatically split the NWB file into a collection of many HDF5 files. +# The ``family`` driver stores the file on disk as a series of fixed-length chunks (each in its own file). +# In practice, to write very large arrays, we can combine this approach with :ref:`iterative_write` to +# avoid having to load all data into memory. In the example shown here we use a manual approach to +# iterative write by using :py:class:`~hdmf.backends.hdf5.h5_utils.H5DataIO` to create an empty dataset and +# then filling in the data afterward. + +#################### +# Step 1: Create the NWBFile as usual +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +from pynwb import NWBFile +from pynwb.base import TimeSeries +from datetime import datetime +from hdmf.backends.hdf5 import H5DataIO +import numpy as np + +# Create an NWBFile object +nwbfile = NWBFile(session_description='example file family', + identifier=str(uuid4()), + session_start_time=datetime.now().astimezone()) + +# Create the data as an empty dataset so that we can write to it later +data = H5DataIO(maxshape=(None, 10), # make the first dimension expandable + dtype=np.float32, # create the data as float32 + shape=(0, 10), # initial data shape to initialize as empty dataset + chunks=(1000, 10) + ) + +# Create a TimeSeries object +time_series = TimeSeries(name='example_timeseries', + data=data, + starting_time=0.0, + rate=1.0, + unit='mV') + +# Add the TimeSeries to the NWBFile +nwbfile.add_acquisition(time_series) + +#################### +# Step 2: Open the new file with the `family` driver and write +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# Here we need to open the file with `h5py` first to set up the driver, and then we can use +# that file with :py:class:`pynwb.NWBHDF5IO`. This is required, because :py:class:`pynwb.NWBHDF5IO` +# currently does not support passing the `memb_size` option required by the `family` driver. + +import h5py +from pynwb import NWBHDF5IO + +# Define the size of the individual files, determining the number of files to create +# chunk_size = 1 * 1024**3 # 1GB per file +chunk_size = 1024**2 # 1MB just for testing + +# filename pattern +filename_pattern = 'family_nwb_file_%d.nwb' + +# Create the HDF5 file using the family driver +with h5py.File(name=filename_pattern, mode='w', driver='family', memb_size=chunk_size) as f: + + # Use NWBHDF5IO to write the NWBFile to the HDF5 file + with NWBHDF5IO(file=f, mode='w') as io: + io.write(nwbfile) + + # Write new data iteratively to the file + for i in range(10): + start_index = i * 1000 + stop_index = start_index + 1000 + data.dataset.resize((stop_index, 10)) # Resize the dataset + data.dataset[start_index: stop_index , :] = i # Set the additional values + +#################### +# .. note:: +# +# Alternatively, we could have also used the :ref:`iterative_write` features to write the data +# iteratively directly as part of the `io.write` call instead of manually afterward. + +#################### +# Step 3: Read a file written with the family driver +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# + + +# Open the HDF5 file using the family driver +with h5py.File(name=filename_pattern, mode='r', driver='family', memb_size=chunk_size) as f: + # Use NWBHDF5IO to read the NWBFile from the HDF5 file + with NWBHDF5IO(file=f, manager=None, mode='r') as io: + nwbfile = io.read() + print(nwbfile) + + +#################### +# .. note:: +# +# The filename you provide when using the ``family`` driver must contain a printf-style integer format code +# (e.g.`%d`), which will be replaced by the file sequence number. +# +# .. note:: +# +# The ``memb_size`` parameter must be set on both write and read. As such, reading the file requires +# the user to know the ``memb_size`` that was used for writing. +# +# .. warning:: +# +# The DANDI archive may not support NWB files that are split in this fashion. +# +# .. note:: +# +# Other file drivers, e.g., ``split`` or ``multi`` could be used in a similar fashion. +# However, not all HDF5 drivers are supported by the the high-level API of +# ``h5py`` and as such may require a bit more complex setup via the the +# low-level HDF5 API in ``h5py``. +# + From 2d00afe30b3116c714e53a39522488e97c9160c5 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Tue, 20 Aug 2024 12:56:52 -0700 Subject: [PATCH 06/13] update ruff linter settings (#1950) * update linter settings * Update `pyproject.toml` * exclude notebooks from ruff linter * Fix ruff formatting in plot_linking_data --------- Co-authored-by: Ryan Ly Co-authored-by: Oliver Ruebel --- docs/gallery/advanced_io/plot_linking_data.py | 4 ++-- pyproject.toml | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/gallery/advanced_io/plot_linking_data.py b/docs/gallery/advanced_io/plot_linking_data.py index 88ba7e10f..00dfe5056 100644 --- a/docs/gallery/advanced_io/plot_linking_data.py +++ b/docs/gallery/advanced_io/plot_linking_data.py @@ -268,8 +268,8 @@ # ------------------------------------------------------------------- # # For extremely large datasets it can be useful to split data across multiple files, e.g., in cases where -# the file stystem does not allow for large files. While we can -# achieve this by writing different components (e.g., :py:meth:`~pynwb.base.TimeSeries`) to different files as described above, +# the file stystem does not allow for large files. While we can achieve this by writing different +# components (e.g., :py:meth:`~pynwb.base.TimeSeries`) to different files as described above, # this option does not allow splitting data from single datasets. An alternative option is to use the # ``family`` driver in ``h5py`` to automatically split the NWB file into a collection of many HDF5 files. # The ``family`` driver stores the file on disk as a series of fixed-length chunks (each in its own file). diff --git a/pyproject.toml b/pyproject.toml index 4873b52e1..befa3bb0f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,7 +91,7 @@ omit = [ ] [tool.ruff] -select = ["E", "F", "T100", "T201", "T203"] +lint.select = ["E", "F", "T100", "T201", "T203"] exclude = [ ".git", ".tox", @@ -100,12 +100,13 @@ exclude = [ "dist/", "src/nwb-schema", "docs/source/conf.py", + "docs/notebooks/*", "src/pynwb/_due.py", "test.py" # remove when pytest comes along ] line-length = 120 -[tool.ruff.per-file-ignores] +[tool.ruff.lint.per-file-ignores] "tests/read_dandi/*" = ["T201"] "docs/gallery/*" = ["E402", "T201"] "src/*/__init__.py" = ["F401"] @@ -115,6 +116,6 @@ line-length = 120 # "test_gallery.py" = ["T201"] # Uncomment when test_gallery.py is created -[tool.ruff.mccabe] +[tool.ruff.lint.mccabe] max-complexity = 17 From 609eaac0830c7e0c57d1c2051718d91ef0314a4f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Sep 2024 01:01:43 +0000 Subject: [PATCH 07/13] Bump actions/download-artifact from 3 to 4.1.7 in /.github/workflows (#1955) Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ryan Ly --- .github/workflows/run_tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index aa121acb4..ac463134b 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -283,7 +283,7 @@ jobs: python-version: '3.12' - name: Download wheel and source distributions from artifact - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: distributions path: dist From aaa4d65f0cc45621aaea90dbddfa810bd19a973d Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Wed, 4 Sep 2024 13:55:12 -0700 Subject: [PATCH 08/13] Numpy 2.0 (#1956) * Update pyproject.toml * Update requirements-min.txt * Update requirements.txt * Update requirements-min.txt * Update requirements-min.txt * Update requirements.txt * Update pyproject.toml * Update export.rst * Update export.rst * Update export.rst * Update CHANGELOG.md --- CHANGELOG.md | 3 +++ docs/source/export.rst | 10 ++++------ pyproject.toml | 4 ++-- requirements-min.txt | 2 +- requirements.txt | 4 ++-- 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82370cff4..5350d081f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## PyNWB 2.8.2 (Upcoming) +### Enhancements and minor changes +- Added support for numpy 2.0. @mavaylon1 [#1956](https://github.com/NeurodataWithoutBorders/pynwb/pull/1956) + ### Documentation and tutorial enhancements - Added pre-release pull request instructions to release process documentation @stephprince [#1928](https://github.com/NeurodataWithoutBorders/pynwb/pull/1928) - Added section on how to use the `family` driver in `h5py` for splitting data across multiple files @oruebel [#1949](https://github.com/NeurodataWithoutBorders/pynwb/pull/1949) diff --git a/docs/source/export.rst b/docs/source/export.rst index 490cd346e..218184f9b 100644 --- a/docs/source/export.rst +++ b/docs/source/export.rst @@ -53,14 +53,12 @@ on the :py:class:`~pynwb.file.NWBFile` before exporting. How do I create a copy of an NWB file with different data layouts (e.g., applying compression)? --------------------------------------------------------------------------------------------------------- -Use the `h5repack `_ command line tool from the HDF5 Group. -See also this `h5repack tutorial `_. +Use the `h5repack `_ command line tool from the HDF5 Group. How do I create a copy of an NWB file with different controls over how links are treated and whether copies are deep or shallow? --------------------------------------------------------------------------------------------------------------------------------- -Use the `h5copy `_ command line tool from the HDF5 Group. -See also this `h5copy tutorial `_. +Use the `h5copy `_ command line tool from the HDF5 Group. How do I generate new object IDs for a newly exported NWB file? @@ -101,8 +99,8 @@ For example: export_io.export(src_io=read_io, nwbfile=nwbfile, write_args={'link_data': False}) # copy linked datasets # the written file will contain no links to external datasets -You can also the `h5copy `_ command line tool \ -from the HDF5 Group. See also this `h5copy tutorial `_. +You can also the `h5copy `_ command line tool \ +from the HDF5 Group. How do I write a newly instantiated ``NWBFile`` to two different file paths? diff --git a/pyproject.toml b/pyproject.toml index befa3bb0f..3ab85a4ae 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,8 +34,8 @@ classifiers = [ ] dependencies = [ "h5py>=2.10", - "hdmf>=3.14.0", - "numpy>=1.18, <2.0", # pin below 2.0 until HDMF supports numpy 2.0 + "hdmf>=3.14.3", + "numpy>=1.18", "pandas>=1.1.5", "python-dateutil>=2.7.3", ] diff --git a/requirements-min.txt b/requirements-min.txt index a047d81c7..eef051b25 100644 --- a/requirements-min.txt +++ b/requirements-min.txt @@ -1,6 +1,6 @@ # minimum versions of package dependencies for installing PyNWB h5py==2.10 # support for selection of datasets with list of indices added in 2.10 -hdmf==3.14.0 +hdmf==3.14.3 numpy==1.18 pandas==1.1.5 python-dateutil==2.7.3 diff --git a/requirements.txt b/requirements.txt index 5b3c49ded..27716cf5a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ # pinned dependencies to reproduce an entire development environment to use PyNWB h5py==3.11.0 -hdmf==3.14.0 -numpy==1.26.4 +hdmf==3.14.3 +numpy==2.1.1 pandas==2.2.2 python-dateutil==2.9.0.post0 From 71ef8e204573366e82ef37a648acac03659e4131 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Thu, 5 Sep 2024 13:13:22 -0700 Subject: [PATCH 09/13] bump upload-artifact version (#1957) --- .github/workflows/run_tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index ac463134b..e365d78cf 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -64,7 +64,7 @@ jobs: - name: Upload distribution as a workspace artifact if: ${{ matrix.upload-wheels }} - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: distributions path: dist From 44ef205770ccbd10e3a2815260f11c911cd63106 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 5 Sep 2024 16:30:33 -0700 Subject: [PATCH 10/13] Expose cache_spec option in NWBHDF5IO.export (#1959) * Expose cache_spec option in NWBHDF5IO.export * Update changelog --- CHANGELOG.md | 1 + src/pynwb/__init__.py | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5350d081f..8c465adec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ ### Bug fixes - Fixed `can_read` method to return False if no nwbfile version can be found @stephprince [#1934](https://github.com/NeurodataWithoutBorders/pynwb/pull/1934) - Changed `epoch_tags` to be a NWBFile property instead of constructor argument. @stephprince [#1935](https://github.com/NeurodataWithoutBorders/pynwb/pull/1935) +- Exposed option to not cache the spec in `NWBHDF5IO.export`. @rly [#1959](https://github.com/NeurodataWithoutBorders/pynwb/pull/1959) ## PyNWB 2.8.1 (July 3, 2024) diff --git a/src/pynwb/__init__.py b/src/pynwb/__init__.py index 278e48948..727838821 100644 --- a/src/pynwb/__init__.py +++ b/src/pynwb/__init__.py @@ -368,7 +368,9 @@ def read(self, **kwargs): 'default': None}, {'name': 'write_args', 'type': dict, 'doc': 'arguments to pass to :py:meth:`~hdmf.backends.io.HDMFIO.write_builder`', - 'default': None}) + 'default': None}, + {'name': 'cache_spec', 'type': bool, 'doc': 'whether to cache the specification to file', + 'default': True}) def export(self, **kwargs): """ Export an NWB file to a new NWB file using the HDF5 backend. From 1178e0d1022220703183e6ebe73e32c4c58543f8 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Mon, 9 Sep 2024 09:54:52 -0700 Subject: [PATCH 11/13] Fix numpy version for py39 (#1963) --- requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 27716cf5a..6d7a17623 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ # pinned dependencies to reproduce an entire development environment to use PyNWB h5py==3.11.0 hdmf==3.14.3 -numpy==2.1.1 +numpy==2.1.1; python_version > "3.9" # numpy 2.1+ is not compatible with py3.9 +numpy==2.0.2; python_version == "3.9" pandas==2.2.2 python-dateutil==2.9.0.post0 From 61965684ec2d33b15e59d3bef3696a6ad9651108 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Mon, 9 Sep 2024 10:25:39 -0700 Subject: [PATCH 12/13] update cached namespace retrieval in validation tests (#1961) * filter out warnings when getting namespaces in test.py * make get_cached_namespaces function public * replace get_namespaces function * update code block in docstring * update CHANGELOG.md --------- Co-authored-by: Ryan Ly --- CHANGELOG.md | 1 + src/pynwb/validate.py | 26 +++++++++++++++----------- test.py | 13 ++----------- tests/integration/ros3/test_ros3.py | 4 ++-- 4 files changed, 20 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c465adec..62dcfe688 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Enhancements and minor changes - Added support for numpy 2.0. @mavaylon1 [#1956](https://github.com/NeurodataWithoutBorders/pynwb/pull/1956) +- Make `get_cached_namespaces_to_validate` a public function @stephprince [#1961](https://github.com/NeurodataWithoutBorders/pynwb/pull/1961) ### Documentation and tutorial enhancements - Added pre-release pull request instructions to release process documentation @stephprince [#1928](https://github.com/NeurodataWithoutBorders/pynwb/pull/1928) diff --git a/src/pynwb/validate.py b/src/pynwb/validate.py index aecfb2556..880f860a6 100644 --- a/src/pynwb/validate.py +++ b/src/pynwb/validate.py @@ -29,7 +29,7 @@ def _validate_helper(io: HDMFIO, namespace: str = CORE_NAMESPACE) -> list: return validator.validate(builder) -def _get_cached_namespaces_to_validate( +def get_cached_namespaces_to_validate( path: str, driver: Optional[str] = None, aws_region: Optional[str] = None, ) -> Tuple[List[str], BuildManager, Dict[str, str]]: """ @@ -39,14 +39,18 @@ def _get_cached_namespaces_to_validate( ------- The following example illustrates how we can use this function to validate against namespaces cached in a file. This is useful, e.g., when a file was created using an extension - >>> from pynwb import validate - >>> from pynwb.validate import _get_cached_namespaces_to_validate - >>> path = "my_nwb_file.nwb" - >>> validate_namespaces, manager, cached_namespaces = _get_cached_namespaces_to_validate(path) - >>> with NWBHDF5IO(path, "r", manager=manager) as reader: - >>> errors = [] - >>> for ns in validate_namespaces: - >>> errors += validate(io=reader, namespace=ns) + + .. code-block:: python + + from pynwb import validate + from pynwb.validate import get_cached_namespaces_to_validate + path = "my_nwb_file.nwb" + validate_namespaces, manager, cached_namespaces = get_cached_namespaces_to_validate(path) + with NWBHDF5IO(path, "r", manager=manager) as reader: + errors = [] + for ns in validate_namespaces: + errors += validate(io=reader, namespace=ns) + :param path: Path for the NWB file :return: Tuple with: - List of strings with the most specific namespace(s) to use for validation. @@ -149,7 +153,7 @@ def validate(**kwargs): io_kwargs = dict(path=path, mode="r", driver=driver) if use_cached_namespaces: - cached_namespaces, manager, namespace_dependencies = _get_cached_namespaces_to_validate( + cached_namespaces, manager, namespace_dependencies = get_cached_namespaces_to_validate( path=path, driver=driver ) io_kwargs.update(manager=manager) @@ -231,7 +235,7 @@ def validate_cli(): if args.list_namespaces: for path in args.paths: - cached_namespaces, _, _ = _get_cached_namespaces_to_validate(path=path) + cached_namespaces, _, _ = get_cached_namespaces_to_validate(path=path) print("\n".join(cached_namespaces)) else: validation_errors, validation_status = validate( diff --git a/test.py b/test.py index 5bddb7c7d..0d9e25990 100644 --- a/test.py +++ b/test.py @@ -153,6 +153,7 @@ def validate_nwbs(): examples_nwbs = glob.glob('*.nwb') import pynwb + from pynwb.validate import get_cached_namespaces_to_validate for nwb in examples_nwbs: try: @@ -171,17 +172,7 @@ def validate_nwbs(): for err in errors: print("Error: %s" % err) - def get_namespaces(nwbfile): - comp = run(["python", "-m", "pynwb.validate", - "--list-namespaces", nwbfile], - stdout=PIPE, stderr=STDOUT, universal_newlines=True, timeout=30) - - if comp.returncode != 0: - return [] - - return comp.stdout.split() - - namespaces = get_namespaces(nwb) + namespaces, _, _ = get_cached_namespaces_to_validate(nwb) if len(namespaces) == 0: FAILURES += 1 diff --git a/tests/integration/ros3/test_ros3.py b/tests/integration/ros3/test_ros3.py index 95a891760..2571e6199 100644 --- a/tests/integration/ros3/test_ros3.py +++ b/tests/integration/ros3/test_ros3.py @@ -1,6 +1,6 @@ from pynwb import NWBHDF5IO from pynwb import validate -from pynwb.validate import _get_cached_namespaces_to_validate +from pynwb.validate import get_cached_namespaces_to_validate from pynwb.testing import TestCase import urllib.request import h5py @@ -85,7 +85,7 @@ def test_dandi_get_cached_namespaces(self): ) } } - found_namespaces, _, found_namespace_dependencies = _get_cached_namespaces_to_validate( + found_namespaces, _, found_namespace_dependencies = get_cached_namespaces_to_validate( path=self.s3_test_path, driver="ros3" ) From b9f9e5a3e9d915acb18521cd760768f323138933 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Mon, 9 Sep 2024 11:12:11 -0700 Subject: [PATCH 13/13] Prepare for release of PyNWB 2.8.2 (#1960) * update changelog * update dependencies * update requirements-doc.txt * revert opt requirements update * update numpy requirement * update environment * add family driver file validation, ignore dandi file validation * revert warning filtering in validation * Update CHANGELOG.md * Update environment-ros3.yml --- CHANGELOG.md | 2 +- environment-ros3.yml | 6 +++--- test.py | 39 +++++++++++++++++++++++++++++++-------- 3 files changed, 35 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62dcfe688..597636cd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # PyNWB Changelog -## PyNWB 2.8.2 (Upcoming) +## PyNWB 2.8.2 (September 9, 2024) ### Enhancements and minor changes - Added support for numpy 2.0. @mavaylon1 [#1956](https://github.com/NeurodataWithoutBorders/pynwb/pull/1956) diff --git a/environment-ros3.yml b/environment-ros3.yml index 84031808f..081408f19 100644 --- a/environment-ros3.yml +++ b/environment-ros3.yml @@ -6,9 +6,9 @@ channels: dependencies: - python==3.12 - h5py==3.11.0 - - hdmf==3.14.1 - - matplotlib==3.8.0 - - numpy==1.26.4 + - hdmf==3.14.3 + - matplotlib==3.8.4 + - numpy==2.1.1 - pandas==2.2.2 - python-dateutil==2.9.0 - setuptools diff --git a/test.py b/test.py index 0d9e25990..f64fcd75d 100644 --- a/test.py +++ b/test.py @@ -3,6 +3,7 @@ import re import argparse import glob +import h5py import inspect import logging import os.path @@ -152,6 +153,9 @@ def validate_nwbs(): logging.info('running validation tests on NWB files') examples_nwbs = glob.glob('*.nwb') + # exclude files downloaded from dandi, validation of those files is handled by dandisets-health-status checks + examples_nwbs = [x for x in examples_nwbs if not x.startswith('sub-')] + import pynwb from pynwb.validate import get_cached_namespaces_to_validate @@ -162,15 +166,34 @@ def validate_nwbs(): ws = list() with warnings.catch_warnings(record=True) as tmp: logging.info("Validating with pynwb.validate method.") - with pynwb.NWBHDF5IO(nwb, mode='r') as io: - errors = pynwb.validate(io) - TOTAL += 1 + is_family_nwb_file = False + try: + with pynwb.NWBHDF5IO(nwb, mode='r') as io: + errors = pynwb.validate(io) + except OSError as e: + # if the file was created with the family driver, need to use the family driver to open it + if 'family driver should be used' in str(e): + is_family_nwb_file = True + match = re.search(r'(\d+)', nwb) + filename_pattern = nwb[:match.start()] + '%d' + nwb[match.end():] # infer the filename pattern + memb_size = 1024**2 # note: the memb_size must be the same as the one used to create the file + with h5py.File(filename_pattern, mode='r', driver='family', memb_size=memb_size) as f: + with pynwb.NWBHDF5IO(file=f, manager=None, mode='r') as io: + errors = pynwb.validate(io) + else: + raise e + + TOTAL += 1 + + if errors: + FAILURES += 1 + ERRORS += 1 + for err in errors: + print("Error: %s" % err) - if errors: - FAILURES += 1 - ERRORS += 1 - for err in errors: - print("Error: %s" % err) + # if file was created with family driver, skip pynwb.validate CLI because not yet supported + if is_family_nwb_file: + continue namespaces, _, _ = get_cached_namespaces_to_validate(nwb)