From 5be83b6dd208a0c8ea59326e32425f0a7987f630 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 11 Jan 2024 14:49:04 -0800 Subject: [PATCH 01/29] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5cfa5a9e..ce8e3dec6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ ## PyNWB 2.6.0 (Upcoming) ### Enhancements and minor changes +- Added support for NWB schema 2.7.0. + - ... + - ... + - ... + - ... - For `NWBHDF5IO()`, change the default of arg `load_namespaces` from `False` to `True`. @bendichter [#1748](https://github.com/NeurodataWithoutBorders/pynwb/pull/1748) - Add `NWBHDF5IO.can_read()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) - Add `pynwb.get_nwbfile_version()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) From d0c40686b0eddcb4d071b418e1c29b3af58e00a6 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 11 Jan 2024 15:37:35 -0800 Subject: [PATCH 02/29] Update OptogeneticSeries to allow 2D data (#1812) Co-authored-by: Steph Prince <40640337+stephprince@users.noreply.github.com> --- CHANGELOG.md | 2 +- src/pynwb/nwb-schema | 2 +- src/pynwb/ogen.py | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce8e3dec6..c2f32d315 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### Enhancements and minor changes - Added support for NWB schema 2.7.0. - ... - - ... + - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) - ... - ... - For `NWBHDF5IO()`, change the default of arg `load_namespaces` from `False` to `True`. @bendichter [#1748](https://github.com/NeurodataWithoutBorders/pynwb/pull/1748) diff --git a/src/pynwb/nwb-schema b/src/pynwb/nwb-schema index b4f8838cb..b8806738f 160000 --- a/src/pynwb/nwb-schema +++ b/src/pynwb/nwb-schema @@ -1 +1 @@ -Subproject commit b4f8838cbfbb7f8a117bd7e0aad19133d26868b4 +Subproject commit b8806738fa0d125970459628d81e0c18da896a1f diff --git a/src/pynwb/ogen.py b/src/pynwb/ogen.py index f410b4235..af11842e4 100644 --- a/src/pynwb/ogen.py +++ b/src/pynwb/ogen.py @@ -37,8 +37,9 @@ class OptogeneticSeries(TimeSeries): __nwbfields__ = ('site',) @docval(*get_docval(TimeSeries.__init__, 'name'), # required - {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': (None, ), # required - 'doc': 'The data values over time. Must be 1D.'}, + {'name': 'data', 'type': ('array_data', 'data', TimeSeries), # required + 'shape': [(None, ), (None, None)], + 'doc': 'The data values over time.'}, {'name': 'site', 'type': OptogeneticStimulusSite, # required 'doc': 'The site to which this stimulus was applied.'}, *get_docval(TimeSeries.__init__, 'resolution', 'conversion', 'timestamps', 'starting_time', 'rate', From 6a5420b88a24478946bdb3de07f07cba56e73bb1 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Thu, 11 Jan 2024 16:03:32 -0800 Subject: [PATCH 03/29] Support stimulus_template as optional column in IntracellularRecordingsTable (#1815) * add stimulus template column option to IntracellularRecordingsTable * add tests for stimulus template column * add example in tutorial for adding stimulus template data * link to nwb-schema PR with stimulus template change * update changelog * add empty TimeSeriesReference method * point to updated nwb-schema PR * remove test caught by docval argument checking * Apply suggestions from code review Co-authored-by: Oliver Ruebel * update tutorial and documentation * Update src/pynwb/base.py Co-authored-by: Ryan Ly * Update CHANGELOG.md --------- Co-authored-by: Ryan Ly Co-authored-by: Oliver Ruebel --- CHANGELOG.md | 1 + docs/gallery/domain/plot_icephys.py | 54 +++++++++++++++++++ src/pynwb/base.py | 20 +++++++ src/pynwb/icephys.py | 30 +++++++++++ src/pynwb/nwb-schema | 2 +- tests/unit/test_base.py | 6 +++ tests/unit/test_icephys_metadata_tables.py | 62 ++++++++++++++++++++++ 7 files changed, 174 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2f32d315..e5a155c5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Added support for NWB schema 2.7.0. - ... - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) + - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - ... - ... - For `NWBHDF5IO()`, change the default of arg `load_namespaces` from `False` to `True`. @bendichter [#1748](https://github.com/NeurodataWithoutBorders/pynwb/pull/1748) diff --git a/docs/gallery/domain/plot_icephys.py b/docs/gallery/domain/plot_icephys.py index 109ec5fcc..2e7f51a23 100644 --- a/docs/gallery/domain/plot_icephys.py +++ b/docs/gallery/domain/plot_icephys.py @@ -97,6 +97,7 @@ # Import additional core datatypes used in the example from pynwb.core import DynamicTable, VectorData +from pynwb.base import TimeSeriesReference, TimeSeriesReferenceVectorData # Import icephys TimeSeries types used from pynwb.icephys import VoltageClampSeries, VoltageClampStimulusSeries @@ -457,6 +458,59 @@ category="electrodes", ) +##################################################################### +# Adding stimulus templates +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +# +# One predefined subcategory column is the ``stimulus_template`` column in the stimuli table. This column is +# used to store template waveforms of stimuli in addition to the actual recorded stimulus that is stored in the +# ``stimulus`` column. The ``stimulus_template`` column contains an idealized version of the template waveform used as +# the stimulus. This can be useful as a noiseless version of the stimulus for data analysis or to validate that the +# recorded stimulus matches the expected waveform of the template. Similar to the ``stimulus`` and ``response`` +# columns, we can specify a relevant time range. + +stimulus_template = VoltageClampStimulusSeries( + name="ccst", + data=[0, 1, 2, 3, 4], + starting_time=0.0, + rate=10e3, + electrode=electrode, + gain=0.02, +) +nwbfile.add_stimulus_template(stimulus_template) + +nwbfile.intracellular_recordings.add_column( + name="stimulus_template", + data=[TimeSeriesReference(0, 5, stimulus_template), # (start_index, index_count, stimulus_template) + TimeSeriesReference(1, 3, stimulus_template), + TimeSeriesReference.empty(stimulus_template)], # if there was no data for that recording, use empty reference + description="Column storing the reference to the stimulus template for the recording (rows).", + category="stimuli", + col_cls=TimeSeriesReferenceVectorData +) + +# we can also add stimulus template data as follows +rowindex = nwbfile.add_intracellular_recording( + electrode=electrode, + stimulus=stimulus, + stimulus_template=stimulus_template, # the full time range of the stimulus template will be used unless specified + recording_tag='A4', + recording_lab_data={'location': 'Isengard'}, + electrode_metadata={'voltage_threshold': 0.14}, + id=13, +) + +##################################################################### +# .. note:: If a stimulus template column exists but there is no stimulus template data for that recording, then +# :py:meth:`~pynwb.file.NWBFile.add_intracellular_recording` will internally set the stimulus template to the +# provided stimulus or response TimeSeries and the start_index and index_count for the missing parameter are +# set to -1. The missing values will be represented via masked numpy arrays. + +##################################################################### +# .. note:: Since stimulus templates are often reused across many recordings, the timestamps in the templates are not +# usually aligned with the recording nor with the reference time of the file. The timestamps often start +# at 0 and are relative to the time of the application of the stimulus. + ##################################################################### # Add a simultaneous recording # --------------------------------- diff --git a/src/pynwb/base.py b/src/pynwb/base.py index 42f7b7ff3..02d2e3c0f 100644 --- a/src/pynwb/base.py +++ b/src/pynwb/base.py @@ -497,6 +497,26 @@ def data(self): # load the data from the timeseries return self.timeseries.data[self.idx_start: (self.idx_start + self.count)] + @classmethod + @docval({'name': 'timeseries', 'type': TimeSeries, 'doc': 'the timeseries object to reference.'}) + def empty(cls, timeseries): + """ + Creates an empty TimeSeriesReference object to represent missing data. + + When missing data needs to be represented, NWB defines ``None`` for the complex data type ``(idx_start, + count, TimeSeries)`` as (-1, -1, TimeSeries) for storage. The exact timeseries object will technically not + matter since the empty reference is a way of indicating a NaN value in a + :py:class:`~pynwb.base.TimeSeriesReferenceVectorData` column. + + An example where this functionality is used is :py:class:`~pynwb.icephys.IntracellularRecordingsTable` + where only one of stimulus or response data was recorded. In such cases, the timeseries object for the + empty stimulus :py:class:`~pynwb.base.TimeSeriesReference` could be set to the response series, or vice versa. + + :returns: Returns :py:class:`~pynwb.base.TimeSeriesReference` + """ + + return cls(-1, -1, timeseries) + @register_class('TimeSeriesReferenceVectorData', CORE_NAMESPACE) class TimeSeriesReferenceVectorData(VectorData): diff --git a/src/pynwb/icephys.py b/src/pynwb/icephys.py index 04382abbc..d3a52d12c 100644 --- a/src/pynwb/icephys.py +++ b/src/pynwb/icephys.py @@ -415,6 +415,12 @@ class IntracellularStimuliTable(DynamicTable): 'index': False, 'table': False, 'class': TimeSeriesReferenceVectorData}, + {'name': 'stimulus_template', + 'description': 'Column storing the reference to the stimulus template for the recording (rows)', + 'required': False, + 'index': False, + 'table': False, + 'class': TimeSeriesReferenceVectorData}, ) @docval(*get_docval(DynamicTable.__init__, 'id', 'columns', 'colnames')) @@ -518,6 +524,13 @@ def __init__(self, **kwargs): {'name': 'stimulus', 'type': TimeSeries, 'doc': 'The TimeSeries (usually a PatchClampSeries) with the stimulus', 'default': None}, + {'name': 'stimulus_template_start_index', 'type': int, 'doc': 'Start index of the stimulus template', + 'default': None}, + {'name': 'stimulus_template_index_count', 'type': int, 'doc': 'Stop index of the stimulus template', + 'default': None}, + {'name': 'stimulus_template', 'type': TimeSeries, + 'doc': 'The TimeSeries (usually a PatchClampSeries) with the stimulus template waveforms', + 'default': None}, {'name': 'response_start_index', 'type': int, 'doc': 'Start index of the response', 'default': None}, {'name': 'response_index_count', 'type': int, 'doc': 'Stop index of the response', 'default': None}, {'name': 'response', 'type': TimeSeries, @@ -553,6 +566,11 @@ def add_recording(self, **kwargs): 'response', kwargs) electrode = popargs('electrode', kwargs) + stimulus_template_start_index, stimulus_template_index_count, stimulus_template = popargs( + 'stimulus_template_start_index', + 'stimulus_template_index_count', + 'stimulus_template', + kwargs) # if electrode is not provided, take from stimulus or response object if electrode is None: @@ -572,6 +590,15 @@ def add_recording(self, **kwargs): response_start_index, response_index_count = self.__compute_index(response_start_index, response_index_count, response, 'response') + stimulus_template_start_index, stimulus_template_index_count = self.__compute_index( + stimulus_template_start_index, + stimulus_template_index_count, + stimulus_template, 'stimulus_template') + + # if stimulus template is already a column in the stimuli table, but stimulus_template was None + if 'stimulus_template' in self.category_tables['stimuli'].colnames and stimulus_template is None: + stimulus_template = stimulus if stimulus is not None else response # set to stimulus if it was provided + # If either stimulus or response are None, then set them to the same TimeSeries to keep the I/O happy response = response if response is not None else stimulus stimulus_provided_is_not_none = stimulus is not None # Store if stimulus is None for error checks later @@ -612,6 +639,9 @@ def add_recording(self, **kwargs): stimuli = {} stimuli['stimulus'] = TimeSeriesReferenceVectorData.TIME_SERIES_REFERENCE_TUPLE( stimulus_start_index, stimulus_index_count, stimulus) + if stimulus_template is not None: + stimuli['stimulus_template'] = TimeSeriesReferenceVectorData.TIME_SERIES_REFERENCE_TUPLE( + stimulus_template_start_index, stimulus_template_index_count, stimulus_template) # Compile the responses table data responses = copy(popargs('response_metadata', kwargs)) diff --git a/src/pynwb/nwb-schema b/src/pynwb/nwb-schema index b8806738f..b48ab122a 160000 --- a/src/pynwb/nwb-schema +++ b/src/pynwb/nwb-schema @@ -1 +1 @@ -Subproject commit b8806738fa0d125970459628d81e0c18da896a1f +Subproject commit b48ab122ab1d2cca13d1be9fb9edc9f4e7cd4ca3 diff --git a/tests/unit/test_base.py b/tests/unit/test_base.py index ad4ce6739..b079464d1 100644 --- a/tests/unit/test_base.py +++ b/tests/unit/test_base.py @@ -877,3 +877,9 @@ def test_data_property_bad_reference(self): IndexError, "'idx_start + count' out of range for timeseries 'test'" ): tsr.data + + def test_empty_reference_creation(self): + tsr = TimeSeriesReference.empty(self._create_time_series_with_rate()) + self.assertFalse(tsr.isvalid()) + self.assertIsNone(tsr.data) + self.assertIsNone(tsr.timestamps) diff --git a/tests/unit/test_icephys_metadata_tables.py b/tests/unit/test_icephys_metadata_tables.py index 34531d6a4..b31ee9215 100644 --- a/tests/unit/test_icephys_metadata_tables.py +++ b/tests/unit/test_icephys_metadata_tables.py @@ -419,6 +419,15 @@ def test_add_row_index_out_of_range(self): response=self.response, id=np.int64(10) ) + with self.assertRaises(IndexError): + ir = IntracellularRecordingsTable() + ir.add_recording( + electrode=self.electrode, + stimulus_template=self.stimulus, + stimulus_template_start_index=10, + response=self.response, + id=np.int64(10) + ) # Stimulus/Response index count too large with self.assertRaises(IndexError): ir = IntracellularRecordingsTable() @@ -438,6 +447,15 @@ def test_add_row_index_out_of_range(self): response=self.response, id=np.int64(10) ) + with self.assertRaises(IndexError): + ir = IntracellularRecordingsTable() + ir.add_recording( + electrode=self.electrode, + stimulus_template=self.stimulus, + stimulus_template_index_count=10, + response=self.response, + id=np.int64(10) + ) # Stimulus/Response start+count combination too large with self.assertRaises(IndexError): ir = IntracellularRecordingsTable() @@ -459,6 +477,16 @@ def test_add_row_index_out_of_range(self): response=self.response, id=np.int64(10) ) + with self.assertRaises(IndexError): + ir = IntracellularRecordingsTable() + ir.add_recording( + electrode=self.electrode, + stimulus_template=self.stimulus, + stimulus_template_start_index=3, + stimulus_template_index_count=4, + response=self.response, + id=np.int64(10) + ) def test_add_row_no_stimulus_and_response(self): with self.assertRaises(ValueError): @@ -469,6 +497,40 @@ def test_add_row_no_stimulus_and_response(self): response=None ) + def test_add_row_with_stimulus_template(self): + ir = IntracellularRecordingsTable() + ir.add_recording( + electrode=self.electrode, + stimulus=self.stimulus, + stimulus_template=self.stimulus, + response=self.response, + id=np.int64(10) + ) + + def test_add_stimulus_template_column(self): + ir = IntracellularRecordingsTable() + ir.add_column(name='stimulus_template', + description='test column', + category='stimuli', + col_cls=TimeSeriesReferenceVectorData) + + def test_add_row_with_no_stimulus_template_when_stimulus_template_column_exists(self): + ir = IntracellularRecordingsTable() + ir.add_recording(electrode=self.electrode, + stimulus=self.stimulus, + response=self.response, + stimulus_template=self.stimulus, + id=np.int64(10)) + + # add row with only stimulus when stimulus template column already exists + ir.add_recording(electrode=self.electrode, + stimulus=self.stimulus, + id=np.int64(20)) + # add row with only response when stimulus template column already exists + ir.add_recording(electrode=self.electrode, + response=self.stimulus, + id=np.int64(30)) + def test_add_column(self): ir = IntracellularRecordingsTable() ir.add_recording( From 5c760da40fd431b85feb4668003ec7ffeecc21a9 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Mon, 5 Feb 2024 16:04:00 -0800 Subject: [PATCH 04/29] Support more stimulus types (#1842) --- CHANGELOG.md | 2 +- docs/gallery/domain/images.py | 2 +- src/pynwb/file.py | 30 ++++++++++++++++++++------- src/pynwb/io/file.py | 6 +++++- src/pynwb/nwb-schema | 2 +- test.py | 6 ++++++ tests/unit/test_file.py | 38 +++++++++++++++++++++++++++++++++++ 7 files changed, 75 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1180bb644..e2aece13c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - ... - - ... + - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - For `NWBHDF5IO()`, change the default of arg `load_namespaces` from `False` to `True`. @bendichter [#1748](https://github.com/NeurodataWithoutBorders/pynwb/pull/1748) - Add `NWBHDF5IO.can_read()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) - Add `pynwb.get_nwbfile_version()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) diff --git a/docs/gallery/domain/images.py b/docs/gallery/domain/images.py index 8b59b75f0..fafc1849f 100644 --- a/docs/gallery/domain/images.py +++ b/docs/gallery/domain/images.py @@ -105,7 +105,7 @@ description="The images presented to the subject as stimuli", ) -nwbfile.add_stimulus(timeseries=optical_series) +nwbfile.add_stimulus(stimulus=optical_series) #################### # ImageSeries: Storing series of images as acquisition diff --git a/src/pynwb/file.py b/src/pynwb/file.py index b473e571a..90be96a62 100644 --- a/src/pynwb/file.py +++ b/src/pynwb/file.py @@ -177,7 +177,7 @@ class NWBFile(MultiContainerInterface, HERDManager): { 'attr': 'stimulus', 'add': '_add_stimulus_internal', - 'type': TimeSeries, + 'type': (NWBDataInterface, DynamicTable), 'get': 'get_stimulus' }, { @@ -356,7 +356,8 @@ class NWBFile(MultiContainerInterface, HERDManager): {'name': 'analysis', 'type': (list, tuple), 'doc': 'result of analysis', 'default': None}, {'name': 'stimulus', 'type': (list, tuple), - 'doc': 'Stimulus TimeSeries objects belonging to this NWBFile', 'default': None}, + 'doc': 'Stimulus TimeSeries, DynamicTable, or NWBDataInterface objects belonging to this NWBFile', + 'default': None}, {'name': 'stimulus_template', 'type': (list, tuple), 'doc': 'Stimulus template TimeSeries objects belonging to this NWBFile', 'default': None}, {'name': 'epochs', 'type': TimeIntervals, @@ -856,14 +857,29 @@ def add_acquisition(self, **kwargs): if use_sweep_table: self._update_sweep_table(nwbdata) - @docval({'name': 'timeseries', 'type': TimeSeries}, - {'name': 'use_sweep_table', 'type': bool, 'default': False, 'doc': 'Use the deprecated SweepTable'}) + @docval({'name': 'stimulus', 'type': (TimeSeries, DynamicTable, NWBDataInterface), 'default': None, + 'doc': 'The stimulus presentation data to add to this NWBFile.'}, + {'name': 'use_sweep_table', 'type': bool, 'default': False, 'doc': 'Use the deprecated SweepTable'}, + {'name': 'timeseries', 'type': TimeSeries, 'default': None, + 'doc': 'The "timeseries" keyword argument is deprecated. Use the "nwbdata" argument instead.'},) def add_stimulus(self, **kwargs): - timeseries = popargs('timeseries', kwargs) - self._add_stimulus_internal(timeseries) + stimulus, timeseries = popargs('stimulus', 'timeseries', kwargs) + if stimulus is None and timeseries is None: + raise ValueError( + "The 'stimulus' keyword argument is required. The 'timeseries' keyword argument can be " + "provided for backwards compatibility but is deprecated in favor of 'stimulus' and will be " + "removed in PyNWB 3.0." + ) + # TODO remove this support in PyNWB 3.0 + if timeseries is not None: + warn("The 'timeseries' keyword argument is deprecated and will be removed in PyNWB 3.0. " + "Use the 'stimulus' argument instead.", DeprecationWarning) + if stimulus is None: + stimulus = timeseries + self._add_stimulus_internal(stimulus) use_sweep_table = popargs('use_sweep_table', kwargs) if use_sweep_table: - self._update_sweep_table(timeseries) + self._update_sweep_table(stimulus) @docval({'name': 'timeseries', 'type': (TimeSeries, Images)}, {'name': 'use_sweep_table', 'type': bool, 'default': False, 'doc': 'Use the deprecated SweepTable'}) diff --git a/src/pynwb/io/file.py b/src/pynwb/io/file.py index ccbfb8e47..1908c6b31 100644 --- a/src/pynwb/io/file.py +++ b/src/pynwb/io/file.py @@ -31,7 +31,11 @@ def __init__(self, spec): self.unmap(stimulus_spec) self.unmap(stimulus_spec.get_group('presentation')) self.unmap(stimulus_spec.get_group('templates')) - self.map_spec('stimulus', stimulus_spec.get_group('presentation').get_neurodata_type('TimeSeries')) + # map "stimulus" to NWBDataInterface and DynamicTable and unmap the spec for TimeSeries because it is + # included in the mapping to NWBDataInterface + self.unmap(stimulus_spec.get_group('presentation').get_neurodata_type('TimeSeries')) + self.map_spec('stimulus', stimulus_spec.get_group('presentation').get_neurodata_type('NWBDataInterface')) + self.map_spec('stimulus', stimulus_spec.get_group('presentation').get_neurodata_type('DynamicTable')) self.map_spec('stimulus_template', stimulus_spec.get_group('templates').get_neurodata_type('TimeSeries')) self.map_spec('stimulus_template', stimulus_spec.get_group('templates').get_neurodata_type('Images')) diff --git a/src/pynwb/nwb-schema b/src/pynwb/nwb-schema index b48ab122a..10d2fc202 160000 --- a/src/pynwb/nwb-schema +++ b/src/pynwb/nwb-schema @@ -1 +1 @@ -Subproject commit b48ab122ab1d2cca13d1be9fb9edc9f4e7cd4ca3 +Subproject commit 10d2fc202151e1136e01f353f9907f4bf974d3ad diff --git a/test.py b/test.py index 16191ae3f..8f6a403ee 100755 --- a/test.py +++ b/test.py @@ -7,6 +7,7 @@ import logging import os.path import os +import shutil from subprocess import run, PIPE, STDOUT import sys import traceback @@ -275,6 +276,9 @@ def clean_up_tests(): "processed_data.nwb", "raw_data.nwb", "scratch_analysis.nwb", + # "sub-P11HMH_ses-20061101_ecephys+image.nwb", # TODO cannot delete this file on windows for some reason + "test_edit.nwb", + "test_edit2.nwb", "test_cortical_surface.nwb", "test_icephys_file.nwb", "test_multicontainerinterface.extensions.yaml", @@ -286,6 +290,8 @@ def clean_up_tests(): if os.path.exists(name): os.remove(name) + shutil.rmtree("zarr_tutorial.nwb.zarr") + def main(): # setup and parse arguments diff --git a/tests/unit/test_file.py b/tests/unit/test_file.py index 756009ff3..0fa065e1a 100644 --- a/tests/unit/test_file.py +++ b/tests/unit/test_file.py @@ -3,6 +3,7 @@ from datetime import datetime, timedelta from dateutil.tz import tzlocal, tzutc +from hdmf.common import DynamicTable from pynwb import NWBFile, TimeSeries, NWBHDF5IO from pynwb.base import Image, Images @@ -149,6 +150,43 @@ def test_add_stimulus(self): 'grams', timestamps=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5])) self.assertEqual(len(self.nwbfile.stimulus), 1) + def test_add_stimulus_timeseries_arg(self): + """Test nwbfile.add_stimulus using the deprecated 'timeseries' keyword argument""" + msg = ( + "The 'timeseries' keyword argument is deprecated and will be removed in PyNWB 3.0. " + "Use the 'stimulus' argument instead." + ) + with self.assertWarnsWith(DeprecationWarning, msg): + self.nwbfile.add_stimulus( + timeseries=TimeSeries( + name='test_ts', + data=[0, 1, 2, 3, 4, 5], + unit='grams', + timestamps=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5] + ) + ) + self.assertEqual(len(self.nwbfile.stimulus), 1) + + def test_add_stimulus_no_stimulus_arg(self): + """Test nwbfile.add_stimulus using the deprecated 'timeseries' keyword argument""" + msg = ( + "The 'stimulus' keyword argument is required. The 'timeseries' keyword argument can be " + "provided for backwards compatibility but is deprecated in favor of 'stimulus' and will be " + "removed in PyNWB 3.0." + ) + with self.assertRaisesWith(ValueError, msg): + self.nwbfile.add_stimulus(None) + self.assertEqual(len(self.nwbfile.stimulus), 0) + + def test_add_stimulus_dynamic_table(self): + dt = DynamicTable( + name='test_dynamic_table', + description='a test dynamic table', + ) + self.nwbfile.add_stimulus(dt) + self.assertEqual(len(self.nwbfile.stimulus), 1) + self.assertIs(self.nwbfile.stimulus['test_dynamic_table'], dt) + def test_add_stimulus_template(self): self.nwbfile.add_stimulus_template(TimeSeries('test_ts', [0, 1, 2, 3, 4, 5], 'grams', timestamps=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5])) From ff264563c5836ee1494107ae02c400025131ade5 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Tue, 6 Feb 2024 17:16:24 -0800 Subject: [PATCH 05/29] Deprecate broken ImagingRetinotopy module (#1813) * Update retinotopy.py * Remove references to retinotopy module * Update schema * Fix test * Updated changelog * Update schema submodule * Update test_retinotopy.py * Update retinotopy.py * Update test_retinotopy.py * Update retinotopy.py * Update test_retinotopy.py * Update retinotopy.py * Update test_retinotopy.py * RuntimeError -> ImportError * Update schema * Revert "Update schema" This reverts commit 08f3a885c84ec49ed52384aa01415c6d892301db. * Update schema --- CHANGELOG.md | 2 + docs/gallery/general/plot_file.py | 5 +- docs/source/api_docs.rst | 1 - src/pynwb/__init__.py | 1 - src/pynwb/io/__init__.py | 1 - src/pynwb/legacy/io/__init__.py | 1 - src/pynwb/nwb-schema | 2 +- src/pynwb/retinotopy.py | 294 ++++++++--------- tests/back_compat/test_import_structure.py | 1 - tests/unit/test_retinotopy.py | 350 +++++++++++---------- 10 files changed, 333 insertions(+), 325 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2aece13c..2e8092c51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Enhancements and minor changes - Added support for NWB schema 2.7.0. - ... + - ... + - Deprecated `ImagingRetinotopy` neurodata type. @rly [#1813](https://github.com/NeurodataWithoutBorders/pynwb/pull/1813) - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - ... diff --git a/docs/gallery/general/plot_file.py b/docs/gallery/general/plot_file.py index beead22f6..2175f8e9e 100644 --- a/docs/gallery/general/plot_file.py +++ b/docs/gallery/general/plot_file.py @@ -108,8 +108,7 @@ :py:class:`~pynwb.ophys.ImageSegmentation`, :py:class:`~pynwb.ophys.MotionCorrection`. - * **Others:** :py:class:`~pynwb.retinotopy.ImagingRetinotopy`, - :py:class:`~pynwb.base.Images`. + * **Others:** :py:class:`~pynwb.base.Images`. * **TimeSeries:** Any :ref:`timeseries_overview` is also a subclass of :py:class:`~pynwb.core.NWBDataInterface` and can be used anywhere :py:class:`~pynwb.core.NWBDataInterface` is allowed. @@ -372,7 +371,7 @@ # Processing modules can be thought of as folders within the file for storing the related processed data. # # .. tip:: Use the NWB schema module names as processing module names where appropriate. -# These are: ``"behavior"``, ``"ecephys"``, ``"icephys"``, ``"ophys"``, ``"ogen"``, ``"retinotopy"``, and ``"misc"``. +# These are: ``"behavior"``, ``"ecephys"``, ``"icephys"``, ``"ophys"``, ``"ogen"``, and ``"misc"``. # # Let's assume that the subject's position was computed from a video tracking algorithm, # so it would be classified as processed data. diff --git a/docs/source/api_docs.rst b/docs/source/api_docs.rst index 3920ad316..94bf1957d 100644 --- a/docs/source/api_docs.rst +++ b/docs/source/api_docs.rst @@ -13,7 +13,6 @@ API Documentation Intracellular Electrophysiology Optophysiology Optogenetics - Retinotopy General Imaging Behavior NWB Base Classes diff --git a/src/pynwb/__init__.py b/src/pynwb/__init__.py index 6e3b3104f..5d9bbc57b 100644 --- a/src/pynwb/__init__.py +++ b/src/pynwb/__init__.py @@ -381,7 +381,6 @@ def export(self, **kwargs): from . import misc # noqa: F401,E402 from . import ogen # noqa: F401,E402 from . import ophys # noqa: F401,E402 -from . import retinotopy # noqa: F401,E402 from . import legacy # noqa: F401,E402 from hdmf.data_utils import DataChunkIterator # noqa: F401,E402 from hdmf.backends.hdf5 import H5DataIO # noqa: F401,E402 diff --git a/src/pynwb/io/__init__.py b/src/pynwb/io/__init__.py index b7e9bea48..e0de46b87 100644 --- a/src/pynwb/io/__init__.py +++ b/src/pynwb/io/__init__.py @@ -9,4 +9,3 @@ from . import misc as __misc from . import ogen as __ogen from . import ophys as __ophys -from . import retinotopy as __retinotopy diff --git a/src/pynwb/legacy/io/__init__.py b/src/pynwb/legacy/io/__init__.py index 97dc7b9d2..70e1d7a77 100644 --- a/src/pynwb/legacy/io/__init__.py +++ b/src/pynwb/legacy/io/__init__.py @@ -8,4 +8,3 @@ from . import misc as __misc from . import ogen as __ogen from . import ophys as __ophys -from . import retinotopy as __retinotopy diff --git a/src/pynwb/nwb-schema b/src/pynwb/nwb-schema index 10d2fc202..f352a93c4 160000 --- a/src/pynwb/nwb-schema +++ b/src/pynwb/nwb-schema @@ -1 +1 @@ -Subproject commit 10d2fc202151e1136e01f353f9907f4bf974d3ad +Subproject commit f352a93c4cbfb202b6a40210e998cab34b05a593 diff --git a/src/pynwb/retinotopy.py b/src/pynwb/retinotopy.py index a345177c0..1dc0f365d 100644 --- a/src/pynwb/retinotopy.py +++ b/src/pynwb/retinotopy.py @@ -1,145 +1,149 @@ -import warnings -from collections.abc import Iterable - -from hdmf.utils import docval, popargs, get_docval - -from . import register_class, CORE_NAMESPACE -from .core import NWBDataInterface, NWBData - - -class RetinotopyImage(NWBData): - """Gray-scale anatomical image of cortical surface. Array structure: [rows][columns] - """ - - __nwbfields__ = ('bits_per_pixel', - 'dimension', - 'format', - 'field_of_view') - - @docval({'name': 'name', 'type': str, 'doc': 'Name of this retinotopy image'}, - {'name': 'data', 'type': Iterable, 'doc': 'Data field.'}, - {'name': 'bits_per_pixel', 'type': int, - 'doc': 'Number of bits used to represent each value. This is necessary to determine maximum ' - '(white) pixel value.'}, - {'name': 'dimension', 'type': Iterable, 'shape': (2, ), 'doc': 'Number of rows and columns in the image.'}, - {'name': 'format', 'type': Iterable, 'doc': 'Format of image. Right now only "raw" supported.'}, - {'name': 'field_of_view', 'type': Iterable, 'shape': (2, ), 'doc': 'Size of viewing area, in meters.'}) - def __init__(self, **kwargs): - bits_per_pixel, dimension, format, field_of_view = popargs( - 'bits_per_pixel', 'dimension', 'format', 'field_of_view', kwargs) - super().__init__(**kwargs) - self.bits_per_pixel = bits_per_pixel - self.dimension = dimension - self.format = format - self.field_of_view = field_of_view - - -class FocalDepthImage(RetinotopyImage): - """Gray-scale image taken with same settings/parameters (e.g., focal depth, - wavelength) as data collection. Array format: [rows][columns]. - """ - - __nwbfields__ = ('focal_depth', ) - - @docval(*get_docval(RetinotopyImage.__init__), - {'name': 'focal_depth', 'type': float, 'doc': 'Focal depth offset, in meters.'}) - def __init__(self, **kwargs): - focal_depth = popargs('focal_depth', kwargs) - super().__init__(**kwargs) - self.focal_depth = focal_depth - - -class RetinotopyMap(NWBData): - """Abstract two-dimensional map of responses to stimuli along a single response axis (e.g., altitude) - """ - - __nwbfields__ = ('field_of_view', - 'dimension') - - @docval({'name': 'name', 'type': str, 'doc': 'the name of this axis map'}, - {'name': 'data', 'type': Iterable, 'shape': (None, None), 'doc': 'data field.'}, - {'name': 'field_of_view', 'type': Iterable, 'shape': (2, ), 'doc': 'Size of viewing area, in meters.'}, - {'name': 'dimension', 'type': Iterable, 'shape': (2, ), - 'doc': 'Number of rows and columns in the image'}) - def __init__(self, **kwargs): - field_of_view, dimension = popargs('field_of_view', 'dimension', kwargs) - super().__init__(**kwargs) - self.field_of_view = field_of_view - self.dimension = dimension - - -class AxisMap(RetinotopyMap): - """Abstract two-dimensional map of responses to stimuli along a single response axis (e.g., altitude) with unit - """ - - __nwbfields__ = ('unit', ) - - @docval(*get_docval(RetinotopyMap.__init__, 'name', 'data', 'field_of_view'), - {'name': 'unit', 'type': str, 'doc': 'Unit that axis data is stored in (e.g., degrees)'}, - *get_docval(RetinotopyMap.__init__, 'dimension')) - def __init__(self, **kwargs): - unit = popargs('unit', kwargs) - super().__init__(**kwargs) - self.unit = unit - - -@register_class('ImagingRetinotopy', CORE_NAMESPACE) -class ImagingRetinotopy(NWBDataInterface): - """ - Intrinsic signal optical imaging or widefield imaging for measuring retinotopy. Stores orthogonal - maps (e.g., altitude/azimuth; radius/theta) of responses to specific stimuli and a combined - polarity map from which to identify visual areas. - This group does not store the raw responses imaged during retinotopic mapping or the - stimuli presented, but rather the resulting phase and power maps after applying a Fourier - transform on the averaged responses. - Note: for data consistency, all images and arrays are stored in the format [row][column] and - [row, col], which equates to [y][x]. Field of view and dimension arrays may appear backward - (i.e., y before x). - """ - - __nwbfields__ = ({'name': 'sign_map', 'child': True}, - {'name': 'axis_1_phase_map', 'child': True}, - {'name': 'axis_1_power_map', 'child': True}, - {'name': 'axis_2_phase_map', 'child': True}, - {'name': 'axis_2_power_map', 'child': True}, - {'name': 'focal_depth_image', 'child': True}, - {'name': 'vasculature_image', 'child': True}, - 'axis_descriptions') - - @docval({'name': 'sign_map', 'type': RetinotopyMap, - 'doc': 'Sine of the angle between the direction of the gradient in axis_1 and axis_2.'}, - {'name': 'axis_1_phase_map', 'type': AxisMap, - 'doc': 'Phase response to stimulus on the first measured axis.'}, - {'name': 'axis_1_power_map', 'type': AxisMap, - 'doc': 'Power response on the first measured axis. Response is scaled so 0.0 is no power in ' - 'the response and 1.0 is maximum relative power.'}, - {'name': 'axis_2_phase_map', 'type': AxisMap, - 'doc': 'Phase response to stimulus on the second measured axis.'}, - {'name': 'axis_2_power_map', 'type': AxisMap, - 'doc': 'Power response on the second measured axis. Response is scaled so 0.0 is no ' - 'power in the response and 1.0 is maximum relative power.'}, - {'name': 'axis_descriptions', 'type': Iterable, 'shape': (2, ), - 'doc': 'Two-element array describing the contents of the two response axis fields. ' - 'Description should be something like ["altitude", "azimuth"] or ["radius", "theta"].'}, - {'name': 'focal_depth_image', 'type': FocalDepthImage, - 'doc': 'Gray-scale image taken with same settings/parameters (e.g., focal depth, wavelength) ' - 'as data collection. Array format: [rows][columns].'}, - {'name': 'vasculature_image', 'type': RetinotopyImage, - 'doc': 'Gray-scale anatomical image of cortical surface. Array structure: [rows][columns].'}, - {'name': 'name', 'type': str, 'doc': 'the name of this container', 'default': 'ImagingRetinotopy'}) - def __init__(self, **kwargs): - axis_1_phase_map, axis_1_power_map, axis_2_phase_map, axis_2_power_map, axis_descriptions, \ - focal_depth_image, sign_map, vasculature_image = popargs( - 'axis_1_phase_map', 'axis_1_power_map', 'axis_2_phase_map', 'axis_2_power_map', - 'axis_descriptions', 'focal_depth_image', 'sign_map', 'vasculature_image', kwargs) - super().__init__(**kwargs) - warnings.warn("The ImagingRetinotopy class currently cannot be written to or read from a file. " - "This is a known bug and will be fixed in a future release of PyNWB.") - self.axis_1_phase_map = axis_1_phase_map - self.axis_1_power_map = axis_1_power_map - self.axis_2_phase_map = axis_2_phase_map - self.axis_2_power_map = axis_2_power_map - self.axis_descriptions = axis_descriptions - self.focal_depth_image = focal_depth_image - self.sign_map = sign_map - self.vasculature_image = vasculature_image +raise ImportError( + "The pynwb.retinotopy module is deprecated. If you are interested in using these neurodata types, " + "please create an issue on https://github.com/NeurodataWithoutBorders/nwb-schema/issues." +) + +# import warnings +# from collections.abc import Iterable + +# from hdmf.utils import docval, popargs, get_docval + +# from . import register_class, CORE_NAMESPACE +# from .core import NWBDataInterface, NWBData + + +# class RetinotopyImage(NWBData): +# """Gray-scale anatomical image of cortical surface. Array structure: [rows][columns] +# """ + +# __nwbfields__ = ('bits_per_pixel', +# 'dimension', +# 'format', +# 'field_of_view') + +# @docval({'name': 'name', 'type': str, 'doc': 'Name of this retinotopy image'}, +# {'name': 'data', 'type': Iterable, 'doc': 'Data field.'}, +# {'name': 'bits_per_pixel', 'type': int, +# 'doc': 'Number of bits used to represent each value. This is necessary to determine maximum ' +# '(white) pixel value.'}, +# {'name': 'dimension', 'type': Iterable, 'shape': (2, ), +# 'doc': 'Number of rows and columns in the image.'}, +# {'name': 'format', 'type': Iterable, 'doc': 'Format of image. Right now only "raw" supported.'}, +# {'name': 'field_of_view', 'type': Iterable, 'shape': (2, ), 'doc': 'Size of viewing area, in meters.'}) +# def __init__(self, **kwargs): +# bits_per_pixel, dimension, format, field_of_view = popargs( +# 'bits_per_pixel', 'dimension', 'format', 'field_of_view', kwargs) +# super().__init__(**kwargs) +# self.bits_per_pixel = bits_per_pixel +# self.dimension = dimension +# self.format = format +# self.field_of_view = field_of_view + + +# class FocalDepthImage(RetinotopyImage): +# """Gray-scale image taken with same settings/parameters (e.g., focal depth, +# wavelength) as data collection. Array format: [rows][columns]. +# """ + +# __nwbfields__ = ('focal_depth', ) + +# @docval(*get_docval(RetinotopyImage.__init__), +# {'name': 'focal_depth', 'type': float, 'doc': 'Focal depth offset, in meters.'}) +# def __init__(self, **kwargs): +# focal_depth = popargs('focal_depth', kwargs) +# super().__init__(**kwargs) +# self.focal_depth = focal_depth + + +# class RetinotopyMap(NWBData): +# """Abstract two-dimensional map of responses to stimuli along a single response axis (e.g., altitude) +# """ + +# __nwbfields__ = ('field_of_view', +# 'dimension') + +# @docval({'name': 'name', 'type': str, 'doc': 'the name of this axis map'}, +# {'name': 'data', 'type': Iterable, 'shape': (None, None), 'doc': 'data field.'}, +# {'name': 'field_of_view', 'type': Iterable, 'shape': (2, ), 'doc': 'Size of viewing area, in meters.'}, +# {'name': 'dimension', 'type': Iterable, 'shape': (2, ), +# 'doc': 'Number of rows and columns in the image'}) +# def __init__(self, **kwargs): +# field_of_view, dimension = popargs('field_of_view', 'dimension', kwargs) +# super().__init__(**kwargs) +# self.field_of_view = field_of_view +# self.dimension = dimension + + +# class AxisMap(RetinotopyMap): +# """Abstract two-dimensional map of responses to stimuli along a single response axis (e.g., altitude) with unit +# """ + +# __nwbfields__ = ('unit', ) + +# @docval(*get_docval(RetinotopyMap.__init__, 'name', 'data', 'field_of_view'), +# {'name': 'unit', 'type': str, 'doc': 'Unit that axis data is stored in (e.g., degrees)'}, +# *get_docval(RetinotopyMap.__init__, 'dimension')) +# def __init__(self, **kwargs): +# unit = popargs('unit', kwargs) +# super().__init__(**kwargs) +# self.unit = unit + + +# @register_class('ImagingRetinotopy', CORE_NAMESPACE) +# class ImagingRetinotopy(NWBDataInterface): +# """ +# Intrinsic signal optical imaging or widefield imaging for measuring retinotopy. Stores orthogonal +# maps (e.g., altitude/azimuth; radius/theta) of responses to specific stimuli and a combined +# polarity map from which to identify visual areas. +# This group does not store the raw responses imaged during retinotopic mapping or the +# stimuli presented, but rather the resulting phase and power maps after applying a Fourier +# transform on the averaged responses. +# Note: for data consistency, all images and arrays are stored in the format [row][column] and +# [row, col], which equates to [y][x]. Field of view and dimension arrays may appear backward +# (i.e., y before x). +# """ + +# __nwbfields__ = ({'name': 'sign_map', 'child': True}, +# {'name': 'axis_1_phase_map', 'child': True}, +# {'name': 'axis_1_power_map', 'child': True}, +# {'name': 'axis_2_phase_map', 'child': True}, +# {'name': 'axis_2_power_map', 'child': True}, +# {'name': 'focal_depth_image', 'child': True}, +# {'name': 'vasculature_image', 'child': True}, +# 'axis_descriptions') + +# @docval({'name': 'sign_map', 'type': RetinotopyMap, +# 'doc': 'Sine of the angle between the direction of the gradient in axis_1 and axis_2.'}, +# {'name': 'axis_1_phase_map', 'type': AxisMap, +# 'doc': 'Phase response to stimulus on the first measured axis.'}, +# {'name': 'axis_1_power_map', 'type': AxisMap, +# 'doc': 'Power response on the first measured axis. Response is scaled so 0.0 is no power in ' +# 'the response and 1.0 is maximum relative power.'}, +# {'name': 'axis_2_phase_map', 'type': AxisMap, +# 'doc': 'Phase response to stimulus on the second measured axis.'}, +# {'name': 'axis_2_power_map', 'type': AxisMap, +# 'doc': 'Power response on the second measured axis. Response is scaled so 0.0 is no ' +# 'power in the response and 1.0 is maximum relative power.'}, +# {'name': 'axis_descriptions', 'type': Iterable, 'shape': (2, ), +# 'doc': 'Two-element array describing the contents of the two response axis fields. ' +# 'Description should be something like ["altitude", "azimuth"] or ["radius", "theta"].'}, +# {'name': 'focal_depth_image', 'type': FocalDepthImage, +# 'doc': 'Gray-scale image taken with same settings/parameters (e.g., focal depth, wavelength) ' +# 'as data collection. Array format: [rows][columns].'}, +# {'name': 'vasculature_image', 'type': RetinotopyImage, +# 'doc': 'Gray-scale anatomical image of cortical surface. Array structure: [rows][columns].'}, +# {'name': 'name', 'type': str, 'doc': 'the name of this container', 'default': 'ImagingRetinotopy'}) +# def __init__(self, **kwargs): +# axis_1_phase_map, axis_1_power_map, axis_2_phase_map, axis_2_power_map, axis_descriptions, \ +# focal_depth_image, sign_map, vasculature_image = popargs( +# 'axis_1_phase_map', 'axis_1_power_map', 'axis_2_phase_map', 'axis_2_power_map', +# 'axis_descriptions', 'focal_depth_image', 'sign_map', 'vasculature_image', kwargs) +# super().__init__(**kwargs) +# self.axis_1_phase_map = axis_1_phase_map +# self.axis_1_power_map = axis_1_power_map +# self.axis_2_phase_map = axis_2_phase_map +# self.axis_2_power_map = axis_2_power_map +# self.axis_descriptions = axis_descriptions +# self.focal_depth_image = focal_depth_image +# self.sign_map = sign_map +# self.vasculature_image = vasculature_image diff --git a/tests/back_compat/test_import_structure.py b/tests/back_compat/test_import_structure.py index 79d4f6ad0..36831929d 100644 --- a/tests/back_compat/test_import_structure.py +++ b/tests/back_compat/test_import_structure.py @@ -78,7 +78,6 @@ def test_outer_import_structure(self): "popargs", "register_class", "register_map", - "retinotopy", "spec", "testing", "validate", diff --git a/tests/unit/test_retinotopy.py b/tests/unit/test_retinotopy.py index 57942d274..9a9f67748 100644 --- a/tests/unit/test_retinotopy.py +++ b/tests/unit/test_retinotopy.py @@ -1,174 +1,182 @@ -import numpy as np - -from pynwb.retinotopy import ImagingRetinotopy, AxisMap, RetinotopyImage, FocalDepthImage, RetinotopyMap from pynwb.testing import TestCase -class ImageRetinotopyConstructor(TestCase): - - def setUp(self): - data = np.ones((2, 2)) - field_of_view = [1, 2] - dimension = [1, 2] - self.sign_map = RetinotopyMap('sign_map', data, field_of_view, dimension) - self.axis_1_phase_map = AxisMap('axis_1_phase_map', data, field_of_view, 'unit', dimension) - self.axis_1_power_map = AxisMap('axis_1_power_map', data, field_of_view, 'unit', dimension) - self.axis_2_phase_map = AxisMap('axis_2_phase_map', data, field_of_view, 'unit', dimension) - self.axis_2_power_map = AxisMap('axis_2_power_map', data, field_of_view, 'unit', dimension) - self.axis_descriptions = ['altitude', 'azimuth'] - - data = [[1, 1], [1, 1]] - bits_per_pixel = 8 - dimension = [3, 4] - format = 'raw' - field_of_view = [1, 2] - focal_depth = 1.0 - self.focal_depth_image = FocalDepthImage('focal_depth_image', data, bits_per_pixel, dimension, format, - field_of_view, focal_depth) - self.vasculature_image = RetinotopyImage('vasculature_image', np.uint16(data), bits_per_pixel, dimension, - format, field_of_view) - - def test_init(self): - """Test that ImagingRetinotopy constructor sets properties correctly.""" - msg = ('The ImagingRetinotopy class currently cannot be written to or read from a file. This is a known bug ' - 'and will be fixed in a future release of PyNWB.') - with self.assertWarnsWith(UserWarning, msg): - ir = ImagingRetinotopy(self.sign_map, self.axis_1_phase_map, self.axis_1_power_map, self.axis_2_phase_map, - self.axis_2_power_map, self.axis_descriptions, self.focal_depth_image, - self.vasculature_image) - self.assertEqual(ir.sign_map, self.sign_map) - self.assertEqual(ir.axis_1_phase_map, self.axis_1_phase_map) - self.assertEqual(ir.axis_1_power_map, self.axis_1_power_map) - self.assertEqual(ir.axis_2_phase_map, self.axis_2_phase_map) - self.assertEqual(ir.axis_2_power_map, self.axis_2_power_map) - self.assertEqual(ir.axis_descriptions, self.axis_descriptions) - self.assertEqual(ir.focal_depth_image, self.focal_depth_image) - self.assertEqual(ir.vasculature_image, self.vasculature_image) - - def test_init_axis_descriptions_wrong_shape(self): - """Test that creating a ImagingRetinotopy with a axis descriptions argument that is not 2 elements raises an - error. - """ - self.axis_descriptions = ['altitude', 'azimuth', 'extra'] - - msg = "ImagingRetinotopy.__init__: incorrect shape for 'axis_descriptions' (got '(3,)', expected '(2,)')" - with self.assertRaisesWith(ValueError, msg): - ImagingRetinotopy(self.sign_map, self.axis_1_phase_map, self.axis_1_power_map, self.axis_2_phase_map, - self.axis_2_power_map, self.axis_descriptions, self.focal_depth_image, - self.vasculature_image) - - -class RetinotopyImageConstructor(TestCase): - - def test_init(self): - """Test that RetinotopyImage constructor sets properties correctly.""" - data = [[1, 1], [1, 1]] - bits_per_pixel = 8 - dimension = [3, 4] - format = 'raw' - field_of_view = [1, 2] - image = RetinotopyImage('vasculature_image', data, bits_per_pixel, dimension, format, field_of_view) - - self.assertEqual(image.name, 'vasculature_image') - self.assertEqual(image.data, data) - self.assertEqual(image.bits_per_pixel, bits_per_pixel) - self.assertEqual(image.dimension, dimension) - self.assertEqual(image.format, format) - self.assertEqual(image.field_of_view, field_of_view) - - def test_init_dimension_wrong_shape(self): - """Test that creating a RetinotopyImage with a dimension argument that is not 2 elements raises an error.""" - data = [[1, 1], [1, 1]] - bits_per_pixel = 8 - dimension = [3, 4, 5] - format = 'raw' - field_of_view = [1, 2] - - msg = "RetinotopyImage.__init__: incorrect shape for 'dimension' (got '(3,)', expected '(2,)')" - with self.assertRaisesWith(ValueError, msg): - RetinotopyImage('vasculature_image', data, bits_per_pixel, dimension, format, field_of_view) - - def test_init_fov_wrong_shape(self): - """Test that creating a RetinotopyImage with a field of view argument that is not 2 elements raises an error.""" - data = [[1, 1], [1, 1]] - bits_per_pixel = 8 - dimension = [3, 4] - format = 'raw' - field_of_view = [1, 2, 3] - - msg = "RetinotopyImage.__init__: incorrect shape for 'field_of_view' (got '(3,)', expected '(2,)')" - with self.assertRaisesWith(ValueError, msg): - RetinotopyImage('vasculature_image', data, bits_per_pixel, dimension, format, field_of_view) - - -class RetinotopyMapConstructor(TestCase): - - def test_init(self): - """Test that RetinotopyMap constructor sets properties correctly.""" - data = np.ones((2, 2)) - field_of_view = [1, 2] - dimension = [1, 2] - map = RetinotopyMap('sign_map', data, field_of_view, dimension) - - self.assertEqual(map.name, 'sign_map') - np.testing.assert_array_equal(map.data, data) - self.assertEqual(map.field_of_view, field_of_view) - self.assertEqual(map.dimension, dimension) - - -class AxisMapConstructor(TestCase): - - def test_init(self): - """Test that AxisMap constructor sets properties correctly.""" - data = np.ones((2, 2)) - field_of_view = [1, 2] - dimension = [1, 2] - map = AxisMap('axis_1_phase', data, field_of_view, 'unit', dimension) - - self.assertEqual(map.name, 'axis_1_phase') - np.testing.assert_array_equal(map.data, data) - self.assertEqual(map.field_of_view, field_of_view) - self.assertEqual(map.dimension, dimension) - self.assertEqual(map.unit, 'unit') - - def test_init_dimension_wrong_shape(self): - """Test that creating an AxisMap with a dimension argument that is not 2 elements raises an error.""" - data = np.ones((2, 2)) - field_of_view = [1, 2] - dimension = [1, 2, 3] - - msg = "AxisMap.__init__: incorrect shape for 'dimension' (got '(3,)', expected '(2,)')" - with self.assertRaisesWith(ValueError, msg): - AxisMap('axis_1_phase', data, field_of_view, 'unit', dimension) - - def test_init_fov_wrong_shape(self): - """Test that creating an AxisMap with a dimension argument that is not 2 elements raises an error.""" - data = np.ones((2, 2)) - field_of_view = [1, 2, 3] - dimension = [1, 2] - - msg = "AxisMap.__init__: incorrect shape for 'field_of_view' (got '(3,)', expected '(2,)')" - with self.assertRaisesWith(ValueError, msg): - AxisMap('axis_1_phase', data, field_of_view, 'unit', dimension) - - -class FocalDepthImageConstructor(TestCase): - - def test_init(self): - """Test that FocalDepthImage constructor sets properties correctly.""" - data = [[1, 1], [1, 1]] - bits_per_pixel = 8 - dimension = [3, 4] - format = 'raw' - field_of_view = [1, 2] - focal_depth = 1.0 - image = FocalDepthImage('focal_depth_image', data, bits_per_pixel, dimension, format, field_of_view, - focal_depth) - - self.assertEqual(image.name, 'focal_depth_image') - self.assertEqual(image.data, data) - self.assertEqual(image.bits_per_pixel, bits_per_pixel) - self.assertEqual(image.dimension, dimension) - self.assertEqual(image.format, format) - self.assertEqual(image.field_of_view, field_of_view) - self.assertEqual(image.focal_depth, focal_depth) +class TestRetinotopy(TestCase): + def test_retinotopy_deprecated(self): + with self.assertRaises(ImportError): + import pynwb.retinotopy # noqa: F401 + +# import numpy as np + +# from pynwb.retinotopy import ImagingRetinotopy, AxisMap, RetinotopyImage, FocalDepthImage, RetinotopyMap +# from pynwb.testing import TestCase + + +# class ImageRetinotopyConstructor(TestCase): + +# def setUp(self): +# data = np.ones((2, 2)) +# field_of_view = [1, 2] +# dimension = [1, 2] +# self.sign_map = RetinotopyMap('sign_map', data, field_of_view, dimension) +# self.axis_1_phase_map = AxisMap('axis_1_phase_map', data, field_of_view, 'unit', dimension) +# self.axis_1_power_map = AxisMap('axis_1_power_map', data, field_of_view, 'unit', dimension) +# self.axis_2_phase_map = AxisMap('axis_2_phase_map', data, field_of_view, 'unit', dimension) +# self.axis_2_power_map = AxisMap('axis_2_power_map', data, field_of_view, 'unit', dimension) +# self.axis_descriptions = ['altitude', 'azimuth'] + +# data = [[1, 1], [1, 1]] +# bits_per_pixel = 8 +# dimension = [3, 4] +# format = 'raw' +# field_of_view = [1, 2] +# focal_depth = 1.0 +# self.focal_depth_image = FocalDepthImage('focal_depth_image', data, bits_per_pixel, dimension, format, +# field_of_view, focal_depth) +# self.vasculature_image = RetinotopyImage('vasculature_image', np.uint16(data), bits_per_pixel, dimension, +# format, field_of_view) + +# def test_init(self): +# """Test that ImagingRetinotopy constructor sets properties correctly.""" +# msg = ('The ImagingRetinotopy class currently cannot be written to or read from a file. This is a known bug ' +# 'and will be fixed in a future release of PyNWB.') +# with self.assertWarnsWith(UserWarning, msg): +# ir = ImagingRetinotopy(self.sign_map, self.axis_1_phase_map, self.axis_1_power_map, self.axis_2_phase_map, +# self.axis_2_power_map, self.axis_descriptions, self.focal_depth_image, +# self.vasculature_image) +# self.assertEqual(ir.sign_map, self.sign_map) +# self.assertEqual(ir.axis_1_phase_map, self.axis_1_phase_map) +# self.assertEqual(ir.axis_1_power_map, self.axis_1_power_map) +# self.assertEqual(ir.axis_2_phase_map, self.axis_2_phase_map) +# self.assertEqual(ir.axis_2_power_map, self.axis_2_power_map) +# self.assertEqual(ir.axis_descriptions, self.axis_descriptions) +# self.assertEqual(ir.focal_depth_image, self.focal_depth_image) +# self.assertEqual(ir.vasculature_image, self.vasculature_image) + +# def test_init_axis_descriptions_wrong_shape(self): +# """Test that creating a ImagingRetinotopy with a axis descriptions argument that is not 2 elements raises an +# error. +# """ +# self.axis_descriptions = ['altitude', 'azimuth', 'extra'] + +# msg = "ImagingRetinotopy.__init__: incorrect shape for 'axis_descriptions' (got '(3,)', expected '(2,)')" +# with self.assertRaisesWith(ValueError, msg): +# ImagingRetinotopy(self.sign_map, self.axis_1_phase_map, self.axis_1_power_map, self.axis_2_phase_map, +# self.axis_2_power_map, self.axis_descriptions, self.focal_depth_image, +# self.vasculature_image) + + +# class RetinotopyImageConstructor(TestCase): + +# def test_init(self): +# """Test that RetinotopyImage constructor sets properties correctly.""" +# data = [[1, 1], [1, 1]] +# bits_per_pixel = 8 +# dimension = [3, 4] +# format = 'raw' +# field_of_view = [1, 2] +# image = RetinotopyImage('vasculature_image', data, bits_per_pixel, dimension, format, field_of_view) + +# self.assertEqual(image.name, 'vasculature_image') +# self.assertEqual(image.data, data) +# self.assertEqual(image.bits_per_pixel, bits_per_pixel) +# self.assertEqual(image.dimension, dimension) +# self.assertEqual(image.format, format) +# self.assertEqual(image.field_of_view, field_of_view) + +# def test_init_dimension_wrong_shape(self): +# """Test that creating a RetinotopyImage with a dimension argument that is not 2 elements raises an error.""" +# data = [[1, 1], [1, 1]] +# bits_per_pixel = 8 +# dimension = [3, 4, 5] +# format = 'raw' +# field_of_view = [1, 2] + +# msg = "RetinotopyImage.__init__: incorrect shape for 'dimension' (got '(3,)', expected '(2,)')" +# with self.assertRaisesWith(ValueError, msg): +# RetinotopyImage('vasculature_image', data, bits_per_pixel, dimension, format, field_of_view) + +# def test_init_fov_wrong_shape(self): +# """Test that creating a RetinotopyImage with a field of view that is not 2 elements raises an error.""" +# data = [[1, 1], [1, 1]] +# bits_per_pixel = 8 +# dimension = [3, 4] +# format = 'raw' +# field_of_view = [1, 2, 3] + +# msg = "RetinotopyImage.__init__: incorrect shape for 'field_of_view' (got '(3,)', expected '(2,)')" +# with self.assertRaisesWith(ValueError, msg): +# RetinotopyImage('vasculature_image', data, bits_per_pixel, dimension, format, field_of_view) + + +# class RetinotopyMapConstructor(TestCase): + +# def test_init(self): +# """Test that RetinotopyMap constructor sets properties correctly.""" +# data = np.ones((2, 2)) +# field_of_view = [1, 2] +# dimension = [1, 2] +# map = RetinotopyMap('sign_map', data, field_of_view, dimension) + +# self.assertEqual(map.name, 'sign_map') +# np.testing.assert_array_equal(map.data, data) +# self.assertEqual(map.field_of_view, field_of_view) +# self.assertEqual(map.dimension, dimension) + + +# class AxisMapConstructor(TestCase): + +# def test_init(self): +# """Test that AxisMap constructor sets properties correctly.""" +# data = np.ones((2, 2)) +# field_of_view = [1, 2] +# dimension = [1, 2] +# map = AxisMap('axis_1_phase', data, field_of_view, 'unit', dimension) + +# self.assertEqual(map.name, 'axis_1_phase') +# np.testing.assert_array_equal(map.data, data) +# self.assertEqual(map.field_of_view, field_of_view) +# self.assertEqual(map.dimension, dimension) +# self.assertEqual(map.unit, 'unit') + +# def test_init_dimension_wrong_shape(self): +# """Test that creating an AxisMap with a dimension argument that is not 2 elements raises an error.""" +# data = np.ones((2, 2)) +# field_of_view = [1, 2] +# dimension = [1, 2, 3] + +# msg = "AxisMap.__init__: incorrect shape for 'dimension' (got '(3,)', expected '(2,)')" +# with self.assertRaisesWith(ValueError, msg): +# AxisMap('axis_1_phase', data, field_of_view, 'unit', dimension) + +# def test_init_fov_wrong_shape(self): +# """Test that creating an AxisMap with a dimension argument that is not 2 elements raises an error.""" +# data = np.ones((2, 2)) +# field_of_view = [1, 2, 3] +# dimension = [1, 2] + +# msg = "AxisMap.__init__: incorrect shape for 'field_of_view' (got '(3,)', expected '(2,)')" +# with self.assertRaisesWith(ValueError, msg): +# AxisMap('axis_1_phase', data, field_of_view, 'unit', dimension) + + +# class FocalDepthImageConstructor(TestCase): + +# def test_init(self): +# """Test that FocalDepthImage constructor sets properties correctly.""" +# data = [[1, 1], [1, 1]] +# bits_per_pixel = 8 +# dimension = [3, 4] +# format = 'raw' +# field_of_view = [1, 2] +# focal_depth = 1.0 +# image = FocalDepthImage('focal_depth_image', data, bits_per_pixel, dimension, format, field_of_view, +# focal_depth) + +# self.assertEqual(image.name, 'focal_depth_image') +# self.assertEqual(image.data, data) +# self.assertEqual(image.bits_per_pixel, bits_per_pixel) +# self.assertEqual(image.dimension, dimension) +# self.assertEqual(image.format, format) +# self.assertEqual(image.field_of_view, field_of_view) +# self.assertEqual(image.focal_depth, focal_depth) From 923ff26ebd47f3c430f84dd469c707b83ab9302d Mon Sep 17 00:00:00 2001 From: rly Date: Wed, 7 Feb 2024 07:39:07 -0800 Subject: [PATCH 06/29] Update submodule to 2.7.0 release --- src/pynwb/nwb-schema | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pynwb/nwb-schema b/src/pynwb/nwb-schema index f352a93c4..d65d42257 160000 --- a/src/pynwb/nwb-schema +++ b/src/pynwb/nwb-schema @@ -1 +1 @@ -Subproject commit f352a93c4cbfb202b6a40210e998cab34b05a593 +Subproject commit d65d42257003543c569ea7ac0cd6d7aee01c88d6 From 7e0eea21f93391d456b55e2b4480ebc8779bcc36 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 8 Feb 2024 13:28:31 -0800 Subject: [PATCH 07/29] Update CHANGELOG.md --- CHANGELOG.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e8092c51..f084ff0bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,13 +3,10 @@ ## PyNWB 2.6.0 (Upcoming) ### Enhancements and minor changes -- Added support for NWB schema 2.7.0. - - ... - - ... +- Added support for NWB schema 2.7.0. See [2.7.0 release notes](https://nwb-schema.readthedocs.io/en/latest/format_release_notes.html) for details - Deprecated `ImagingRetinotopy` neurodata type. @rly [#1813](https://github.com/NeurodataWithoutBorders/pynwb/pull/1813) - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - - ... - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - For `NWBHDF5IO()`, change the default of arg `load_namespaces` from `False` to `True`. @bendichter [#1748](https://github.com/NeurodataWithoutBorders/pynwb/pull/1748) - Add `NWBHDF5IO.can_read()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) From 90d6b1d39b4f2bdd53f36b52273e96f36fb6f59c Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Fri, 16 Feb 2024 10:05:03 +0900 Subject: [PATCH 08/29] Exclude pynwb retinotopy from sphinx apidoc (#1846) * Exclude pynwb retinotopy from sphinx * Update conf.py * Update conf.py * Update conf.py * Fix sphinx apidoc exclude --- docs/source/conf.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index c46d2edd5..8e3d42ab3 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -209,6 +209,12 @@ def __call__(self, filename): # directories to ignore when looking for source files. exclude_patterns = ['_build', 'test.py'] +# List of patterns, relative to source directory, of modules to be +# excluded by apidoc when generating rst files. +apidoc_exclude = [ + "../../src/pynwb/retinotopy.py", +] + # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None @@ -411,7 +417,8 @@ def run_apidoc(_): out_dir = os.path.dirname(__file__) src_dir = os.path.join(out_dir, '../../src') sys.path.append(src_dir) - apidoc_main(['-f', '-e', '--no-toc', '-o', out_dir, src_dir]) + apidoc_exclude_abs = [os.path.join(out_dir, f) for f in apidoc_exclude] + apidoc_main(['-f', '-e', '--no-toc', '-o', out_dir, src_dir, *apidoc_exclude_abs]) from abc import abstractproperty From 905ef65d3a30aee1ae597a70adf24d060af5b077 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Fri, 16 Feb 2024 13:19:15 +0900 Subject: [PATCH 09/29] Try closing and removing downloaded file (#1847) --- docs/gallery/general/plot_read_basics.py | 7 +++++++ test.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/gallery/general/plot_read_basics.py b/docs/gallery/general/plot_read_basics.py index c4a829d75..0d684e5f5 100644 --- a/docs/gallery/general/plot_read_basics.py +++ b/docs/gallery/general/plot_read_basics.py @@ -283,3 +283,10 @@ # object and accessing its attributes, but it may be useful to explore the data in a # more interactive, visual way. See :ref:`analysistools-explore` for an updated list of programs for # exploring NWB files. + +#################### +# Close the open NWB file +# ----------------------- +# It is good practice, especially on Windows, to close any files that you have opened. + +io.close() diff --git a/test.py b/test.py index 8f6a403ee..c251fd838 100755 --- a/test.py +++ b/test.py @@ -276,7 +276,7 @@ def clean_up_tests(): "processed_data.nwb", "raw_data.nwb", "scratch_analysis.nwb", - # "sub-P11HMH_ses-20061101_ecephys+image.nwb", # TODO cannot delete this file on windows for some reason + "sub-P11HMH_ses-20061101_ecephys+image.nwb", "test_edit.nwb", "test_edit2.nwb", "test_cortical_surface.nwb", From 46dcea828b6e4eb8bc468d7f13be2326fef9b80c Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Fri, 22 Mar 2024 22:32:07 -0700 Subject: [PATCH 10/29] Update CHANGELOG.md --- CHANGELOG.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32500ba70..de1e869a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ # PyNWB Changelog -## PyNWB 2.6.1 (March 25, 2024) +## PyNWB 2.7.0 (Upcoming) + +### Enhancements and minor changes +- Added support for NWB schema 2.7.0. See [2.7.0 release notes](https://nwb-schema.readthedocs.io/en/latest/format_release_notes.html) for details + - Deprecated `ImagingRetinotopy` neurodata type. @rly [#1813](https://github.com/NeurodataWithoutBorders/pynwb/pull/1813) + - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) + - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) + - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) ### Bug fixes - Fix bug with reading file with linked `TimeSeriesReferenceVectorData` @rly [#1865](https://github.com/NeurodataWithoutBorders/pynwb/pull/1865) @@ -9,11 +16,6 @@ ## PyNWB 2.6.0 (February 21, 2024) ### Enhancements and minor changes -- Added support for NWB schema 2.7.0. See [2.7.0 release notes](https://nwb-schema.readthedocs.io/en/latest/format_release_notes.html) for details - - Deprecated `ImagingRetinotopy` neurodata type. @rly [#1813](https://github.com/NeurodataWithoutBorders/pynwb/pull/1813) - - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) - - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - For `NWBHDF5IO()`, change the default of arg `load_namespaces` from `False` to `True`. @bendichter [#1748](https://github.com/NeurodataWithoutBorders/pynwb/pull/1748) - Add `NWBHDF5IO.can_read()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) - Add `pynwb.get_nwbfile_version()`. @bendichter [#1703](https://github.com/NeurodataWithoutBorders/pynwb/pull/1703) From 8d9aaa34dac658bb064ef95b863675646502c085 Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Sat, 23 Mar 2024 07:09:59 -0700 Subject: [PATCH 11/29] Update to ruff, update workflow versions (#1853) --- .codespellrc | 8 - .coveragerc | 13 - .github/PULL_REQUEST_TEMPLATE/release.md | 4 +- .github/workflows/check_sphinx_links.yml | 6 +- .github/workflows/codespell.yml | 3 +- .github/workflows/deploy_release.yml | 10 +- .github/workflows/generate_test_files.yml | 4 +- .github/workflows/ruff.yml | 11 + .github/workflows/run_all_tests.yml | 68 +- .github/workflows/run_coverage.yml | 10 +- .github/workflows/run_dandi_read_tests.yml | 6 +- .github/workflows/run_flake8.yml | 31 - .github/workflows/run_inspector_tests.yml | 6 +- .github/workflows/run_tests.yml | 40 +- CHANGELOG.md | 5 +- MANIFEST.in | 2 +- Makefile | 83 - README.rst | 30 +- docs/CONTRIBUTING.rst | 38 +- docs/gallery/domain/images.py | 21 +- docs/gallery/general/extensions.py | 6 - docs/source/conf.py | 7 +- docs/source/install_developers.rst | 34 +- environment-ros3.yml | 19 +- pyproject.toml | 111 + requirements-dev.txt | 14 +- requirements-min.txt | 1 - requirements.txt | 1 - setup.cfg | 42 - setup.py | 81 - src/pynwb/__init__.py | 11 +- src/pynwb/_version.py | 658 ------ src/pynwb/icephys.py | 6 +- test.py | 8 +- tox.ini | 68 +- versioneer.py | 2194 -------------------- 36 files changed, 325 insertions(+), 3335 deletions(-) delete mode 100644 .codespellrc delete mode 100644 .coveragerc create mode 100644 .github/workflows/ruff.yml delete mode 100644 .github/workflows/run_flake8.yml delete mode 100644 Makefile create mode 100644 pyproject.toml delete mode 100644 setup.cfg delete mode 100755 setup.py delete mode 100644 src/pynwb/_version.py mode change 100755 => 100644 test.py delete mode 100644 versioneer.py diff --git a/.codespellrc b/.codespellrc deleted file mode 100644 index a38689dfe..000000000 --- a/.codespellrc +++ /dev/null @@ -1,8 +0,0 @@ -[codespell] -# in principle .ipynb can be corrected -- a good number of typos there -# nwb-schema -- excluding since submodule, should have its own fixes/checks -skip = .git,*.pdf,*.svg,venvs,env,nwb-schema -ignore-regex = ^\s*"image/\S+": ".* -# it is optin in a url -# potatos - demanded to be left alone, autogenerated -ignore-words-list = optin,potatos diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index def839969..000000000 --- a/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True -source = src/ -omit = - src/pynwb/_version.py - src/pynwb/_due.py - src/pynwb/testing/* - src/pynwb/legacy/* - -[report] -exclude_lines = - pragma: no cover - @abstract diff --git a/.github/PULL_REQUEST_TEMPLATE/release.md b/.github/PULL_REQUEST_TEMPLATE/release.md index 8a15d5ee2..b7154c83c 100644 --- a/.github/PULL_REQUEST_TEMPLATE/release.md +++ b/.github/PULL_REQUEST_TEMPLATE/release.md @@ -2,10 +2,10 @@ Prepare for release of PyNWB [version] ### Before merging: - [ ] Major and minor releases: Update package versions in `requirements.txt`, `requirements-dev.txt`, - `requirements-doc.txt`, `requirements-min.txt`, `environment-ros3.yml`, and `setup.py` as needed. + `requirements-doc.txt`, `requirements-min.txt`, and `environment-ros3.yml` as needed. - [ ] Check legal file dates and information in `Legal.txt`, `license.txt`, `README.rst`, `docs/source/conf.py`, and any other locations as needed -- [ ] Update `setup.py` as needed +- [ ] Update `pyproject.toml` as needed - [ ] Update `README.rst` as needed - [ ] Update `src/pynwb/nwb-schema` submodule as needed. Check the version number and commit SHA manually - [ ] Update changelog (set release date) in `CHANGELOG.md` and any other docs as needed diff --git a/.github/workflows/check_sphinx_links.yml b/.github/workflows/check_sphinx_links.yml index e1eddb97a..49da87755 100644 --- a/.github/workflows/check_sphinx_links.yml +++ b/.github/workflows/check_sphinx_links.yml @@ -15,15 +15,15 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.12' - name: Install Sphinx dependencies and package run: | diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 7aa79c9e7..b7bef25db 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -14,6 +14,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 + - name: Codespell uses: codespell-project/actions-codespell@v2 diff --git a/.github/workflows/deploy_release.yml b/.github/workflows/deploy_release.yml index f9abba102..2f6cb8619 100644 --- a/.github/workflows/deploy_release.yml +++ b/.github/workflows/deploy_release.yml @@ -10,15 +10,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo with submodules - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.12' - name: Install build dependencies run: | @@ -28,11 +28,11 @@ jobs: - name: Run tox tests run: | - tox -e py311-upgraded + tox -e py312-upgraded - name: Build wheel and source distribution run: | - tox -e build-py311-upgraded + tox -e build-py312-upgraded ls -1 dist - name: Test installation from a wheel diff --git a/.github/workflows/generate_test_files.yml b/.github/workflows/generate_test_files.yml index 48e33a0b3..27848909b 100644 --- a/.github/workflows/generate_test_files.yml +++ b/.github/workflows/generate_test_files.yml @@ -17,13 +17,13 @@ jobs: - { name: pynwb-1.5.1, pynwb-version: "1.5.1", python-version: "3.8"} - { name: pynwb-2.1.0, pynwb-version: "2.1.0", python-version: "3.9"} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} diff --git a/.github/workflows/ruff.yml b/.github/workflows/ruff.yml new file mode 100644 index 000000000..1933fa75e --- /dev/null +++ b/.github/workflows/ruff.yml @@ -0,0 +1,11 @@ +name: Ruff +on: pull_request + +jobs: + ruff: + runs-on: ubuntu-latest + steps: + - name: Checkout repo + uses: actions/checkout@v4 + - name: Run ruff + uses: chartboost/ruff-action@v1 diff --git a/.github/workflows/run_all_tests.yml b/.github/workflows/run_all_tests.yml index c47941c21..1935c7392 100644 --- a/.github/workflows/run_all_tests.yml +++ b/.github/workflows/run_all_tests.yml @@ -26,23 +26,23 @@ jobs: - { name: linux-python3.9 , test-tox-env: py39 , build-tox-env: build-py39 , python-ver: "3.9" , os: ubuntu-latest } - { name: linux-python3.10 , test-tox-env: py310 , build-tox-env: build-py310 , python-ver: "3.10", os: ubuntu-latest } - { name: linux-python3.11 , test-tox-env: py311 , build-tox-env: build-py311 , python-ver: "3.11", os: ubuntu-latest } - - { name: linux-python3.11-optional , test-tox-env: py311-optional , build-tox-env: build-py311-optional , python-ver: "3.11", os: ubuntu-latest } - - { name: linux-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: ubuntu-latest } - - { name: linux-python3.11-prerelease , test-tox-env: py311-prerelease, build-tox-env: build-py311-prerelease, python-ver: "3.11", os: ubuntu-latest } + - { name: linux-python3.12 , test-tox-env: py312 , build-tox-env: build-py312 , python-ver: "3.12", os: ubuntu-latest } + - { name: linux-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: ubuntu-latest } + - { name: linux-python3.12-prerelease , test-tox-env: py312-prerelease, build-tox-env: build-py312-prerelease, python-ver: "3.12", os: ubuntu-latest } - { name: windows-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: windows-latest } - { name: windows-python3.9 , test-tox-env: py39 , build-tox-env: build-py39 , python-ver: "3.9" , os: windows-latest } - { name: windows-python3.10 , test-tox-env: py310 , build-tox-env: build-py310 , python-ver: "3.10", os: windows-latest } - { name: windows-python3.11 , test-tox-env: py311 , build-tox-env: build-py311 , python-ver: "3.11", os: windows-latest } - - { name: windows-python3.11-optional , test-tox-env: py311-optional , build-tox-env: build-py311-optional , python-ver: "3.11", os: windows-latest } - - { name: windows-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: windows-latest } - - { name: windows-python3.11-prerelease, test-tox-env: py311-prerelease, build-tox-env: build-py311-prerelease, python-ver: "3.11", os: windows-latest } + - { name: windows-python3.12 , test-tox-env: py312 , build-tox-env: build-py312 , python-ver: "3.12", os: windows-latest } + - { name: windows-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: windows-latest } + - { name: windows-python3.12-prerelease, test-tox-env: py312-prerelease, build-tox-env: build-py312-prerelease, python-ver: "3.11", os: windows-latest } - { name: macos-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: macos-latest } - { name: macos-python3.9 , test-tox-env: py39 , build-tox-env: build-py39 , python-ver: "3.9" , os: macos-latest } - { name: macos-python3.10 , test-tox-env: py310 , build-tox-env: build-py310 , python-ver: "3.10", os: macos-latest } - { name: macos-python3.11 , test-tox-env: py311 , build-tox-env: build-py311 , python-ver: "3.11", os: macos-latest } - - { name: macos-python3.11-optional , test-tox-env: py311-optional , build-tox-env: build-py311-optional , python-ver: "3.11", os: macos-latest } - - { name: macos-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: macos-latest } - - { name: macos-python3.11-prerelease , test-tox-env: py311-prerelease, build-tox-env: build-py311-prerelease, python-ver: "3.11", os: macos-latest } + - { name: macos-python3.12 , test-tox-env: py312 , build-tox-env: build-py312 , python-ver: "3.12", os: macos-latest } + - { name: macos-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: macos-latest } + - { name: macos-python3.12-prerelease , test-tox-env: py312-prerelease, build-tox-env: build-py312-prerelease, python-ver: "3.12", os: macos-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -50,13 +50,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-ver }} @@ -90,14 +90,14 @@ jobs: matrix: include: - { name: linux-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: ubuntu-latest } - - { name: linux-gallery-python3.11-upgraded , test-tox-env: gallery-py311-upgraded , python-ver: "3.11", os: ubuntu-latest } - - { name: linux-gallery-python3.11-prerelease , test-tox-env: gallery-py311-prerelease, python-ver: "3.11", os: ubuntu-latest } + - { name: linux-gallery-python3.12-upgraded , test-tox-env: gallery-py312-upgraded , python-ver: "3.12", os: ubuntu-latest } + - { name: linux-gallery-python3.12-prerelease , test-tox-env: gallery-py312-prerelease, python-ver: "3.12", os: ubuntu-latest } - { name: windows-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: windows-latest } - - { name: windows-gallery-python3.11-upgraded , test-tox-env: gallery-py311-upgraded , python-ver: "3.11", os: windows-latest } - - { name: windows-gallery-python3.11-prerelease, test-tox-env: gallery-py311-prerelease, python-ver: "3.11", os: windows-latest } + - { name: windows-gallery-python3.12-upgraded , test-tox-env: gallery-py312-upgraded , python-ver: "3.12", os: windows-latest } + - { name: windows-gallery-python3.12-prerelease, test-tox-env: gallery-py312-prerelease, python-ver: "3.12", os: windows-latest } - { name: macos-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: macos-latest } - - { name: macos-gallery-python3.11-upgraded , test-tox-env: gallery-py311-upgraded , python-ver: "3.11", os: macos-latest } - - { name: macos-gallery-python3.11-prerelease , test-tox-env: gallery-py311-prerelease, python-ver: "3.11", os: macos-latest } + - { name: macos-gallery-python3.12-upgraded , test-tox-env: gallery-py312-upgraded , python-ver: "3.12", os: macos-latest } + - { name: macos-gallery-python3.12-prerelease , test-tox-env: gallery-py312-prerelease, python-ver: "3.12", os: macos-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -105,13 +105,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-ver }} @@ -139,9 +139,9 @@ jobs: - { name: conda-linux-python3.9 , test-tox-env: py39 , build-tox-env: build-py39 , python-ver: "3.9" , os: ubuntu-latest } - { name: conda-linux-python3.10 , test-tox-env: py310 , build-tox-env: build-py310 , python-ver: "3.10", os: ubuntu-latest } - { name: conda-linux-python3.11 , test-tox-env: py311 , build-tox-env: build-py311 , python-ver: "3.11", os: ubuntu-latest } - - { name: conda-linux-python3.11-optional , test-tox-env: py311-optional , build-tox-env: build-py311-optional , python-ver: "3.11", os: ubuntu-latest } - - { name: conda-linux-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: ubuntu-latest } - - { name: conda-linux-python3.11-prerelease, test-tox-env: py311-prerelease, build-tox-env: build-py311-prerelease, python-ver: "3.11", os: ubuntu-latest } + - { name: conda-linux-python3.12 , test-tox-env: py312 , build-tox-env: build-py312 , python-ver: "3.12", os: ubuntu-latest } + - { name: conda-linux-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: ubuntu-latest } + - { name: conda-linux-python3.12-prerelease, test-tox-env: py312-prerelease, build-tox-env: build-py312-prerelease, python-ver: "3.12", os: ubuntu-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -149,13 +149,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Conda - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v3 with: auto-update-conda: true python-version: ${{ matrix.python-ver }} @@ -196,9 +196,9 @@ jobs: fail-fast: false matrix: include: - - { name: conda-linux-python3.11-ros3 , python-ver: "3.11", os: ubuntu-latest } - - { name: conda-windows-python3.11-ros3, python-ver: "3.11", os: windows-latest } - - { name: conda-macos-python3.11-ros3 , python-ver: "3.11", os: macos-latest } + - { name: conda-linux-python3.12-ros3 , python-ver: "3.12", os: ubuntu-latest } + - { name: conda-windows-python3.12-ros3, python-ver: "3.12", os: windows-latest } + - { name: conda-macos-python3.12-ros3 , python-ver: "3.12", os: macos-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -206,13 +206,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Conda - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v3 with: auto-update-conda: true activate-environment: ros3 @@ -243,9 +243,9 @@ jobs: fail-fast: false matrix: include: - - { name: conda-linux-gallery-python3.11-ros3 , python-ver: "3.11", os: ubuntu-latest } - - { name: conda-windows-gallery-python3.11-ros3, python-ver: "3.11", os: windows-latest } - - { name: conda-macos-gallery-python3.11-ros3 , python-ver: "3.11", os: macos-latest } + - { name: conda-linux-gallery-python3.12-ros3 , python-ver: "3.12", os: ubuntu-latest } + - { name: conda-windows-gallery-python3.12-ros3, python-ver: "3.12", os: windows-latest } + - { name: conda-macos-gallery-python3.12-ros3 , python-ver: "3.12", os: macos-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -253,13 +253,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Conda - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v3 with: auto-update-conda: true activate-environment: ros3 diff --git a/.github/workflows/run_coverage.yml b/.github/workflows/run_coverage.yml index 18dc00903..400de00f3 100644 --- a/.github/workflows/run_coverage.yml +++ b/.github/workflows/run_coverage.yml @@ -24,7 +24,7 @@ jobs: os: [ubuntu-latest, macos-latest, windows-latest] env: OS: ${{ matrix.os }} - PYTHON: '3.11' + PYTHON: '3.12' steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -32,13 +32,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON }} @@ -63,11 +63,13 @@ jobs: python -m coverage report -m - name: Upload coverage to Codecov - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: unit files: coverage.xml fail_ci_if_error: true + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - name: Run integration tests and generate coverage report run: | diff --git a/.github/workflows/run_dandi_read_tests.yml b/.github/workflows/run_dandi_read_tests.yml index 7148d209e..df9ef4613 100644 --- a/.github/workflows/run_dandi_read_tests.yml +++ b/.github/workflows/run_dandi_read_tests.yml @@ -17,15 +17,15 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.12' - name: Install run dependencies run: | diff --git a/.github/workflows/run_flake8.yml b/.github/workflows/run_flake8.yml deleted file mode 100644 index a57042c66..000000000 --- a/.github/workflows/run_flake8.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Run style check -on: pull_request - -jobs: - run-flake8: - runs-on: ubuntu-latest - steps: - - name: Cancel non-latest runs - uses: styfle/cancel-workflow-action@0.11.0 - with: - all_but_latest: true - access_token: ${{ github.token }} - - - uses: actions/checkout@v3 - with: - submodules: 'recursive' - fetch-depth: 0 # tags are required for versioneer to determine the version - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: '3.11' - - - name: Install flake8 - run: | - python -m pip install --upgrade pip - python -m pip install flake8 - python -m pip list - - - name: Run flake8 - run: flake8 diff --git a/.github/workflows/run_inspector_tests.yml b/.github/workflows/run_inspector_tests.yml index da7efff5f..cb8d57458 100644 --- a/.github/workflows/run_inspector_tests.yml +++ b/.github/workflows/run_inspector_tests.yml @@ -15,15 +15,15 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.12' - name: Update pip run: python -m pip install --upgrade pip diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index e4479a554..d2b3d169a 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -21,9 +21,9 @@ jobs: include: - { name: linux-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: ubuntu-latest } # NOTE config below with "upload-wheels: true" specifies that wheels should be uploaded as an artifact - - { name: linux-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: ubuntu-latest , upload-wheels: true } + - { name: linux-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: ubuntu-latest , upload-wheels: true } - { name: windows-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: windows-latest } - - { name: windows-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: windows-latest } + - { name: windows-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: windows-latest } - { name: macos-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: macos-latest } steps: - name: Cancel non-latest runs @@ -32,13 +32,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-ver }} @@ -79,9 +79,9 @@ jobs: matrix: include: - { name: linux-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: ubuntu-latest } - - { name: linux-gallery-python3.11-upgraded , test-tox-env: gallery-py311-upgraded, python-ver: "3.11", os: ubuntu-latest } + - { name: linux-gallery-python3.12-upgraded , test-tox-env: gallery-py312-upgraded, python-ver: "3.12", os: ubuntu-latest } - { name: windows-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: windows-latest } - - { name: windows-gallery-python3.11-upgraded, test-tox-env: gallery-py311-upgraded, python-ver: "3.11", os: windows-latest } + - { name: windows-gallery-python3.12-upgraded, test-tox-env: gallery-py312-upgraded, python-ver: "3.12", os: windows-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -89,13 +89,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-ver }} @@ -120,7 +120,7 @@ jobs: matrix: include: - { name: conda-linux-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: ubuntu-latest } - - { name: conda-linux-python3.11-upgraded , test-tox-env: py311-upgraded , build-tox-env: build-py311-upgraded , python-ver: "3.11", os: ubuntu-latest } + - { name: conda-linux-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: ubuntu-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -128,13 +128,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Conda - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v3 with: auto-update-conda: true python-version: ${{ matrix.python-ver }} @@ -174,7 +174,7 @@ jobs: fail-fast: false matrix: include: - - { name: conda-linux-python3.11-ros3 , python-ver: "3.11", os: ubuntu-latest } + - { name: conda-linux-python3.12-ros3 , python-ver: "3.12", os: ubuntu-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -182,13 +182,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Conda - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v3 with: auto-update-conda: true activate-environment: ros3 @@ -219,7 +219,7 @@ jobs: fail-fast: false matrix: include: - - { name: conda-linux-gallery-python3.11-ros3 , python-ver: "3.11", os: ubuntu-latest } + - { name: conda-linux-gallery-python3.12-ros3 , python-ver: "3.12", os: ubuntu-latest } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -227,13 +227,13 @@ jobs: all_but_latest: true access_token: ${{ github.token }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Conda - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v3 with: auto-update-conda: true activate-environment: ros3 @@ -271,15 +271,15 @@ jobs: access_token: ${{ github.token }} - name: Checkout repo with submodules - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: 'recursive' fetch-depth: 0 # tags are required for versioneer to determine the version - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.12' - name: Download wheel and source distributions from artifact uses: actions/download-artifact@v3 diff --git a/CHANGELOG.md b/CHANGELOG.md index 06f8a31b3..7da2ccd12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ # PyNWB Changelog -## PyNWB 2.6.1 (March 25, 2024) +## PyNWB 2.7.0 (Upcoming) + +### Enhancements and minor changes +- Added support for python 3.12 and upgraded dependency versions. This also includes infrastructure updates for developers. @mavaylon1 [#1853](https://github.com/NeurodataWithoutBorders/pynwb/pull/1853) ### Bug fixes - Fix bug with reading file with linked `TimeSeriesReferenceVectorData` @rly [#1865](https://github.com/NeurodataWithoutBorders/pynwb/pull/1865) diff --git a/MANIFEST.in b/MANIFEST.in index 04c3ad5c8..dd0fdadda 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,4 @@ -include license.txt Legal.txt versioneer.py src/pynwb/_version.py src/pynwb/_due.py +include license.txt Legal.txt src/pynwb/_due.py include requirements.txt requirements-dev.txt requirements-doc.txt requirements-min.txt environment-ros3.yml include test.py tox.ini diff --git a/Makefile b/Makefile deleted file mode 100644 index 4005c8915..000000000 --- a/Makefile +++ /dev/null @@ -1,83 +0,0 @@ -PYTHON = python -FLAKE = flake8 -COVERAGE = coverage - -help: - @echo "Please use \`make ' where is one of" - @echo " init to install required packages" - @echo " build to build the python package(s)" - @echo " install to build and install the python package(s)" - @echo " develop to build and install the python package(s) for development" - @echo " test to run all integration and unit tests" - @echo " htmldoc to make the HTML documentation and open it with the default browser" - @echo " coverage to run tests, build coverage HTML report and open it with the default browser" - @echo "" - @echo "Advanced targets" - @echo " apidoc to generate API docs *.rst files from sources" - @echo " coverage-only to run tests and build coverage report" - @echo " coverage-open to open coverage HTML report in the default browser" - @echo " htmlclean to remove all generated documentation" - @echo " htmldoc-only to make the HTML documentation" - @echo " htmldoc-open to open the HTML documentation with the default browser" - @echo " pdfdoc to make the LaTeX sources and build the PDF of the documentation" - -init: - pip install -r requirements.txt -r requirements-dev.txt -r requirements-doc.txt - -build: - $(PYTHON) setup.py build - -install: build - $(PYTHON) setup.py install - -develop: build - $(PYTHON) setup.py develop - -test: - pip install -r requirements-dev.txt - tox - -flake: - $(FLAKE) --exclude=nwb-schema src/ - $(FLAKE) tests/ - $(FLAKE) --ignore E402,W504 docs/gallery - -checkpdb: - find {src,tests} -name "*.py" -exec grep -Hn -e pdb -e breakpoint -e print {} \; - -devtest: - $(PYTHON) test.py - -testclean: - rm *.npy *.nwb *.yaml - -apidoc: - pip install -r requirements-doc.txt - cd docs && $(MAKE) apidoc - -htmldoc-only: apidoc - cd docs && $(MAKE) html - -htmlclean: - cd docs && $(MAKE) clean - -htmldoc-open: - @echo "" - @echo "To view the HTML documentation open: docs/_build/html/index.html" - open docs/_build/html/index.html || xdg-open docs/_build/html/index.html - -htmldoc: htmldoc-only htmldoc-open - -pdfdoc: - cd docs && $(MAKE) latexpdf - @echo "" - @echo "To view the PDF documentation open: docs/_build/latex/PyNWB.pdf" - -coverage-only: - tox -e localcoverage - -coverage-open: - @echo "To view coverage data open: ./tests/coverage/htmlcov/index.html" - open ./tests/coverage/htmlcov/index.html || xdg-open ./tests/coverage/htmlcov/index.html - -coverage: coverage-only coverage-open diff --git a/README.rst b/README.rst index 14eb32fce..d554207cb 100644 --- a/README.rst +++ b/README.rst @@ -13,35 +13,21 @@ Latest Release .. image:: https://anaconda.org/conda-forge/pynwb/badges/version.svg :target: https://anaconda.org/conda-forge/pynwb -Code Coverage -============== - -.. image:: https://github.com/NeurodataWithoutBorders/pynwb/workflows/Run%20coverage/badge.svg - :target: https://github.com/NeurodataWithoutBorders/pynwb/actions?query=workflow%3A%22Run+coverage%22 - -Overall test coverage - -.. image:: https://codecov.io/gh/NeurodataWithoutBorders/pynwb/branch/dev/graph/badge.svg - :target: https://codecov.io/gh/NeurodataWithoutBorders/pynwb - -Unit test coverage - -.. image:: https://codecov.io/gh/NeurodataWithoutBorders/pynwb/branch/dev/graph/badge.svg?flag=unit - :target: https://codecov.io/gh/NeurodataWithoutBorders/pynwb - -Integration test coverage - -.. image:: https://codecov.io/gh/NeurodataWithoutBorders/pynwb/branch/dev/graph/badge.svg?flag=integration - :target: https://codecov.io/gh/NeurodataWithoutBorders/pynwb Overall Health ============== +.. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_coverage.yml/badge.svg + :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_coverage.yml + .. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_tests.yml/badge.svg :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_tests.yml -.. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_flake8.yml/badge.svg - :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_flake8.yml +.. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/codespell.yml/badge.svg + :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/codespell.yml + +.. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/ruff.yml/badge.svg + :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/ruff.yml .. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/check_external_links.yml/badge.svg :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/check_external_links.yml diff --git a/docs/CONTRIBUTING.rst b/docs/CONTRIBUTING.rst index f774f49bf..2ee5d48cb 100644 --- a/docs/CONTRIBUTING.rst +++ b/docs/CONTRIBUTING.rst @@ -115,11 +115,11 @@ Projects are currently used mainly on the NeurodataWithoutBorders organization l .. _sec-styleguides: -Styleguides ------------ +Style Guides +------------ -Git Commit Message Styleguide -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Git Commit Message Style Guide +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Use the present tense ("Add feature" not "Added feature") * The first line should be short and descriptive. @@ -127,8 +127,8 @@ Git Commit Message Styleguide * If a commit fixes an issues, then include "Fix #X" where X is the number of the issue. * Reference relevant issues and pull requests liberally after the first line. -Documentation Styleguide -^^^^^^^^^^^^^^^^^^^^^^^^ +Documentation Style Guide +^^^^^^^^^^^^^^^^^^^^^^^^^ All documentations is written in reStructuredText (RST) using Sphinx. @@ -137,15 +137,31 @@ Did you fix whitespace, format code, or make a purely cosmetic patch in source c Source code changes that are purely cosmetic in nature and do not add anything substantial to the stability, functionality, or testability will generally not be accepted unless they have been approved beforehand. One of the main reasons is that there are a lot of hidden costs in addition to writing the code itself, and with the limited resources of the project, we need to optimize developer time. E.g,. someone needs to test and review PRs, backporting of bug fixes gets harder, it creates noise and pollutes the git repo and many other cost factors. -Format Specification Styleguide -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Format Specification Style Guide +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Coming soon** -Python Code Styleguide -^^^^^^^^^^^^^^^^^^^^^^ +Python Code Style Guide +^^^^^^^^^^^^^^^^^^^^^^^ + +Before you create a Pull Request, make sure you are following the PyNWB style guide. +To check whether your code conforms to the PyNWB style guide, simply run the ruff_ tool in the project's root +directory. ``ruff`` will also sort imports automatically and check against additional code style rules. + +We also use ``ruff`` to sort python imports automatically and double-check that the codebase +conforms to PEP8 standards, while using the codespell_ tool to check spelling. + +``ruff`` and ``codespell`` are installed when you follow the developer installation instructions. See +:ref:`install_developers`. + +.. _ruff: https://beta.ruff.rs/docs/ +.. _codespell: https://github.com/codespell-project/codespell + +.. code:: -Python coding style is checked via ``flake8`` for automatic checking of PEP8 style during pull requests. + $ ruff check . + $ codespell Endorsement ----------- diff --git a/docs/gallery/domain/images.py b/docs/gallery/domain/images.py index 58e9a8e8b..135e18c8c 100644 --- a/docs/gallery/domain/images.py +++ b/docs/gallery/domain/images.py @@ -13,7 +13,8 @@ * :py:class:`~pynwb.image.OpticalSeries` 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; +* :py:class:`~pynwb.image.GrayscaleImage`, :py:class:`~pynwb.image.RGBImage`, + :py:class:`~pynwb.image.RGBAImage`, for static images; The following examples will reference variables that may not be defined within the block they are used in. For clarity, we define them here: @@ -136,19 +137,23 @@ # External Files # ^^^^^^^^^^^^^^ # -# 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 :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. +# 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 +# :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 :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. +# 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. # # 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 frames, -# and the third file has 3 frames, then this attribute will have values `[0, 2, 4]`. +# 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 = [ os.path.relpath(movie_path, nwbfile_path) for movie_path in moviefiles_path diff --git a/docs/gallery/general/extensions.py b/docs/gallery/general/extensions.py index 4ec8f4749..ddf9159c7 100644 --- a/docs/gallery/general/extensions.py +++ b/docs/gallery/general/extensions.py @@ -12,12 +12,6 @@ For a more in-depth, step-by-step guide on how to create, document, and publish NWB extensions, we highly recommend visiting the :nwb_overview:`extension tutorial ` on the :nwb_overview:`nwb overview <>` website. - -.. seealso:: - - For more information on available tools for creating extensions, see - :nwb_overview:`here `. - """ #################### diff --git a/docs/source/conf.py b/docs/source/conf.py index 6b101c23c..6ceee9d50 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -33,8 +33,7 @@ # version is used. sys.path.insert(0, os.path.join(project_root, 'src')) -from pynwb._version import get_versions - +import pynwb # -- Autodoc configuration ----------------------------------------------------- @@ -191,9 +190,9 @@ def __call__(self, filename): # built documents. # # The short X.Y version. -version = '{}'.format(get_versions()['version']) +version = pynwb.__version__ # The full version, including alpha/beta/rc tags. -release = '{}'.format(get_versions()['version']) +release = pynwb.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/docs/source/install_developers.rst b/docs/source/install_developers.rst index b2c2d18e7..428a7e592 100644 --- a/docs/source/install_developers.rst +++ b/docs/source/install_developers.rst @@ -79,12 +79,12 @@ After you have created and activated a virtual environment, clone the PyNWB git package requirements using the `pip `_ Python package manager, and install PyNWB in editable mode. -.. code:: +.. code:: bash - $ git clone --recurse-submodules https://github.com/NeurodataWithoutBorders/pynwb.git - $ cd pynwb - $ pip install -r requirements.txt - $ pip install -e . + git clone --recurse-submodules https://github.com/NeurodataWithoutBorders/pynwb.git + cd pynwb + pip install -r requirements.txt -r requirements-dev.txt + pip install -e . Run tests @@ -93,31 +93,19 @@ Run tests For running the tests, it is required to install the development requirements. Again, first activate your virtualenv or conda environment. -.. code:: +.. code:: bash - $ git clone --recurse-submodules https://github.com/NeurodataWithoutBorders/pynwb.git - $ cd pynwb - $ pip install -r requirements.txt -r requirements-dev.txt - $ pip install -e . - $ tox + git clone --recurse-submodules https://github.com/NeurodataWithoutBorders/pynwb.git + cd pynwb + pip install -r requirements.txt -r requirements-dev.txt + pip install -e . + tox For debugging it can be useful to keep the intermediate NWB files created by the tests. To keep these files create the environment variables ``CLEAN_NWB``/``CLEAN_HDMF`` and set them to ``1``. -Following PyNWB Style Guide ---------------------------- - -Before you create a Pull Request, make sure you are following PyNWB style guide -(`PEP8 `_). To do that simply run -the following command in the project's root directory. - -.. code:: - - $ flake8 - - FAQ --- diff --git a/environment-ros3.yml b/environment-ros3.yml index 07838258e..155d2a938 100644 --- a/environment-ros3.yml +++ b/environment-ros3.yml @@ -4,18 +4,19 @@ channels: - conda-forge - defaults dependencies: - - python==3.11 - - h5py==3.8.0 + - python==3.12 + - h5py==3.10.0 - hdmf==3.12.2 - - matplotlib==3.7.1 - - numpy==1.24.2 - - pandas==2.0.0 + - matplotlib==3.8.0 + - numpy==1.26 + - pandas==2.1.2 - python-dateutil==2.8.2 - setuptools - - dandi==0.59.0 # NOTE: dandi does not support osx-arm64 - - fsspec==2023.6.0 - - requests==2.28.1 - - aiohttp==3.8.3 + - pytest==7.4.3 # This is for the upcoming pytest update + - dandi==0.60.0 # NOTE: dandi does not support osx-arm64 + - fsspec==2024.2.0 + - requests==2.31.0 + - aiohttp==3.9.3 - pip - pip: - remfile==0.1.9 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..1bae035af --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] # hatchling for build | hatch-vcs for versioning +build-backend = "hatchling.build" # the build backend used + +[project] +name = "pynwb" +authors = [ + { name="Andrew Tritt", email="ajtritt@lbl.gov" }, + { name="Ryan Ly", email="rly@lbl.gov" }, + { name="Oliver Ruebel", email="oruebel@lbl.gov" }, + { name="Ben Dichter", email="ben.dichter@gmail.com" }, + { name="Matthew Avaylon", email="mavaylon@lbl.gov" } +] +description= "Package for working with Neurodata stored in the NWB format." +readme = "README.rst" +requires-python = ">=3.8" +license = {text = "BSD-3-Clause"} +classifiers = [ + "Programming Language :: Python", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: BSD License", + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "Operating System :: Microsoft :: Windows", + "Operating System :: MacOS", + "Operating System :: Unix", + "Topic :: Scientific/Engineering :: Medical Science Apps." +] +dependencies = [ + "h5py>=2.10", + "hdmf>=3.12.2", + "numpy>=1.18", # match the version used in hdmf + "pandas>=1.1.5", + "python-dateutil>=2.7.3", +] +dynamic = ["version"] # the build backend will compute the version dynamically from git tag (or a __version__) + +[project.optional-dependencies] +# Add optional dependencies here + +[project.urls] +"Homepage" = "https://github.com/NeurodataWithoutBorders/pynwb" +"Bug Tracker" = "https://github.com/NeurodataWithoutBorders/pynwb/issues" + +[tool.hatch.version] +source = "vcs" + +[tool.hatch.build.hooks.vcs] +# this file is created/updated when the package is installed and used in +# src/pynwb/__init__.py to set `__version__` (from _version.py). +version-file = "src/pynwb/_version.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/pynwb"] + +# [tool.pytest.ini_options] # TODO: uncomment when pytest is integrated +# # Addopts creates a shortcut for pytest. For example below, running `pytest` will actually run `pytest --cov --cov-report html`. +# addopts = "--cov --cov-report html" # generates coverage report in html format without showing anything on the terminal. + +[tool.codespell] +skip = "htmlcov,.git,.mypy_cache,.pytest_cache,.coverage,*.pdf,*.svg,venvs,.tox,nwb-schema,./docs/_build/*,*.ipynb" +ignore-words-list = "optin,potatos" + +[tool.coverage.run] +branch = true +source = ["src/"] +omit = [ + "src/pynwb/_due.py", + "src/pynwb/testing/*", + "src/pynwb/legacy/*" +] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "@abstract" +] + +[tool.ruff] +select = ["E", "F", "T100", "T201", "T203"] +exclude = [ + ".git", + ".tox", + "__pycache__", + "build/", + "dist/", + "src/nwb-schema", + "docs/source/conf.py", + "src/pynwb/_due.py", + "test.py" # remove when pytest comes along +] +line-length = 120 + +[tool.ruff.per-file-ignores] +"tests/read_dandi/*" = ["T201"] +"docs/gallery/*" = ["E402", "T201"] +"src/*/__init__.py" = ["F401"] +"src/pynwb/_version.py" = ["T201"] +"src/pynwb/validate.py" = ["T201"] +"scripts/*" = ["T201"] + +# "test_gallery.py" = ["T201"] # Uncomment when test_gallery.py is created + +[tool.ruff.mccabe] +max-complexity = 17 + diff --git a/requirements-dev.txt b/requirements-dev.txt index da53e22bf..173090a57 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,12 +3,10 @@ # versions of requirements may be installed due to package incompatibilities. # black==24.3.0 -codespell==2.2.4 -coverage==7.2.2 -flake8==6.0.0 -flake8-debugger==4.1.2 -flake8-print==5.0.0 +codespell==2.2.6 +coverage==7.3.2 +pytest==7.4.3 isort==5.12.0 -pytest==7.1.2 -pytest-cov==4.0.0 -tox==4.4.8 +pytest-cov==4.1.0 +tox==4.11.3 +ruff==0.1.3 diff --git a/requirements-min.txt b/requirements-min.txt index 0e8bde429..f6b765b0b 100644 --- a/requirements-min.txt +++ b/requirements-min.txt @@ -4,4 +4,3 @@ hdmf==3.12.2 numpy==1.18 pandas==1.1.5 python-dateutil==2.7.3 -setuptools diff --git a/requirements.txt b/requirements.txt index ad5d748bd..836052317 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,3 @@ hdmf==3.12.2 numpy==1.26.1 pandas==2.1.2 python-dateutil==2.8.2 -setuptools==65.5.1 \ No newline at end of file diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index d44fcc2b1..000000000 --- a/setup.cfg +++ /dev/null @@ -1,42 +0,0 @@ -[versioneer] -VCS = git -versionfile_source = src/pynwb/_version.py -versionfile_build = pynwb/_version.py -tag_prefix = '' -style = pep440-pre - -[flake8] -max-line-length = 120 -max-complexity = 17 -exclude = - .git, - .tox, - __pycache__, - build/, - dist/, - src/pynwb/nwb-schema/ - docs/_build/, - docs/source/conf.py - docs/source/tutorials/ - versioneer.py, - src/pynwb/_version.py - src/pynwb/_due.py -per-file-ignores = - docs/gallery/*:E402,E501,T201 - docs/source/tutorials/*:E402,T201 - src/pynwb/io/__init__.py:F401 - src/pynwb/legacy/io/__init__.py:F401 - tests/integration/__init__.py:F401 - src/pynwb/testing/__init__.py:F401 - src/pynwb/validate.py:T201 - tests/read_dandi/read_first_nwb_asset.py:T201 - setup.py:T201 - test.py:T201 - scripts/*:T201 -extend-ignore = E203 - -[metadata] -description_file = README.rst - -[isort] -profile = black diff --git a/setup.py b/setup.py deleted file mode 100755 index 2a9ecb19e..000000000 --- a/setup.py +++ /dev/null @@ -1,81 +0,0 @@ -# -*- coding: utf-8 -*- - -import sys - -from setuptools import setup, find_packages - -# Some Python installations don't add the current directory to path. -if '' not in sys.path: - sys.path.insert(0, '') - -import versioneer - -with open('README.rst', 'r') as fp: - readme = fp.read() - -pkgs = find_packages('src', exclude=['data']) -print('found these packages:', pkgs) - -schema_dir = 'nwb-schema/core' - -reqs = [ - 'h5py>=2.10', - 'hdmf>=3.12.2', - 'numpy>=1.16', - 'pandas>=1.1.5', - 'python-dateutil>=2.7.3', - 'setuptools' -] - -print(reqs) - -setup_args = { - 'name': 'pynwb', - 'version': versioneer.get_version(), - 'cmdclass': versioneer.get_cmdclass(), - 'description': 'Package for working with Neurodata stored in the NWB format', - 'long_description': readme, - 'long_description_content_type': 'text/x-rst; charset=UTF-8', - 'author': 'Andrew Tritt', - 'author_email': 'ajtritt@lbl.gov', - 'url': 'https://github.com/NeurodataWithoutBorders/pynwb', - 'license': "BSD", - 'install_requires': reqs, - 'packages': pkgs, - 'package_dir': {'': 'src'}, - 'package_data': {'pynwb': ["%s/*.yaml" % schema_dir, "%s/*.json" % schema_dir]}, - 'python_requires': '>=3.8', - 'classifiers': [ - "Programming Language :: Python", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "License :: OSI Approved :: BSD License", - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Intended Audience :: Science/Research", - "Operating System :: Microsoft :: Windows", - "Operating System :: MacOS", - "Operating System :: Unix", - "Topic :: Scientific/Engineering :: Medical Science Apps." - ], - 'keywords': 'Neuroscience ' - 'python ' - 'HDF ' - 'HDF5 ' - 'cross-platform ' - 'open-data ' - 'data-format ' - 'open-source ' - 'open-science ' - 'reproducible-research ' - 'PyNWB ' - 'NWB ' - 'NWB:N ' - 'NeurodataWithoutBorders', - 'zip_safe': False -} - -if __name__ == '__main__': - setup(**setup_args) diff --git a/src/pynwb/__init__.py b/src/pynwb/__init__.py index 5e29caede..607fe6a9e 100644 --- a/src/pynwb/__init__.py +++ b/src/pynwb/__init__.py @@ -391,8 +391,15 @@ def export(self, **kwargs): from hdmf.data_utils import DataChunkIterator # noqa: F401,E402 from hdmf.backends.hdf5 import H5DataIO # noqa: F401,E402 -from . import _version # noqa: F401,E402 -__version__ = _version.get_versions()['version'] +try: + # see https://effigies.gitlab.io/posts/python-packaging-2023/ + from ._version import __version__ +except ImportError: # pragma: no cover + # this is a relatively slower method for getting the version string + from importlib.metadata import version # noqa: E402 + + __version__ = version("pynwb") + del version from ._due import due, BibTeX # noqa: E402 due.cite( diff --git a/src/pynwb/_version.py b/src/pynwb/_version.py deleted file mode 100644 index bf16355e1..000000000 --- a/src/pynwb/_version.py +++ /dev/null @@ -1,658 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.26 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440-pre" - cfg.tag_prefix = "" - cfg.parentdir_prefix = "None" - cfg.versionfile_source = "src/pynwb/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} diff --git a/src/pynwb/icephys.py b/src/pynwb/icephys.py index 2de21d571..bed2d4ecd 100644 --- a/src/pynwb/icephys.py +++ b/src/pynwb/icephys.py @@ -491,15 +491,15 @@ def __init__(self, **kwargs): if required_dynamic_table_missing: if required_dynamic_table_given[2] < 0: dynamic_table_arg.append(IntracellularResponsesTable) - if not dynamic_table_arg[-1].name in categories_arg: + if dynamic_table_arg[-1].name not in categories_arg: categories_arg.insert(0, dynamic_table_arg[-1].name) if required_dynamic_table_given[1] < 0: dynamic_table_arg.append(IntracellularStimuliTable()) - if not dynamic_table_arg[-1].name in categories_arg: + if dynamic_table_arg[-1].name not in categories_arg: categories_arg.insert(0, dynamic_table_arg[-1].name) if required_dynamic_table_given[0] < 0: dynamic_table_arg.append(IntracellularElectrodesTable()) - if not dynamic_table_arg[-1].name in categories_arg: + if dynamic_table_arg[-1].name not in categories_arg: categories_arg.insert(0, dynamic_table_arg[-1].name) kwargs['category_tables'] = dynamic_table_arg kwargs['categories'] = categories_arg diff --git a/test.py b/test.py old mode 100755 new mode 100644 index 16191ae3f..231facf58 --- a/test.py +++ b/test.py @@ -11,6 +11,7 @@ import sys import traceback import unittest +import importlib.util flags = { 'pynwb': 2, @@ -68,8 +69,11 @@ def run_test_suite(directory, description="", verbose=True): def _import_from_file(script): - import imp - return imp.load_source(os.path.basename(script), script) + modname = os.path.basename(script) + spec = importlib.util.spec_from_file_location(os.path.basename(script), script) + module = importlib.util.module_from_spec(spec) + sys.modules[modname] = module + spec.loader.exec_module(module) warning_re = re.compile("Parent module '[a-zA-Z0-9]+' not found while handling absolute import") diff --git a/tox.ini b/tox.ini index 10b1e0df4..798da6fe6 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,7 @@ # and then run "tox" from this directory. [tox] -envlist = py38, py39, py310, py311 +envlist = py38, py39, py310, py311, py312 requires = pip >= 22.0 [testenv] @@ -12,7 +12,7 @@ download = True usedevelop = True setenv = PYTHONDONTWRITEBYTECODE = 1 - VIRTUALENV_PIP = 22.3.1 + VIRTUALENV_PIP = 23.3.1 install_command = python -m pip install -U {opts} {packages} @@ -24,41 +24,22 @@ commands = python -m pip list python test.py -v -# Env to create coverage report locally -[testenv:localcoverage] -basepython = python3.11 -commands = - python -m coverage run test.py --pynwb - coverage html -d tests/coverage/htmlcov - -# Test with python 3.11; pinned dev and optional reqs -[testenv:py311-optional] -basepython = python3.11 -install_command = - python -m pip install {opts} {packages} -deps = - -rrequirements-dev.txt - ; -rrequirements-opt.txt -commands = {[testenv]commands} - -# Test with python 3.11; pinned dev and optional reqs; upgraded run reqs -[testenv:py311-upgraded] -basepython = python3.11 +# Test with python 3.12; pinned dev reqs; upgraded run reqs +[testenv:py312-upgraded] +basepython = python3.12 install_command = python -m pip install -U {opts} {packages} deps = -rrequirements-dev.txt - ; -rrequirements-opt.txt commands = {[testenv]commands} -# Test with python 3.11; pinned dev and optional reqs; upgraded, pre-release run reqs -[testenv:py311-prerelease] -basepython = python3.11 +# Test with python 3.12; pinned dev reqs; upgraded, pre-release run reqs +[testenv:py312-prerelease] +basepython = python3.12 install_command = python -m pip install -U --pre {opts} {packages} deps = -rrequirements-dev.txt - ; -rrequirements-opt.txt commands = {[testenv]commands} # Test with python 3.8; pinned dev reqs; minimum run reqs @@ -91,29 +72,24 @@ commands = {[testenv:build]commands} basepython = python3.11 commands = {[testenv:build]commands} -[testenv:build-py311-optional] -basepython = python3.11 -deps = - -rrequirements-dev.txt - ; -rrequirements-opt.txt +[testenv:build-py312] +basepython = python3.12 commands = {[testenv:build]commands} -[testenv:build-py311-upgraded] -basepython = python3.11 +[testenv:build-py312-upgraded] +basepython = python3.12 install_command = python -m pip install -U {opts} {packages} deps = -rrequirements-dev.txt - ; -rrequirements-opt.txt commands = {[testenv:build]commands} -[testenv:build-py311-prerelease] -basepython = python3.11 +[testenv:build-py312-prerelease] +basepython = python3.12 install_command = python -m pip install -U --pre {opts} {packages} deps = -rrequirements-dev.txt - ; -rrequirements-opt.txt commands = {[testenv:build]commands} [testenv:build-py38-minimum] @@ -129,7 +105,7 @@ deps = null commands = python -c "import pynwb" # Envs that will execute gallery tests that do not require ROS3 -# Test with pinned dev, doc, run, and optional reqs +# Test with pinned dev, doc, and run reqs [testenv:gallery] install_command = python -m pip install -U {opts} {packages} @@ -162,9 +138,9 @@ basepython = python3.11 deps = {[testenv:gallery]deps} commands = {[testenv:gallery]commands} -# Test with python 3.11; pinned dev, doc, and optional reqs; upgraded run reqs -[testenv:gallery-py311-upgraded] -basepython = python3.11 +# Test with python 3.12; pinned dev, and doc reqs; upgraded run reqs +[testenv:gallery-py312-upgraded] +basepython = python3.12 deps = -rrequirements-dev.txt commands = @@ -174,9 +150,9 @@ commands = python -m pip list python test.py --example -# Test with python 3.11; pinned dev, doc, and optional reqs; pre-release run reqs -[testenv:gallery-py311-prerelease] -basepython = python3.11 +# Test with python 3.12; pinned dev, doc, and optional reqs; pre-release run reqs +[testenv:gallery-py312-prerelease] +basepython = python3.12 deps = -rrequirements-dev.txt commands = @@ -191,4 +167,4 @@ commands = basepython = python3.8 deps = -rrequirements-min.txt -commands = {[testenv:gallery]commands} \ No newline at end of file +commands = {[testenv:gallery]commands} diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 223db1d9c..000000000 --- a/versioneer.py +++ /dev/null @@ -1,2194 +0,0 @@ - -# Version: 0.26 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain (Unlicense) -* Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3 -* [![Latest Version][pypi-image]][pypi-url] -* [![Build Status][travis-image]][travis-url] - -This is a tool for managing a recorded version number in setuptools-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -Versioneer provides two installation modes. The "classic" vendored mode installs -a copy of versioneer into your repository. The experimental build-time dependency mode -is intended to allow you to skip this step and simplify the process of upgrading. - -### Vendored mode - -* `pip install versioneer` to somewhere in your $PATH -* add a `[tool.versioneer]` section to your `pyproject.toml or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* run `versioneer install --vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -### Build-time dependency mode - -* `pip install versioneer` to somewhere in your $PATH -* add a `[tool.versioneer]` section to your `pyproject.toml or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* add `versioneer` to the `requires` key of the `build-system` table in - `pyproject.toml`: - ```toml - [build-system] - requires = ["setuptools", "versioneer"] - build-backend = "setuptools.build_meta" - ``` -* run `versioneer install --no-vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other languages) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg` and `pyproject.toml`, if necessary, - to include any new configuration settings indicated by the release notes. - See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install --[no-]vendor` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - -## Similar projects - -* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time - dependency -* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of - versioneer -* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools - plugin - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg -[pypi-url]: https://pypi.python.org/pypi/versioneer/ -[travis-image]: -https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg -[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer - -""" -# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring -# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements -# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error -# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with -# pylint:disable=attribute-defined-outside-init,too-many-arguments - -import configparser -import errno -import json -import os -import re -import subprocess -import sys -from pathlib import Path -from typing import Callable, Dict -import functools -try: - import tomli - have_tomli = True -except ImportError: - have_tomli = False - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - my_path = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(my_path)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise OSError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - root = Path(root) - pyproject_toml = root / "pyproject.toml" - setup_cfg = root / "setup.cfg" - section = None - if pyproject_toml.exists() and have_tomli: - try: - with open(pyproject_toml, 'rb') as fobj: - pp = tomli.load(fobj) - section = pp['tool']['versioneer'] - except (tomli.TOMLDecodeError, KeyError): - pass - if not section: - parser = configparser.ConfigParser() - with open(setup_cfg) as cfg_file: - parser.read_file(cfg_file) - parser.get("versioneer", "VCS") # raise error if missing - - section = parser["versioneer"] - - cfg = VersioneerConfig() - cfg.VCS = section['VCS'] - cfg.style = section.get("style", "") - cfg.versionfile_source = section.get("versionfile_source") - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = section.get("tag_prefix") - if cfg.tag_prefix in ("''", '""', None): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - cfg.verbose = section.get("verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -LONG_VERSION_PY['git'] = r''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.26 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%%d" %% (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [versionfile_source] - if ipy: - files.append(ipy) - if "VERSIONEER_PEP518" not in globals(): - try: - my_path = __file__ - if my_path.endswith(".pyc") or my_path.endswith(".pyo"): - my_path = os.path.splitext(my_path)[0] + ".py" - versioneer_file = os.path.relpath(my_path) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - with open(".gitattributes", "r") as fobj: - for line in fobj: - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - break - except OSError: - pass - if not present: - with open(".gitattributes", "a+") as fobj: - fobj.write(f"{versionfile_source} export-subst\n") - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.26) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except OSError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools subclasses used by Versioneer. - - If the package uses a different cmdclass (e.g. one from numpy), it - should be provide as an argument. - """ - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to setuptools - from setuptools import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # pip install -e . and setuptool/editable_wheel will invoke build_py - # but the build_py command is not expected to copy any files. - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py = cmds['build_py'] - else: - from setuptools.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - if getattr(self, "editable_mode", False): - # During editable installs `.py` and data files are - # not copied to build_lib - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext = cmds['build_ext'] - else: - from setuptools.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_ext.run(self) - if self.inplace: - # build_ext --inplace will only build extensions in - # build/lib<..> dir with no _version.py to write to. - # As in place builds will already have a _version.py - # in the module dir, we do not need to write one. - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - if not os.path.exists(target_versionfile): - print(f"Warning: {target_versionfile} does not exist, skipping " - "version update. This can happen if you are running build_ext " - "without first running build_py.") - return - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.setuptools_buildexe import py2exe as _py2exe - except ImportError: - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # sdist farms its file list building out to egg_info - if 'egg_info' in cmds: - _sdist = cmds['egg_info'] - else: - from setuptools.command.egg_info import egg_info as _egg_info - - class cmd_egg_info(_egg_info): - def find_sources(self): - # egg_info.find_sources builds the manifest list and writes it - # in one shot - super().find_sources() - - # Modify the filelist and normalize it - root = get_root() - cfg = get_config_from_root(root) - self.filelist.append('versioneer.py') - if cfg.versionfile_source: - # There are rare cases where versionfile_source might not be - # included by default, so we must be explicit - self.filelist.append(cfg.versionfile_source) - self.filelist.sort() - self.filelist.remove_duplicates() - - # The write method is hidden in the manifest_maker instance that - # generated the filelist and was thrown away - # We will instead replicate their final normalization (to unicode, - # and POSIX-style paths) - from setuptools import unicode_utils - normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') - for f in self.filelist.files] - - manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') - with open(manifest_filename, 'w') as fobj: - fobj.write('\n'.join(normalized)) - - cmds['egg_info'] = cmd_egg_info - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist = cmds['sdist'] - else: - from setuptools.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -OLD_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - -INIT_PY_SNIPPET = """ -from . import {0} -__version__ = {0}.get_versions()['version'] -""" - - -def do_setup(): - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (OSError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except OSError: - old = "" - module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] - snippet = INIT_PY_SNIPPET.format(module) - if OLD_SNIPPET in old: - print(" replacing boilerplate in %s" % ipy) - with open(ipy, "w") as f: - f.write(old.replace(OLD_SNIPPET, snippet)) - elif snippet not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(snippet) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -def setup_command(): - """Set up Versioneer and exit with appropriate error code.""" - errors = do_setup() - errors += scan_setup_py() - sys.exit(1 if errors else 0) - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - setup_command() From d125a7b011b2fd144d85f74c9c8801a8b0c07548 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Mon, 25 Mar 2024 12:49:07 -0700 Subject: [PATCH 12/29] fix link checker badge in readme (#1871) --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index d554207cb..d5d99789a 100644 --- a/README.rst +++ b/README.rst @@ -29,8 +29,8 @@ Overall Health .. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/ruff.yml/badge.svg :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/ruff.yml -.. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/check_external_links.yml/badge.svg - :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/check_external_links.yml +.. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/check_sphinx_links.yml/badge.svg + :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/check_sphinx_links.yml .. image:: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_inspector_tests.yml/badge.svg :target: https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_inspector_tests.yml From 65b2b9e98f8ae53a885411d53bf19c19ae69c102 Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Mon, 25 Mar 2024 13:16:08 -0700 Subject: [PATCH 13/29] Update software_process.rst to use pyproject.toml (#1868) * Update software_process.rst to use pyproject.toml * Update software_process.rst * Update docs/source/software_process.rst Co-authored-by: Steph Prince <40640337+stephprince@users.noreply.github.com> * Update docs/source/software_process.rst Co-authored-by: Steph Prince <40640337+stephprince@users.noreply.github.com> --------- Co-authored-by: Steph Prince <40640337+stephprince@users.noreply.github.com> --- docs/source/software_process.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/software_process.rst b/docs/source/software_process.rst index 07fd97246..2bc7d5596 100644 --- a/docs/source/software_process.rst +++ b/docs/source/software_process.rst @@ -36,7 +36,7 @@ codecov_, which shows line by line which lines are covered by the tests. Installation Requirements ------------------------- -:pynwb:`setup.py ` contains a list of package dependencies and their version ranges allowed for +:pynwb:`pyproject.toml ` contains a list of package dependencies and their version ranges allowed for running PyNWB. As a library, upper bound version constraints create more harm than good in the long term (see this `blog post`_) so we avoid setting upper bounds on requirements. From 1c313b4a5b39bca029d0cc297c551ddcbe2cedb1 Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Mon, 25 Mar 2024 13:55:54 -0700 Subject: [PATCH 14/29] Update .gitignore (#1870) --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index f130e0cc0..c0a2aca3e 100644 --- a/.gitignore +++ b/.gitignore @@ -74,3 +74,6 @@ tests/coverage/htmlcov # macos .DS_Store + +# Version +_version.py From 270291ad1834dca6c970c6f9dc695501031cef5f Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Mon, 25 Mar 2024 17:50:09 -0700 Subject: [PATCH 15/29] Update GitHub release checklist (#1872) * Update GitHub release checklist * Update release.md --- .github/PULL_REQUEST_TEMPLATE/release.md | 29 ++++++++++++++++-------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE/release.md b/.github/PULL_REQUEST_TEMPLATE/release.md index b7154c83c..615a7d58e 100644 --- a/.github/PULL_REQUEST_TEMPLATE/release.md +++ b/.github/PULL_REQUEST_TEMPLATE/release.md @@ -1,25 +1,34 @@ Prepare for release of PyNWB [version] ### Before merging: +- [ ] Make sure all PRs to be included in this release have been merged to `dev`. - [ ] Major and minor releases: Update package versions in `requirements.txt`, `requirements-dev.txt`, - `requirements-doc.txt`, `requirements-min.txt`, and `environment-ros3.yml` as needed. + `requirements-doc.txt`, `requirements-opt.txt`, and `environment-ros3.yml` to the latest versions, + and update dependency ranges in `pyproject.toml` and minimums in `requirements-min.txt` as needed. + Run `pip install pur && pur -r requirements-dev.txt -r requirements.txt -r requirements-opt.txt` + and manually update `environment-ros3.yml`. - [ ] Check legal file dates and information in `Legal.txt`, `license.txt`, `README.rst`, `docs/source/conf.py`, and any other locations as needed - [ ] Update `pyproject.toml` as needed - [ ] Update `README.rst` as needed -- [ ] Update `src/pynwb/nwb-schema` submodule as needed. Check the version number and commit SHA manually +- [ ] Update `src/pynwb/nwb-schema` submodule as needed. Check the version number and commit SHA + manually. Make sure we are using the latest release and not the latest commit on the `main` branch. - [ ] Update changelog (set release date) in `CHANGELOG.md` and any other docs as needed - [ ] Run tests locally including gallery, validation, and streaming tests, and inspect all warnings and outputs - (`python test.py -v -p -i -b -w -r > out.txt 2>&1`) -- [ ] Test docs locally (`make clean`, `make html`) -- [ ] Push changes to this PR and make sure all PRs to be included in this release have been merged -- [ ] Check that the readthedocs build for this PR succeeds (build latest to pull the new branch, then activate and - build docs for new branch): https://readthedocs.org/projects/pynwb/builds/ + (`python test.py -v -p -i -b -w -r > out.txt 2>&1`). Try to remove all warnings. +- [ ] Test docs locally and inspect all warnings and outputs `cd docs; make clean && make html` +- [ ] After pushing this branch to GitHub, manually trigger the "Run all tests" GitHub Actions workflow on this + branch by going to https://github.com/NeurodataWithoutBorders/pynwb/actions/workflows/run_all_tests.yml, selecting + "Run workflow" on the right, selecting this branch, and clicking "Run workflow". Make sure all tests pass. +- [ ] Check that the readthedocs build for this PR succeeds (see the PR check) ### After merging: 1. Create release by following steps in `docs/source/make_a_release.rst` or use alias `git pypi-release [tag]` if set up 2. After the CI bot creates the new release (wait ~10 min), update the release notes on the [GitHub releases page](https://github.com/NeurodataWithoutBorders/pynwb/releases) with the changelog -3. Check that the readthedocs "latest" and "stable" builds run and succeed -4. Update [conda-forge/pynwb-feedstock](https://github.com/conda-forge/pynwb-feedstock) with the latest version number - and SHA256 retrieved from PyPI > PyNWB > Download Files > View hashes for the `.tar.gz` file. Re-render as needed +3. Check that the readthedocs "stable" build runs and succeeds +4. Either monitor [conda-forge/pynwb-feedstock](https://github.com/conda-forge/pynwb-feedstock) for the + regro-cf-autotick-bot bot to create a PR updating the version of HDMF to the latest PyPI release, usually within + 24 hours of release, or manually create a PR updating `recipe/meta.yaml` with the latest version number + and SHA256 retrieved from PyPI > PyNWB > Download Files > View hashes for the `.tar.gz` file. Re-render and update + dependencies as needed. From 4fcf10568d150f88da77e7c6480b41ecbafbd0a4 Mon Sep 17 00:00:00 2001 From: Ben Dichter Date: Fri, 29 Mar 2024 12:05:06 -0400 Subject: [PATCH 16/29] Update plot_editing.py (#1876) --- docs/gallery/advanced_io/plot_editing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gallery/advanced_io/plot_editing.py b/docs/gallery/advanced_io/plot_editing.py index a371dc588..cf19bb610 100644 --- a/docs/gallery/advanced_io/plot_editing.py +++ b/docs/gallery/advanced_io/plot_editing.py @@ -103,7 +103,7 @@ io.write(nwbfile) ############################################## -# The ``None``value in the first component of ``maxshape`` means that the +# The ``None`` value in the first component of ``maxshape`` means that the # the first dimension of the dataset is unlimited. By setting the second dimension # of ``maxshape`` to ``100``, that dimension is fixed to be no larger than ``100``. # If you do not specify a``maxshape``, then the shape of the dataset will be fixed From faa88847bdd867cec0e313afc89bc1d7a9ff4fc7 Mon Sep 17 00:00:00 2001 From: Ben Dichter Date: Sun, 31 Mar 2024 12:07:07 -0400 Subject: [PATCH 17/29] add docstrings for get_timestamps and get_data_in_units (#1878) --- src/pynwb/base.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/pynwb/base.py b/src/pynwb/base.py index 980d20d9a..4417c371f 100644 --- a/src/pynwb/base.py +++ b/src/pynwb/base.py @@ -328,12 +328,31 @@ def time_unit(self): return self.__time_unit def get_timestamps(self): + """ + Get the timestamps of this TimeSeries. If timestamps are not stored in this TimeSeries, generate timestamps. + """ if self.fields.get('timestamps'): return self.timestamps else: return np.arange(len(self.data)) / self.rate + self.starting_time def get_data_in_units(self): + """ + Get the data of this TimeSeries in the specified unit of measurement, applying the conversion factor and offset: + + .. math:: + out = data * conversion + offset + + If the field 'channel_conversion' is present, the conversion factor is applied to each channel separately: + + .. math:: + out_{channel} = data * conversion_{channel} + offset + + Returns + ------- + np.ndarray + + """ if "channel_conversion" in self.fields: scale_factor = self.conversion * self.channel_conversion[:, np.newaxis] else: From af63c5fef090682ef91bc37db73c36cf6c3a83f3 Mon Sep 17 00:00:00 2001 From: Heberto Mayorquin Date: Mon, 1 Apr 2024 01:22:05 -0600 Subject: [PATCH 18/29] Add mock units table (#1875) Co-authored-by: Ben Dichter --- CHANGELOG.md | 1 + src/pynwb/testing/mock/ecephys.py | 30 ++++++++++++++++++++++++++++++ tests/unit/test_mock.py | 3 +++ 3 files changed, 34 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a7515c3e..5c1949712 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - Added support for python 3.12 and upgraded dependency versions. This also includes infrastructure updates for developers. @mavaylon1 [#1853](https://github.com/NeurodataWithoutBorders/pynwb/pull/1853) +- Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) ### Bug fixes - Fix bug with reading file with linked `TimeSeriesReferenceVectorData` @rly [#1865](https://github.com/NeurodataWithoutBorders/pynwb/pull/1865) diff --git a/src/pynwb/testing/mock/ecephys.py b/src/pynwb/testing/mock/ecephys.py index 54edf7680..97831c3de 100644 --- a/src/pynwb/testing/mock/ecephys.py +++ b/src/pynwb/testing/mock/ecephys.py @@ -9,6 +9,7 @@ from ...ecephys import ElectricalSeries, ElectrodeGroup, SpikeEventSeries from .device import mock_Device from .utils import name_generator +from ...misc import Units def mock_ElectrodeGroup( @@ -119,3 +120,32 @@ def mock_SpikeEventSeries( nwbfile.add_acquisition(spike_event_series) return spike_event_series + + +def mock_Units( + num_units: int = 10, + max_spikes_per_unit: int = 10, + seed: int = 0, + nwbfile: Optional[NWBFile] = None, +) -> Units: + + units_table = Units() + units_table.add_column(name="unit_name", description="a readable identifier for the unit") + + rng = np.random.default_rng(seed=seed) + + times = rng.random(size=(num_units, max_spikes_per_unit)).cumsum(axis=1) + spikes_per_unit = rng.integers(1, max_spikes_per_unit, size=num_units) + + spike_times = [] + for unit_index in range(num_units): + + # Not all units have the same number of spikes + spike_times = times[unit_index, : spikes_per_unit[unit_index]] + unit_name = f"unit_{unit_index}" + units_table.add_unit(spike_times=spike_times, unit_name=unit_name) + + if nwbfile is not None: + nwbfile.units = units_table + + return units_table diff --git a/tests/unit/test_mock.py b/tests/unit/test_mock.py index 72174f018..2ce777b65 100644 --- a/tests/unit/test_mock.py +++ b/tests/unit/test_mock.py @@ -35,6 +35,7 @@ mock_ElectrodeTable, mock_ElectricalSeries, mock_SpikeEventSeries, + mock_Units, ) from pynwb.testing.mock.icephys import ( @@ -82,6 +83,7 @@ mock_IntracellularElectrode, mock_CurrentClampStimulusSeries, mock_IntracellularRecordingsTable, + mock_Units, ] @@ -119,3 +121,4 @@ def test_name_generator(): assert name_generator("TimeSeries") == "TimeSeries" assert name_generator("TimeSeries") == "TimeSeries2" + From 9af54a21ade15047c92c79bc1c61553e004ef710 Mon Sep 17 00:00:00 2001 From: Ben Dichter Date: Mon, 1 Apr 2024 07:53:24 -0400 Subject: [PATCH 19/29] add .get_timestamps to tutorial (#1879) --- docs/gallery/general/plot_read_basics.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/gallery/general/plot_read_basics.py b/docs/gallery/general/plot_read_basics.py index 0d684e5f5..d800adbe5 100644 --- a/docs/gallery/general/plot_read_basics.py +++ b/docs/gallery/general/plot_read_basics.py @@ -213,7 +213,9 @@ after = 3.0 # Get the stimulus times for all stimuli -stim_on_times = stimulus_presentation.timestamps[:] +# get_timestamps() works whether the time is stored as an array of timestamps or as +# starting time and sampling rate. +stim_on_times = stimulus_presentation.get_timestamps() for unit in range(3): unit_spike_times = nwbfile.units["spike_times"][unit] From 2259bede338f2f202229bda0af15d7e3cea47369 Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Mon, 1 Apr 2024 07:18:02 -0700 Subject: [PATCH 20/29] Improve get_data_in_units docstring (#1880) * Improve get_data_in_units docstring * Update base.py --------- Co-authored-by: Cody Baker <51133164+CodyCBakerPhD@users.noreply.github.com> --- src/pynwb/base.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/pynwb/base.py b/src/pynwb/base.py index 4417c371f..98fb62372 100644 --- a/src/pynwb/base.py +++ b/src/pynwb/base.py @@ -343,14 +343,17 @@ def get_data_in_units(self): .. math:: out = data * conversion + offset - If the field 'channel_conversion' is present, the conversion factor is applied to each channel separately: + If the field 'channel_conversion' is present, the conversion factor for each channel is additionally applied + to each channel: .. math:: - out_{channel} = data * conversion_{channel} + offset + out_{channel} = data * conversion * conversion_{channel} + offset + + NOTE: This will read the entire dataset into memory. Returns ------- - np.ndarray + :class:`numpy.ndarray` """ if "channel_conversion" in self.fields: From 001a9fd670ba88b5b825a3ed7896e5d5e0269cf6 Mon Sep 17 00:00:00 2001 From: Heberto Mayorquin Date: Wed, 24 Apr 2024 11:29:19 -0600 Subject: [PATCH 21/29] Add default `name="units"` to `Units` object in the `mock_Units` testing function (#1883) --- CHANGELOG.md | 2 +- src/pynwb/testing/mock/ecephys.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c1949712..9bffea855 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - Added support for python 3.12 and upgraded dependency versions. This also includes infrastructure updates for developers. @mavaylon1 [#1853](https://github.com/NeurodataWithoutBorders/pynwb/pull/1853) -- Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) +- Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) and [#1883](https://github.com/NeurodataWithoutBorders/pynwb/pull/1883) ### Bug fixes - Fix bug with reading file with linked `TimeSeriesReferenceVectorData` @rly [#1865](https://github.com/NeurodataWithoutBorders/pynwb/pull/1865) diff --git a/src/pynwb/testing/mock/ecephys.py b/src/pynwb/testing/mock/ecephys.py index 97831c3de..36796c267 100644 --- a/src/pynwb/testing/mock/ecephys.py +++ b/src/pynwb/testing/mock/ecephys.py @@ -129,7 +129,7 @@ def mock_Units( nwbfile: Optional[NWBFile] = None, ) -> Units: - units_table = Units() + units_table = Units(name="units") # This is for nwbfile.units= mock_Units() to work units_table.add_column(name="unit_name", description="a readable identifier for the unit") rng = np.random.default_rng(seed=seed) From ff1a03cb8300527bda3f356fb0c7c48f4b97faea Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 25 Apr 2024 13:39:04 -0500 Subject: [PATCH 22/29] Do not auto-set timezone, allow date (#1886) --- CHANGELOG.md | 6 +- docs/gallery/advanced_io/h5dataio.py | 6 +- docs/gallery/advanced_io/linking_data.py | 7 +- docs/gallery/advanced_io/parallelio.py | 2 +- .../advanced_io/plot_iterative_write.py | 8 +- docs/gallery/domain/images.py | 21 +-- docs/gallery/general/add_remove_containers.py | 4 +- docs/gallery/general/extensions.py | 19 ++- docs/gallery/general/object_id.py | 8 +- docs/gallery/general/plot_file.py | 2 +- docs/gallery/general/plot_timeintervals.py | 7 +- docs/gallery/general/scratch.py | 12 +- src/pynwb/file.py | 41 ++--- src/pynwb/io/file.py | 32 +++- src/pynwb/testing/mock/file.py | 3 +- src/pynwb/testing/testh5io.py | 7 +- tests/integration/hdf5/test_base.py | 5 +- tests/integration/hdf5/test_io.py | 4 +- .../integration/hdf5/test_modular_storage.py | 3 +- tests/integration/hdf5/test_nwbfile.py | 141 +++++++++++++++--- tests/unit/test_epoch.py | 3 +- tests/unit/test_extension.py | 5 +- tests/unit/test_file.py | 75 +++++++--- tests/unit/test_icephys.py | 13 +- tests/unit/test_scratch.py | 3 +- 25 files changed, 265 insertions(+), 172 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bffea855..b2cb599be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,13 @@ - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - Added support for python 3.12 and upgraded dependency versions. This also includes infrastructure updates for developers. @mavaylon1 [#1853](https://github.com/NeurodataWithoutBorders/pynwb/pull/1853) -- Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) and [#1883](https://github.com/NeurodataWithoutBorders/pynwb/pull/1883) +- Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) and [#1883](https://github.com/NeurodataWithoutBorders/pynwb/pull/1883) +- Allow datetimes without a timezone and without a time. @rly [#1886](https://github.com/NeurodataWithoutBorders/pynwb/pull/1886) +- No longer automatically set the timezone to the local timezone when not provided. [#1886](https://github.com/NeurodataWithoutBorders/pynwb/pull/1886) ### Bug fixes - Fix bug with reading file with linked `TimeSeriesReferenceVectorData` @rly [#1865](https://github.com/NeurodataWithoutBorders/pynwb/pull/1865) -- Fix bug where extra keyword arguments could not be passed to `NWBFile.add_{x}_column`` for use in custom `VectorData`` classes. @rly [#1861](https://github.com/NeurodataWithoutBorders/pynwb/pull/1861) +- Fix bug where extra keyword arguments could not be passed to `NWBFile.add_{x}_column` for use in custom `VectorData` classes. @rly [#1861](https://github.com/NeurodataWithoutBorders/pynwb/pull/1861) ## PyNWB 2.6.0 (February 21, 2024) diff --git a/docs/gallery/advanced_io/h5dataio.py b/docs/gallery/advanced_io/h5dataio.py index 3b4391655..5b5f73bc2 100644 --- a/docs/gallery/advanced_io/h5dataio.py +++ b/docs/gallery/advanced_io/h5dataio.py @@ -19,12 +19,9 @@ # from datetime import datetime - -from dateutil.tz import tzlocal - from pynwb import NWBFile -start_time = datetime(2017, 4, 3, 11, tzinfo=tzlocal()) +start_time = datetime(2017, 4, 3, hour=11, minute=0) nwbfile = NWBFile( session_description="demonstrate advanced HDF5 I/O features", @@ -32,7 +29,6 @@ session_start_time=start_time, ) - #################### # Normally if we create a :py:class:`~pynwb.base.TimeSeries` we would do diff --git a/docs/gallery/advanced_io/linking_data.py b/docs/gallery/advanced_io/linking_data.py index 2f79d1488..93f93c825 100644 --- a/docs/gallery/advanced_io/linking_data.py +++ b/docs/gallery/advanced_io/linking_data.py @@ -51,15 +51,12 @@ # sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_linking_data.png' from datetime import datetime -from uuid import uuid4 - import numpy as np -from dateutil.tz import tzlocal - from pynwb import NWBHDF5IO, NWBFile, TimeSeries +from uuid import uuid4 # Create the base data -start_time = datetime(2017, 4, 3, 11, tzinfo=tzlocal()) +start_time = datetime(2017, 4, 3, hour=11, minute=0) data = np.arange(1000).reshape((100, 10)) timestamps = np.arange(100) filename1 = "external1_example.nwb" diff --git a/docs/gallery/advanced_io/parallelio.py b/docs/gallery/advanced_io/parallelio.py index 53abdf239..f04ef4a87 100644 --- a/docs/gallery/advanced_io/parallelio.py +++ b/docs/gallery/advanced_io/parallelio.py @@ -32,7 +32,7 @@ # from datetime import datetime # from hdmf.backends.hdf5.h5_utils import H5DataIO # -# start_time = datetime(2018, 4, 25, 2, 30, 3, tzinfo=tz.gettz("US/Pacific")) +# start_time = datetime(2018, 4, 25, hour=2, minute=30, second=3) # fname = "test_parallel_pynwb.nwb" # rank = MPI.COMM_WORLD.rank # The process ID (integer 0-3 for 4-process run) # diff --git a/docs/gallery/advanced_io/plot_iterative_write.py b/docs/gallery/advanced_io/plot_iterative_write.py index 958981a0b..36b8bc0be 100644 --- a/docs/gallery/advanced_io/plot_iterative_write.py +++ b/docs/gallery/advanced_io/plot_iterative_write.py @@ -110,12 +110,8 @@ # sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_iterative_write.png' from datetime import datetime -from uuid import uuid4 - -from dateutil.tz import tzlocal - from pynwb import NWBHDF5IO, NWBFile, TimeSeries - +from uuid import uuid4 def write_test_file(filename, data, close_io=True): """ @@ -129,7 +125,7 @@ def write_test_file(filename, data, close_io=True): """ # Create a test NWBfile - start_time = datetime(2017, 4, 3, 11, tzinfo=tzlocal()) + start_time = datetime(2017, 4, 3, hour=11, minute=30) nwbfile = NWBFile( session_description="demonstrate iterative write", identifier=str(uuid4()), diff --git a/docs/gallery/domain/images.py b/docs/gallery/domain/images.py index d6eef24b3..b4511e3c5 100644 --- a/docs/gallery/domain/images.py +++ b/docs/gallery/domain/images.py @@ -19,23 +19,18 @@ 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 -from uuid import uuid4 - import numpy as np -from dateutil import tz -from dateutil.tz import tzlocal +import os from PIL import Image - from pynwb import NWBHDF5IO, NWBFile from pynwb.base import Images from pynwb.image import GrayscaleImage, ImageSeries, OpticalSeries, RGBAImage, RGBImage +from uuid import uuid4 +# Define file paths used in the tutorial nwbfile_path = os.path.abspath("images_tutorial.nwb") moviefiles_path = [ os.path.abspath("image/file_1.tiff"), @@ -50,12 +45,12 @@ # Create an :py:class:`~pynwb.file.NWBFile` object with the required fields # (``session_description``, ``identifier``, ``session_start_time``) and additional metadata. -session_start_time = datetime(2018, 4, 25, 2, 30, 3, tzinfo=tz.gettz("US/Pacific")) +session_start_time = datetime(2018, 4, 25, hour=2, minute=30) 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", ], @@ -138,13 +133,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 +147,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 = [ diff --git a/docs/gallery/general/add_remove_containers.py b/docs/gallery/general/add_remove_containers.py index 86aa373b2..fcb74e72a 100644 --- a/docs/gallery/general/add_remove_containers.py +++ b/docs/gallery/general/add_remove_containers.py @@ -33,7 +33,7 @@ nwbfile = NWBFile( session_description="demonstrate adding to an NWB file", identifier="NWB123", - session_start_time=datetime.datetime.now(datetime.timezone.utc), + session_start_time=datetime.datetime.now(), ) filename = "nwbfile.nwb" @@ -91,7 +91,7 @@ nwbfile = NWBFile( session_description="demonstrate export of an NWB file", identifier="NWB123", - session_start_time=datetime.datetime.now(datetime.timezone.utc), + session_start_time=datetime.datetime.now(), ) data1 = list(range(100, 200, 10)) timestamps1 = np.arange(10, dtype=float) diff --git a/docs/gallery/general/extensions.py b/docs/gallery/general/extensions.py index ddf9159c7..7e232f168 100644 --- a/docs/gallery/general/extensions.py +++ b/docs/gallery/general/extensions.py @@ -164,16 +164,15 @@ def __init__(self, **kwargs): # To demonstrate this, first we will make some simulated data using our extensions. from datetime import datetime - -from dateutil.tz import tzlocal - from pynwb import NWBFile +from uuid import uuid4 -start_time = datetime(2017, 4, 3, 11, tzinfo=tzlocal()) -create_date = datetime(2017, 4, 15, 12, tzinfo=tzlocal()) +session_start_time = datetime(2017, 4, 3, hour=11, minute=0) nwbfile = NWBFile( - "demonstrate caching", "NWB456", start_time, file_create_date=create_date + session_description="demonstrate caching", + identifier=str(uuid4()), + session_start_time=session_start_time, ) device = nwbfile.create_device(name="trodes_rig123") @@ -333,9 +332,6 @@ class PotatoSack(MultiContainerInterface): # Then use the objects (again, this would often be done in a different file). from datetime import datetime - -from dateutil.tz import tzlocal - from pynwb import NWBHDF5IO, NWBFile # You can add potatoes to a potato sack in different ways @@ -343,8 +339,11 @@ class PotatoSack(MultiContainerInterface): potato_sack.add_potato(Potato("potato2", 3.0, 4.0)) potato_sack.create_potato("big_potato", 10.0, 20.0) +session_start_time = datetime(2017, 4, 3, hour=12, minute=0) nwbfile = NWBFile( - "a file with metadata", "NB123A", datetime(2018, 6, 1, tzinfo=tzlocal()) + session_description="a file with metadata", + identifier=str(uuid4()), + session_start_time = session_start_time, ) pmod = nwbfile.create_processing_module("module_name", "desc") diff --git a/docs/gallery/general/object_id.py b/docs/gallery/general/object_id.py index a4de45625..25f125805 100644 --- a/docs/gallery/general/object_id.py +++ b/docs/gallery/general/object_id.py @@ -16,16 +16,14 @@ """ -from datetime import datetime +# sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_objectid.png' +from datetime import datetime import numpy as np -from dateutil.tz import tzlocal - -# sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_objectid.png' from pynwb import NWBFile, TimeSeries # set up the NWBFile -start_time = datetime(2019, 4, 3, 11, tzinfo=tzlocal()) +start_time = datetime(2019, 4, 3, hour=11, minute=0) nwbfile = NWBFile( session_description="demonstrate NWB object IDs", identifier="NWB456", diff --git a/docs/gallery/general/plot_file.py b/docs/gallery/general/plot_file.py index 5c59abf8d..5bfa837ee 100644 --- a/docs/gallery/general/plot_file.py +++ b/docs/gallery/general/plot_file.py @@ -165,7 +165,7 @@ # Use keyword arguments when constructing :py:class:`~pynwb.file.NWBFile` objects. # -session_start_time = datetime(2018, 4, 25, 2, 30, 3, tzinfo=tz.gettz("US/Pacific")) +session_start_time = datetime(2018, 4, 25, hour=2, minute=30, second=3, tzinfo=tz.gettz("US/Pacific")) nwbfile = NWBFile( session_description="Mouse exploring an open field", # required diff --git a/docs/gallery/general/plot_timeintervals.py b/docs/gallery/general/plot_timeintervals.py index 4069fd4a4..3a4ad306a 100644 --- a/docs/gallery/general/plot_timeintervals.py +++ b/docs/gallery/general/plot_timeintervals.py @@ -36,18 +36,15 @@ # sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_timeintervals.png' from datetime import datetime -from uuid import uuid4 - import numpy as np -from dateutil.tz import tzlocal - from pynwb import NWBFile, TimeSeries +from uuid import uuid4 # create the NWBFile nwbfile = NWBFile( session_description="my first synthetic recording", # required identifier=str(uuid4()), # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal()), # required + session_start_time=datetime(2017, 4, 3, hour=11), # required experimenter="Baggins, Bilbo", # optional lab="Bag End Laboratory", # optional institution="University of Middle Earth at the Shire", # optional diff --git a/docs/gallery/general/scratch.py b/docs/gallery/general/scratch.py index 0e00c5e96..9083e4081 100644 --- a/docs/gallery/general/scratch.py +++ b/docs/gallery/general/scratch.py @@ -27,24 +27,20 @@ # To demonstrate linking and scratch space, lets assume we are starting with some acquired data. # -from datetime import datetime +# sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_scratch.png' +from datetime import datetime import numpy as np -from dateutil.tz import tzlocal - -# sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnails_scratch.png' from pynwb import NWBHDF5IO, NWBFile, TimeSeries # set up the NWBFile -start_time = datetime(2019, 4, 3, 11, tzinfo=tzlocal()) -create_date = datetime(2019, 4, 15, 12, tzinfo=tzlocal()) +start_time = datetime(2019, 4, 3, hour=11, minute=0) nwb = NWBFile( session_description="demonstrate NWBFile scratch", # required identifier="NWB456", # required session_start_time=start_time, # required - file_create_date=create_date, -) # optional +) # make some fake data timestamps = np.linspace(0, 100, 1024) diff --git a/src/pynwb/file.py b/src/pynwb/file.py index 0b294e873..06b7fbe07 100644 --- a/src/pynwb/file.py +++ b/src/pynwb/file.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, date, timedelta from dateutil.tz import tzlocal from collections.abc import Iterable from warnings import warn @@ -104,8 +104,8 @@ class Subject(NWBContainer): 'doc': ('The weight of the subject, including units. Using kilograms is recommended. e.g., "0.02 kg". ' 'If a float is provided, then the weight will be stored as "[value] kg".'), 'default': None}, - {'name': 'date_of_birth', 'type': datetime, 'default': None, - 'doc': 'The datetime of the date of birth. May be supplied instead of age.'}, + {'name': 'date_of_birth', 'type': (datetime, date), 'default': None, + 'doc': 'The date of birth, which may include time and timezone. May be supplied instead of age.'}, {'name': 'strain', 'type': str, 'doc': 'The strain of the subject, e.g., "C57BL/6J"', 'default': None}, ) def __init__(self, **kwargs): @@ -141,10 +141,6 @@ def __init__(self, **kwargs): if isinstance(args_to_set["age"], timedelta): args_to_set["age"] = pd.Timedelta(args_to_set["age"]).isoformat() - date_of_birth = args_to_set['date_of_birth'] - if date_of_birth and date_of_birth.tzinfo is None: - args_to_set['date_of_birth'] = _add_missing_timezone(date_of_birth) - for key, val in args_to_set.items(): setattr(self, key, val) @@ -308,10 +304,11 @@ class NWBFile(MultiContainerInterface, HERDManager): @docval({'name': 'session_description', 'type': str, 'doc': 'a description of the session where this data was generated'}, {'name': 'identifier', 'type': str, 'doc': 'a unique text identifier for the file'}, - {'name': 'session_start_time', 'type': datetime, 'doc': 'the start date and time of the recording session'}, - {'name': 'file_create_date', 'type': ('array_data', datetime), + {'name': 'session_start_time', 'type': (datetime, date), + 'doc': 'the start date and time of the recording session'}, + {'name': 'file_create_date', 'type': ('array_data', datetime, date), 'doc': 'the date and time the file was created and subsequent modifications made', 'default': None}, - {'name': 'timestamps_reference_time', 'type': datetime, + {'name': 'timestamps_reference_time', 'type': (datetime, date), 'doc': 'date and time corresponding to time zero of all timestamps; defaults to value ' 'of session_start_time', 'default': None}, {'name': 'experimenter', 'type': (tuple, list, str), @@ -466,26 +463,18 @@ def __init__(self, **kwargs): kwargs['name'] = 'root' super().__init__(**kwargs) - # add timezone to session_start_time if missing - session_start_time = args_to_set['session_start_time'] - if session_start_time.tzinfo is None: - args_to_set['session_start_time'] = _add_missing_timezone(session_start_time) - # set timestamps_reference_time to session_start_time if not provided - # if provided, ensure that it has a timezone timestamps_reference_time = args_to_set['timestamps_reference_time'] if timestamps_reference_time is None: args_to_set['timestamps_reference_time'] = args_to_set['session_start_time'] - elif timestamps_reference_time.tzinfo is None: - raise ValueError("'timestamps_reference_time' must be a timezone-aware datetime object.") # convert file_create_date to list and add timezone if missing file_create_date = args_to_set['file_create_date'] if file_create_date is None: file_create_date = datetime.now(tzlocal()) - if isinstance(file_create_date, datetime): + if isinstance(file_create_date, (datetime, date)): file_create_date = [file_create_date] - args_to_set['file_create_date'] = list(map(_add_missing_timezone, file_create_date)) + args_to_set['file_create_date'] = file_create_date # backwards-compatibility code for ic_electrodes / icephys_electrodes icephys_electrodes = args_to_set['icephys_electrodes'] @@ -1155,18 +1144,6 @@ def copy(self): return NWBFile(**kwargs) -def _add_missing_timezone(date): - """ - Add local timezone information on a datetime object if it is missing. - """ - if not isinstance(date, datetime): - raise ValueError("require datetime object") - if date.tzinfo is None: - warn("Date is missing timezone information. Updating to local timezone.", stacklevel=2) - return date.replace(tzinfo=tzlocal()) - return date - - def _tablefunc(table_name, description, columns): t = DynamicTable(name=table_name, description=description) for c in columns: diff --git a/src/pynwb/io/file.py b/src/pynwb/io/file.py index 1908c6b31..15c2c1c06 100644 --- a/src/pynwb/io/file.py +++ b/src/pynwb/io/file.py @@ -1,4 +1,4 @@ -from dateutil.parser import parse as dateutil_parse +import datetime from hdmf.build import ObjectMapper @@ -8,6 +8,22 @@ from .utils import get_nwb_version +def parse_datetime(datestr): + """Parse an ISO 8601 date string into a datetime object or a date object. + + If the date string does not contain a time component, then parse into a date object. + + :param datestr: str + :return: datetime.datetime or datetime.date + """ + if isinstance(datestr, bytes): + datestr = datestr.decode("utf-8") + dt = datetime.datetime.fromisoformat(datestr) + if "T" not in datestr: + dt = dt.date() + return dt + + @register_map(NWBFile) class NWBFileMap(ObjectMapper): @@ -157,19 +173,19 @@ def scratch(self, builder, manager): @ObjectMapper.constructor_arg('session_start_time') def dateconversion(self, builder, manager): datestr = builder.get('session_start_time').data - date = dateutil_parse(datestr) - return date + dt = parse_datetime(datestr) + return dt @ObjectMapper.constructor_arg('timestamps_reference_time') def dateconversion_trt(self, builder, manager): datestr = builder.get('timestamps_reference_time').data - date = dateutil_parse(datestr) - return date + dt = parse_datetime(datestr) + return dt @ObjectMapper.constructor_arg('file_create_date') def dateconversion_list(self, builder, manager): datestr = builder.get('file_create_date').data - dates = list(map(dateutil_parse, datestr)) + dates = list(map(parse_datetime, datestr)) return dates @ObjectMapper.constructor_arg('file_name') @@ -223,8 +239,8 @@ def dateconversion(self, builder, manager): return else: datestr = dob_builder.data - date = dateutil_parse(datestr) - return date + dt = parse_datetime(datestr) + return dt @ObjectMapper.constructor_arg("age__reference") def age_reference_none(self, builder, manager): diff --git a/src/pynwb/testing/mock/file.py b/src/pynwb/testing/mock/file.py index 943f86dcb..50369e7e1 100644 --- a/src/pynwb/testing/mock/file.py +++ b/src/pynwb/testing/mock/file.py @@ -1,7 +1,6 @@ from typing import Optional from uuid import uuid4 from datetime import datetime -from dateutil.tz import tzlocal from ...file import NWBFile, Subject from .utils import name_generator @@ -10,7 +9,7 @@ def mock_NWBFile( session_description: str = 'session_description', identifier: Optional[str] = None, - session_start_time: datetime = datetime(1970, 1, 1, tzinfo=tzlocal()), + session_start_time: datetime = datetime(1970, 1, 1), **kwargs ): return NWBFile( diff --git a/src/pynwb/testing/testh5io.py b/src/pynwb/testing/testh5io.py index 7234e79f5..45ae8cebe 100644 --- a/src/pynwb/testing/testh5io.py +++ b/src/pynwb/testing/testh5io.py @@ -1,5 +1,4 @@ from datetime import datetime -from dateutil.tz import tzlocal, tzutc import os from abc import ABCMeta, abstractmethod import warnings @@ -33,8 +32,8 @@ def getContainer(self, nwbfile): def setUp(self): self.container = self.setUpContainer() - self.start_time = datetime(1971, 1, 1, 12, tzinfo=tzutc()) - self.create_date = datetime(2018, 4, 15, 12, tzinfo=tzlocal()) + self.start_time = datetime(1971, 1, 1, 12) + self.create_date = datetime(2018, 4, 15, 12) self.container_type = self.container.__class__.__name__ self.filename = 'test_%s.nwb' % self.container_type self.export_filename = 'test_export_%s.nwb' % self.container_type @@ -226,7 +225,7 @@ def setUp(self): container_type = self.getContainerType().replace(" ", "_") session_description = 'A file to test writing and reading a %s' % container_type identifier = 'TEST_%s' % container_type - session_start_time = datetime(1971, 1, 1, 12, tzinfo=tzutc()) + session_start_time = datetime(1971, 1, 1, 12) self.nwbfile = NWBFile( session_description=session_description, identifier=identifier, diff --git a/tests/integration/hdf5/test_base.py b/tests/integration/hdf5/test_base.py index 60f8510ff..75c346012 100644 --- a/tests/integration/hdf5/test_base.py +++ b/tests/integration/hdf5/test_base.py @@ -1,6 +1,5 @@ import numpy as np from datetime import datetime -from dateutil.tz import tzlocal from pynwb import TimeSeries, NWBFile, NWBHDF5IO from pynwb.base import Images, Image, ImageReferences @@ -34,7 +33,7 @@ def test_timestamps_linking(self): tsa = TimeSeries(name='a', data=np.linspace(0, 1, 1000), timestamps=np.arange(1000.), unit='m') tsb = TimeSeries(name='b', data=np.linspace(0, 1, 1000), timestamps=tsa, unit='m') nwbfile = NWBFile(identifier='foo', - session_start_time=datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal()), + session_start_time=datetime(2017, 5, 1, 12, 0, 0), session_description='bar') nwbfile.add_acquisition(tsa) nwbfile.add_acquisition(tsb) @@ -52,7 +51,7 @@ def test_data_linking(self): tsb = TimeSeries(name='b', data=tsa, timestamps=np.arange(1000.), unit='m') tsc = TimeSeries(name='c', data=tsb, timestamps=np.arange(1000.), unit='m') nwbfile = NWBFile(identifier='foo', - session_start_time=datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal()), + session_start_time=datetime(2017, 5, 1, 12, 0, 0), session_description='bar') nwbfile.add_acquisition(tsa) nwbfile.add_acquisition(tsb) diff --git a/tests/integration/hdf5/test_io.py b/tests/integration/hdf5/test_io.py index d68334c89..da22a0651 100644 --- a/tests/integration/hdf5/test_io.py +++ b/tests/integration/hdf5/test_io.py @@ -245,7 +245,7 @@ class TestAppend(TestCase): def setUp(self): self.nwbfile = NWBFile(session_description='hi', identifier='hi', - session_start_time=datetime(1970, 1, 1, 12, tzinfo=tzutc())) + session_start_time=datetime(1970, 1, 1, 12)) self.path = "test_append.nwb" def tearDown(self): @@ -312,7 +312,7 @@ class TestH5DataIO(TestCase): def setUp(self): self.nwbfile = NWBFile(session_description='a', identifier='b', - session_start_time=datetime(1970, 1, 1, 12, tzinfo=tzutc())) + session_start_time=datetime(1970, 1, 1, 12)) self.path = "test_pynwb_io_hdf5_h5dataIO.h5" def tearDown(self): diff --git a/tests/integration/hdf5/test_modular_storage.py b/tests/integration/hdf5/test_modular_storage.py index fba5d02db..09c916bfb 100644 --- a/tests/integration/hdf5/test_modular_storage.py +++ b/tests/integration/hdf5/test_modular_storage.py @@ -1,7 +1,6 @@ import os import gc from datetime import datetime -from dateutil.tz import tzutc import numpy as np from hdmf.backends.hdf5 import HDF5IO @@ -19,7 +18,7 @@ def setUp(self): self.link_filename = os.path.join(os.getcwd(), 'test_time_series_modular_link.nwb') # Make the data container file write - self.start_time = datetime(1971, 1, 1, 12, tzinfo=tzutc()) + self.start_time = datetime(1971, 1, 1, 12) self.data = np.arange(2000).reshape((1000, 2)) self.timestamps = np.linspace(0, 1, 1000) # The container before roundtrip diff --git a/tests/integration/hdf5/test_nwbfile.py b/tests/integration/hdf5/test_nwbfile.py index e164ec649..641928598 100644 --- a/tests/integration/hdf5/test_nwbfile.py +++ b/tests/integration/hdf5/test_nwbfile.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, date from dateutil.tz import tzlocal, tzutc import pandas as pd import numpy as np @@ -21,7 +21,12 @@ def setUp(self): """ Set up an NWBFile object with an acquisition TimeSeries, analysis TimeSeries, and a processing module """ self.start_time = datetime(1970, 1, 1, 12, tzinfo=tzutc()) self.ref_time = datetime(1979, 1, 1, 0, tzinfo=tzutc()) - self.create_date = datetime(2017, 4, 15, 12, tzinfo=tzlocal()) + # try some dates with/without timezone and time + self.create_date = [ + datetime(2017, 5, 1, 12, tzinfo=tzlocal()), + datetime(2017, 5, 2, 13), + datetime(2017, 5, 2), + ] self.manager = get_manager() self.filename = 'test_nwbfileio.h5' self.nwbfile = NWBFile(session_description='a test NWB File', @@ -152,16 +157,61 @@ def getContainer(self, nwbfile): return nwbfile +class TestNWBFileNoTimezoneRoundTrip(TestNWBFileIO): + """ Test that an NWBFile with no timezone information can be written to and read from file """ + + def build_nwbfile(self): + description = 'test nwbfile no time' + identifier = 'TEST_no_time' + start_time = datetime(2024, 4, 10, 0, 21) + + self.container = NWBFile( + session_description=description, + identifier=identifier, + session_start_time=start_time + ) + + def roundtripContainer(self, cache_spec=False): + self.read_nwbfile = super().roundtripContainer(cache_spec=cache_spec) + self.assertEqual(self.read_nwbfile.session_start_time, self.container.session_start_time) + self.assertIsNone(self.read_nwbfile.session_start_time.tzinfo) + return self.read_nwbfile + + +class TestNWBFileNoTimeRoundTrip(TestNWBFileIO): + """ Test that an NWBFile with no time information can be written to and read from file """ + + def build_nwbfile(self): + description = 'test nwbfile no time' + identifier = 'TEST_no_time' + start_time = date(2024, 4, 9) + + self.container = NWBFile( + session_description=description, + identifier=identifier, + session_start_time=start_time + ) + + def roundtripContainer(self, cache_spec=False): + self.read_nwbfile = super().roundtripContainer(cache_spec=cache_spec) + self.assertEqual(self.read_nwbfile.session_start_time, self.container.session_start_time) + self.assertIsInstance(self.read_nwbfile.session_start_time, date) + self.assertNotIsInstance(self.read_nwbfile.session_start_time, datetime) + return self.read_nwbfile + + class TestExperimentersConstructorRoundtrip(TestNWBFileIO): """ Test that a list of multiple experimenters in a constructor is written to and read from file """ def build_nwbfile(self): description = 'test nwbfile experimenter' identifier = 'TEST_experimenter' - self.nwbfile = NWBFile(session_description=description, - identifier=identifier, - session_start_time=self.start_time, - experimenter=('experimenter1', 'experimenter2')) + self.container = NWBFile( + session_description=description, + identifier=identifier, + session_start_time=self.start_time, + experimenter=('experimenter1', 'experimenter2') + ) class TestExperimentersSetterRoundtrip(TestNWBFileIO): @@ -170,10 +220,12 @@ class TestExperimentersSetterRoundtrip(TestNWBFileIO): def build_nwbfile(self): description = 'test nwbfile experimenter' identifier = 'TEST_experimenter' - self.nwbfile = NWBFile(session_description=description, - identifier=identifier, - session_start_time=self.start_time) - self.nwbfile.experimenter = ('experimenter1', 'experimenter2') + self.container = NWBFile( + session_description=description, + identifier=identifier, + session_start_time=self.start_time + ) + self.container.experimenter = ('experimenter1', 'experimenter2') class TestPublicationsConstructorRoundtrip(TestNWBFileIO): @@ -182,10 +234,12 @@ class TestPublicationsConstructorRoundtrip(TestNWBFileIO): def build_nwbfile(self): description = 'test nwbfile publications' identifier = 'TEST_publications' - self.nwbfile = NWBFile(session_description=description, - identifier=identifier, - session_start_time=self.start_time, - related_publications=('pub1', 'pub2')) + self.container = NWBFile( + session_description=description, + identifier=identifier, + session_start_time=self.start_time, + related_publications=('pub1', 'pub2') + ) class TestPublicationsSetterRoundtrip(TestNWBFileIO): @@ -194,10 +248,12 @@ class TestPublicationsSetterRoundtrip(TestNWBFileIO): def build_nwbfile(self): description = 'test nwbfile publications' identifier = 'TEST_publications' - self.nwbfile = NWBFile(session_description=description, - identifier=identifier, - session_start_time=self.start_time) - self.nwbfile.related_publications = ('pub1', 'pub2') + self.container = NWBFile( + session_description=description, + identifier=identifier, + session_start_time=self.start_time + ) + self.container.related_publications = ('pub1', 'pub2') class TestSubjectIO(NWBH5IOMixin, TestCase): @@ -251,6 +307,55 @@ def getContainer(self, nwbfile): return nwbfile.subject +class TestSubjectDOBNoDateSetIO(NWBH5IOMixin, TestCase): + + def setUpContainer(self): + """ Return the test Subject """ + return Subject( + age="P90D", + description="An unfortunate rat", + genotype="WT", + sex="M", + species="Rattus norvegicus", + subject_id="RAT123", + weight="2 kg", + date_of_birth=date(2024, 4, 9), + strain="my_strain", + ) + + def addContainer(self, nwbfile): + """ Add the test Subject to the given NWBFile """ + nwbfile.subject = self.container + + def getContainer(self, nwbfile): + """ Return the test Subject from the given NWBFile """ + return nwbfile.subject + + +class TestSubjectMinimalSetIO(NWBH5IOMixin, TestCase): + + def setUpContainer(self): + """ Return the test Subject """ + return Subject( + age="P90D", + description="An unfortunate rat", + genotype="WT", + sex="M", + species="Rattus norvegicus", + subject_id="RAT123", + weight="2 kg", + strain="my_strain", + ) + + def addContainer(self, nwbfile): + """ Add the test Subject to the given NWBFile """ + nwbfile.subject = self.container + + def getContainer(self, nwbfile): + """ Return the test Subject from the given NWBFile """ + return nwbfile.subject + + class TestEmptySubjectIO(TestSubjectIO): def setUpContainer(self): diff --git a/tests/unit/test_epoch.py b/tests/unit/test_epoch.py index 318ad3943..4bf2637df 100644 --- a/tests/unit/test_epoch.py +++ b/tests/unit/test_epoch.py @@ -1,7 +1,6 @@ import numpy as np import pandas as pd from datetime import datetime -from dateutil import tz from pynwb.epoch import TimeIntervals from pynwb import TimeSeries, NWBFile @@ -67,7 +66,7 @@ def test_dataframe_roundtrip_drop_ts(self): self.assertEqual(obtained.loc[2, 'foo'], df.loc[2, 'foo']) def test_no_tags(self): - nwbfile = NWBFile("a file with header data", "NB123A", datetime(1970, 1, 1, tzinfo=tz.tzutc())) + nwbfile = NWBFile("a file with header data", "NB123A", datetime(1970, 1, 1)) df = self.get_dataframe() for i, row in df.iterrows(): nwbfile.add_epoch(start_time=row['start_time'], stop_time=row['stop_time']) diff --git a/tests/unit/test_extension.py b/tests/unit/test_extension.py index 7664bbf22..abbb6511a 100644 --- a/tests/unit/test_extension.py +++ b/tests/unit/test_extension.py @@ -2,7 +2,6 @@ import random import string from datetime import datetime -from dateutil.tz import tzlocal from tempfile import gettempdir from hdmf.spec import RefSpec @@ -108,7 +107,7 @@ def __init__(self, **kwargs): super().__init__(**kwargs) self.test_attr = test_attr - nwbfile = NWBFile("a file with header data", "NB123A", datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal())) + nwbfile = NWBFile("a file with header data", "NB123A", datetime(2017, 5, 1, 12, 0, 0)) nwbfile.add_lab_meta_data(MyTestMetaData(name='test_name', test_attr=5.)) @@ -128,7 +127,7 @@ def test_lab_meta_auto(self): MyTestMetaData = get_class('MyTestMetaData', self.prefix) - nwbfile = NWBFile("a file with header data", "NB123A", datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal())) + nwbfile = NWBFile("a file with header data", "NB123A", datetime(2017, 5, 1, 12, 0, 0)) nwbfile.add_lab_meta_data(MyTestMetaData(name='test_name', test_attr=5.)) diff --git a/tests/unit/test_file.py b/tests/unit/test_file.py index 98446fa46..fc44dfdd8 100644 --- a/tests/unit/test_file.py +++ b/tests/unit/test_file.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -from datetime import datetime, timedelta +from datetime import datetime, date, timedelta from dateutil.tz import tzlocal, tzutc from hdmf.common import DynamicTable @@ -9,7 +9,7 @@ from hdmf.utils import docval, get_docval, popargs from pynwb import NWBFile, TimeSeries, NWBHDF5IO from pynwb.base import Image, Images -from pynwb.file import Subject, ElectrodeTable, _add_missing_timezone +from pynwb.file import Subject, ElectrodeTable from pynwb.epoch import TimeIntervals from pynwb.ecephys import ElectricalSeries from pynwb.testing import TestCase, remove_test_file @@ -19,9 +19,10 @@ class NWBFileTest(TestCase): def setUp(self): self.start = datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal()) self.ref_time = datetime(1979, 1, 1, 0, tzinfo=tzutc()) + # try some dates with/without timezone and time self.create = [datetime(2017, 5, 1, 12, tzinfo=tzlocal()), - datetime(2017, 5, 2, 13, 0, 0, 1, tzinfo=tzutc()), - datetime(2017, 5, 2, 14, tzinfo=tzutc())] + datetime(2017, 5, 2, 13), + datetime(2017, 5, 2)] self.path = 'nwbfile_test.h5' self.nwbfile = NWBFile(session_description='a test session description for a test NWBFile', identifier='FILE123', @@ -502,6 +503,22 @@ def test_multi_publications(self): related_publications=('pub1', 'pub2')) self.assertTupleEqual(self.nwbfile.related_publications, ('pub1', 'pub2')) + def test_session_start_time_no_timezone(self): + self.nwbfile = NWBFile( + session_description='a test session description for a test NWBFile', + identifier='FILE123', + session_start_time=datetime(2024, 4, 10, 0, 21), + ) + self.assertIsNone(self.nwbfile.session_start_time.tzinfo) + + def test_session_start_time_no_time(self): + self.nwbfile = NWBFile( + session_description='a test session description for a test NWBFile', + identifier='FILE123', + session_start_time=date(2024, 4, 10), + ) + self.assertEqual(self.nwbfile.session_start_time, date(2024, 4, 10)) + class SubjectTest(TestCase): def setUp(self): @@ -517,7 +534,7 @@ def setUp(self): date_of_birth=datetime(2017, 5, 1, 12, tzinfo=tzlocal()), strain='my_strain', ) - self.start = datetime(2017, 5, 1, 12, tzinfo=tzlocal()) + self.start = datetime(2017, 5, 1, 12) self.path = 'nwbfile_test.h5' self.nwbfile = NWBFile( 'a test session description for a test NWBFile', @@ -586,6 +603,35 @@ def test_subject_age_duration(self): self.assertEqual(subject.age, "P1DT3H46M39S") + def test_dob_no_timezone(self): + self.subject = Subject( + age='P90D', + age__reference="birth", + description='An unfortunate rat', + genotype='WT', + sex='M', + species='Rattus norvegicus', + subject_id='RAT123', + weight='2 kg', + date_of_birth=datetime(2024, 4, 10, 0, 21), + strain='my_strain', + ) + + def test_dob_no_time(self): + self.subject = Subject( + age='P90D', + age__reference="birth", + description='An unfortunate rat', + genotype='WT', + sex='M', + species='Rattus norvegicus', + subject_id='RAT123', + weight='2 kg', + date_of_birth=date(2024, 4, 10), + strain='my_strain', + ) + + class TestCacheSpec(TestCase): """Test whether the file can be written and read when caching the spec.""" @@ -643,22 +689,3 @@ def test_reftime_default(self): # 'timestamps_reference_time' should default to 'session_start_time' self.assertEqual(self.nwbfile.timestamps_reference_time, self.start_time) - -class TestTimestampsRefAware(TestCase): - def setUp(self): - self.start_time = datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal()) - self.ref_time_notz = datetime(1979, 1, 1, 0, 0, 0) - - def test_reftime_tzaware(self): - with self.assertRaises(ValueError): - # 'timestamps_reference_time' must be a timezone-aware datetime - NWBFile('test session description', - 'TEST124', - self.start_time, - timestamps_reference_time=self.ref_time_notz) - - -class TestTimezone(TestCase): - def test_raise_warning__add_missing_timezone(self): - with self.assertWarnsWith(UserWarning, "Date is missing timezone information. Updating to local timezone."): - _add_missing_timezone(datetime(2017, 5, 1, 12)) diff --git a/tests/unit/test_icephys.py b/tests/unit/test_icephys.py index e0e8332f9..8ff1a67ba 100644 --- a/tests/unit/test_icephys.py +++ b/tests/unit/test_icephys.py @@ -14,7 +14,6 @@ from pynwb.testing import TestCase from pynwb.file import NWBFile # Needed to test icephys functionality defined on NWBFile from datetime import datetime -from dateutil.tz import tzlocal def GetElectrode(): @@ -46,7 +45,7 @@ def test_sweep_table_depractation_warn(self): _ = NWBFile( session_description='NWBFile icephys test', identifier='NWB123', # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal()), + session_start_time=datetime(2017, 4, 3, 11), ic_electrodes=[self.icephys_electrode, ], sweep_table=SweepTable()) @@ -57,14 +56,14 @@ def test_ic_electrodes_parameter_deprecation(self): _ = NWBFile( session_description='NWBFile icephys test', identifier='NWB123', # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal()), + session_start_time=datetime(2017, 4, 3, 11), ic_electrodes=[self.icephys_electrode, ]) def test_icephys_electrodes_parameter(self): nwbfile = NWBFile( session_description='NWBFile icephys test', identifier='NWB123', # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal()), + session_start_time=datetime(2017, 4, 3, 11), icephys_electrodes=[self.icephys_electrode, ]) self.assertEqual(nwbfile.get_icephys_electrode('test_iS'), self.icephys_electrode) @@ -73,7 +72,7 @@ def test_add_ic_electrode_deprecation(self): nwbfile = NWBFile( session_description='NWBFile icephys test', identifier='NWB123', # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal())) + session_start_time=datetime(2017, 4, 3, 11)) msg = "NWBFile.add_ic_electrode has been replaced by NWBFile.add_icephys_electrode." with self.assertWarnsWith(DeprecationWarning, msg): @@ -83,7 +82,7 @@ def test_ic_electrodes_attribute_deprecation(self): nwbfile = NWBFile( session_description='NWBFile icephys test', identifier='NWB123', # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal()), + session_start_time=datetime(2017, 4, 3, 11), icephys_electrodes=[self.icephys_electrode, ]) # make sure NWBFile.ic_electrodes property warns @@ -100,7 +99,7 @@ def test_create_ic_electrode_deprecation(self): nwbfile = NWBFile( session_description='NWBFile icephys test', identifier='NWB123', # required - session_start_time=datetime(2017, 4, 3, 11, tzinfo=tzlocal())) + session_start_time=datetime(2017, 4, 3, 11)) device = Device(name='device_name') msg = "NWBFile.create_ic_electrode has been replaced by NWBFile.create_icephys_electrode." with self.assertWarnsWith(DeprecationWarning, msg): diff --git a/tests/unit/test_scratch.py b/tests/unit/test_scratch.py index 398ae2f78..c04a00e99 100644 --- a/tests/unit/test_scratch.py +++ b/tests/unit/test_scratch.py @@ -1,5 +1,4 @@ from datetime import datetime -from dateutil.tz import tzlocal import numpy as np from numpy.testing import assert_array_equal import pandas as pd @@ -15,7 +14,7 @@ def setUp(self): self.nwbfile = NWBFile( session_description='a file to test writing and reading scratch data', identifier='TEST_scratch', - session_start_time=datetime(2017, 5, 1, 12, 0, 0, tzinfo=tzlocal()) + session_start_time=datetime(2017, 5, 1, 12, 0, 0) ) def test_constructor_list(self): From 54b42b4b0527465e8d547804ac078ccccf75c499 Mon Sep 17 00:00:00 2001 From: Steph Prince <40640337+stephprince@users.noreply.github.com> Date: Thu, 25 Apr 2024 12:06:05 -0700 Subject: [PATCH 23/29] ignore cache warnings in sphinx (#1893) Co-authored-by: Ryan Ly --- docs/source/conf.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/source/conf.py b/docs/source/conf.py index 6f69fc4c1..4eaf1a19b 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -168,6 +168,8 @@ def __call__(self, filename): nitpick_ignore = [('py:class', 'Intracomm'), ('py:class', 'BaseStorageSpec')] +suppress_warnings = ["config.cache"] + # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] From d7f5f26b9d46b61790dd3e152089ab8679263ea0 Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Mon, 29 Apr 2024 07:53:06 -0700 Subject: [PATCH 24/29] Support py3.9/3.9 on workflows (#1895) * Support py3.9/3.9 on workflows * Update run_tests.yml --- .github/workflows/run_all_tests.yml | 6 +++--- .github/workflows/run_tests.yml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/run_all_tests.yml b/.github/workflows/run_all_tests.yml index 1935c7392..d11b06d82 100644 --- a/.github/workflows/run_all_tests.yml +++ b/.github/workflows/run_all_tests.yml @@ -36,8 +36,8 @@ jobs: - { name: windows-python3.12 , test-tox-env: py312 , build-tox-env: build-py312 , python-ver: "3.12", os: windows-latest } - { name: windows-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: windows-latest } - { name: windows-python3.12-prerelease, test-tox-env: py312-prerelease, build-tox-env: build-py312-prerelease, python-ver: "3.11", os: windows-latest } - - { name: macos-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: macos-latest } - - { name: macos-python3.9 , test-tox-env: py39 , build-tox-env: build-py39 , python-ver: "3.9" , os: macos-latest } + - { name: macos-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: macos-13 } + - { name: macos-python3.9 , test-tox-env: py39 , build-tox-env: build-py39 , python-ver: "3.9" , os: macos-13 } - { name: macos-python3.10 , test-tox-env: py310 , build-tox-env: build-py310 , python-ver: "3.10", os: macos-latest } - { name: macos-python3.11 , test-tox-env: py311 , build-tox-env: build-py311 , python-ver: "3.11", os: macos-latest } - { name: macos-python3.12 , test-tox-env: py312 , build-tox-env: build-py312 , python-ver: "3.12", os: macos-latest } @@ -95,7 +95,7 @@ jobs: - { name: windows-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: windows-latest } - { name: windows-gallery-python3.12-upgraded , test-tox-env: gallery-py312-upgraded , python-ver: "3.12", os: windows-latest } - { name: windows-gallery-python3.12-prerelease, test-tox-env: gallery-py312-prerelease, python-ver: "3.12", os: windows-latest } - - { name: macos-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: macos-latest } + - { name: macos-gallery-python3.8-minimum , test-tox-env: gallery-py38-minimum , python-ver: "3.8" , os: macos-13 } - { name: macos-gallery-python3.12-upgraded , test-tox-env: gallery-py312-upgraded , python-ver: "3.12", os: macos-latest } - { name: macos-gallery-python3.12-prerelease , test-tox-env: gallery-py312-prerelease, python-ver: "3.12", os: macos-latest } steps: diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index d2b3d169a..c0d520429 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -24,7 +24,7 @@ jobs: - { name: linux-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: ubuntu-latest , upload-wheels: true } - { name: windows-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: windows-latest } - { name: windows-python3.12-upgraded , test-tox-env: py312-upgraded , build-tox-env: build-py312-upgraded , python-ver: "3.12", os: windows-latest } - - { name: macos-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: macos-latest } + - { name: macos-python3.8-minimum , test-tox-env: py38-minimum , build-tox-env: build-py38-minimum , python-ver: "3.8" , os: macos-13 } steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 From 73d6dfa929215329c9df48a4657634c058d0c324 Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Wed, 1 May 2024 17:22:47 -0700 Subject: [PATCH 25/29] Update pyproject.toml (#1898) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 1bae035af..7f5f71663 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,7 +34,7 @@ classifiers = [ dependencies = [ "h5py>=2.10", "hdmf>=3.12.2", - "numpy>=1.18", # match the version used in hdmf + "numpy>=1.18, <2.0", # pin below 2.0 until HDMF supports numpy 2.0 "pandas>=1.1.5", "python-dateutil>=2.7.3", ] From 6cfcf398320b6620616d4b0747e04d488a683ffc Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Thu, 2 May 2024 09:24:16 -0700 Subject: [PATCH 26/29] Update run_all_tests.yml for ros3 using macos-13 (#1899) --- .github/workflows/run_all_tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/run_all_tests.yml b/.github/workflows/run_all_tests.yml index d11b06d82..7a65434b9 100644 --- a/.github/workflows/run_all_tests.yml +++ b/.github/workflows/run_all_tests.yml @@ -198,7 +198,7 @@ jobs: include: - { name: conda-linux-python3.12-ros3 , python-ver: "3.12", os: ubuntu-latest } - { name: conda-windows-python3.12-ros3, python-ver: "3.12", os: windows-latest } - - { name: conda-macos-python3.12-ros3 , python-ver: "3.12", os: macos-latest } + - { name: conda-macos-python3.12-ros3 , python-ver: "3.12", os: macos-13 } # This is due to DANDI not supporting osx-arm64. Will support macos-latest when this changes. steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 @@ -245,7 +245,7 @@ jobs: include: - { name: conda-linux-gallery-python3.12-ros3 , python-ver: "3.12", os: ubuntu-latest } - { name: conda-windows-gallery-python3.12-ros3, python-ver: "3.12", os: windows-latest } - - { name: conda-macos-gallery-python3.12-ros3 , python-ver: "3.12", os: macos-latest } + - { name: conda-macos-gallery-python3.12-ros3 , python-ver: "3.12", os: macos-13 } # This is due to DANDI not supporting osx-arm64. Will support macos-latest when this changes. steps: - name: Cancel non-latest runs uses: styfle/cancel-workflow-action@0.11.0 From 376e6abaf48ba948fe6d646cc396e34f4a488a52 Mon Sep 17 00:00:00 2001 From: Heberto Mayorquin Date: Thu, 2 May 2024 12:04:23 -0600 Subject: [PATCH 27/29] Add `grid_spacing` and `origin_coords` to the fields of `ImagingPlane` (#1892) Co-authored-by: Ryan Ly --- CHANGELOG.md | 1 + src/pynwb/ophys.py | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2cb599be..650c81443 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - Added support for python 3.12 and upgraded dependency versions. This also includes infrastructure updates for developers. @mavaylon1 [#1853](https://github.com/NeurodataWithoutBorders/pynwb/pull/1853) +- Added `grid_spacing`, `grid_spacing_unit`, `origin_coords`, `origin_coords_unit` to `ImagingPlane` fields. @h-mayorquin [#1892](https://github.com/NeurodataWithoutBorders/pynwb/pull/1892) - Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) and [#1883](https://github.com/NeurodataWithoutBorders/pynwb/pull/1883) - Allow datetimes without a timezone and without a time. @rly [#1886](https://github.com/NeurodataWithoutBorders/pynwb/pull/1886) - No longer automatically set the timezone to the local timezone when not provided. [#1886](https://github.com/NeurodataWithoutBorders/pynwb/pull/1886) diff --git a/src/pynwb/ophys.py b/src/pynwb/ophys.py index bdff47592..6f1483079 100644 --- a/src/pynwb/ophys.py +++ b/src/pynwb/ophys.py @@ -43,7 +43,12 @@ class ImagingPlane(NWBContainer): 'manifold', 'conversion', 'unit', - 'reference_frame') + 'reference_frame', + 'grid_spacing', + 'grid_spacing_unit', + 'origin_coords', + 'origin_coords_unit' + ) @docval(*get_docval(NWBContainer.__init__, 'name'), # required {'name': 'optical_channel', 'type': (list, OpticalChannel), # required From 78ebc86086eed04bfdc99adb1768f7920d71c92f Mon Sep 17 00:00:00 2001 From: Ryan Ly Date: Thu, 2 May 2024 13:55:37 -0700 Subject: [PATCH 28/29] Update coverage call, don't install in editable mode in testing (#1897) * Update coverage call, don't install in editable mode in testing * Cleaner version --------- Co-authored-by: Matthew Avaylon --- .github/workflows/run_all_tests.yml | 4 ++-- .github/workflows/run_coverage.yml | 10 +++++----- .github/workflows/run_dandi_read_tests.yml | 2 +- .github/workflows/run_inspector_tests.yml | 3 +-- .github/workflows/run_tests.yml | 4 ++-- CHANGELOG.md | 1 + pyproject.toml | 16 ++++++---------- tox.ini | 7 +++---- 8 files changed, 21 insertions(+), 26 deletions(-) diff --git a/.github/workflows/run_all_tests.yml b/.github/workflows/run_all_tests.yml index 7a65434b9..dab896025 100644 --- a/.github/workflows/run_all_tests.yml +++ b/.github/workflows/run_all_tests.yml @@ -224,7 +224,7 @@ jobs: - name: Install run dependencies run: | pip install -r requirements-dev.txt - pip install -e . + pip install . conda info conda list pip list @@ -271,7 +271,7 @@ jobs: - name: Install run dependencies run: | pip install matplotlib - pip install -e . + pip install . pip list - name: Conda reporting diff --git a/.github/workflows/run_coverage.yml b/.github/workflows/run_coverage.yml index 400de00f3..5f060abbf 100644 --- a/.github/workflows/run_coverage.yml +++ b/.github/workflows/run_coverage.yml @@ -53,20 +53,20 @@ jobs: - name: Install package run: | - python -m pip install -e . # must install in editable mode for coverage to find sources + python -m pip install . python -m pip list - name: Run unit tests and generate coverage report run: | python -m coverage run test.py --pynwb python -m coverage xml # codecov uploader requires xml format - python -m coverage report -m + python -m coverage report - name: Upload coverage to Codecov uses: codecov/codecov-action@v4 with: flags: unit - files: coverage.xml + file: coverage.xml fail_ci_if_error: true env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} @@ -77,13 +77,13 @@ jobs: # validation CLI tests generate separate .coverage files that need to be merged python -m coverage combine python -m coverage xml # codecov uploader requires xml format - python -m coverage report -m + python -m coverage report - name: Upload coverage to Codecov uses: codecov/codecov-action@v4 with: flags: integration - files: coverage.xml + file: coverage.xml fail_ci_if_error: true env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/run_dandi_read_tests.yml b/.github/workflows/run_dandi_read_tests.yml index df9ef4613..cdde371c6 100644 --- a/.github/workflows/run_dandi_read_tests.yml +++ b/.github/workflows/run_dandi_read_tests.yml @@ -31,7 +31,7 @@ jobs: run: | python -m pip install dandi fsspec requests aiohttp pytest python -m pip uninstall -y pynwb # uninstall pynwb - python -m pip install -e . + python -m pip install . python -m pip list - name: Conda reporting diff --git a/.github/workflows/run_inspector_tests.yml b/.github/workflows/run_inspector_tests.yml index cb8d57458..120e30a79 100644 --- a/.github/workflows/run_inspector_tests.yml +++ b/.github/workflows/run_inspector_tests.yml @@ -34,8 +34,7 @@ jobs: git clone https://github.com/NeurodataWithoutBorders/nwbinspector.git cd nwbinspector python -m pip install -r requirements.txt pytest - # must install in editable mode for coverage to find sources - python -m pip install -e . # this might install a pinned version of pynwb instead of the current one + python -m pip install . # this might install a pinned version of pynwb instead of the current one cd .. python -m pip uninstall -y pynwb # uninstall the pinned version of pynwb python -m pip install . # reinstall current branch of pynwb diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index c0d520429..b512b2de0 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -200,7 +200,7 @@ jobs: - name: Install run dependencies run: | pip install -r requirements-dev.txt - pip install -e . + pip install . conda info conda list pip list @@ -245,7 +245,7 @@ jobs: - name: Install run dependencies run: | pip install matplotlib - pip install -e . + pip install . pip list - name: Conda reporting diff --git a/CHANGELOG.md b/CHANGELOG.md index 650c81443..625a7e786 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) and [#1883](https://github.com/NeurodataWithoutBorders/pynwb/pull/1883) - Allow datetimes without a timezone and without a time. @rly [#1886](https://github.com/NeurodataWithoutBorders/pynwb/pull/1886) - No longer automatically set the timezone to the local timezone when not provided. [#1886](https://github.com/NeurodataWithoutBorders/pynwb/pull/1886) +- Updated testing to not install in editable mode and not run `coverage` by default. [#1897](https://github.com/NeurodataWithoutBorders/pynwb/pull/1897) ### Bug fixes - Fix bug with reading file with linked `TimeSeriesReferenceVectorData` @rly [#1865](https://github.com/NeurodataWithoutBorders/pynwb/pull/1865) diff --git a/pyproject.toml b/pyproject.toml index 7f5f71663..ab2fceb33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,28 +58,24 @@ version-file = "src/pynwb/_version.py" [tool.hatch.build.targets.wheel] packages = ["src/pynwb"] -# [tool.pytest.ini_options] # TODO: uncomment when pytest is integrated -# # Addopts creates a shortcut for pytest. For example below, running `pytest` will actually run `pytest --cov --cov-report html`. -# addopts = "--cov --cov-report html" # generates coverage report in html format without showing anything on the terminal. - [tool.codespell] skip = "htmlcov,.git,.mypy_cache,.pytest_cache,.coverage,*.pdf,*.svg,venvs,.tox,nwb-schema,./docs/_build/*,*.ipynb" ignore-words-list = "optin,potatos" [tool.coverage.run] branch = true -source = ["src/"] -omit = [ - "src/pynwb/_due.py", - "src/pynwb/testing/*", - "src/pynwb/legacy/*" -] +source = ["pynwb"] [tool.coverage.report] exclude_lines = [ "pragma: no cover", "@abstract" ] +omit = [ + "*/pynwb/_due.py", + "*/pynwb/testing/*", + "*/pynwb/legacy/*" +] [tool.ruff] select = ["E", "F", "T100", "T201", "T203"] diff --git a/tox.ini b/tox.ini index 798da6fe6..8aecbb544 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,6 @@ requires = pip >= 22.0 [testenv] download = True -usedevelop = True setenv = PYTHONDONTWRITEBYTECODE = 1 VIRTUALENV_PIP = 23.3.1 @@ -112,7 +111,7 @@ install_command = deps = -rrequirements.txt commands = - python -m pip install -e . + python -m pip install . python -m pip install -r requirements-doc.txt # NOTE: allensdk (requirements-doc.txt) requires pynwb python -m pip check python -m pip list @@ -144,7 +143,7 @@ basepython = python3.12 deps = -rrequirements-dev.txt commands = - python -m pip install -U -e . + python -m pip install -U . python -m pip install -r requirements-doc.txt # NOTE: allensdk (requirements-doc.txt) requires pynwb python -m pip check python -m pip list @@ -156,7 +155,7 @@ basepython = python3.12 deps = -rrequirements-dev.txt commands = - python -m pip install -U --pre -e . + python -m pip install -U --pre . python -m pip install -r requirements-doc.txt # NOTE: allensdk (requirements-doc.txt) requires pynwb python -m pip check python -m pip list From f136410f558e40871f506a129c78c08fa0300681 Mon Sep 17 00:00:00 2001 From: Matthew Avaylon Date: Thu, 2 May 2024 16:27:14 -0700 Subject: [PATCH 29/29] Update SpatialSeries to have bounds field (#1869) Co-authored-by: Ryan Ly --- CHANGELOG.md | 9 +++++---- docs/gallery/domain/plot_behavior.py | 4 ++++ src/pynwb/behavior.py | 7 +++++-- tests/integration/hdf5/test_behavior.py | 17 +++++++++++++++++ tests/unit/test_behavior.py | 2 ++ 5 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 tests/integration/hdf5/test_behavior.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 625a7e786..36bd0a35d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,11 +3,12 @@ ## PyNWB 2.7.0 (Upcoming) ### Enhancements and minor changes +- Added `bounds` field to `SpatialSeries` to set optional boundary range (min, max) for each dimension of data. @mavaylon1 [#1869](https://github.com/NeurodataWithoutBorders/pynwb/pull/1869/files) - Added support for NWB schema 2.7.0. See [2.7.0 release notes](https://nwb-schema.readthedocs.io/en/latest/format_release_notes.html) for details - - Deprecated `ImagingRetinotopy` neurodata type. @rly [#1813](https://github.com/NeurodataWithoutBorders/pynwb/pull/1813) - - Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) - - Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) - - Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) +- Deprecated `ImagingRetinotopy` neurodata type. @rly [#1813](https://github.com/NeurodataWithoutBorders/pynwb/pull/1813) +- Modified `OptogeneticSeries` to allow 2D data, primarily in extensions of `OptogeneticSeries`. @rly [#1812](https://github.com/NeurodataWithoutBorders/pynwb/pull/1812) +- Support `stimulus_template` as optional predefined column in `IntracellularStimuliTable`. @stephprince [#1815](https://github.com/NeurodataWithoutBorders/pynwb/pull/1815) +- Support `NWBDataInterface` and `DynamicTable` in `NWBFile.stimulus`. @rly [#1842](https://github.com/NeurodataWithoutBorders/pynwb/pull/1842) - Added support for python 3.12 and upgraded dependency versions. This also includes infrastructure updates for developers. @mavaylon1 [#1853](https://github.com/NeurodataWithoutBorders/pynwb/pull/1853) - Added `grid_spacing`, `grid_spacing_unit`, `origin_coords`, `origin_coords_unit` to `ImagingPlane` fields. @h-mayorquin [#1892](https://github.com/NeurodataWithoutBorders/pynwb/pull/1892) - Added `mock_Units` for generating Units tables. @h-mayorquin [#1875](https://github.com/NeurodataWithoutBorders/pynwb/pull/1875) and [#1883](https://github.com/NeurodataWithoutBorders/pynwb/pull/1883) diff --git a/docs/gallery/domain/plot_behavior.py b/docs/gallery/domain/plot_behavior.py index 8f341bea1..35fbae81f 100644 --- a/docs/gallery/domain/plot_behavior.py +++ b/docs/gallery/domain/plot_behavior.py @@ -105,6 +105,9 @@ # # For position data ``reference_frame`` indicates the zero-position, e.g. # the 0,0 point might be the bottom-left corner of an enclosure, as viewed from the tracking camera. +# In :py:class:`~pynwb.behavior.SpatialSeries`, the ``bounds`` field allows the user to set +# the boundary range, i.e., (min, max), for each dimension of ``data``. The units are the same as in ``data``. +# This field does not enforce a boundary on the dataset itself. timestamps = np.linspace(0, 50) / 200 @@ -112,6 +115,7 @@ name="SpatialSeries", description="Position (x, y) in an open field.", data=position_data, + bounds=[(0,50), (0,50)], timestamps=timestamps, reference_frame="(0,0) is bottom left corner", ) diff --git a/src/pynwb/behavior.py b/src/pynwb/behavior.py index b9388e8df..1b3078535 100644 --- a/src/pynwb/behavior.py +++ b/src/pynwb/behavior.py @@ -23,9 +23,11 @@ class SpatialSeries(TimeSeries): __nwbfields__ = ('reference_frame',) @docval(*get_docval(TimeSeries.__init__, 'name'), # required - {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': ((None, ), (None, None)), # required + {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': ((None, ), (None, None)), # required 'doc': ('The data values. Can be 1D or 2D. The first dimension must be time. If 2D, there can be 1, 2, ' 'or 3 columns, which represent x, y, and z.')}, + {'name': 'bounds', 'type': list, 'shape': ((1, 2), (2, 2), (3, 2)), 'default': None, + 'doc': 'The boundary range (min, max) for each dimension of data.'}, {'name': 'reference_frame', 'type': str, # required 'doc': 'description defining what the zero-position is'}, {'name': 'unit', 'type': str, 'doc': 'The base unit of measurement (should be SI unit)', @@ -36,7 +38,7 @@ def __init__(self, **kwargs): """ Create a SpatialSeries TimeSeries dataset """ - name, data, reference_frame, unit = popargs('name', 'data', 'reference_frame', 'unit', kwargs) + name, data, bounds, reference_frame, unit = popargs('name', 'data', 'bounds', 'reference_frame', 'unit', kwargs) super().__init__(name, data, unit, **kwargs) # NWB 2.5 restricts length of second dimension to be <= 3 @@ -47,6 +49,7 @@ def __init__(self, **kwargs): "The second dimension should have length <= 3 to represent at most x, y, z." % (name, str(data_shape))) + self.bounds = bounds self.reference_frame = reference_frame @staticmethod diff --git a/tests/integration/hdf5/test_behavior.py b/tests/integration/hdf5/test_behavior.py new file mode 100644 index 000000000..d4b230bcc --- /dev/null +++ b/tests/integration/hdf5/test_behavior.py @@ -0,0 +1,17 @@ +import numpy as np + +from pynwb.behavior import SpatialSeries +from pynwb.testing import AcquisitionH5IOMixin, TestCase + + +class TestSpatialSeriesIO(AcquisitionH5IOMixin, TestCase): + + def setUpContainer(self): + """ Return the test TimeSeries to read/write """ + return SpatialSeries( + name='test_sS', + data=np.ones((3, 2)), + bounds=[(-1,1),(-1,1),(-1,1)], + reference_frame='reference_frame', + timestamps=[1., 2., 3.] + ) diff --git a/tests/unit/test_behavior.py b/tests/unit/test_behavior.py index 0b7173da0..6bcf1a9eb 100644 --- a/tests/unit/test_behavior.py +++ b/tests/unit/test_behavior.py @@ -12,11 +12,13 @@ def test_init(self): sS = SpatialSeries( name='test_sS', data=np.ones((3, 2)), + bounds=[(-1,1),(-1,1),(-1,1)], reference_frame='reference_frame', timestamps=[1., 2., 3.] ) self.assertEqual(sS.name, 'test_sS') self.assertEqual(sS.unit, 'meters') + self.assertEqual(sS.bounds, [(-1,1),(-1,1),(-1,1)]) self.assertEqual(sS.reference_frame, 'reference_frame') def test_set_unit(self):