diff --git a/doc/source/api_reference.rst b/doc/source/api_reference.rst index 6f0379a54..f82a2591c 100644 --- a/doc/source/api_reference.rst +++ b/doc/source/api_reference.rst @@ -6,4 +6,4 @@ API Reference .. testsetup:: * from neo import SpikeTrain - import quantities as pq \ No newline at end of file + from neo import units as un \ No newline at end of file diff --git a/doc/source/core.rst b/doc/source/core.rst index 8b449bef3..fad94e965 100644 --- a/doc/source/core.rst +++ b/doc/source/core.rst @@ -66,7 +66,7 @@ cut across the simple container hierarchy. NumPy compatibility =================== -Neo data objects inherit from :py:class:`Quantity`, which in turn inherits from NumPy +Neo data objects inherit from :py:class:`Quantity` (by using units module), which in turn inherits from NumPy :py:class:`ndarray`. This means that a Neo :py:class:`AnalogSignal` is also a :py:class:`Quantity` and an array, giving you access to all of the methods available for those objects. diff --git a/doc/source/images/generate_diagram.py b/doc/source/images/generate_diagram.py index 67a21cb29..a510d2601 100644 --- a/doc/source/images/generate_diagram.py +++ b/doc/source/images/generate_diagram.py @@ -10,7 +10,8 @@ from datetime import datetime import numpy as np -import quantities as pq +from neo import units as un + from matplotlib import pyplot from matplotlib.patches import Rectangle, ArrowStyle, FancyArrowPatch from matplotlib.font_manager import FontProperties @@ -173,7 +174,7 @@ def generate_diagram(filename, rect_pos, rect_width, figsize): else: t1 = attrname - if attrtype == pq.Quantity: + if attrtype == un.Quantity: if attr[2] == 0: t2 = 'Quantity scalar' else: diff --git a/examples/generated_data.py b/examples/generated_data.py index 9f6f30753..e14702798 100644 --- a/examples/generated_data.py +++ b/examples/generated_data.py @@ -6,10 +6,11 @@ from __future__ import division # Use same division in Python 2 and 3 import numpy as np -import quantities as pq + from matplotlib import pyplot as plt import neo +from neo import units as un def generate_block(n_segments=3, n_channels=8, n_units=3, @@ -48,7 +49,7 @@ def generate_block(n_segments=3, n_channels=8, n_units=3, sig = np.random.randn(data_samples) sig[feature_pos:feature_pos + feature_samples] += wave - signal = neo.AnalogSignal(sig * pq.mV, sampling_rate=1 * pq.kHz) + signal = neo.AnalogSignal(sig * un.mV, sampling_rate=1 * un.kHz) seg.analogsignals.append(signal) rc.analogsignals.append(signal) @@ -59,7 +60,7 @@ def generate_block(n_segments=3, n_channels=8, n_units=3, feature_spikes = np.random.rand(5) * feature_len + feature_time spikes = np.hstack([random_spikes, feature_spikes]) - train = neo.SpikeTrain(spikes * pq.s, 1 * pq.s) + train = neo.SpikeTrain(spikes * un.s, 1 * un.s) seg.spiketrains.append(train) u.spiketrains.append(train) diff --git a/examples/simple_plot_with_matplotlib.py b/examples/simple_plot_with_matplotlib.py index ed6ba0253..8590c991a 100644 --- a/examples/simple_plot_with_matplotlib.py +++ b/examples/simple_plot_with_matplotlib.py @@ -6,10 +6,12 @@ import urllib import numpy as np -import quantities as pq + from matplotlib import pyplot import neo +from neo import units as un + url = 'https://portal.g-node.org/neo/' # distantfile = url + 'neuroexplorer/File_neuroexplorer_2.nex' @@ -33,8 +35,8 @@ ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) ax1.set_title(seg.file_origin) - mint = 0 * pq.s - maxt = np.inf * pq.s + mint = 0 * un.s + maxt = np.inf * un.s for i, asig in enumerate(seg.analogsignals): times = asig.times.rescale('s').magnitude asig = asig.rescale('mV').magnitude diff --git a/neo/core/analogsignal.py b/neo/core/analogsignal.py index efaf9e210..1f135023f 100644 --- a/neo/core/analogsignal.py +++ b/neo/core/analogsignal.py @@ -22,11 +22,12 @@ import logging import numpy as np -import quantities as pq from neo.core.baseneo import BaseNeo, MergeError, merge_annotations from neo.core.channelindex import ChannelIndex +from neo import units as un + logger = logging.getLogger("Neo") @@ -49,7 +50,7 @@ def _get_sampling_rate(sampling_rate, sampling_period): def _new_AnalogSignalArray(cls, signal, units=None, dtype=None, copy=True, - t_start=0*pq.s, sampling_rate=None, + t_start=0*un.s, sampling_rate=None, sampling_period=None, name=None, file_origin=None, description=None, annotations=None): @@ -64,7 +65,7 @@ def _new_AnalogSignalArray(cls, signal, units=None, dtype=None, copy=True, **annotations) -class AnalogSignal(BaseNeo, pq.Quantity): +class AnalogSignal(BaseNeo, un.Quantity): ''' Array of one or more continuous analog signals. @@ -79,10 +80,10 @@ class AnalogSignal(BaseNeo, pq.Quantity): *Usage*:: >>> from neo.core import AnalogSignal - >>> import quantities as pq + >>> >>> sigarr = AnalogSignal([[1, 2, 3], [4, 5, 6]], units='V', - ... sampling_rate=1*pq.Hz) + ... sampling_rate=1*un.Hz) >>> >>> sigarr >> from neo.core import (Block, Segment, ChannelIndex, ... AnalogSignal) - >>> from quantities import nA, kHz + >>> from neo.units import nA, kHz >>> import numpy as np >>> >>> # create a Block with 3 Segment and 2 ChannelIndex objects diff --git a/neo/core/channelindex.py b/neo/core/channelindex.py index ea76ff1dd..822e5808e 100644 --- a/neo/core/channelindex.py +++ b/neo/core/channelindex.py @@ -11,7 +11,7 @@ from __future__ import absolute_import, division, print_function import numpy as np -import quantities as pq +from neo import units as un from neo.core.container import Container @@ -32,7 +32,7 @@ class ChannelIndex(Container): >>> from neo.core import (Block, Segment, ChannelIndex, ... AnalogSignal) - >>> from quantities import nA, kHz + >>> from neo.units import nA, kHz >>> import numpy as np >>> >>> # create a Block with 3 Segment and 2 ChannelIndex objects @@ -120,7 +120,7 @@ class ChannelIndex(Container): _necessary_attrs = (('index', np.ndarray, 1, np.dtype('i')),) _recommended_attrs = ((('channel_names', np.ndarray, 1, np.dtype('S')), ('channel_ids', np.ndarray, 1, np.dtype('i')), - ('coordinates', pq.Quantity, 2)) + + ('coordinates', un.Quantity, 2)) + Container._recommended_attrs) def __init__(self, index, channel_names=None, channel_ids=None, diff --git a/neo/core/epoch.py b/neo/core/epoch.py index 3a0ca1c16..41ad9f7d9 100644 --- a/neo/core/epoch.py +++ b/neo/core/epoch.py @@ -12,10 +12,12 @@ import sys import numpy as np -import quantities as pq + from neo.core.baseneo import BaseNeo, merge_annotations +from neo import units as un + PY_VER = sys.version_info[0] def _new_epoch(cls, times=None, durations=None, labels=None, units=None, @@ -27,14 +29,14 @@ def _new_epoch(cls, times=None, durations=None, labels=None, units=None, return Epoch( times=times, durations=durations, labels=labels, units=units, name=name, file_origin=file_origin, description=description, **annotations) -class Epoch(BaseNeo, pq.Quantity): +class Epoch(BaseNeo, un.Quantity): ''' Array of epochs. *Usage*:: >>> from neo.core import Epoch - >>> from quantities import s, ms + >>> from neo.units import s, ms >>> import numpy as np >>> >>> epc = Epoch(times=np.arange(0, 30, 10)*s, @@ -67,16 +69,16 @@ class Epoch(BaseNeo, pq.Quantity): _single_parent_objects = ('Segment',) _quantity_attr = 'times' - _necessary_attrs = (('times', pq.Quantity, 1), - ('durations', pq.Quantity, 1), + _necessary_attrs = (('times', un.Quantity, 1), + ('durations', un.Quantity, 1), ('labels', np.ndarray, 1, np.dtype('S'))) def __new__(cls, times=None, durations=None, labels=None, units=None, name=None, description=None, file_origin=None, **annotations): if times is None: - times = np.array([]) * pq.s + times = np.array([]) * un.s if durations is None: - durations = np.array([]) * pq.s + durations = np.array([]) * un.s if labels is None: labels = np.array([], dtype='S') if units is None: @@ -90,16 +92,16 @@ def __new__(cls, times=None, durations=None, labels=None, units=None, if hasattr(units, 'dimensionality'): dim = units.dimensionality else: - dim = pq.quantity.validate_dimensionality(units) + dim = un.quantity.validate_dimensionality(units) # check to make sure the units are time # this approach is much faster than comparing the # reference dimensionality if (len(dim) != 1 or list(dim.values())[0] != 1 or - not isinstance(list(dim.keys())[0], pq.UnitTime)): + not isinstance(list(dim.keys())[0], un.UnitTime)): ValueError("Unit %s has dimensions %s, not [time]" % (units, dim.simplified)) - obj = pq.Quantity.__new__(cls, times, units=dim) + obj = un.Quantity.__new__(cls, times, units=dim) obj.durations = durations obj.labels = labels obj.segment = None @@ -147,7 +149,7 @@ def __repr__(self): @property def times(self): - return pq.Quantity(self) + return un.Quantity(self) def merge(self, other): ''' diff --git a/neo/core/event.py b/neo/core/event.py index e92b9a9ff..ed298c0ef 100644 --- a/neo/core/event.py +++ b/neo/core/event.py @@ -12,10 +12,11 @@ import sys import numpy as np -import quantities as pq from neo.core.baseneo import BaseNeo, merge_annotations +from neo import units as un + PY_VER = sys.version_info[0] def _new_event(cls, signal, times = None, labels=None, units=None, name=None, @@ -28,14 +29,14 @@ def _new_event(cls, signal, times = None, labels=None, units=None, name=None, return Event(signal=signal, times=times, labels=labels, units=units, name=name, file_origin=file_origin, description=description, **annotations) -class Event(BaseNeo, pq.Quantity): +class Event(BaseNeo, un.Quantity): ''' Array of events. *Usage*:: >>> from neo.core import Event - >>> from quantities import s + >>> from neo.units import s >>> import numpy as np >>> >>> evt = Event(np.arange(0, 30, 10)*s, @@ -64,13 +65,13 @@ class Event(BaseNeo, pq.Quantity): _single_parent_objects = ('Segment',) _quantity_attr = 'times' - _necessary_attrs = (('times', pq.Quantity, 1), + _necessary_attrs = (('times', un.Quantity, 1), ('labels', np.ndarray, 1, np.dtype('S'))) def __new__(cls, times=None, labels=None, units=None, name=None, description=None, file_origin=None, **annotations): if times is None: - times = np.array([]) * pq.s + times = np.array([]) * un.s if labels is None: labels = np.array([], dtype='S') if units is None: @@ -84,16 +85,17 @@ def __new__(cls, times=None, labels=None, units=None, name=None, description=Non if hasattr(units, 'dimensionality'): dim = units.dimensionality else: - dim = pq.quantity.validate_dimensionality(units) + dim = un.quantity.validate_dimensionality(units) # check to make sure the units are time # this approach is much faster than comparing the # reference dimensionality if (len(dim) != 1 or list(dim.values())[0] != 1 or - not isinstance(list(dim.keys())[0], pq.UnitTime)): + not isinstance(list(dim.keys())[0], un.UnitTime)): ValueError("Unit %s has dimensions %s, not [time]" % (units, dim.simplified)) - obj = pq.Quantity(times, units=dim).view(cls) + obj = un.Quantity(times, units=dim).view(cls) + obj.labels = labels obj.segment = None return obj @@ -138,7 +140,7 @@ def __repr__(self): @property def times(self): - return pq.Quantity(self) + return un.Quantity(self) def merge(self, other): ''' diff --git a/neo/core/event_BACKUP_4347.py b/neo/core/event_BACKUP_4347.py new file mode 100644 index 000000000..ed298c0ef --- /dev/null +++ b/neo/core/event_BACKUP_4347.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- +''' +This module defines :class:`Event`, an array of events. + +:class:`Event` derives from :class:`BaseNeo`, from +:module:`neo.core.baseneo`. +''' + +# needed for python 3 compatibility +from __future__ import absolute_import, division, print_function + +import sys + +import numpy as np + +from neo.core.baseneo import BaseNeo, merge_annotations + +from neo import units as un + +PY_VER = sys.version_info[0] + +def _new_event(cls, signal, times = None, labels=None, units=None, name=None, + file_origin=None, description=None, + annotations=None): + ''' + A function to map Event.__new__ to function that + does not do the unit checking. This is needed for pickle to work. + ''' + return Event(signal=signal, times=times, labels=labels, units=units, name=name, file_origin=file_origin, + description=description, **annotations) + +class Event(BaseNeo, un.Quantity): + ''' + Array of events. + + *Usage*:: + + >>> from neo.core import Event + >>> from neo.units import s + >>> import numpy as np + >>> + >>> evt = Event(np.arange(0, 30, 10)*s, + ... labels=np.array(['trig0', 'trig1', 'trig2'], + ... dtype='S')) + >>> + >>> evt.times + array([ 0., 10., 20.]) * s + >>> evt.labels + array(['trig0', 'trig1', 'trig2'], + dtype='|S5') + + *Required attributes/properties*: + :times: (quantity array 1D) The time of the events. + :labels: (numpy.array 1D dtype='S') Names or labels for the events. + + *Recommended attributes/properties*: + :name: (str) A label for the dataset. + :description: (str) Text description. + :file_origin: (str) Filesystem path or URL of the original data file. + + Note: Any other additional arguments are assumed to be user-specific + metadata and stored in :attr:`annotations`. + + ''' + + _single_parent_objects = ('Segment',) + _quantity_attr = 'times' + _necessary_attrs = (('times', un.Quantity, 1), + ('labels', np.ndarray, 1, np.dtype('S'))) + + def __new__(cls, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + if times is None: + times = np.array([]) * un.s + if labels is None: + labels = np.array([], dtype='S') + if units is None: + # No keyword units, so get from `times` + try: + units = times.units + dim = units.dimensionality + except AttributeError: + raise ValueError('you must specify units') + else: + if hasattr(units, 'dimensionality'): + dim = units.dimensionality + else: + dim = un.quantity.validate_dimensionality(units) + # check to make sure the units are time + # this approach is much faster than comparing the + # reference dimensionality + if (len(dim) != 1 or list(dim.values())[0] != 1 or + not isinstance(list(dim.keys())[0], un.UnitTime)): + ValueError("Unit %s has dimensions %s, not [time]" % + (units, dim.simplified)) + + obj = un.Quantity(times, units=dim).view(cls) + + obj.labels = labels + obj.segment = None + return obj + + def __init__(self, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + ''' + Initialize a new :class:`Event` instance. + ''' + BaseNeo.__init__(self, name=name, file_origin=file_origin, + description=description, **annotations) + def __reduce__(self): + ''' + Map the __new__ function onto _new_BaseAnalogSignal, so that pickle + works + ''' + return _new_event, (self.__class__, self.times, np.array(self), self.labels, self.units, + self.name, self.file_origin, self.description, + self.annotations) + + def __array_finalize__(self, obj): + super(Event, self).__array_finalize__(obj) + self.labels = getattr(obj, 'labels', None) + self.annotations = getattr(obj, 'annotations', None) + self.name = getattr(obj, 'name', None) + self.file_origin = getattr(obj, 'file_origin', None) + self.description = getattr(obj, 'description', None) + self.segment = getattr(obj, 'segment', None) + + def __repr__(self): + ''' + Returns a string representing the :class:`Event`. + ''' + # need to convert labels to unicode for python 3 or repr is messed up + if PY_VER == 3: + labels = self.labels.astype('U') + else: + labels = self.labels + objs = ['%s@%s' % (label, time) for label, time in zip(labels, + self.times)] + return '' % ', '.join(objs) + + @property + def times(self): + return un.Quantity(self) + + def merge(self, other): + ''' + Merge the another :class:`Event` into this one. + + The :class:`Event` objects are concatenated horizontally + (column-wise), :func:`np.hstack`). + + If the attributes of the two :class:`Event` are not + compatible, and Exception is raised. + ''' + othertimes = other.times.rescale(self.times.units) + times = np.hstack([self.times, othertimes]) * self.times.units + labels = np.hstack([self.labels, other.labels]) + kwargs = {} + for name in ("name", "description", "file_origin"): + attr_self = getattr(self, name) + attr_other = getattr(other, name) + if attr_self == attr_other: + kwargs[name] = attr_self + else: + kwargs[name] = "merge(%s, %s)" % (attr_self, attr_other) + + merged_annotations = merge_annotations(self.annotations, + other.annotations) + kwargs.update(merged_annotations) + return Event(times=times, labels=labels, **kwargs) + + def _copy_data_complement(self, other): + ''' + Copy the metadata from another :class:`Event`. + ''' + for attr in ("labels", "name", "file_origin", "description", + "annotations"): + setattr(self, attr, getattr(other, attr, None)) + + def duplicate_with_new_data(self, signal): + ''' + Create a new :class:`Event` with the same metadata + but different data + ''' + new = self.__class__(times=signal) + new._copy_data_complement(self) + return new + + def time_slice(self, t_start, t_stop): + ''' + Creates a new :class:`Event` corresponding to the time slice of + the original :class:`Event` between (and including) times + :attr:`t_start` and :attr:`t_stop`. Either parameter can also be None + to use infinite endpoints for the time interval. + ''' + _t_start = t_start + _t_stop = t_stop + if t_start is None: + _t_start = -np.inf + if t_stop is None: + _t_stop = np.inf + + indices = (self >= _t_start) & (self <= _t_stop) + new_evt = self[indices] + + return new_evt \ No newline at end of file diff --git a/neo/core/event_BASE_4347.py b/neo/core/event_BASE_4347.py new file mode 100644 index 000000000..94e3b772c --- /dev/null +++ b/neo/core/event_BASE_4347.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +''' +This module defines :class:`Event`, an array of events. + +:class:`Event` derives from :class:`BaseNeo`, from +:module:`neo.core.baseneo`. +''' + +# needed for python 3 compatibility +from __future__ import absolute_import, division, print_function + +import sys + +import numpy as np +from neo import units as un + +from neo.core.baseneo import BaseNeo, merge_annotations + +PY_VER = sys.version_info[0] + + +class Event(BaseNeo, un.Quantity): + ''' + Array of events. + + *Usage*:: + + >>> from neo.core import Event + >>> from quantities import s + >>> import numpy as np + >>> + >>> evt = Event(np.arange(0, 30, 10)*s, + ... labels=np.array(['trig0', 'trig1', 'trig2'], + ... dtype='S')) + >>> + >>> evt.times + array([ 0., 10., 20.]) * s + >>> evt.labels + array(['trig0', 'trig1', 'trig2'], + dtype='|S5') + + *Required attributes/properties*: + :times: (quantity array 1D) The time of the events. + :labels: (numpy.array 1D dtype='S') Names or labels for the events. + + *Recommended attributes/properties*: + :name: (str) A label for the dataset. + :description: (str) Text description. + :file_origin: (str) Filesystem path or URL of the original data file. + + Note: Any other additional arguments are assumed to be user-specific + metadata and stored in :attr:`annotations`. + + ''' + + _single_parent_objects = ('Segment',) + _quantity_attr = 'times' + _necessary_attrs = (('times', un.Quantity, 1), + ('labels', np.ndarray, 1, np.dtype('S'))) + + def __new__(cls, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + if times is None: + times = np.array([]) * un.s + if labels is None: + labels = np.array([], dtype='S') + if units is None: + # No keyword units, so get from `times` + try: + units = times.units + dim = units.dimensionality + except AttributeError: + raise ValueError('you must specify units') + else: + if hasattr(units, 'dimensionality'): + dim = units.dimensionality + else: + dim = un.quantity.validate_dimensionality(units) + # check to make sure the units are time + # this approach is much faster than comparing the + # reference dimensionality + if (len(dim) != 1 or list(dim.values())[0] != 1 or + not isinstance(list(dim.keys())[0], un.UnitTime)): + ValueError("Unit %s has dimensions %s, not [time]" % + (units, dim.simplified)) + + obj = un.Quantity.__new__(cls, times, units=dim) + obj.labels = labels + obj.segment = None + return obj + + def __init__(self, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + ''' + Initialize a new :class:`Event` instance. + ''' + BaseNeo.__init__(self, name=name, file_origin=file_origin, + description=description, **annotations) + + def __array_finalize__(self, obj): + super(Event, self).__array_finalize__(obj) + self.labels = getattr(obj, 'labels', None) + self.annotations = getattr(obj, 'annotations', None) + self.name = getattr(obj, 'name', None) + self.file_origin = getattr(obj, 'file_origin', None) + self.description = getattr(obj, 'description', None) + self.segment = getattr(obj, 'segment', None) + + def __repr__(self): + ''' + Returns a string representing the :class:`Event`. + ''' + # need to convert labels to unicode for python 3 or repr is messed up + if PY_VER == 3: + labels = self.labels.astype('U') + else: + labels = self.labels + objs = ['%s@%s' % (label, time) for label, time in zip(labels, + self.times)] + return '' % ', '.join(objs) + + @property + def times(self): + return un.Quantity(self) + + def merge(self, other): + ''' + Merge the another :class:`Event` into this one. + + The :class:`Event` objects are concatenated horizontally + (column-wise), :func:`np.hstack`). + + If the attributes of the two :class:`Event` are not + compatible, and Exception is raised. + ''' + othertimes = other.times.rescale(self.times.units) + times = np.hstack([self.times, othertimes]) * self.times.units + labels = np.hstack([self.labels, other.labels]) + kwargs = {} + for name in ("name", "description", "file_origin"): + attr_self = getattr(self, name) + attr_other = getattr(other, name) + if attr_self == attr_other: + kwargs[name] = attr_self + else: + kwargs[name] = "merge(%s, %s)" % (attr_self, attr_other) + + merged_annotations = merge_annotations(self.annotations, + other.annotations) + kwargs.update(merged_annotations) + return Event(times=times, labels=labels, **kwargs) + + def _copy_data_complement(self, other): + ''' + Copy the metadata from another :class:`Event`. + ''' + for attr in ("labels", "name", "file_origin", "description", + "annotations"): + setattr(self, attr, getattr(other, attr, None)) + + def duplicate_with_new_data(self, signal): + ''' + Create a new :class:`Event` with the same metadata + but different data + ''' + new = self.__class__(times=signal) + new._copy_data_complement(self) + return new \ No newline at end of file diff --git a/neo/core/event_LOCAL_4347.py b/neo/core/event_LOCAL_4347.py new file mode 100644 index 000000000..acf12596c --- /dev/null +++ b/neo/core/event_LOCAL_4347.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +''' +This module defines :class:`Event`, an array of events. + +:class:`Event` derives from :class:`BaseNeo`, from +:module:`neo.core.baseneo`. +''' + +# needed for python 3 compatibility +from __future__ import absolute_import, division, print_function + +import sys + +import numpy as np +from neo import units as un + +from neo.core.baseneo import BaseNeo, merge_annotations + +PY_VER = sys.version_info[0] + +def _new_event(cls, signal, times = None, labels=None, units=None, name=None, + file_origin=None, description=None, + annotations=None): + ''' + A function to map Event.__new__ to function that + does not do the unit checking. This is needed for pickle to work. + ''' + return Event(signal=signal, times=times, labels=labels, units=units, name=name, file_origin=file_origin, + description=description, **annotations) + +class Event(BaseNeo, un.Quantity): + ''' + Array of events. + + *Usage*:: + + >>> from neo.core import Event + >>> from quantities import s + >>> import numpy as np + >>> + >>> evt = Event(np.arange(0, 30, 10)*s, + ... labels=np.array(['trig0', 'trig1', 'trig2'], + ... dtype='S')) + >>> + >>> evt.times + array([ 0., 10., 20.]) * s + >>> evt.labels + array(['trig0', 'trig1', 'trig2'], + dtype='|S5') + + *Required attributes/properties*: + :times: (quantity array 1D) The time of the events. + :labels: (numpy.array 1D dtype='S') Names or labels for the events. + + *Recommended attributes/properties*: + :name: (str) A label for the dataset. + :description: (str) Text description. + :file_origin: (str) Filesystem path or URL of the original data file. + + Note: Any other additional arguments are assumed to be user-specific + metadata and stored in :attr:`annotations`. + + ''' + + _single_parent_objects = ('Segment',) + _quantity_attr = 'times' + _necessary_attrs = (('times', un.Quantity, 1), + ('labels', np.ndarray, 1, np.dtype('S'))) + + def __new__(cls, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + if times is None: + times = np.array([]) * un.s + if labels is None: + labels = np.array([], dtype='S') + if units is None: + # No keyword units, so get from `times` + try: + units = times.units + dim = units.dimensionality + except AttributeError: + raise ValueError('you must specify units') + else: + if hasattr(units, 'dimensionality'): + dim = units.dimensionality + else: + dim = un.quantity.validate_dimensionality(units) + # check to make sure the units are time + # this approach is much faster than comparing the + # reference dimensionality + if (len(dim) != 1 or list(dim.values())[0] != 1 or + not isinstance(list(dim.keys())[0], un.UnitTime)): + ValueError("Unit %s has dimensions %s, not [time]" % + (units, dim.simplified)) + + obj = un.Quantity(times, units=dim).view(cls) + obj.labels = labels + obj.segment = None + return obj + + def __init__(self, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + ''' + Initialize a new :class:`Event` instance. + ''' + BaseNeo.__init__(self, name=name, file_origin=file_origin, + description=description, **annotations) + def __reduce__(self): + ''' + Map the __new__ function onto _new_BaseAnalogSignal, so that pickle + works + ''' + return _new_event, (self.__class__, self.times, np.array(self), self.labels, self.units, + self.name, self.file_origin, self.description, + self.annotations) + + def __array_finalize__(self, obj): + super(Event, self).__array_finalize__(obj) + self.labels = getattr(obj, 'labels', None) + self.annotations = getattr(obj, 'annotations', None) + self.name = getattr(obj, 'name', None) + self.file_origin = getattr(obj, 'file_origin', None) + self.description = getattr(obj, 'description', None) + self.segment = getattr(obj, 'segment', None) + + def __repr__(self): + ''' + Returns a string representing the :class:`Event`. + ''' + # need to convert labels to unicode for python 3 or repr is messed up + if PY_VER == 3: + labels = self.labels.astype('U') + else: + labels = self.labels + objs = ['%s@%s' % (label, time) for label, time in zip(labels, + self.times)] + return '' % ', '.join(objs) + + @property + def times(self): + return un.Quantity(self) + + def merge(self, other): + ''' + Merge the another :class:`Event` into this one. + + The :class:`Event` objects are concatenated horizontally + (column-wise), :func:`np.hstack`). + + If the attributes of the two :class:`Event` are not + compatible, and Exception is raised. + ''' + othertimes = other.times.rescale(self.times.units) + times = np.hstack([self.times, othertimes]) * self.times.units + labels = np.hstack([self.labels, other.labels]) + kwargs = {} + for name in ("name", "description", "file_origin"): + attr_self = getattr(self, name) + attr_other = getattr(other, name) + if attr_self == attr_other: + kwargs[name] = attr_self + else: + kwargs[name] = "merge(%s, %s)" % (attr_self, attr_other) + + merged_annotations = merge_annotations(self.annotations, + other.annotations) + kwargs.update(merged_annotations) + return Event(times=times, labels=labels, **kwargs) + + def _copy_data_complement(self, other): + ''' + Copy the metadata from another :class:`Event`. + ''' + for attr in ("labels", "name", "file_origin", "description", + "annotations"): + setattr(self, attr, getattr(other, attr, None)) + + def duplicate_with_new_data(self, signal): + ''' + Create a new :class:`Event` with the same metadata + but different data + ''' + new = self.__class__(times=signal) + new._copy_data_complement(self) + return new + + def time_slice(self, t_start, t_stop): + ''' + Creates a new :class:`Event` corresponding to the time slice of + the original :class:`Event` between (and including) times + :attr:`t_start` and :attr:`t_stop`. Either parameter can also be None + to use infinite endpoints for the time interval. + ''' + _t_start = t_start + _t_stop = t_stop + if t_start is None: + _t_start = -np.inf + if t_stop is None: + _t_stop = np.inf + + indices = (self >= _t_start) & (self <= _t_stop) + new_evt = self[indices] + + return new_evt \ No newline at end of file diff --git a/neo/core/event_REMOTE_4347.py b/neo/core/event_REMOTE_4347.py new file mode 100644 index 000000000..5dce693dd --- /dev/null +++ b/neo/core/event_REMOTE_4347.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +''' +This module defines :class:`Event`, an array of events. + +:class:`Event` derives from :class:`BaseNeo`, from +:module:`neo.core.baseneo`. +''' + +# needed for python 3 compatibility +from __future__ import absolute_import, division, print_function + +import sys + +import numpy as np + +from neo.core.baseneo import BaseNeo, merge_annotations + +from neo import units as un + +PY_VER = sys.version_info[0] + + +class Event(BaseNeo, un.Quantity): + ''' + Array of events. + + *Usage*:: + + >>> from neo.core import Event + >>> from neo.units import s + >>> import numpy as np + >>> + >>> evt = Event(np.arange(0, 30, 10)*s, + ... labels=np.array(['trig0', 'trig1', 'trig2'], + ... dtype='S')) + >>> + >>> evt.times + array([ 0., 10., 20.]) * s + >>> evt.labels + array(['trig0', 'trig1', 'trig2'], + dtype='|S5') + + *Required attributes/properties*: + :times: (quantity array 1D) The time of the events. + :labels: (numpy.array 1D dtype='S') Names or labels for the events. + + *Recommended attributes/properties*: + :name: (str) A label for the dataset. + :description: (str) Text description. + :file_origin: (str) Filesystem path or URL of the original data file. + + Note: Any other additional arguments are assumed to be user-specific + metadata and stored in :attr:`annotations`. + + ''' + + _single_parent_objects = ('Segment',) + _quantity_attr = 'times' + _necessary_attrs = (('times', un.Quantity, 1), + ('labels', np.ndarray, 1, np.dtype('S'))) + + def __new__(cls, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + if times is None: + times = np.array([]) * un.s + if labels is None: + labels = np.array([], dtype='S') + if units is None: + # No keyword units, so get from `times` + try: + units = times.units + dim = units.dimensionality + except AttributeError: + raise ValueError('you must specify units') + else: + if hasattr(units, 'dimensionality'): + dim = units.dimensionality + else: + dim = un.quantity.validate_dimensionality(units) + # check to make sure the units are time + # this approach is much faster than comparing the + # reference dimensionality + if (len(dim) != 1 or list(dim.values())[0] != 1 or + not isinstance(list(dim.keys())[0], un.UnitTime)): + ValueError("Unit %s has dimensions %s, not [time]" % + (units, dim.simplified)) + + obj = un.Quantity.__new__(cls, times, units=dim) + obj.labels = labels + obj.segment = None + return obj + + def __init__(self, times=None, labels=None, units=None, name=None, description=None, + file_origin=None, **annotations): + ''' + Initialize a new :class:`Event` instance. + ''' + BaseNeo.__init__(self, name=name, file_origin=file_origin, + description=description, **annotations) + + def __array_finalize__(self, obj): + super(Event, self).__array_finalize__(obj) + self.labels = getattr(obj, 'labels', None) + self.annotations = getattr(obj, 'annotations', None) + self.name = getattr(obj, 'name', None) + self.file_origin = getattr(obj, 'file_origin', None) + self.description = getattr(obj, 'description', None) + self.segment = getattr(obj, 'segment', None) + + def __repr__(self): + ''' + Returns a string representing the :class:`Event`. + ''' + # need to convert labels to unicode for python 3 or repr is messed up + if PY_VER == 3: + labels = self.labels.astype('U') + else: + labels = self.labels + objs = ['%s@%s' % (label, time) for label, time in zip(labels, + self.times)] + return '' % ', '.join(objs) + + @property + def times(self): + return un.Quantity(self) + + def merge(self, other): + ''' + Merge the another :class:`Event` into this one. + + The :class:`Event` objects are concatenated horizontally + (column-wise), :func:`np.hstack`). + + If the attributes of the two :class:`Event` are not + compatible, and Exception is raised. + ''' + othertimes = other.times.rescale(self.times.units) + times = np.hstack([self.times, othertimes]) * self.times.units + labels = np.hstack([self.labels, other.labels]) + kwargs = {} + for name in ("name", "description", "file_origin"): + attr_self = getattr(self, name) + attr_other = getattr(other, name) + if attr_self == attr_other: + kwargs[name] = attr_self + else: + kwargs[name] = "merge(%s, %s)" % (attr_self, attr_other) + + merged_annotations = merge_annotations(self.annotations, + other.annotations) + kwargs.update(merged_annotations) + return Event(times=times, labels=labels, **kwargs) + + def _copy_data_complement(self, other): + ''' + Copy the metadata from another :class:`Event`. + ''' + for attr in ("labels", "name", "file_origin", "description", + "annotations"): + setattr(self, attr, getattr(other, attr, None)) + + def duplicate_with_new_data(self, signal): + ''' + Create a new :class:`Event` with the same metadata + but different data + ''' + new = self.__class__(times=signal) + new._copy_data_complement(self) + return new \ No newline at end of file diff --git a/neo/core/irregularlysampledsignal.py b/neo/core/irregularlysampledsignal.py index 540b1605c..21f71b739 100644 --- a/neo/core/irregularlysampledsignal.py +++ b/neo/core/irregularlysampledsignal.py @@ -23,10 +23,10 @@ from __future__ import absolute_import, division, print_function import numpy as np -import quantities as pq from neo.core.baseneo import BaseNeo, MergeError, merge_annotations +from neo import units as un def _new_IrregularlySampledSignal(cls, times, signal, units=None, time_units=None, dtype=None, copy=True, name=None, file_origin=None, description=None, @@ -40,7 +40,7 @@ def _new_IrregularlySampledSignal(cls, times, signal, units=None, time_units=Non description=description, **annotations) -class IrregularlySampledSignal(BaseNeo, pq.Quantity): +class IrregularlySampledSignal(BaseNeo, un.Quantity): ''' An array of one or more analog signals with samples taken at arbitrary time points. @@ -51,7 +51,7 @@ class IrregularlySampledSignal(BaseNeo, pq.Quantity): *Usage*:: >>> from neo.core import IrregularlySampledSignal - >>> from quantities import s, nA + >>> from neo.units import s, nA >>> >>> irsig0 = IrregularlySampledSignal([0.0, 1.23, 6.78], [1, 2, 3], ... units='mV', time_units='ms') @@ -106,8 +106,8 @@ class IrregularlySampledSignal(BaseNeo, pq.Quantity): _single_parent_objects = ('Segment', 'ChannelIndex') _quantity_attr = 'signal' - _necessary_attrs = (('times', pq.Quantity, 1), - ('signal', pq.Quantity, 2)) + _necessary_attrs = (('times', un.Quantity, 1), + ('signal', un.Quantity, 2)) def __new__(cls, times, signal, units=None, time_units=None, dtype=None, copy=True, name=None, file_origin=None, @@ -124,7 +124,7 @@ def __new__(cls, times, signal, units=None, time_units=None, dtype=None, units = signal.units else: raise ValueError("Units must be specified") - elif isinstance(signal, pq.Quantity): + elif isinstance(signal, un.Quantity): # could improve this test, what if units is a string? if units != signal.units: signal = signal.rescale(units) @@ -133,19 +133,19 @@ def __new__(cls, times, signal, units=None, time_units=None, dtype=None, time_units = times.units else: raise ValueError("Time units must be specified") - elif isinstance(times, pq.Quantity): + elif isinstance(times, un.Quantity): # could improve this test, what if units is a string? if time_units != times.units: times = times.rescale(time_units) # should check time units have correct dimensions - obj = pq.Quantity.__new__(cls, signal, units=units, + obj = un.Quantity.__new__(cls, signal, units=units, dtype=dtype, copy=copy) if obj.ndim == 1: obj = obj.reshape(-1, 1) if len(times) != obj.shape[0]: raise ValueError("times array and signal array must " "have same length") - obj.times = pq.Quantity(times, units=time_units, + obj.times = un.Quantity(times, units=time_units, dtype=float, copy=copy) obj.segment = None obj.channel_index = None @@ -226,11 +226,11 @@ def __getitem__(self, i): ''' obj = super(IrregularlySampledSignal, self).__getitem__(i) if isinstance(i, int): # a single point in time across all channels - obj = pq.Quantity(obj.magnitude, units=obj.units) + obj = un.Quantity(obj.magnitude, units=obj.units) elif isinstance(i, tuple): j, k = i if isinstance(j, int): # a single point in time across some channels - obj = pq.Quantity(obj.magnitude, units=obj.units) + obj = un.Quantity(obj.magnitude, units=obj.units) else: if isinstance(j, slice): obj.times = self.times.__getitem__(j) @@ -435,15 +435,15 @@ def rescale(self, units): Return a copy of the :class:`IrregularlySampledSignal` converted to the specified units ''' - to_dims = pq.quantity.validate_dimensionality(units) + to_dims = un.quantity.validate_dimensionality(units) if self.dimensionality == to_dims: to_u = self.units signal = np.array(self) else: - to_u = pq.Quantity(1.0, to_dims) - from_u = pq.Quantity(1.0, self.dimensionality) + to_u = un.Quantity(1.0, to_dims) + from_u = un.Quantity(1.0, self.dimensionality) try: - cf = pq.quantity.get_conversion_factor(from_u, to_u) + cf = un.quantity.get_conversion_factor(from_u, to_u) except AssertionError: raise ValueError('Unable to convert between units of "%s" \ and "%s"' % (from_u._dimensionality, diff --git a/neo/core/segment.py b/neo/core/segment.py index 9d429c31e..d1aef1273 100644 --- a/neo/core/segment.py +++ b/neo/core/segment.py @@ -27,7 +27,7 @@ class Segment(Container): *Usage*:: >>> from neo.core import Segment, SpikeTrain, AnalogSignal - >>> from quantities import Hz, s + >>> from neo.units import Hz, s >>> >>> seg = Segment(index=5) >>> diff --git a/neo/core/spiketrain.py b/neo/core/spiketrain.py index 749d1bfae..2447871dd 100644 --- a/neo/core/spiketrain.py +++ b/neo/core/spiketrain.py @@ -22,10 +22,10 @@ from __future__ import absolute_import, division, print_function import numpy as np -import quantities as pq from neo.core.baseneo import BaseNeo +from neo import units as un def check_has_dimensions_time(*values): ''' @@ -36,7 +36,7 @@ def check_has_dimensions_time(*values): for value in values: dim = value.dimensionality if (len(dim) != 1 or list(dim.values())[0] != 1 or - not isinstance(list(dim.keys())[0], pq.UnitTime)): + not isinstance(list(dim.keys())[0], un.UnitTime)): errmsgs.append("value %s has dimensions %s, not [time]" % (value, dim.simplified)) if errmsgs: @@ -89,8 +89,8 @@ def _check_waveform_dimensions(spiketrain): def _new_spiketrain(cls, signal, t_stop, units=None, dtype=None, - copy=True, sampling_rate=1.0 * pq.Hz, - t_start=0.0 * pq.s, waveforms=None, left_sweep=None, + copy=True, sampling_rate=1.0 * un.Hz, + t_start=0.0 * un.s, waveforms=None, left_sweep=None, name=None, file_origin=None, description=None, annotations=None): ''' @@ -104,7 +104,7 @@ def _new_spiketrain(cls, signal, t_stop, units=None, dtype=None, description, **annotations) -class SpikeTrain(BaseNeo, pq.Quantity): +class SpikeTrain(BaseNeo, un.Quantity): ''' :class:`SpikeTrain` is a :class:`Quantity` array of spike times. @@ -114,7 +114,7 @@ class SpikeTrain(BaseNeo, pq.Quantity): *Usage*:: >>> from neo.core import SpikeTrain - >>> from quantities import s + >>> from neo.units import s >>> >>> train = SpikeTrain([3, 4, 5]*s, t_stop=10.0) >>> train2 = train[1:3] @@ -194,16 +194,16 @@ class SpikeTrain(BaseNeo, pq.Quantity): _single_parent_objects = ('Segment', 'Unit') _quantity_attr = 'times' - _necessary_attrs = (('times', pq.Quantity, 1), - ('t_start', pq.Quantity, 0), - ('t_stop', pq.Quantity, 0)) - _recommended_attrs = ((('waveforms', pq.Quantity, 3), - ('left_sweep', pq.Quantity, 0), - ('sampling_rate', pq.Quantity, 0)) + + _necessary_attrs = (('times', un.Quantity, 1), + ('t_start', un.Quantity, 0), + ('t_stop', un.Quantity, 0)) + _recommended_attrs = ((('waveforms', un.Quantity, 3), + ('left_sweep', un.Quantity, 0), + ('sampling_rate', un.Quantity, 0)) + BaseNeo._recommended_attrs) def __new__(cls, times, t_stop, units=None, dtype=None, copy=True, - sampling_rate=1.0 * pq.Hz, t_start=0.0 * pq.s, waveforms=None, + sampling_rate=1.0 * un.Hz, t_start=0.0 * un.s, waveforms=None, left_sweep=None, name=None, file_origin=None, description=None, **annotations): ''' @@ -228,7 +228,7 @@ def __new__(cls, times, t_stop, units=None, dtype=None, copy=True, if hasattr(units, 'dimensionality'): dim = units.dimensionality else: - dim = pq.quantity.validate_dimensionality(units) + dim = un.quantity.validate_dimensionality(units) if hasattr(times, 'dimensionality'): if times.dimensionality.items() == dim.items(): @@ -263,11 +263,11 @@ def __new__(cls, times, t_stop, units=None, dtype=None, copy=True, # this approach is orders of magnitude faster than comparing the # reference dimensionality if (len(dim) != 1 or list(dim.values())[0] != 1 or - not isinstance(list(dim.keys())[0], pq.UnitTime)): + not isinstance(list(dim.keys())[0], un.UnitTime)): ValueError("Unit has dimensions %s, not [time]" % dim.simplified) # Construct Quantity from data - obj = pq.Quantity(times, units=units, dtype=dtype, copy=copy).view(cls) + obj = un.Quantity(times, units=units, dtype=dtype, copy=copy).view(cls) # if the dtype and units match, just copy the values here instead # of doing the much more expensive creation of a new Quantity @@ -277,14 +277,14 @@ def __new__(cls, times, t_stop, units=None, dtype=None, copy=True, t_start.dimensionality.items() == dim.items()): obj.t_start = t_start.copy() else: - obj.t_start = pq.Quantity(t_start, units=dim, dtype=obj.dtype) + obj.t_start = un.Quantity(t_start, units=dim, dtype=obj.dtype) if (hasattr(t_stop, 'dtype') and t_stop.dtype == obj.dtype and hasattr(t_stop, 'dimensionality') and t_stop.dimensionality.items() == dim.items()): obj.t_stop = t_stop.copy() else: - obj.t_stop = pq.Quantity(t_stop, units=dim, dtype=obj.dtype) + obj.t_stop = un.Quantity(t_stop, units=dim, dtype=obj.dtype) # Store attributes obj.waveforms = waveforms @@ -301,7 +301,7 @@ def __new__(cls, times, t_stop, units=None, dtype=None, copy=True, return obj def __init__(self, times, t_stop, units=None, dtype=np.float, - copy=True, sampling_rate=1.0 * pq.Hz, t_start=0.0 * pq.s, + copy=True, sampling_rate=1.0 * un.Hz, t_start=0.0 * un.s, waveforms=None, left_sweep=None, name=None, file_origin=None, description=None, **annotations): ''' @@ -322,9 +322,9 @@ def rescale(self, units): Return a copy of the :class:`SpikeTrain` converted to the specified units ''' - if self.dimensionality == pq.quantity.validate_dimensionality(units): + if self.dimensionality == un.quantity.validate_dimensionality(units): return self.copy() - spikes = self.view(pq.Quantity) + spikes = self.view(un.Quantity) return SpikeTrain(times=spikes, t_stop=self.t_stop, units=units, sampling_rate=self.sampling_rate, t_start=self.t_start, waveforms=self.waveforms, @@ -438,7 +438,7 @@ def __add__(self, time): Raises an exception if new time points fall outside :attr:`t_start` or :attr:`t_stop` ''' - spikes = self.view(pq.Quantity) + spikes = self.view(un.Quantity) check_has_dimensions_time(time) _check_time_in_range(spikes + time, self.t_start, self.t_stop) return SpikeTrain(times=spikes + time, t_stop=self.t_stop, @@ -456,7 +456,7 @@ def __sub__(self, time): Raises an exception if new time points fall outside :attr:`t_start` or :attr:`t_stop` ''' - spikes = self.view(pq.Quantity) + spikes = self.view(un.Quantity) check_has_dimensions_time(time) _check_time_in_range(spikes - time, self.t_start, self.t_stop) return SpikeTrain(times=spikes - time, t_stop=self.t_stop, @@ -480,7 +480,7 @@ def __setitem__(self, i, value): Set the value the item or slice :attr:`i`. ''' if not hasattr(value, "units"): - value = pq.Quantity(value, units=self.units) + value = un.Quantity(value, units=self.units) # or should we be strict: raise ValueError("Setting a value # requires a quantity")? # check for values outside t_start, t_stop @@ -489,7 +489,7 @@ def __setitem__(self, i, value): def __setslice__(self, i, j, value): if not hasattr(value, "units"): - value = pq.Quantity(value, units=self.units) + value = un.Quantity(value, units=self.units) _check_time_in_range(value, self.t_start, self.t_stop) super(SpikeTrain, self).__setslice__(i, j, value) diff --git a/neo/io/alphaomegaio.py b/neo/io/alphaomegaio.py index d1a28a62b..7ff663d06 100644 --- a/neo/io/alphaomegaio.py +++ b/neo/io/alphaomegaio.py @@ -80,11 +80,11 @@ # note neo.core need only numpy and quantities import numpy as np -import quantities as pq from neo.io.baseio import BaseIO from neo.core import Block, Segment, AnalogSignal +from neo import units as un class AlphaOmegaIO(BaseIO): """ @@ -333,7 +333,7 @@ def count_samples(m_length): ind += count sampling_rate = \ - file_blocks[list_chan[ind_chan]]['m_SampleRate'] * pq.kHz + file_blocks[list_chan[ind_chan]]['m_SampleRate'] * un.kHz t_start = (start_index / sampling_rate).simplified if lazy: ana_sig = AnalogSignal([], @@ -343,7 +343,7 @@ def count_samples(m_length): [list_chan[ind_chan]]['m_Name'], file_origin = \ os.path.basename(self.filename), - units = pq.dimensionless) + units = un.dimensionless) ana_sig.lazy_shape = chan_len[ind_chan] else: ana_sig = AnalogSignal(temp_array, @@ -353,7 +353,7 @@ def count_samples(m_length): [list_chan[ind_chan]]['m_Name'], file_origin = \ os.path.basename(self.filename), - units = pq.dimensionless) + units = un.dimensionless) # todo apibreak: create ChannelIndex for each signals # ana_sig.channel_index = \ # file_blocks[list_chan[ind_chan]]['m_numChannel'] diff --git a/neo/io/asciisignalio.py b/neo/io/asciisignalio.py index 0f825ad5e..eb37867e5 100644 --- a/neo/io/asciisignalio.py +++ b/neo/io/asciisignalio.py @@ -14,7 +14,7 @@ import os import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import AnalogSignal, Segment @@ -91,10 +91,10 @@ def read_segment(self, skiprows =0, timecolumn = None, - sampling_rate = 1.*pq.Hz, - t_start = 0.*pq.s, + sampling_rate = 1.*un.Hz, + t_start = 0.*un.s, - unit = pq.V, + unit = un.V, method = 'genfromtxt', @@ -123,13 +123,13 @@ def read_segment(self, if type(sampling_rate) == float or type(sampling_rate)==int: # if not quantitities Hz by default - sampling_rate = sampling_rate*pq.Hz + sampling_rate = sampling_rate*un.Hz if type(t_start) == float or type(t_start)==int: # if not quantitities s by default - t_start = t_start*pq.s + t_start = t_start*un.s - unit = pq.Quantity(1, unit) + unit = un.Quantity(1, unit) @@ -161,8 +161,8 @@ def read_segment(self, sig = np.array( tab , dtype = 'f') if timecolumn is not None: - sampling_rate = 1./np.mean(np.diff(sig[:,timecolumn])) * pq.Hz - t_start = sig[0,timecolumn] * pq.s + sampling_rate = 1./np.mean(np.diff(sig[:,timecolumn])) * un.Hz + t_start = sig[0,timecolumn] * un.s diff --git a/neo/io/asciispiketrainio.py b/neo/io/asciispiketrainio.py index 378da3dd0..fb4323f24 100644 --- a/neo/io/asciispiketrainio.py +++ b/neo/io/asciispiketrainio.py @@ -13,7 +13,7 @@ import os import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, SpikeTrain @@ -80,8 +80,8 @@ def read_segment(self, lazy = False, cascade = True, delimiter = '\t', - t_start = 0.*pq.s, - unit = pq.s, + t_start = 0.*un.s, + unit = un.s, ): """ Arguments: @@ -89,7 +89,7 @@ def read_segment(self, t_start : time start of all spiketrain 0 by default unit : unit of spike times, can be a str or directly a Quantities """ - unit = pq.Quantity(1, unit) + unit = un.Quantity(1, unit) seg = Segment(file_origin = os.path.basename(self.filename)) if not cascade: diff --git a/neo/io/axonio.py b/neo/io/axonio.py index 2ca459309..7b9956c86 100644 --- a/neo/io/axonio.py +++ b/neo/io/axonio.py @@ -42,7 +42,7 @@ from io import open, BufferedReader import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Block, Segment, AnalogSignal, Event @@ -235,10 +235,10 @@ def read_block(self, lazy=False, cascade=True): # sampling_rate if version < 2.: sampling_rate = 1. / (header['fADCSampleInterval'] * - nbchannel * 1.e-6) * pq.Hz + nbchannel * 1.e-6) * un.Hz elif version >= 2.: sampling_rate = 1.e6 / \ - header['protocol']['fADCSequenceInterval'] * pq.Hz + header['protocol']['fADCSequenceInterval'] * un.Hz # construct block # one sweep = one segment in a block @@ -288,17 +288,17 @@ def read_block(self, lazy=False, cascade=True): if (fSynchTimeUnit == 0): t_start = float(episode_array[j]['offset']) / sampling_rate else: - t_start = float(episode_array[j]['offset']) * fSynchTimeUnit *1e-6* pq.s + t_start = float(episode_array[j]['offset']) * fSynchTimeUnit *1e-6* un.s t_start = t_start.rescale('s') try: - pq.Quantity(1, unit) + un.Quantity(1, unit) except: unit = '' if lazy: - signal = [] * pq.Quantity(1, unit) + signal = [] * un.Quantity(1, unit) else: - signal = pq.Quantity(subdata[:, n], unit) + signal = un.Quantity(subdata[:, n], unit) anaSig = AnalogSignal(signal, sampling_rate=sampling_rate, t_start=t_start, @@ -325,10 +325,10 @@ def read_block(self, lazy=False, cascade=True): # attach all tags to the first segment. seg = bl.segments[0] if lazy: - ea = Event(times=[] * pq.s, labels=np.array([], dtype='S')) + ea = Event(times=[] * un.s, labels=np.array([], dtype='S')) ea.lazy_shape = len(times) else: - ea = Event(times=times * pq.s, labels=labels, + ea = Event(times=times * un.s, labels=labels, comments=comments) seg.events.append(ea) @@ -548,7 +548,7 @@ def read_protocol(self): 'lNumSamplesPerEpisode'] / nADC) # Number of samples per episode nEpi = header['lActualEpisodes'] # Actual number of episodes sampling_rate = 1.e6 / header['protocol'][ - 'fADCSequenceInterval'] * pq.Hz + 'fADCSequenceInterval'] * un.Hz # Make a list of segments with analog signals with just holding levels # List of segments relates to number of episodes, as for recorded data @@ -557,13 +557,13 @@ def read_protocol(self): seg = Segment(index=epiNum) # One analog signal for each DAC in segment (episode) for DACNum in range(nDAC): - t_start = 0 * pq.s # TODO: Possibly check with episode array + t_start = 0 * un.s # TODO: Possibly check with episode array name = header['listDACInfo'][DACNum]['DACChNames'] unit = header['listDACInfo'][DACNum]['DACChUnits'].\ replace(b'\xb5', b'u').decode('utf-8') # \xb5 is µ signal = np.ones(nSam) *\ header['listDACInfo'][DACNum]['fDACHoldingLevel'] *\ - pq.Quantity(1, unit) + un.Quantity(1, unit) ana_sig = AnalogSignal(signal, sampling_rate=sampling_rate, t_start=t_start, name=name.decode("utf-8"), channel_index=DACNum) @@ -581,7 +581,7 @@ def read_protocol(self): epoch['lEpochDurationInc'] * epiNum dif = i_end-i_begin ana_sig[i_begin:i_end] = np.ones((dif, 1)) *\ - pq.Quantity(1, unit) * (epoch['fEpochInitLevel'] + + un.Quantity(1, unit) * (epoch['fEpochInitLevel'] + epoch['fEpochLevelInc'] * epiNum) i_last += epoch['lEpochInitDuration'] diff --git a/neo/io/blackrockio.py b/neo/io/blackrockio.py index 701fa7907..ca3a4ba0f 100644 --- a/neo/io/blackrockio.py +++ b/neo/io/blackrockio.py @@ -51,7 +51,7 @@ import types import numpy as np -import quantities as pq +from neo import units as un import neo from neo.io.baseio import BaseIO @@ -1004,7 +1004,7 @@ def __nev_params(self, param_name): 'max_res': self.__nev_basic_header['timestamp_resolution'], 'channel_ids': self.__nev_ext_header[b'NEUEVWAV']['electrode_id'], 'channel_labels': self.__channel_labels[self.__nev_spec](), - 'event_unit': pq.CompoundUnit("1.0/{0} * s".format( + 'event_unit': un.CompoundUnit("1.0/{0} * s".format( self.__nev_basic_header['timestamp_resolution'])), 'nb_units': dict(zip( self.__nev_ext_header[b'NEUEVWAV']['electrode_id'], @@ -1013,10 +1013,10 @@ def __nev_params(self, param_name): 'waveform_size': self.__waveform_size[self.__nev_spec](), 'waveform_dtypes': self.__get_waveforms_dtype(), 'waveform_sampling_rate': - self.__nev_basic_header['sample_resolution'] * pq.Hz, - 'waveform_time_unit': pq.CompoundUnit("1.0/{0} * s".format( + self.__nev_basic_header['sample_resolution'] * un.Hz, + 'waveform_time_unit': un.CompoundUnit("1.0/{0} * s".format( self.__nev_basic_header['sample_resolution'])), - 'waveform_unit': pq.uV} + 'waveform_unit': un.uV} return nev_parameters[param_name] @@ -1242,8 +1242,8 @@ def __get_nsx_param_variant_a(self, param_name, nsx_nb): self.__nsx_ext_header[nsx_nb].dtype.itemsize * self.__nsx_basic_header[nsx_nb]['channel_count'], 'sampling_rate': - 30000 / self.__nsx_basic_header[nsx_nb]['period'] * pq.Hz, - 'time_unit': pq.CompoundUnit("1.0/{0}*s".format( + 30000 / self.__nsx_basic_header[nsx_nb]['period'] * un.Hz, + 'time_unit': un.CompoundUnit("1.0/{0}*s".format( 30000 / self.__nsx_basic_header[nsx_nb]['period']))} return nsx_parameters[param_name] @@ -1272,8 +1272,8 @@ def __get_nsx_param_variant_b(self, param_name, nsx_nb): self.__nsx_basic_header[nsx_nb]['bytes_in_headers'], 'sampling_rate': self.__nsx_basic_header[nsx_nb]['timestamp_resolution'] / - self.__nsx_basic_header[nsx_nb]['period'] * pq.Hz, - 'time_unit': pq.CompoundUnit("1.0/{0}*s".format( + self.__nsx_basic_header[nsx_nb]['period'] * un.Hz, + 'time_unit': un.CompoundUnit("1.0/{0}*s".format( self.__nsx_basic_header[nsx_nb]['timestamp_resolution'] / self.__nsx_basic_header[nsx_nb]['period']))} @@ -1558,7 +1558,7 @@ def __transform_times(self, n, default_n): """ highest_res = self.__nev_params('event_unit') - if isinstance(n, pq.Quantity): + if isinstance(n, un.Quantity): n = [n.rescale(highest_res)] elif hasattr(n, "__len__"): n = [tp.rescale(highest_res) if tp is not None @@ -1847,7 +1847,7 @@ def __read_analogsignal( t_start=data_times[0].rescale(nsx_time_unit) anasig = AnalogSignal( - signal=pq.Quantity(sig_ch, units[idx_ch].decode(), copy=False), + signal=un.Quantity(sig_ch, units[idx_ch].decode(), copy=False), sampling_rate=sampling_rate, t_start=t_start, name=labels[idx_ch], @@ -1877,16 +1877,16 @@ def __read_unit(self, unit_id, channel_idx): desc = 'Unit from channel: {0}, id: {1}'.format( channel_idx, self.__get_unit_classification(unit_id)) - un = Unit( + unit_to_return = Unit( name=name, description=desc, file_origin='.'.join([self._filenames['nev'], 'nev'])) # add additional annotations - un.annotate(ch_idx=int(channel_idx)) - un.annotate(unit_id=int(unit_id)) + unit_to_return.annotate(ch_idx=int(channel_idx)) + unit_to_return.annotate(unit_id=int(unit_id)) - return un + return unit_to_return def __read_recordingchannelgroup( self, channel_idx, index=None, channel_units=None, cascade=True): @@ -1895,6 +1895,7 @@ def __read_recordingchannelgroup( given index for the given channels containing a neo.core.unit.Unit object list of the given units. """ + from neo import units as un rcg = ChannelIndex( np.array([channel_idx]), @@ -1924,11 +1925,11 @@ def __read_recordingchannelgroup( connector_pin=self.__nev_ext_header[ b'NEUEVWAV']['connector_pin'][get_idx], energy_threshold=self.__nev_ext_header[ - b'NEUEVWAV']['energy_threshold'][get_idx] * pq.uV, + b'NEUEVWAV']['energy_threshold'][get_idx] * un.uV, hi_threshold=self.__nev_ext_header[ - b'NEUEVWAV']['hi_threshold'][get_idx] * pq.uV, + b'NEUEVWAV']['hi_threshold'][get_idx] * un.uV, lo_threshold=self.__nev_ext_header[ - b'NEUEVWAV']['lo_threshold'][get_idx] * pq.uV, + b'NEUEVWAV']['lo_threshold'][get_idx] * un.uV, nb_sorted_units=self.__nev_ext_header[ b'NEUEVWAV']['nb_sorted_units'][get_idx], waveform_size=self.__waveform_size[self.__nev_spec]( diff --git a/neo/io/blackrockio_deprecated.py b/neo/io/blackrockio_deprecated.py index c92eedca9..488410e5b 100644 --- a/neo/io/blackrockio_deprecated.py +++ b/neo/io/blackrockio_deprecated.py @@ -7,7 +7,7 @@ import struct import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import (Block, Segment, @@ -56,7 +56,7 @@ class BlackrockIO(BaseIO): write_params = None - def __init__(self, filename, full_range=8192.*pq.mV) : + def __init__(self, filename, full_range=8192.*un.mV) : """Initialize Blackrock reader. **Arguments** @@ -186,8 +186,8 @@ def read_segment(self, n_start, n_stop, chlist=None, lazy=False, cascade=True): # Create an AnalogSignal with the data in it anasig = AnalogSignal(signal=sig, - sampling_rate=self.header.f_samp*pq.Hz, - t_start=t_start*pq.s, file_origin=self.filename, + sampling_rate=self.header.f_samp*un.Hz, + t_start=t_start*un.s, file_origin=self.filename, description='Channel %d from %f to %f' % (ch, t_start, t_stop), channel_index=int(ch)) diff --git a/neo/io/brainvisionio.py b/neo/io/brainvisionio.py index ddd9dcbd8..69f18c3df 100644 --- a/neo/io/brainvisionio.py +++ b/neo/io/brainvisionio.py @@ -14,7 +14,7 @@ import re import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, Event @@ -73,7 +73,7 @@ def read_segment(self, lazy=False, cascade=True): 'DataOrientation'] == 'MULTIPLEXED', NotImplementedError nb_channel = int(header['Common Infos']['NumberOfChannels']) sampling_rate = 1.e6 / float( - header['Common Infos']['SamplingInterval']) * pq.Hz + header['Common Infos']['SamplingInterval']) * un.Hz fmt = header['Binary Infos']['BinaryFormat'] fmts = { 'INT_16':np.int16, 'INT_32':np.int32, 'IEEE_FLOAT_32':np.float32,} @@ -97,7 +97,7 @@ def read_segment(self, lazy=False, cascade=True): for c in range(nb_channel): name, ref, res, units = header['Channel Infos'][ 'Ch%d' % (c + 1,)].split(',') - units = pq.Quantity(1, units.replace('µ', 'u')) + units = un.Quantity(1, units.replace('µ', 'u')) if lazy: signal = [] * units else: @@ -126,7 +126,7 @@ def read_segment(self, lazy=False, cascade=True): times.append(float(pos) / sampling_rate.magnitude) labels.append(label) all_types = np.array(all_types) - times = np.array(times) * pq.s + times = np.array(times) * un.s labels = np.array(labels, dtype='S') for type_ in np.unique(all_types): ind = type_ == all_types diff --git a/neo/io/brainwaredamio.py b/neo/io/brainwaredamio.py index 5fea6f6b2..29ea084cf 100644 --- a/neo/io/brainwaredamio.py +++ b/neo/io/brainwaredamio.py @@ -35,7 +35,7 @@ # numpy and quantities are already required by neo import numpy as np -import quantities as pq +from neo import units as un # needed core neo modules from neo.core import (AnalogSignal, Block, @@ -228,17 +228,17 @@ def _read_segment(self, fobject, lazy): # handle lazy loading if lazy: - sig = AnalogSignal([], t_start=t_start*pq.d, + sig = AnalogSignal([], t_start=t_start*un.d, file_origin=self._filename, - sampling_period=1.*pq.s, - units=pq.mV, + sampling_period=1.*un.s, + units=un.mV, dtype=np.float) sig.lazy_shape = len(signal) else: - sig = AnalogSignal(signal.astype(np.float)*pq.mV, - t_start=t_start*pq.d, + sig = AnalogSignal(signal.astype(np.float)*un.mV, + t_start=t_start*un.d, file_origin=self._filename, - sampling_period=1.*pq.s, + sampling_period=1.*un.s, copy=False) # Note: setting the sampling_period to 1 s is arbitrary diff --git a/neo/io/brainwaref32io.py b/neo/io/brainwaref32io.py index 54534c640..7841c1198 100644 --- a/neo/io/brainwaref32io.py +++ b/neo/io/brainwaref32io.py @@ -33,7 +33,7 @@ # numpy and quantities are already required by neo import numpy as np -import quantities as pq +from neo import units as un # needed core neo modules from neo.core import Block, ChannelIndex, Segment, SpikeTrain, Unit @@ -286,16 +286,16 @@ def __save_segment(self): self.__spiketimes = [] if self.__lazy: - train = SpikeTrain(pq.Quantity([], dtype=np.float32, - units=pq.ms), - t_start=0*pq.ms, t_stop=self.__t_stop * pq.ms, + train = SpikeTrain(un.Quantity([], dtype=np.float32, + units=un.ms), + t_start=0*un.ms, t_stop=self.__t_stop * un.ms, file_origin=self._filename) train.lazy_shape = len(self.__spiketimes) else: - times = pq.Quantity(self.__spiketimes, dtype=np.float32, - units=pq.ms) + times = un.Quantity(self.__spiketimes, dtype=np.float32, + units=un.ms) train = SpikeTrain(times, - t_start=0*pq.ms, t_stop=self.__t_stop * pq.ms, + t_start=0*un.ms, t_stop=self.__t_stop * un.ms, file_origin=self._filename) self.__seg.spiketrains = [train] diff --git a/neo/io/brainwaresrcio.py b/neo/io/brainwaresrcio.py index 0f94ec370..6ed0ef981 100755 --- a/neo/io/brainwaresrcio.py +++ b/neo/io/brainwaresrcio.py @@ -43,7 +43,7 @@ # numpy and quantities are already required by neo import numpy as np -import quantities as pq +from neo import units as un # needed core neo modules from neo.core import (Block, Event, @@ -469,7 +469,7 @@ def _assign_sequence(self, data_obj): used since manual reorganization may be needed. """ if isinstance(data_obj, Unit): - self.logger.warning('Unknown Unit found, adding to Units list') + self.logger.warning('Unknown Unit found, adding to un list') self._chx.units.append(data_obj) if data_obj.name: self._unitdict[data_obj.name] = data_obj @@ -494,22 +494,22 @@ def _assign_sequence(self, data_obj): 'skipping', type(data_obj)) _default_datetime = datetime(1, 1, 1) - _default_t_start = pq.Quantity(0., units=pq.ms, dtype=np.float32) - _init_default_spiketrain = SpikeTrain(times=pq.Quantity([], units=pq.ms, + _default_t_start = un.Quantity(0., units=un.ms, dtype=np.float32) + _init_default_spiketrain = SpikeTrain(times=un.Quantity([], units=un.ms, dtype=np.float32), - t_start=pq.Quantity(0, units=pq.ms, + t_start=un.Quantity(0, units=un.ms, dtype=np.float32 ), - t_stop=pq.Quantity(1, units=pq.ms, + t_stop=un.Quantity(1, units=un.ms, dtype=np.float32), - waveforms=pq.Quantity([[[]]], + waveforms=un.Quantity([[[]]], dtype=np.int8, - units=pq.mV), + units=un.mV), dtype=np.float32, copy=False, timestamp=_default_datetime, respwin=np.array([], dtype=np.int32), dama_index=-1, - trig2=pq.Quantity([], units=pq.ms, + trig2=un.Quantity([], units=un.ms, dtype=np.uint8), side='') @@ -519,7 +519,7 @@ def _combine_events(self, events): with single events into one long Event """ if not events or self._lazy: - event = Event(times=pq.Quantity([], units=pq.s), + event = Event(times=un.Quantity([], units=un.s), labels=np.array([], dtype='S'), senders=np.array([], dtype='S'), t_start=0) @@ -537,7 +537,7 @@ def _combine_events(self, events): times = np.array(times, dtype=np.float32) t_start = times.min() - times = pq.Quantity(times-t_start, units=pq.d).rescale(pq.s) + times = un.Quantity(times-t_start, units=un.d).rescale(un.s) labels = np.array(labels) senders = np.array(senders) @@ -593,7 +593,7 @@ def _combine_spiketrains(self, spiketrains): # get the times of the spiketrains and combine them waveforms = [itrain.waveforms for itrain in spiketrains] rawtrains = np.array(np.concatenate(spiketrains, axis=1)) - times = pq.Quantity(rawtrains, units=pq.ms, copy=False) + times = un.Quantity(rawtrains, units=un.ms, copy=False) lens1 = np.array([wave.shape[1] for wave in waveforms]) lens2 = np.array([wave.shape[2] for wave in waveforms]) if lens1.max() != lens1.min() or lens2.max() != lens2.min(): @@ -611,7 +611,7 @@ def _combine_spiketrains(self, spiketrains): # extract the trig2 annotation trig2 = np.array(np.concatenate([itrain.annotations['trig2'] for itrain in spiketrains], axis=1)) - trig2 = pq.Quantity(trig2, units=pq.ms) + trig2 = un.Quantity(trig2, units=un.ms) elif hasattr(spiketrains[0], 'units'): return self._combine_spiketrains([spiketrains]) else: @@ -619,7 +619,7 @@ def _combine_spiketrains(self, spiketrains): times = np.concatenate(times, axis=0) # get the times of the SpikeTrains and combine them - times = pq.Quantity(times, units=pq.ms, copy=False) + times = un.Quantity(times, units=un.ms, copy=False) # get the waveforms of the SpikeTrains and combine them # these should be a 3D array with the first axis being the spike, @@ -628,8 +628,8 @@ def _combine_spiketrains(self, spiketrains): waveforms = np.concatenate(waveforms, axis=0) # extract the trig2 annotation - trig2 = pq.Quantity(np.hstack(trig2), - units=pq.ms, copy=False) + trig2 = un.Quantity(np.hstack(trig2), + units=un.ms, copy=False) if not times.size: return self._default_spiketrain.copy() @@ -639,10 +639,10 @@ def _combine_spiketrains(self, spiketrains): if self._lazy: timesshape = times.shape - times = pq.Quantity([], units=pq.ms, copy=False) - waveforms = pq.Quantity([[[]]], units=pq.mV) + times = un.Quantity([], units=un.ms, copy=False) + waveforms = un.Quantity([[[]]], units=un.mV) else: - waveforms = pq.Quantity(waveforms, units=pq.mV, copy=False) + waveforms = un.Quantity(waveforms, units=un.mV, copy=False) train = SpikeTrain(times=times, copy=False, t_start=self._default_t_start.copy(), t_stop=t_stop, @@ -788,7 +788,7 @@ def __read_comment(self): # char * numchars -- comment text text = self.__read_str(numchars2, utf=False) - comment = Event(times=pq.Quantity(time, units=pq.d), labels=text, + comment = Event(times=un.Quantity(time, units=un.d), labels=text, sender=sender, file_origin=self._file_origin) self._seg0.events.append(comment) @@ -924,8 +924,8 @@ def __read_segment(self): trains = zip(*trains) # int32 -- SpikeTrain length in ms - spiketrainlen = pq.Quantity(np.fromfile(self._fsrc, dtype=np.int32, - count=1)[0], units=pq.ms, copy=False) + spiketrainlen = un.Quantity(np.fromfile(self._fsrc, dtype=np.int32, + count=1)[0], units=un.ms, copy=False) segments = [] for train in trains: @@ -1092,9 +1092,9 @@ def __read_segment_list_var(self): """ # float32 -- DA conversion clock period in microsec - sampling_period = pq.Quantity(np.fromfile(self._fsrc, + sampling_period = un.Quantity(np.fromfile(self._fsrc, dtype=np.float32, count=1), - units=pq.us, copy=False)[0] + units=un.us, copy=False)[0] # segment_collection -- this is based off a segment_collection segments = self.__read_segment_list() @@ -1447,8 +1447,8 @@ def __read_unit_unsorted(self): # int32 -- SpikeTrain length in ms # int32 * 4 -- response and spon period boundaries parts = np.fromfile(self._fsrc, dtype=np.int32, count=5) - t_stop = pq.Quantity(parts[0].astype('float32'), - units=pq.ms, copy=False) + t_stop = un.Quantity(parts[0].astype('float32'), + units=un.ms, copy=False) respwin = parts[1:] # (data_obj) -- list of SpikeTrains diff --git a/neo/io/elanio.py b/neo/io/elanio.py index 1889491e1..a97e7aebf 100644 --- a/neo/io/elanio.py +++ b/neo/io/elanio.py @@ -25,7 +25,7 @@ import re import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, Event @@ -150,7 +150,7 @@ def read_segment(self, lazy=False, cascade=True): # sampling rate sample l = f.readline() - sampling_rate = 1. / float(l) * pq.Hz + sampling_rate = 1. / float(l) * un.Hz # nb channel l = f.readline() @@ -207,13 +207,13 @@ def read_segment(self, lazy=False, cascade=True): (max_physic[c] - min_physic[c]) + min_physic[c] try: - unit = pq.Quantity(1, units[c]) + unit = un.Quantity(1, units[c]) except: - unit = pq.Quantity(1, '') + unit = un.Quantity(1, '') ana_sig = AnalogSignal( sig * unit, sampling_rate=sampling_rate, - t_start=0. * pq.s, name=labels[c], channel_index=c) + t_start=0. * un.s, name=labels[c], channel_index=c) if lazy: ana_sig.lazy_shape = data.shape[0] ana_sig.annotate(channel_name=labels[c]) @@ -230,11 +230,11 @@ def read_segment(self, lazy=False, cascade=True): labels.append(str(r[0][1])) reject_codes.append(str(r[0][2])) if lazy: - times = [] * pq.S + times = [] * un.S labels = np.array([], dtype='S') reject_codes = [] else: - times = np.array(times) * pq.s + times = np.array(times) * un.s labels = np.array(labels) reject_codes = np.array(reject_codes) ea = Event(times=times, labels=labels, reject_codes=reject_codes) @@ -308,9 +308,9 @@ def read_segment(self, lazy=False, cascade=True): #~ for i, anaSig in enumerate(seg._analogsignals) : #~ # in elan file unit is supposed to be in microV to have a big range #~ # so auto translate - #~ if anaSig.units == pq.V or anaSig.units == pq.mV: + #~ if anaSig.units == un.V or anaSig.units == un.mV: #~ s = anaSig.rescale('uV').magnitude - #~ elif anaSig.units == pq.uV: + #~ elif anaSig.units == un.uV: #~ s = anaSig.magnitude #~ else: #~ # automatic range in arbitrry unit diff --git a/neo/io/elphyio.py b/neo/io/elphyio.py index 032fb40db..c82af666f 100644 --- a/neo/io/elphyio.py +++ b/neo/io/elphyio.py @@ -53,8 +53,7 @@ filled with other NEO structures: >>> import numpy as np ->>> import quantities as pq ->>> a = AnalogSignal( signal=np.random.rand(300), t_start=42*pq.ms) +>>> a = AnalogSignal( signal=np.random.rand(300), t_start=42*Units.ms) >>> s.analogsignals.append( a ) and added to a newly created NEO Block: @@ -85,7 +84,7 @@ # note neo.core needs only numpy and quantities import numpy as np -import quantities as pq +from neo import units as un # I need to subclass BaseIO from neo.io.baseio import BaseIO @@ -4164,10 +4163,10 @@ def read_segment( self, episode ): analog_signal = AnalogSignal( signal.data['y'], units = signal.y_unit, - t_start = signal.t_start * getattr(pq, signal.x_unit.strip()), - t_stop = signal.t_stop * getattr(pq, signal.x_unit.strip()), - #sampling_rate = signal.sampling_frequency * pq.kHz, - sampling_period = signal.sampling_period * getattr(pq, signal.x_unit.strip()), + t_start = signal.t_start * getattr(un, signal.x_unit.strip()), + t_stop = signal.t_stop * getattr(un, signal.x_unit.strip()), + #sampling_rate = signal.sampling_frequency * un.kHz, + sampling_period = signal.sampling_period * getattr(un, signal.x_unit.strip()), channel_name="episode %s, channel %s" % ( int(episode+1), int(channel+1) ) ) analog_signal.segment = segment @@ -4237,7 +4236,7 @@ def read_event( self, episode, evt ): """ event = self.elphy_file.get_event(episode, evt) neo_event = Event( - times=event.times * pq.s, + times=event.times * un.s, channel_name="episode %s, event channel %s" % (episode + 1, evt + 1) ) return neo_event @@ -4256,7 +4255,7 @@ def read_spiketrain( self, episode, spk ): """ block = self.elphy_file.layout.episode_block(episode) spike = self.elphy_file.get_spiketrain(episode, spk) - spikes = spike.times * pq.s + spikes = spike.times * un.s #print "read_spiketrain() - spikes: %s" % (len(spikes)) #print "read_spiketrain() - spikes:",spikes dct = { diff --git a/neo/io/exampleio.py b/neo/io/exampleio.py index a7f1effcb..e9cc76214 100644 --- a/neo/io/exampleio.py +++ b/neo/io/exampleio.py @@ -22,7 +22,7 @@ # note neo.core needs only numpy and quantities import numpy as np -import quantities as pq +from neo import units as un # but my specific IO can depend on many other packages try: @@ -211,9 +211,9 @@ def read_segment(self, n = 1000 # neo.io support quantities my vector use second for unit - eva = Event(timevect[(np.random.rand(n)*timevect.size).astype('i')]* pq.s) + eva = Event(timevect[(np.random.rand(n)*timevect.size).astype('i')]* un.s) # all duration are the same - eva.durations = np.ones(n)*500*pq.ms # Event doesn't have durations. Is Epoch intended here? + eva.durations = np.ones(n)*500*un.ms # Event doesn't have durations. Is Epoch intended here? # label l = [ ] for i in range(n): @@ -246,16 +246,16 @@ def read_analogsignal(self , if lazy: - anasig = AnalogSignal([], units='V', sampling_rate=sr * pq.Hz, - t_start=t_start * pq.s, + anasig = AnalogSignal([], units='V', sampling_rate=sr * un.Hz, + t_start=t_start * un.s, channel_index=channel_index) # we add the attribute lazy_shape with the size if loaded anasig.lazy_shape = tvect.shape else: # create analogsignal (sinus of 3 Hz) sig = np.sin(2*np.pi*tvect*sinus_freq + channel_index/5.*2*np.pi)+np.random.rand(tvect.size) - anasig = AnalogSignal(sig, units= 'V', sampling_rate=sr * pq.Hz, - t_start=t_start * pq.s, + anasig = AnalogSignal(sig, units= 'V', sampling_rate=sr * un.Hz, + t_start=t_start * un.s, channel_index=channel_index) # for attributes out of neo you can annotate @@ -295,8 +295,8 @@ def read_spiketrain(self , t_start) # create a spiketrain - spiketr = SpikeTrain(times, t_start = t_start*pq.s, t_stop = (t_start+segment_duration)*pq.s , - units = pq.s, + spiketr = SpikeTrain(times, t_start = t_start*un.s, t_stop = (t_start+segment_duration)*un.s , + units = un.s, name = 'it is a spiketrain from exampleio', ) @@ -317,9 +317,9 @@ def read_spiketrain(self , # in our case it is mono electrode so dim 1 is size 1 waveforms = np.tile( w[np.newaxis,np.newaxis,:], ( num_spike_by_spiketrain ,1, 1) ) waveforms *= np.random.randn(*waveforms.shape)/6+1 - spiketr.waveforms = waveforms*pq.mV - spiketr.sampling_rate = sr * pq.Hz - spiketr.left_sweep = 1.5* pq.s + spiketr.waveforms = waveforms*un.mV + spiketr.sampling_rate = sr * un.Hz + spiketr.left_sweep = 1.5* un.s # for attributes out of neo you can annotate spiketr.annotate(channel_index = channel_index) diff --git a/neo/io/hdf5io.py b/neo/io/hdf5io.py index 166731d50..c647dcd71 100644 --- a/neo/io/hdf5io.py +++ b/neo/io/hdf5io.py @@ -9,7 +9,7 @@ import logging import pickle import numpy as np -import quantities as pq +from neo import units as un try: import h5py except ImportError as err: @@ -329,7 +329,7 @@ def _get_quantity(self, node): else: value = node.value unit_str = [x for x in node.attrs.keys() if "unit" in x][0].split("__")[1] - units = getattr(pq, unit_str) + units = getattr(un, unit_str) return value * units def _get_standard_attributes(self, node): diff --git a/neo/io/igorproio.py b/neo/io/igorproio.py index b86a202f5..576e3b463 100644 --- a/neo/io/igorproio.py +++ b/neo/io/igorproio.py @@ -13,7 +13,7 @@ from __future__ import absolute_import from warnings import warn import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Block, Segment, AnalogSignal try: @@ -102,8 +102,8 @@ def read_analogsignal(self, lazy=False, cascade=True): assert header['topFullScale'] == 0 units = "".join(header['dataUnits']) time_units = "".join(header['xUnits']) or "s" - t_start = pq.Quantity(header['hsB'], time_units) - sampling_period = pq.Quantity(header['hsA'], time_units) + t_start = un.Quantity(header['hsB'], time_units) + sampling_period = un.Quantity(header['hsA'], time_units) if self.parse_notes: try: annotations = self.parse_notes(note) diff --git a/neo/io/kwikio.py b/neo/io/kwikio.py index 06bc7d820..10895698b 100644 --- a/neo/io/kwikio.py +++ b/neo/io/kwikio.py @@ -17,7 +17,7 @@ from __future__ import division import numpy as np -import quantities as pq +from neo import units as un import os try: @@ -114,6 +114,7 @@ def read_block(self, assert isinstance(cluster_metadata, str) blk = Block() if cascade: + seg = Segment(file_origin=self.filename) blk.segments += [seg] for model in self.models: @@ -150,7 +151,7 @@ def read_block(self, ana.channel_index = chx seg.analogsignals.append(ana) - seg.duration = model.duration * pq.s + seg.duration = model.duration * un.s blk.create_many_to_one_relationship() return blk @@ -166,8 +167,9 @@ def read_analogsignal(self, model, units='uV', units: str, default = "uV" SI units of the raw trace according to voltage_gain given to klusta """ + arr = model.traces[:]*model.metadata['voltage_gain'] - ana = AnalogSignal(arr, sampling_rate=model.sample_rate*pq.Hz, + ana = AnalogSignal(arr, sampling_rate=model.sample_rate*un.Hz, units=units, file_origin=model.metadata['raw_data_files']) return ana @@ -195,7 +197,7 @@ def read_spiketrain(self, cluster_id, model, print("Exception: cluster_id (%d) not found !! " % cluster_id) return clusters = model.spike_clusters - idx = np.argwhere(clusters == cluster_id) + idx = un.argwhere(clusters == cluster_id) if get_waveforms: w = model.all_waveforms[idx] # klusta: num_spikes, samples_per_spike, num_chans = w.shape @@ -204,7 +206,8 @@ def read_spiketrain(self, cluster_id, model, w = None sptr = SpikeTrain(times=model.spike_times[idx], t_stop=model.duration, waveforms=w, units='s', - sampling_rate=model.sample_rate*pq.Hz, + sampling_rate=model.sample_rate*un.Hz, file_origin=self.filename, **{'cluster_id': cluster_id}) return sptr + diff --git a/neo/io/micromedio.py b/neo/io/micromedio.py index c2846952f..eddb105ab 100644 --- a/neo/io/micromedio.py +++ b/neo/io/micromedio.py @@ -22,7 +22,7 @@ file = io.BufferedReader import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, Epoch, Event @@ -139,8 +139,8 @@ def read_segment(self, cascade=True, lazy=False, ): f.seek(pos, 0) code = np.fromfile(f, dtype='u2', count=Num_Chan) - units = {-1: pq.nano * pq.V, 0: pq.uV, 1: pq.mV, 2: 1, 100: pq.percent, - 101: pq.dimensionless, 102: pq.dimensionless} + units = {-1: un.nano * un.V, 0: un.uV, 1: un.mV, 2: 1, 100: un.percent, + 101: un.dimensionless, 102: un.dimensionless} for c in range(Num_Chan): zname2, pos, length = zones['LABCOD'] @@ -154,10 +154,10 @@ def read_segment(self, cascade=True, lazy=False, ): if k in units.keys(): unit = units[k] else: - unit = pq.uV + unit = un.uV f.seek(8, 1) - sampling_rate, = f.read_f('H') * pq.Hz + sampling_rate, = f.read_f('H') * un.Hz sampling_rate *= Rate_Min if lazy: @@ -177,7 +177,7 @@ def read_segment(self, cascade=True, lazy=False, ): seg.analogsignals.append(ana_sig) sampling_rate = np.mean( - [ana_sig.sampling_rate for ana_sig in seg.analogsignals]) * pq.Hz + [ana_sig.sampling_rate for ana_sig in seg.analogsignals]) * un.Hz # Read trigger and notes for zname, label_dtype in [('TRIGGER', 'u2'), ('NOTE', 'S40')]: diff --git a/neo/io/neomatlabio.py b/neo/io/neomatlabio.py index a77f80169..fb997daab 100644 --- a/neo/io/neomatlabio.py +++ b/neo/io/neomatlabio.py @@ -18,7 +18,7 @@ import re import numpy as np -import quantities as pq +from neo import units as un # check scipy try: @@ -143,7 +143,8 @@ class NeoMatlabIO(BaseIO): This Python code generates the same block as in the previous scenario:: import neo - import quantities as pq + from neo import units as un + from scipy import rand, array bl = neo.Block(name='my block with neo') @@ -151,13 +152,13 @@ class NeoMatlabIO(BaseIO): seg = neo.Segment(name='segment' + str(s)) bl.segments.append(seg) for a in range(5): - anasig = neo.AnalogSignal(rand(100)*pq.mV, t_start=0*pq.s, sampling_rate=100*pq.Hz) + anasig = neo.AnalogSignal(rand(100)*un.mV, t_start=0*un.s, sampling_rate=100*un.Hz) seg.analogsignals.append(anasig) for t in range(7): - sptr = neo.SpikeTrain(rand(40)*pq.ms, t_start=0*pq.ms, t_stop=10*pq.ms) + sptr = neo.SpikeTrain(rand(40)*un.ms, t_start=0*un.ms, t_stop=10*un.ms) seg.spiketrains.append(sptr) - ev = neo.Event([0, 10, 30]*pq.ms, labels=array(['trig0', 'trig1', 'trig2'])) - ep = neo.Epoch([10, 20]*pq.ms, durations=[4, 10]*pq.ms, labels=array(['a0', 'a1'])) + ev = neo.Event([0, 10, 30]*un.ms, labels=array(['trig0', 'trig1', 'trig2'])) + ep = neo.Epoch([10, 20]*un.ms, durations=[4, 10]*un.ms, labels=array(['a0', 'a1'])) seg.events.append(ev) seg.epochs.append(ep) @@ -295,7 +296,7 @@ def create_struct_from_obj(self, ob): if getattr(ob, attrname) is None: continue - if attrtype == pq.Quantity: + if attrtype == un.Quantity: #ndim = attr[2] struct[attrname] = getattr(ob, attrname).magnitude struct[attrname + '_units'] = getattr( @@ -313,7 +314,7 @@ def create_ob_from_struct(self, struct, classname, # check if hinerits Quantity #~ is_quantity = False #~ for attr in cl._necessary_attrs: - #~ if attr[0] == '' and attr[1] == pq.Quantity: + #~ if attr[0] == '' and attr[1] == un.Quantity: #~ is_quantity = True #~ break #~ is_quantiy = hasattr(cl, '_quantity_attr') @@ -327,7 +328,7 @@ def create_ob_from_struct(self, struct, classname, getattr(struct, quantity_attr + '_units'))) if "sampling_rate" in (at[0] for at in cl._necessary_attrs): # put fake value for now, put correct value later - data_complement["sampling_rate"] = 0 * pq.kHz + data_complement["sampling_rate"] = 0 * un.kHz if "t_stop" in (at[0] for at in cl._necessary_attrs): if len(arr) > 0: data_complement["t_stop"] = arr.max() @@ -396,17 +397,17 @@ def create_ob_from_struct(self, struct, classname, ob.lazy_shape = item.shape else: item = item.astype(dt) - elif attrtype == pq.Quantity: + elif attrtype == un.Quantity: ndim = dict_attributes[attrname][1] units = str(getattr(struct, attrname+'_units')) if ndim == 0: - item = pq.Quantity(item, units) + item = un.Quantity(item, units) else: if lazy: - item = pq.Quantity([], units) + item = un.Quantity([], units) item.lazy_shape = item.shape else: - item = pq.Quantity(item, units) + item = un.Quantity(item, units) else: item = attrtype(item) diff --git a/neo/io/nestio.py b/neo/io/nestio.py index 0ba1688d7..98b380fc3 100644 --- a/neo/io/nestio.py +++ b/neo/io/nestio.py @@ -19,15 +19,15 @@ import warnings from datetime import datetime import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Block, Segment, SpikeTrain, AnalogSignal -value_type_dict = {'V': pq.mV, - 'I': pq.pA, - 'g': pq.CompoundUnit("10^-9*S"), - 'no type': pq.dimensionless} +value_type_dict = {'V': un.mV, + 'I': un.pA, + 'g': un.CompoundUnit("10^-9*S"), + 'no type': un.dimensionless} class NestIO(BaseIO): @@ -41,8 +41,8 @@ class NestIO(BaseIO): files = ['membrane_voltages-1261-0.dat', 'spikes-1258-0.gdf'] r = NestIO(filenames=files) - seg = r.read_segment(gid_list=[], t_start=400 * pq.ms, - t_stop=600 * pq.ms, + seg = r.read_segment(gid_list=[], t_start=400 * un.ms, + t_stop=600 * un.ms, id_column_gdf=0, time_column_gdf=1, id_column_dat=0, time_column_dat=1, value_columns_dat=2) @@ -261,8 +261,8 @@ def _check_input_times(self, t_start, t_stop, mandatory=True): Checks input times for existence and setting default values if necessary. - t_start: pq.quantity.Quantity, start time of the time range to load. - t_stop: pq.quantity.Quantity, stop time of the time range to load. + t_start: un.quantity.Quantity, start time of the time range to load. + t_stop: un.quantity.Quantity, stop time of the time range to load. mandatory: bool, if True times can not be None and an error will be raised. if False, time values of None will be replaced by -infinity or infinity, respectively. default: True. @@ -271,15 +271,15 @@ def _check_input_times(self, t_start, t_stop, mandatory=True): if mandatory: raise ValueError('No t_start specified.') else: - t_stop = np.inf * pq.s + t_stop = np.inf * un.s if t_start is None: if mandatory: raise ValueError('No t_stop specified.') else: - t_start = -np.inf * pq.s + t_start = -np.inf * un.s for time in (t_start, t_stop): - if not isinstance(time, pq.quantity.Quantity): + if not isinstance(time, un.quantity.Quantity): raise TypeError('Time value (%s) is not a quantity.' % time) return t_start, t_stop @@ -318,7 +318,7 @@ def _check_input_values_parameters(self, value_columns, value_types, 'not match (%i,%i,%i)' % (len(value_types), len(value_units), len(value_columns))) - if not all([isinstance(vunit, pq.UnitQuantity) for vunit in + if not all([isinstance(vunit, un.UnitQuantity) for vunit in value_units]): raise ValueError('No value unit or standard value type specified.') @@ -353,13 +353,13 @@ def _check_input_sampling_period(self, sampling_period, time_column, """ Checks sampling period, times and time unit for consistency. - sampling_period: pq.quantity.Quantity, sampling period of data to load. + sampling_period: un.quantity.Quantity, sampling period of data to load. time_column: int, column id of times in data to load. - time_unit: pq.quantity.Quantity, unit of time used in the data to load. + time_unit: un.quantity.Quantity, unit of time used in the data to load. data: numpy array, the data to be loaded / interpreted. Returns - pq.quantities.Quantity object, the updated sampling period. + un.quantities.Quantity object, the updated sampling period. """ if sampling_period is None: if time_column is not None: @@ -373,9 +373,9 @@ def _check_input_sampling_period(self, sampling_period, time_column, else: raise ValueError('Can not estimate sampling rate without time ' 'column id provided.') - sampling_period = pq.CompoundUnit(str(dt) + '*' + sampling_period = un.CompoundUnit(str(dt) + '*' + time_unit.units.u_symbol) - elif not isinstance(sampling_period, pq.UnitQuantity): + elif not isinstance(sampling_period, un.UnitQuantity): raise ValueError("sampling_period is not specified as a unit.") return sampling_period @@ -388,8 +388,8 @@ def _get_conditions_and_sorting(self, id_column, time_column, gid_list, id_column: int, id of the column containing gids. time_column: int, id of the column containing times. gid_list: list of int, gid to be loaded. - t_start: pq.quantity.Quantity, start of the time range to be loaded. - t_stop: pq.quantity.Quantity, stop of the time range to be loaded. + t_start: un.quantity.Quantity, start of the time range to be loaded. + t_stop: un.quantity.Quantity, stop of the time range to be loaded. Returns updated [condition, condition_column, sorting_column]. @@ -424,9 +424,9 @@ def _get_selected_ids(self, gid, id_column, time_column, t_start, t_stop, gid: int, gid to be loaded. id_column: int, id of the column containing gids. time_column: int, id of the column containing times. - t_start: pq.quantity.Quantity, start of the time range to load. - t_stop: pq.quantity.Quantity, stop of the time range to load. - time_unit: pq.quantity.Quantity, time unit of the data to load. + t_start: un.quantity.Quantity, start of the time range to load. + t_stop: un.quantity.Quantity, stop of the time range to load. + time_unit: un.quantity.Quantity, time unit of the data to load. data: numpy array, data to load. Returns @@ -453,7 +453,7 @@ def _get_selected_ids(self, gid, id_column, time_column, t_start, t_stop, selected_ids = gid_ids + id_shifts return selected_ids - def read_block(self, gid_list=None, time_unit=pq.ms, t_start=None, + def read_block(self, gid_list=None, time_unit=un.ms, t_start=None, t_stop=None, sampling_period=None, id_column_dat=0, time_column_dat=1, value_columns_dat=2, id_column_gdf=0, time_column_gdf=1, value_types=None, @@ -468,7 +468,7 @@ def read_block(self, gid_list=None, time_unit=pq.ms, t_start=None, seg.block = blk return blk - def read_segment(self, gid_list=None, time_unit=pq.ms, t_start=None, + def read_segment(self, gid_list=None, time_unit=un.ms, t_start=None, t_stop=None, sampling_period=None, id_column_dat=0, time_column_dat=1, value_columns_dat=2, id_column_gdf=0, time_column_gdf=1, value_types=None, @@ -486,7 +486,7 @@ def read_segment(self, gid_list=None, time_unit=pq.ms, t_start=None, trains of all neurons. time_unit : Quantity (time), optional, default: quantities.ms The time unit of recorded time stamps in DAT as well as GDF files. - t_start : Quantity (time), optional, default: 0 * pq.ms + t_start : Quantity (time), optional, default: 0 * un.ms Start time of SpikeTrain. t_stop : Quantity (time), default: None Stop time of SpikeTrain. t_stop must be specified, the default None @@ -558,7 +558,7 @@ def read_segment(self, gid_list=None, time_unit=pq.ms, t_start=None, return seg - def read_analogsignal(self, gid=None, time_unit=pq.ms, t_start=None, + def read_analogsignal(self, gid=None, time_unit=un.ms, t_start=None, t_stop=None, sampling_period=None, id_column=0, time_column=1, value_column=2, value_type=None, value_unit=None, lazy=False): @@ -574,7 +574,7 @@ def read_analogsignal(self, gid=None, time_unit=pq.ms, t_start=None, neurons. time_unit : Quantity (time), optional, default: quantities.ms The time unit of recorded time stamps. - t_start : Quantity (time), optional, default: 0 * pq.ms + t_start : Quantity (time), optional, default: 0 * un.ms Start time of SpikeTrain. t_stop : Quantity (time), default: None Stop time of SpikeTrain. t_stop must be specified, the default None @@ -612,7 +612,7 @@ def read_analogsignal(self, gid=None, time_unit=pq.ms, t_start=None, lazy=lazy)[0] def read_spiketrain( - self, gdf_id=None, time_unit=pq.ms, t_start=None, t_stop=None, + self, gdf_id=None, time_unit=un.ms, t_start=None, t_stop=None, id_column=0, time_column=1, lazy=False, cascade=True, **args): """ Reads a SpikeTrain with specified neuron ID from the GDF data. diff --git a/neo/io/neuroexplorerio.py b/neo/io/neuroexplorerio.py index f7fcd8c13..4bdf5d058 100644 --- a/neo/io/neuroexplorerio.py +++ b/neo/io/neuroexplorerio.py @@ -17,7 +17,7 @@ import struct import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, SpikeTrain, Epoch, Event @@ -95,19 +95,19 @@ def read_segment(self, lazy=False, cascade=True): if entity_header['type'] == 0: # neuron if lazy: - spike_times = [] * pq.s + spike_times = [] * un.s else: spike_times = np.memmap(self.filename, np.dtype('i4'), 'r', shape=(entity_header['n']), offset=entity_header['offset']) spike_times = spike_times.astype('f8') / global_header[ - 'freq'] * pq.s + 'freq'] * un.s sptr = SpikeTrain( times=spike_times, t_start=global_header['tbeg'] / - global_header['freq'] * pq.s, + global_header['freq'] * un.s, t_stop=global_header['tend'] / - global_header['freq'] * pq.s, + global_header['freq'] * un.s, name=entity_header['name']) if lazy: sptr.lazy_shape = entity_header['n'] @@ -117,13 +117,13 @@ def read_segment(self, lazy=False, cascade=True): if entity_header['type'] == 1: # event if lazy: - event_times = [] * pq.s + event_times = [] * un.s else: event_times = np.memmap(self.filename, np.dtype('i4'), 'r', shape=(entity_header['n']), offset=entity_header['offset']) event_times = event_times.astype('f8') / global_header[ - 'freq'] * pq.s + 'freq'] * un.s labels = np.array([''] * event_times.size, dtype='S') evar = Event(times=event_times, labels=labels, channel_name=entity_header['name']) @@ -134,20 +134,20 @@ def read_segment(self, lazy=False, cascade=True): if entity_header['type'] == 2: # interval if lazy: - start_times = [] * pq.s - stop_times = [] * pq.s + start_times = [] * un.s + stop_times = [] * un.s else: start_times = np.memmap(self.filename, np.dtype('i4'), 'r', shape=(entity_header['n']), offset=entity_header['offset']) start_times = start_times.astype('f8') / global_header[ - 'freq'] * pq.s + 'freq'] * un.s stop_times = np.memmap(self.filename, np.dtype('i4'), 'r', shape=(entity_header['n']), offset=entity_header['offset'] + entity_header['n'] * 4) stop_times = stop_times.astype('f') / global_header[ - 'freq'] * pq.s + 'freq'] * un.s epar = Epoch(times=start_times, durations=stop_times - start_times, labels=np.array([''] * start_times.size, @@ -160,7 +160,7 @@ def read_segment(self, lazy=False, cascade=True): if entity_header['type'] == 3: # spiketrain and wavefoms if lazy: - spike_times = [] * pq.s + spike_times = [] * un.s waveforms = None else: @@ -168,7 +168,7 @@ def read_segment(self, lazy=False, cascade=True): shape=(entity_header['n']), offset=entity_header['offset']) spike_times = spike_times.astype('f8') / global_header[ - 'freq'] * pq.s + 'freq'] * un.s waveforms = np.memmap(self.filename, np.dtype('i2'), 'r', shape=(entity_header['n'], 1, @@ -177,20 +177,20 @@ def read_segment(self, lazy=False, cascade=True): entity_header['n'] * 4) waveforms = (waveforms.astype('f') * entity_header['ADtoMV'] + - entity_header['MVOffset']) * pq.mV - t_stop = global_header['tend'] / global_header['freq'] * pq.s + entity_header['MVOffset']) * un.mV + t_stop = global_header['tend'] / global_header['freq'] * un.s if spike_times.size > 0: t_stop = max(t_stop, max(spike_times)) sptr = SpikeTrain( times=spike_times, t_start=global_header['tbeg'] / - global_header['freq'] * pq.s, + global_header['freq'] * un.s, #~ t_stop = max(globalHeader['tend']/ - #~ globalHeader['freq']*pq.s,max(spike_times)), + #~ globalHeader['freq']*un.s,max(spike_times)), t_stop=t_stop, name=entity_header['name'], waveforms=waveforms, - sampling_rate=entity_header['WFrequency'] * pq.Hz, - left_sweep=0 * pq.ms) + sampling_rate=entity_header['WFrequency'] * un.Hz, + left_sweep=0 * un.ms) if lazy: sptr.lazy_shape = entity_header['n'] sptr.annotate(channel_index=entity_header['WireNumber']) @@ -216,7 +216,7 @@ def read_segment(self, lazy=False, cascade=True): del timestamps, fragment_starts if lazy: - signal = [] * pq.mV + signal = [] * un.mV else: signal = np.memmap(self.filename, np.dtype('i2'), 'r', shape=(entity_header['NPointsWave']), @@ -224,11 +224,11 @@ def read_segment(self, lazy=False, cascade=True): signal = signal.astype('f') signal *= entity_header['ADtoMV'] signal += entity_header['MVOffset'] - signal = signal * pq.mV + signal = signal * un.mV ana_sig = AnalogSignal( - signal=signal, t_start=t_start * pq.s, - sampling_rate=entity_header['WFrequency'] * pq.Hz, + signal=signal, t_start=t_start * un.s, + sampling_rate=entity_header['WFrequency'] * un.Hz, name=entity_header['name'], channel_index=entity_header['WireNumber']) if lazy: @@ -238,14 +238,14 @@ def read_segment(self, lazy=False, cascade=True): if entity_header['type'] == 6: # markers : TO TEST if lazy: - times = [] * pq.s + times = [] * un.s labels = np.array([], dtype='S') markertype = None else: times = np.memmap(self.filename, np.dtype('i4'), 'r', shape=(entity_header['n']), offset=entity_header['offset']) - times = times.astype('f8') / global_header['freq'] * pq.s + times = times.astype('f8') / global_header['freq'] * un.s fid.seek(entity_header['offset'] + entity_header['n'] * 4) markertype = fid.read(64).replace('\x00', '') labels = np.memmap( diff --git a/neo/io/neuroscopeio.py b/neo/io/neuroscopeio.py index 5b04480ce..42f5a22d9 100644 --- a/neo/io/neuroscopeio.py +++ b/neo/io/neuroscopeio.py @@ -22,7 +22,7 @@ from xml.etree import ElementTree import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.io.rawbinarysignalio import RawBinarySignalIO @@ -87,7 +87,7 @@ def read_block(self, acq = root.find('acquisitionSystem') nbits = int(acq.find('nBits').text) nbchannel = int(acq.find('nChannels').text) - sampling_rate = float(acq.find('samplingRate').text)*pq.Hz + sampling_rate = float(acq.find('samplingRate').text)*un.Hz voltage_range = float(acq.find('voltageRange').text) #offset = int(acq.find('offset').text) amplification = float(acq.find('amplification').text) @@ -110,8 +110,8 @@ def read_block(self, reader = RawBinarySignalIO(filename = self.filename.replace('.xml', '.dat')) seg2 = reader.read_segment(cascade = True, lazy = lazy, sampling_rate = sampling_rate, - t_start = 0.*pq.s, - unit = pq.V, nbchannel = nbchannel, + t_start = 0.*un.s, + unit = un.V, nbchannel = nbchannel, bytesoffset = 0, dtype = np.int16 if nbits<=16 else np.int32, rangemin = -voltage_range/2., diff --git a/neo/io/neuroshareapiio.py b/neo/io/neuroshareapiio.py index 2113ba983..3fe2ddf2c 100644 --- a/neo/io/neuroshareapiio.py +++ b/neo/io/neuroshareapiio.py @@ -14,7 +14,7 @@ # note neo.core needs only numpy and quantities import numpy as np -import quantities as pq +from neo import units as un import os @@ -289,8 +289,8 @@ def read_analogsignal(self, segment_duration=float(self.metadata["TimeSpan"]) if lazy: - anasig = AnalogSignal([], units="V", sampling_rate = self.metadata["sampRate"] * pq.Hz, - t_start=t_start * pq.s, + anasig = AnalogSignal([], units="V", sampling_rate = self.metadata["sampRate"] * un.Hz, + t_start=t_start * un.s, ) #create a dummie time vector tvect = np.arange(t_start, t_start+ segment_duration , 1./self.metadata["sampRate"]) @@ -316,9 +316,9 @@ def read_analogsignal(self, #read the data from the sig object sig,_,_ = sig.get_data(index = startat, count = bins) #store it to the 'AnalogSignal' object - anasig = AnalogSignal(sig, units = sigUnits, sampling_rate=self.metadata["sampRate"] * pq.Hz, - t_start=t_start * pq.s, - t_stop = (t_start+segment_duration)*pq.s, + anasig = AnalogSignal(sig, units = sigUnits, sampling_rate=self.metadata["sampRate"] * un.Hz, + t_start=t_start * un.s, + t_stop = (t_start+segment_duration)*un.s, channel_index=channel_index) # annotate from which electrode the signal comes from @@ -350,9 +350,9 @@ def read_spiketrain(self , if lazy: # we add the attribute lazy_shape with the size if lazy - spiketr = SpikeTrain(times,units = pq.s, + spiketr = SpikeTrain(times,units = un.s, t_stop = t_start+segment_duration, - t_start = t_start*pq.s,lazy_shape = 40) + t_start = t_start*un.s,lazy_shape = 40) else: #get the spike data from a specific channel index @@ -375,12 +375,12 @@ def read_spiketrain(self , times.append(timeStamp) #create a spike train object - spiketr = SpikeTrain(times,units = pq.s, + spiketr = SpikeTrain(times,units = un.s, t_stop = t_start+segment_duration, - t_start = t_start*pq.s, + t_start = t_start*un.s, name ="spikes from electrode"+tempSpks.label[-3:], - waveforms = waveforms*pq.volt, - sampling_rate = sr * pq.Hz, + waveforms = waveforms*un.volt, + sampling_rate = sr * un.Hz, file_origin = self.filename, annotate = ("channel_index:"+ str(channel_index))) @@ -420,7 +420,7 @@ def read_eventarray(self,lazy = False, cascade = True, tempTimeStamp.append(tempData) #create an event array eva = Event(labels = np.array(tempNames,dtype = "S"), - times = np.array(tempTimeStamp)*pq.s, + times = np.array(tempTimeStamp)*un.s, file_origin = self.filename, description = "the trigger events (without durations)") return eva @@ -469,8 +469,8 @@ def read_epocharray(self,lazy = False, cascade = True, #pass durations.append(tempData1-tempData) epa = Epoch(file_origin = self.filename, - times = np.array(tempTimeStamp)*pq.s, - durations = np.array(durations)*pq.s, + times = np.array(tempTimeStamp)*un.s, + durations = np.array(durations)*un.s, labels = np.array(tempNames,dtype = "S"), description = "digital events with duration") return epa diff --git a/neo/io/neurosharectypesio.py b/neo/io/neurosharectypesio.py index 4d5f8f590..0a52cfbe0 100644 --- a/neo/io/neurosharectypesio.py +++ b/neo/io/neurosharectypesio.py @@ -29,7 +29,7 @@ file = io.BufferedReader import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, SpikeTrain, Event @@ -198,7 +198,7 @@ def read_segment(self, import_neuroshare_segment = True, ctypes.sizeof(pData), ctypes.byref(pdwDataRetSize) ) times.append(pdTimeStamp.value) labels.append(str(pData.value)) - ea.times = times*pq.s + ea.times = times*un.s ea.labels = np.array(labels, dtype ='S') else : ea.lazy_shape = entityInfo.dwItemCount @@ -212,7 +212,7 @@ def read_segment(self, import_neuroshare_segment = True, dwIndexCount = entityInfo.dwItemCount if lazy: - signal = [ ]*pq.Quantity(1, pAnalogInfo.szUnits) + signal = [ ]*un.Quantity(1, pAnalogInfo.szUnits) else: pdwContCount = ctypes.c_uint32(0) pData = np.zeros( (entityInfo.dwItemCount,), dtype = 'float64') @@ -225,7 +225,7 @@ def read_segment(self, import_neuroshare_segment = True, dwStopIndex, ctypes.byref( pdwContCount) , pData[total_read:].ctypes.data_as(ctypes.POINTER(ctypes.c_double))) total_read += pdwContCount.value - signal = pq.Quantity(pData, units=pAnalogInfo.szUnits, copy = False) + signal = un.Quantity(pData, units=pAnalogInfo.szUnits, copy = False) #t_start dwIndex = 0 @@ -233,8 +233,8 @@ def read_segment(self, import_neuroshare_segment = True, neuroshare.ns_GetTimeByIndex( hFile, dwEntityID, dwIndex, ctypes.byref(pdTime)) anaSig = AnalogSignal(signal, - sampling_rate = pAnalogInfo.dSampleRate*pq.Hz, - t_start = pdTime.value * pq.s, + sampling_rate = pAnalogInfo.dSampleRate*un.Hz, + t_start = pdTime.value * un.s, name = str(entityInfo.szEntityLabel), ) anaSig.annotate( probe_info = str(pAnalogInfo.szProbeInfo)) @@ -263,7 +263,7 @@ def read_segment(self, import_neuroshare_segment = True, ctypes.byref(pSourceInfo), ctypes.sizeof(pSourceInfo) ) if lazy: - sptr = SpikeTrain(times, name = str(entityInfo.szEntityLabel), t_stop = 0.*pq.s) + sptr = SpikeTrain(times, name = str(entityInfo.szEntityLabel), t_stop = 0.*un.s) sptr.lazy_shape = entityInfo.dwItemCount else: pdTimeStamp = ctypes.c_double(0.) @@ -284,11 +284,11 @@ def read_segment(self, import_neuroshare_segment = True, times[dwIndex] = pdTimeStamp.value waveforms[dwIndex, :,:] = pData[:nsample*nsource].reshape(nsample ,nsource).transpose() - sptr = SpikeTrain(times = pq.Quantity(times, units = 's', copy = False), + sptr = SpikeTrain(times = un.Quantity(times, units = 's', copy = False), t_stop = times.max(), - waveforms = pq.Quantity(waveforms, units = str(pdwSegmentInfo.szUnits), copy = False ), - left_sweep = nsample/2./float(pdwSegmentInfo.dSampleRate)*pq.s, - sampling_rate = float(pdwSegmentInfo.dSampleRate)*pq.Hz, + waveforms = un.Quantity(waveforms, units = str(pdwSegmentInfo.szUnits), copy = False ), + left_sweep = nsample/2./float(pdwSegmentInfo.dSampleRate)*un.s, + sampling_rate = float(pdwSegmentInfo.dSampleRate)*un.Hz, name = str(entityInfo.szEntityLabel), ) seg.spiketrains.append(sptr) @@ -302,15 +302,15 @@ def read_segment(self, import_neuroshare_segment = True, ctypes.byref(pNeuralInfo), ctypes.sizeof(pNeuralInfo)) if lazy: - times = [ ]*pq.s - t_stop = 0*pq.s + times = [ ]*un.s + t_stop = 0*un.s else: pData = np.zeros( (entityInfo.dwItemCount,), dtype = 'float64') dwStartIndex = 0 dwIndexCount = entityInfo.dwItemCount neuroshare.ns_GetNeuralData( hFile, dwEntityID, dwStartIndex, dwIndexCount, pData.ctypes.data_as(ctypes.POINTER(ctypes.c_double))) - times = pData*pq.s + times = pData*un.s t_stop = times.max() sptr = SpikeTrain(times, t_stop =t_stop, name = str(entityInfo.szEntityLabel),) diff --git a/neo/io/nixio.py b/neo/io/nixio.py index 9f1761038..f25d959b7 100644 --- a/neo/io/nixio.py +++ b/neo/io/nixio.py @@ -24,7 +24,7 @@ import itertools from hashlib import md5 -import quantities as pq +from neo import units as un import numpy as np from neo.io.baseio import BaseIO @@ -259,7 +259,7 @@ def _source_chx_to_neo(self, nix_source): if "coordinates" in chx[0]: coord_units = chx[0]["coordinates.units"] coord_values = list(c["coordinates"] for c in chx) - neo_attrs["coordinates"] = pq.Quantity(coord_values, coord_units) + neo_attrs["coordinates"] = un.Quantity(coord_values, coord_units) rcg = ChannelIndex(**neo_attrs) self._object_map[nix_source.id] = rcg return rcg @@ -288,30 +288,30 @@ def _signal_da_to_neo(self, nix_da_group, lazy): unit = nix_da_group[0].unit if lazy: - signaldata = pq.Quantity(np.empty(0), unit) + signaldata = un.Quantity(np.empty(0), unit) lazy_shape = (len(nix_da_group[0]), len(nix_da_group)) else: signaldata = np.array([d[:] for d in nix_da_group]).transpose() - signaldata = pq.Quantity(signaldata, unit) + signaldata = un.Quantity(signaldata, unit) lazy_shape = None timedim = self._get_time_dimension(nix_da_group[0]) if (neo_type == "neo.analogsignal" or isinstance(timedim, nix.pycore.SampledDimension)): if lazy: - sampling_period = pq.Quantity(1, timedim.unit) - t_start = pq.Quantity(0, timedim.unit) + sampling_period = un.Quantity(1, timedim.unit) + t_start = un.Quantity(0, timedim.unit) else: if "sampling_interval.units" in metadata.props: sample_units = metadata["sampling_interval.units"] else: sample_units = timedim.unit - sampling_period = pq.Quantity(timedim.sampling_interval, + sampling_period = un.Quantity(timedim.sampling_interval, sample_units) if "t_start.units" in metadata.props: tsunits = metadata["t_start.units"] else: tsunits = timedim.unit - t_start = pq.Quantity(timedim.offset, tsunits) + t_start = un.Quantity(timedim.offset, tsunits) neo_signal = AnalogSignal( signal=signaldata, sampling_period=sampling_period, t_start=t_start, **neo_attrs @@ -319,9 +319,9 @@ def _signal_da_to_neo(self, nix_da_group, lazy): elif neo_type == "neo.irregularlysampledsignal"\ or isinstance(timedim, nix.pycore.RangeDimension): if lazy: - times = pq.Quantity(np.empty(0), timedim.unit) + times = un.Quantity(np.empty(0), timedim.unit) else: - times = pq.Quantity(timedim.ticks, timedim.unit) + times = un.Quantity(timedim.ticks, timedim.unit) neo_signal = IrregularlySampledSignal( signal=signaldata, times=times, **neo_attrs ) @@ -339,18 +339,20 @@ def _mtag_eest_to_neo(self, nix_mtag, lazy): time_unit = nix_mtag.positions.unit if lazy: - times = pq.Quantity(np.empty(0), time_unit) + times = un.Quantity(np.empty(0), time_unit) lazy_shape = np.shape(nix_mtag.positions) else: - times = pq.Quantity(nix_mtag.positions, time_unit) + times = un.Quantity(nix_mtag.positions, time_unit) lazy_shape = None if neo_type == "neo.epoch": if lazy: - durations = pq.Quantity(np.empty(0), nix_mtag.extents.unit) + durations = un.Quantity(np.empty(0), nix_mtag.extents.unit) labels = np.empty(0, dtype='S') else: - durations = pq.Quantity(nix_mtag.extents, + + durations = un.Quantity(nix_mtag.extents, nix_mtag.extents.unit) + labels = np.array(nix_mtag.positions.dimensions[0].labels, dtype="S") eest = Epoch(times=times, durations=durations, labels=labels, @@ -369,7 +371,7 @@ def _mtag_eest_to_neo(self, nix_mtag, lazy): del neo_attrs["t_start.units"] else: t_start_units = time_unit - t_start = pq.Quantity(neo_attrs["t_start"], t_start_units) + t_start = un.Quantity(neo_attrs["t_start"], t_start_units) del neo_attrs["t_start"] else: t_start = None @@ -379,7 +381,7 @@ def _mtag_eest_to_neo(self, nix_mtag, lazy): del neo_attrs["t_stop.units"] else: t_stop_units = time_unit - t_stop = pq.Quantity(neo_attrs["t_stop"], t_stop_units) + t_stop = un.Quantity(neo_attrs["t_stop"], t_stop_units) del neo_attrs["t_stop"] else: t_stop = None @@ -399,21 +401,23 @@ def _mtag_eest_to_neo(self, nix_mtag, lazy): wfda = nix_mtag.features[0].data wftime = self._get_time_dimension(wfda) if lazy: - eest.waveforms = pq.Quantity(np.empty((0, 0, 0)), + + eest.waveforms = un.Quantity(np.empty((0, 0, 0)), wfda.unit) - eest.sampling_period = pq.Quantity(1, wftime.unit) - eest.left_sweep = pq.Quantity(0, wftime.unit) + eest.sampling_period = un.Quantity(1, wftime.unit) + eest.left_sweep = un.Quantity(0, wftime.unit) + else: - eest.waveforms = pq.Quantity(wfda, wfda.unit) + eest.waveforms = un.Quantity(wfda, wfda.unit) if interval_units is None: interval_units = wftime.unit - eest.sampling_period = pq.Quantity( + eest.sampling_period = un.Quantity( wftime.sampling_interval, interval_units ) if left_sweep_units is None: left_sweep_units = wftime.unit if "left_sweep" in wfda.metadata: - eest.left_sweep = pq.Quantity( + eest.left_sweep = un.Quantity( wfda.metadata["left_sweep"], left_sweep_units ) else: @@ -531,14 +535,14 @@ def _write_object(self, obj, loc=""): newhash = self._hash_object(obj) if oldhash != newhash: attr = self._neo_attr_to_nix(obj) - if isinstance(obj, pq.Quantity): + if isinstance(obj, un.Quantity): attr.update(self._neo_data_to_nix(obj)) if oldhash is None: nixobj = self._create_nix_obj(loc, attr) else: nixobj = self._get_object_at(objpath) self._write_attr_annotations(nixobj, attr, objpath) - if isinstance(obj, pq.Quantity): + if isinstance(obj, un.Quantity): self._write_data(nixobj, attr, objpath) else: nixobj = self._get_object_at(objpath) @@ -1100,7 +1104,7 @@ def _write_property(self, section, name, v): :return: The newly created property """ - if isinstance(v, pq.Quantity): + if isinstance(v, un.Quantity): if len(v.shape): section[name] = list(nix.Value(vv) for vv in v.magnitude) else: @@ -1116,7 +1120,7 @@ def _write_property(self, section, name, v): values = [] unit = None for item in v: - if isinstance(item, pq.Quantity): + if isinstance(item, un.Quantity): unit = str(item.dimensionality) item = nix.Value(item.magnitude.item()) elif isinstance(item, Iterable): @@ -1173,7 +1177,7 @@ def _nix_attr_to_neo(nix_obj): values = prop.values values = list(v.value for v in values) if prop.unit: - values = pq.Quantity(values, prop.unit) + values = un.Quantity(values, prop.unit) if len(values) == 1: neo_attrs[prop.name] = values[0] else: diff --git a/neo/io/plexonio.py b/neo/io/plexonio.py index 515292b85..a25a73bb8 100644 --- a/neo/io/plexonio.py +++ b/neo/io/plexonio.py @@ -20,7 +20,7 @@ import os import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, SpikeTrain, Event @@ -264,7 +264,7 @@ def read_segment(self, lazy=False, cascade=True, load_spike_waveform=True): times = evarrays[chan]['times'] labels = evarrays[chan]['labels'] ea = Event( - times*pq.s, + times*un.s, labels=labels, channel_name=eventHeaders[chan]['Name'], channel_index=chan @@ -291,10 +291,10 @@ def read_segment(self, lazy=False, cascade=True, load_spike_waveform=True): slowChannelHeaders[chan]['PreampGain']) signal = sigarrays[chan] * gain anasig = AnalogSignal( - signal * pq.V, + signal * un.V, sampling_rate=float( - slowChannelHeaders[chan]['ADFreq']) * pq.Hz, - t_start=t_starts[chan] * pq.s, + slowChannelHeaders[chan]['ADFreq']) * un.Hz, + t_start=t_starts[chan] * un.s, channel_index=slowChannelHeaders[chan]['Channel'], channel_name=slowChannelHeaders[chan]['Name']) if lazy: @@ -324,13 +324,13 @@ def read_segment(self, lazy=False, cascade=True, load_spike_waveform=True): gain = global_header['SpikeMaxMagnitudeMV'] / ( .5 * 2. ** (global_header['BitsPerSpikeSample']) * global_header['SpikePreAmpGain']) - waveforms = swfarrays[chan, unit] * gain * pq.V + waveforms = swfarrays[chan, unit] * gain * un.V else: waveforms = None sptr = SpikeTrain( times, units='s', - t_stop=t_stop*pq.s, + t_stop=t_stop*un.s, waveforms=waveforms ) sptr.annotate(unit_name = dspChannelHeaders[chan]['Name']) diff --git a/neo/io/pynnio.py b/neo/io/pynnio.py index 4a30c64a3..dbfe3cf02 100644 --- a/neo/io/pynnio.py +++ b/neo/io/pynnio.py @@ -15,7 +15,7 @@ from itertools import chain import numpy -import quantities as pq +from neo import units as un import warnings from neo.io.baseio import BaseIO @@ -29,9 +29,9 @@ UNITS_MAP = { - 'spikes': pq.ms, - 'v': pq.mV, - 'gsyn': pq.UnitQuantity('microsiemens', 1e-6*pq.S, 'uS', 'µS'), # checked + 'spikes': un.ms, + 'v': un.mV, + 'gsyn': un.UnitQuantity('microsiemens', 1e-6*un.S, 'uS', 'µS'), # checked } @@ -69,7 +69,7 @@ def _extract_signals(self, data, metadata, lazy): if lazy and data.size > 0: signal = AnalogSignal([], units=self._determine_units(metadata), - sampling_period=metadata['dt']*pq.ms) + sampling_period=metadata['dt']*un.ms) signal.lazy_shape = None else: arr = numpy.vstack(self._extract_array(data, channel_index) @@ -77,7 +77,7 @@ def _extract_signals(self, data, metadata, lazy): if len(arr) > 0: signal = AnalogSignal(arr.T, units=self._determine_units(metadata), - sampling_period=metadata['dt']*pq.ms) + sampling_period=metadata['dt']*un.ms) if signal is not None: signal.annotate(label=metadata["label"], variable=metadata["variable"]) @@ -87,12 +87,12 @@ def _extract_spikes(self, data, metadata, channel_index, lazy): spiketrain = None if lazy: if channel_index in data[:, 1]: - spiketrain = SpikeTrain([], units=pq.ms, t_stop=0.0) + spiketrain = SpikeTrain([], units=un.ms, t_stop=0.0) spiketrain.lazy_shape = None else: spike_times = self._extract_array(data, channel_index) if len(spike_times) > 0: - spiketrain = SpikeTrain(spike_times, units=pq.ms, t_stop=spike_times.max()) + spiketrain = SpikeTrain(spike_times, units=un.ms, t_stop=spike_times.max()) if spiketrain is not None: spiketrain.annotate(label=metadata["label"], channel_index=channel_index, @@ -139,7 +139,7 @@ def write_segment(self, segment): if 'label' not in metadata: metadata['label'] = 'unknown' if 'dt' not in metadata: # dt not included in annotations if Segment contains only AnalogSignals - metadata['dt'] = s0.sampling_period.rescale(pq.ms).magnitude + metadata['dt'] = s0.sampling_period.rescale(un.ms).magnitude metadata['n'] = n data = numpy.empty((n, 2)) # if the 'variable' annotation is a standard one from PyNN, we rescale diff --git a/neo/io/rawbinarysignalio.py b/neo/io/rawbinarysignalio.py index 73ab35d9d..cece961b4 100644 --- a/neo/io/rawbinarysignalio.py +++ b/neo/io/rawbinarysignalio.py @@ -14,7 +14,7 @@ import os import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal @@ -82,9 +82,9 @@ def read_segment(self, cascade = True, lazy = False, - sampling_rate = 1.*pq.Hz, - t_start = 0.*pq.s, - unit = pq.V, + sampling_rate = 1.*un.Hz, + t_start = 0.*un.s, + unit = un.V, nbchannel = 1, bytesoffset = 0, @@ -114,13 +114,13 @@ def read_segment(self, if type(sampling_rate) == float or type(sampling_rate)==int: # if not quantitities Hz by default - sampling_rate = sampling_rate*pq.Hz + sampling_rate = sampling_rate*un.Hz if type(t_start) == float or type(t_start)==int: # if not quantitities s by default - t_start = t_start*pq.s + t_start = t_start*un.s - unit = pq.Quantity(1, unit) + unit = un.Quantity(1, unit) if lazy: sig = [] diff --git a/neo/io/spike2io.py b/neo/io/spike2io.py index bc4207472..abe02c422 100644 --- a/neo/io/spike2io.py +++ b/neo/io/spike2io.py @@ -27,7 +27,7 @@ import sys import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal, SpikeTrain, Event @@ -215,7 +215,7 @@ def read_one_channel_continuous(self, fid, channel_num, header, # sample rate if take_ideal_sampling_rate: - sampling_rate = channelHeader.ideal_rate * pq.Hz + sampling_rate = channelHeader.ideal_rate * un.Hz else: if header.system_id in [1, 2, 3, 4, 5]: # Before version 5 #~ print channel_num, channelHeader.divide, \ @@ -225,7 +225,7 @@ def read_one_channel_continuous(self, fid, channel_num, header, else: sample_interval = (channelHeader.l_chan_dvd * header.us_per_time * header.dtime_base) - sampling_rate = (1. / sample_interval) * pq.Hz + sampling_rate = (1. / sample_interval) * un.Hz # read blocks header to preallocate memory by jumping block to block if channelHeader.blocks==0: @@ -255,23 +255,23 @@ def read_one_channel_continuous(self, fid, channel_num, header, ana_sigs = [] if channelHeader.unit in unit_convert: - unit = pq.Quantity(1, unit_convert[channelHeader.unit]) + unit = un.Quantity(1, unit_convert[channelHeader.unit]) else: # print channelHeader.unit try: - unit = pq.Quantity(1, channelHeader.unit) + unit = un.Quantity(1, channelHeader.unit) except: - unit = pq.Quantity(1, '') + unit = un.Quantity(1, '') for b, bs in enumerate(blocksize): if lazy: signal = [] * unit else: - signal = pq.Quantity(np.empty(bs, dtype='f4'), units=unit) + signal = un.Quantity(np.empty(bs, dtype='f4'), units=unit) ana_sig = AnalogSignal( signal, sampling_rate=sampling_rate, t_start=(starttimes[b] * header.us_per_time * - header.dtime_base * pq.s), + header.dtime_base * un.s), channel_index=channel_num) ana_sigs.append(ana_sig) @@ -357,7 +357,7 @@ def read_one_channel_event_or_spike(self, fid, channel_num, header, elif channelHeader.kind in [6, 7]: # correct value for t_stop to be put in later - sptr = SpikeTrain([] * pq.s, t_stop=1e99) + sptr = SpikeTrain([] * un.s, t_stop=1e99) sptr.annotate(channel_index=channel_num, ced_unit = 0) sptr.lazy_shape = totalitems return sptr @@ -380,7 +380,7 @@ def read_one_channel_event_or_spike(self, fid, channel_num, header, ## Step 3 convert in neo standard class: eventarrays or spiketrains alltimes = alltrigs['tick'].astype( - 'f') * header.us_per_time * header.dtime_base * pq.s + 'f') * header.us_per_time * header.dtime_base * un.s if channelHeader.kind in [2, 3, 4, 5, 8]: #events @@ -424,13 +424,13 @@ def read_one_channel_event_or_spike(self, fid, channel_num, header, header.dtime_base) if channelHeader.unit in unit_convert: - unit = pq.Quantity(1, unit_convert[channelHeader.unit]) + unit = un.Quantity(1, unit_convert[channelHeader.unit]) else: #print channelHeader.unit try: - unit = pq.Quantity(1, channelHeader.unit) + unit = un.Quantity(1, channelHeader.unit) except: - unit = pq.Quantity(1, '') + unit = un.Quantity(1, '') if len(alltimes) > 0: # can get better value from associated AnalogSignal(s) ? @@ -441,7 +441,7 @@ def read_one_channel_event_or_spike(self, fid, channel_num, header, if not self.ced_units: sptr = SpikeTrain(alltimes, waveforms = waveforms*unit, - sampling_rate = (1./sample_interval)*pq.Hz, + sampling_rate = (1./sample_interval)*un.Hz, t_stop = t_stop ) sptr.annotate(channel_index = channel_num, ced_unit = 0) @@ -451,7 +451,7 @@ def read_one_channel_event_or_spike(self, fid, channel_num, header, for i in set(alltrigs['marker'] & 255): sptr = SpikeTrain(alltimes[alltrigs['marker'] == i], waveforms = waveforms[alltrigs['marker'] == i]*unit, - sampling_rate = (1./sample_interval)*pq.Hz, + sampling_rate = (1./sample_interval)*un.Hz, t_stop = t_stop ) sptr.annotate(channel_index = channel_num, ced_unit = i) diff --git a/neo/io/stimfitio.py b/neo/io/stimfitio.py index cf6a42856..c06179df1 100644 --- a/neo/io/stimfitio.py +++ b/neo/io/stimfitio.py @@ -32,7 +32,7 @@ import sys import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Block, Segment, AnalogSignal @@ -132,9 +132,9 @@ def read_block(self, lazy=False, cascade=True): if not cascade: return bl - dt = np.round(self.stfio_rec.dt * 1e-3, 9) * pq.s # ms to s + dt = np.round(self.stfio_rec.dt * 1e-3, 9) * un.s # ms to s sampling_rate = 1.0/dt - t_start = 0 * pq.s + t_start = 0 * un.s # iterate over sections first: for j, recseg in enumerate(self.stfio_rec[0]): @@ -146,14 +146,14 @@ def read_block(self, lazy=False, cascade=True): name = recsig.name unit = recsig.yunits try: - pq.Quantity(1, unit) + un.Quantity(1, unit) except: unit = '' if lazy: - signal = pq.Quantity([], unit) + signal = un.Quantity([], unit) else: - signal = pq.Quantity(recsig[j], unit) + signal = un.Quantity(recsig[j], unit) anaSig = AnalogSignal(signal, sampling_rate=sampling_rate, t_start=t_start, name=str(name), channel_index=i) diff --git a/neo/io/tdtio.py b/neo/io/tdtio.py index d4418230e..06ce291a1 100644 --- a/neo/io/tdtio.py +++ b/neo/io/tdtio.py @@ -23,7 +23,7 @@ import sys import numpy as np -import quantities as pq +from neo import units as un import itertools from neo.io.baseio import BaseIO @@ -174,10 +174,10 @@ def read_segment(self, blockname=None, lazy=False, cascade=True, sortname=''): if type_label in ['EVTYPE_STRON', 'EVTYPE_STROFF']: if lazy: - times = [ ]*pq.s + times = [ ]*un.s labels = np.array([ ], dtype=str) else: - times = (tsq[mask3]['timestamp'] - global_t_start) * pq.s + times = (tsq[mask3]['timestamp'] - global_t_start) * un.s labels = tsq[mask3]['eventoffset'].view('float64').astype('S') ea = Event(times=times, name=code, @@ -195,29 +195,29 @@ def read_segment(self, blockname=None, lazy=False, cascade=True, sortname=''): sr = tsq[mask4]['frequency'][0] waveformsize = tsq[mask4]['size'][0]-10 if lazy: - times = [ ]*pq.s + times = [ ]*un.s waveforms = None else: - times = (tsq[mask4]['timestamp'] - global_t_start) * pq.s + times = (tsq[mask4]['timestamp'] - global_t_start) * un.s dt = np.dtype(data_formats[ tsq[mask3]['dataformat'][0]]) waveforms = get_chunks(tsq[mask4]['size'],tsq[mask4]['eventoffset'], tev_array).view(dt) waveforms = waveforms.reshape(nb_spike, -1, waveformsize) - waveforms = waveforms * pq.mV + waveforms = waveforms * un.mV if nb_spike > 0: - # t_start = (tsq['timestamp'][0] - global_t_start) * pq.s # this hould work but not - t_start = 0 *pq.s - t_stop = (tsq['timestamp'][-1] - global_t_start) * pq.s + # t_start = (tsq['timestamp'][0] - global_t_start) * un.s # this hould work but not + t_start = 0 *un.s + t_stop = (tsq['timestamp'][-1] - global_t_start) * un.s else: - t_start = 0 *pq.s - t_stop = 0 *pq.s + t_start = 0 *un.s + t_stop = 0 *un.s st = SpikeTrain(times = times, name = 'Chan{0} Code{1}'.format(channel,sortcode), t_start = t_start, t_stop = t_stop, waveforms = waveforms, - left_sweep = waveformsize/2./sr * pq.s, - sampling_rate = sr * pq.Hz, + left_sweep = waveformsize/2./sr * un.s, + sampling_rate = sr * un.Hz, ) st.annotate(channel_index=channel) if lazy: @@ -243,10 +243,10 @@ def read_segment(self, blockname=None, lazy=False, cascade=True, sortname=''): sig_array = tev_array signal = get_chunks(tsq[mask3]['size'],tsq[mask3]['eventoffset'], sig_array).view(dt) - anasig = AnalogSignal(signal = signal* pq.V, + anasig = AnalogSignal(signal = signal* un.V, name = '{0} {1}'.format(code, channel), - sampling_rate = sr * pq.Hz, - t_start = (tsq[mask3]['timestamp'][0] - global_t_start) * pq.s, + sampling_rate = sr * un.Hz, + t_start = (tsq[mask3]['timestamp'][0] - global_t_start) * un.s, channel_index = int(channel) ) if lazy: diff --git a/neo/io/winedrio.py b/neo/io/winedrio.py index 363e5f573..a2243ce35 100644 --- a/neo/io/winedrio.py +++ b/neo/io/winedrio.py @@ -19,7 +19,7 @@ import sys import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Segment, AnalogSignal @@ -119,9 +119,9 @@ def read_segment(self , lazy = False, cascade = True): unit = header['YU%d'%c] try : - unit = pq.Quantity(1., unit) + unit = un.Quantity(1., unit) except: - unit = pq.Quantity(1., '') + unit = un.Quantity(1., '') if lazy: signal = [ ] * unit @@ -129,8 +129,8 @@ def read_segment(self , lazy = False, cascade = True): signal = (data[:,header['YO%d'%c]].astype('f4')-YZ) *AD/( YCF*YAG*(ADCMAX+1)) * unit ana = AnalogSignal(signal, - sampling_rate=pq.Hz / DT, - t_start=0. * pq.s, + sampling_rate=un.Hz / DT, + t_start=0. * un.s, name=header['YN%d' % c], channel_index=c) if lazy: diff --git a/neo/io/winwcpio.py b/neo/io/winwcpio.py index dd7bbba6c..e5f79361e 100644 --- a/neo/io/winwcpio.py +++ b/neo/io/winwcpio.py @@ -17,7 +17,7 @@ import sys import numpy as np -import quantities as pq +from neo import units as un from neo.io.baseio import BaseIO from neo.core import Block, Segment, AnalogSignal @@ -125,9 +125,9 @@ def read_block(self , lazy = False, unit = header['YU%d'%c] try : - unit = pq.Quantity(1., unit) + unit = un.Quantity(1., unit) except: - unit = pq.Quantity(1., '') + unit = un.Quantity(1., '') if lazy: signal = [ ] * unit @@ -138,10 +138,10 @@ def read_block(self , lazy = False, signal = data[:,header['YO%d'%c]].astype('f4')*VMax/ADCMAX/YG * unit anaSig = AnalogSignal(signal, sampling_rate= - pq.Hz / + un.Hz / analysisHeader['SamplingInterval'] , t_start=analysisHeader['TimeRecorded'] * - pq.s, + un.s, name=header['YN%d'%c], channel_index=c) if lazy: diff --git a/neo/test/coretest/test_analogsignal.py b/neo/test/coretest/test_analogsignal.py index 553d8c6a2..8a1090b9a 100644 --- a/neo/test/coretest/test_analogsignal.py +++ b/neo/test/coretest/test_analogsignal.py @@ -15,7 +15,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un try: from IPython.lib.pretty import pretty @@ -64,87 +64,87 @@ def test__fake_neo__nocascade(self): class TestAnalogSignalConstructor(unittest.TestCase): def test__create_from_list(self): data = range(10) - rate = 1000*pq.Hz + rate = 1000*un.Hz signal = AnalogSignal(data, sampling_rate=rate, units="mV") assert_neo_object_is_compliant(signal) - self.assertEqual(signal.t_start, 0*pq.ms) + self.assertEqual(signal.t_start, 0*un.ms) self.assertEqual(signal.t_stop, len(data)/rate) - self.assertEqual(signal[9, 0], 9000*pq.uV) + self.assertEqual(signal[9, 0], 9000*un.uV) def test__create_from_np_array(self): data = np.arange(10.0) - rate = 1*pq.kHz + rate = 1*un.kHz signal = AnalogSignal(data, sampling_rate=rate, units="uV") assert_neo_object_is_compliant(signal) - self.assertEqual(signal.t_start, 0*pq.ms) + self.assertEqual(signal.t_start, 0*un.ms) self.assertEqual(signal.t_stop, data.size/rate) - self.assertEqual(signal[9, 0], 0.009*pq.mV) + self.assertEqual(signal[9, 0], 0.009*un.mV) def test__create_from_quantities_array(self): - data = np.arange(10.0) * pq.mV - rate = 5000*pq.Hz + data = np.arange(10.0) * un.mV + rate = 5000*un.Hz signal = AnalogSignal(data, sampling_rate=rate) assert_neo_object_is_compliant(signal) - self.assertEqual(signal.t_start, 0*pq.ms) + self.assertEqual(signal.t_start, 0*un.ms) self.assertEqual(signal.t_stop, data.size/rate) - self.assertEqual(signal[9, 0], 0.009*pq.V) + self.assertEqual(signal[9, 0], 0.009*un.V) def test__create_from_array_no_units_ValueError(self): data = np.arange(10.0) self.assertRaises(ValueError, AnalogSignal, data, - sampling_rate=1 * pq.kHz) + sampling_rate=1 * un.kHz) def test__create_from_quantities_array_inconsistent_units_ValueError(self): - data = np.arange(10.0) * pq.mV + data = np.arange(10.0) * un.mV self.assertRaises(ValueError, AnalogSignal, data, - sampling_rate=1 * pq.kHz, units="nA") + sampling_rate=1 * un.kHz, units="nA") def test__create_without_sampling_rate_or_period_ValueError(self): - data = np.arange(10.0) * pq.mV + data = np.arange(10.0) * un.mV self.assertRaises(ValueError, AnalogSignal, data) def test__create_with_None_sampling_rate_should_raise_ValueError(self): - data = np.arange(10.0) * pq.mV + data = np.arange(10.0) * un.mV self.assertRaises(ValueError, AnalogSignal, data, sampling_rate=None) def test__create_with_None_t_start_should_raise_ValueError(self): - data = np.arange(10.0) * pq.mV - rate = 5000 * pq.Hz + data = np.arange(10.0) * un.mV + rate = 5000 * un.Hz self.assertRaises(ValueError, AnalogSignal, data, sampling_rate=rate, t_start=None) def test__create_inconsistent_sampling_rate_and_period_ValueError(self): - data = np.arange(10.0) * pq.mV + data = np.arange(10.0) * un.mV self.assertRaises(ValueError, AnalogSignal, data, - sampling_rate=1 * pq.kHz, sampling_period=5 * pq.s) + sampling_rate=1 * un.kHz, sampling_period=5 * un.s) def test__create_with_copy_true_should_return_copy(self): - data = np.arange(10.0) * pq.mV - rate = 5000*pq.Hz + data = np.arange(10.0) * un.mV + rate = 5000*un.Hz signal = AnalogSignal(data, copy=True, sampling_rate=rate) - data[3] = 99*pq.mV + data[3] = 99*un.mV assert_neo_object_is_compliant(signal) - self.assertNotEqual(signal[3, 0], 99*pq.mV) + self.assertNotEqual(signal[3, 0], 99*un.mV) def test__create_with_copy_false_should_return_view(self): - data = np.arange(10.0) * pq.mV - rate = 5000*pq.Hz + data = np.arange(10.0) * un.mV + rate = 5000*un.Hz signal = AnalogSignal(data, copy=False, sampling_rate=rate) - data[3] = 99*pq.mV + data[3] = 99*un.mV assert_neo_object_is_compliant(signal) - self.assertEqual(signal[3, 0], 99*pq.mV) + self.assertEqual(signal[3, 0], 99*un.mV) def test__create2D_with_copy_false_should_return_view(self): - data = np.arange(10.0) * pq.mV + data = np.arange(10.0) * un.mV data = data.reshape((5, 2)) - rate = 5000*pq.Hz + rate = 5000*un.Hz signal = AnalogSignal(data, copy=False, sampling_rate=rate) - data[3, 0] = 99*pq.mV + data[3, 0] = 99*un.mV assert_neo_object_is_compliant(signal) - self.assertEqual(signal[3, 0], 99*pq.mV) + self.assertEqual(signal[3, 0], 99*un.mV) def test__create_with_additional_argument(self): - signal = AnalogSignal([1, 2, 3], units="mV", sampling_rate=1*pq.kHz, + signal = AnalogSignal([1, 2, 3], units="mV", sampling_rate=1*un.kHz, file_origin='crack.txt', ratname='Nicolas') assert_neo_object_is_compliant(signal) self.assertEqual(signal.annotations, {'ratname': 'Nicolas'}) @@ -157,12 +157,12 @@ def test__create_with_additional_argument(self): class TestAnalogSignalProperties(unittest.TestCase): def setUp(self): - self.t_start = [0.0*pq.ms, 100*pq.ms, -200*pq.ms] - self.rates = [1*pq.kHz, 420*pq.Hz, 999*pq.Hz] - self.rates2 = [2*pq.kHz, 290*pq.Hz, 1111*pq.Hz] - self.data = [np.arange(10.0)*pq.nA, - np.arange(-100.0, 100.0, 10.0)*pq.mV, - np.random.uniform(size=100)*pq.uV] + self.t_start = [0.0*un.ms, 100*un.ms, -200*un.ms] + self.rates = [1*un.kHz, 420*un.Hz, 999*un.Hz] + self.rates2 = [2*un.kHz, 290*un.Hz, 1111*un.Hz] + self.data = [np.arange(10.0)*un.nA, + np.arange(-100.0, 100.0, 10.0)*un.mV, + np.random.uniform(size=100)*un.uV] self.signals = [AnalogSignal(D, sampling_rate=r, t_start=t, testattr='test') for r, D, t in zip(self.rates, @@ -233,7 +233,7 @@ def test__times_getter(self): targ = np.arange(self.data[i].size) targ = targ/self.rates[i] + self.t_start[i] assert_neo_object_is_compliant(signal) - assert_arrays_almost_equal(signal.times, targ, 1e-12*pq.ms) + assert_arrays_almost_equal(signal.times, targ, 1e-12*un.ms) def test__duplicate_with_new_array(self): signal1 = self.signals[1] @@ -300,8 +300,8 @@ def test__pretty(self): class TestAnalogSignalArrayMethods(unittest.TestCase): def setUp(self): self.data1 = np.arange(10.0) - self.data1quant = self.data1 * pq.nA - self.signal1 = AnalogSignal(self.data1quant, sampling_rate=1*pq.kHz, + self.data1quant = self.data1 * un.nA + self.signal1 = AnalogSignal(self.data1quant, sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') self.signal1.segment = 1 @@ -336,7 +336,7 @@ def test__slice_should_return_AnalogSignalArray(self): self.assertEqual(result.annotations, self.signal1.annotations) def test__slice_should_let_access_to_parents_objects(self): - result = self.signal1.time_slice(1*pq.ms,3*pq.ms) + result = self.signal1.time_slice(1*un.ms,3*un.ms) self.assertEqual(result.segment, self.signal1.segment) self.assertEqual(result.channel_index, self.signal1.channel_index) @@ -390,43 +390,43 @@ def test__getitem_should_return_single_quantity(self): result1 = self.signal1[0, 0] result2 = self.signal1[9, 0] - self.assertIsInstance(result1, pq.Quantity) + self.assertIsInstance(result1, un.Quantity) self.assertFalse(hasattr(result1, 'name')) self.assertFalse(hasattr(result1, 'description')) self.assertFalse(hasattr(result1, 'file_origin')) self.assertFalse(hasattr(result1, 'annotations')) - self.assertIsInstance(result2, pq.Quantity) + self.assertIsInstance(result2, un.Quantity) self.assertFalse(hasattr(result2, 'name')) self.assertFalse(hasattr(result2, 'description')) self.assertFalse(hasattr(result2, 'file_origin')) self.assertFalse(hasattr(result2, 'annotations')) - self.assertEqual(result1, 0*pq.nA) - self.assertEqual(result2, 9*pq.nA) + self.assertEqual(result1, 0*un.nA) + self.assertEqual(result2, 9*un.nA) def test__getitem_out_of_bounds_IndexError(self): self.assertRaises(IndexError, self.signal1.__getitem__, (10, 0)) def test_comparison_operators(self): - assert_array_equal(self.signal1 >= 5*pq.nA, + assert_array_equal(self.signal1 >= 5*un.nA, np.array([False, False, False, False, False, True, True, True, True, True]).reshape(-1, 1)) - assert_array_equal(self.signal1 >= 5*pq.pA, + assert_array_equal(self.signal1 >= 5*un.pA, np.array([False, True, True, True, True, True, True, True, True, True]).reshape(-1, 1)) def test__comparison_with_inconsistent_units_should_raise_Exception(self): - self.assertRaises(ValueError, self.signal1.__gt__, 5*pq.mV) + self.assertRaises(ValueError, self.signal1.__gt__, 5*un.mV) def test__simple_statistics(self): - self.assertEqual(self.signal1.max(), 9*pq.nA) - self.assertEqual(self.signal1.min(), 0*pq.nA) - self.assertEqual(self.signal1.mean(), 4.5*pq.nA) + self.assertEqual(self.signal1.max(), 9*un.nA) + self.assertEqual(self.signal1.min(), 0*un.nA) + self.assertEqual(self.signal1.mean(), 4.5*un.nA) def test__rescale_same(self): result = self.signal1.copy() - result = result.rescale(pq.nA) + result = result.rescale(un.nA) self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) @@ -435,13 +435,13 @@ def test__rescale_same(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(result.units, 1*pq.nA) + self.assertEqual(result.units, 1*un.nA) assert_array_equal(result.magnitude, self.data1.reshape(-1, 1)) assert_same_sub_schema(result, self.signal1) def test__rescale_new(self): result = self.signal1.copy() - result = result.rescale(pq.pA) + result = result.rescale(un.pA) self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) @@ -450,19 +450,19 @@ def test__rescale_new(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(result.units, 1*pq.pA) + self.assertEqual(result.units, 1*un.pA) assert_arrays_almost_equal(np.array(result), self.data1.reshape(-1, 1)*1000., 1e-10) def test__rescale_new_incompatible_ValueError(self): - self.assertRaises(ValueError, self.signal1.rescale, pq.mV) + self.assertRaises(ValueError, self.signal1.rescale, un.mV) class TestAnalogSignalEquality(unittest.TestCase): def test__signals_with_different_data_complement_should_be_not_equal(self): signal1 = AnalogSignal(np.arange(10.0), units="mV", - sampling_rate=1*pq.kHz) + sampling_rate=1*un.kHz) signal2 = AnalogSignal(np.arange(10.0), units="mV", - sampling_rate=2*pq.kHz) + sampling_rate=2*un.kHz) assert_neo_object_is_compliant(signal1) assert_neo_object_is_compliant(signal2) self.assertNotEqual(signal1, signal2) @@ -471,9 +471,9 @@ def test__signals_with_different_data_complement_should_be_not_equal(self): class TestAnalogSignalCombination(unittest.TestCase): def setUp(self): self.data1 = np.arange(10.0) - self.data1quant = self.data1 * pq.mV + self.data1quant = self.data1 * un.mV self.signal1 = AnalogSignal(self.data1quant, - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') @@ -486,7 +486,7 @@ def test__compliant(self): self.assertEqual(self.signal1.annotations, {'arg1': 'test'}) def test__add_const_quantity_should_preserve_data_complement(self): - result = self.signal1 + 0.065*pq.V + result = self.signal1 + 0.065*un.V self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -495,14 +495,14 @@ def test__add_const_quantity_should_preserve_data_complement(self): self.assertEqual(result.annotations, {'arg1': 'test'}) assert_array_equal(result.magnitude.flatten(), self.data1 + 65) - self.assertEqual(self.signal1[9, 0], 9*pq.mV) - self.assertEqual(result[9, 0], 74*pq.mV) + self.assertEqual(self.signal1[9, 0], 9*un.mV) + self.assertEqual(result[9, 0], 74*un.mV) self.assertEqual(self.signal1.t_start, result.t_start) self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) def test__add_quantity_should_preserve_data_complement(self): data2 = np.arange(10.0, 20.0).reshape(-1, 1) - data2quant = data2*pq.mV + data2quant = data2*un.mV result = self.signal1 + data2quant self.assertIsInstance(result, AnalogSignal) @@ -513,7 +513,7 @@ def test__add_quantity_should_preserve_data_complement(self): self.assertEqual(result.annotations, {'arg1': 'test'}) targ = AnalogSignal(np.arange(10.0, 30.0, 2.0), units="mV", - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(targ) @@ -523,8 +523,8 @@ def test__add_quantity_should_preserve_data_complement(self): def test__add_two_consistent_signals_should_preserve_data_complement(self): data2 = np.arange(10.0, 20.0) - data2quant = data2*pq.mV - signal2 = AnalogSignal(data2quant, sampling_rate=1*pq.kHz) + data2quant = data2*un.mV + signal2 = AnalogSignal(data2quant, sampling_rate=1*un.kHz) assert_neo_object_is_compliant(signal2) result = self.signal1 + signal2 @@ -536,7 +536,7 @@ def test__add_two_consistent_signals_should_preserve_data_complement(self): self.assertEqual(result.annotations, {'arg1': 'test'}) targ = AnalogSignal(np.arange(10.0, 30.0, 2.0), units="mV", - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(targ) @@ -545,17 +545,17 @@ def test__add_two_consistent_signals_should_preserve_data_complement(self): assert_same_sub_schema(result, targ) def test__add_signals_with_inconsistent_data_complement_ValueError(self): - self.signal1.t_start = 0.0*pq.ms + self.signal1.t_start = 0.0*un.ms assert_neo_object_is_compliant(self.signal1) signal2 = AnalogSignal(np.arange(10.0), units="mV", - t_start=100.0*pq.ms, sampling_rate=0.5*pq.kHz) + t_start=100.0*un.ms, sampling_rate=0.5*un.kHz) assert_neo_object_is_compliant(signal2) self.assertRaises(ValueError, self.signal1.__add__, signal2) def test__subtract_const_should_preserve_data_complement(self): - result = self.signal1 - 65*pq.mV + result = self.signal1 - 65*un.mV self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -563,13 +563,13 @@ def test__subtract_const_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9, 0], 9*pq.mV) - self.assertEqual(result[9, 0], -56*pq.mV) + self.assertEqual(self.signal1[9, 0], 9*un.mV) + self.assertEqual(result[9, 0], -56*un.mV) assert_array_equal(result.magnitude.flatten(), self.data1 - 65) self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) def test__subtract_from_const_should_return_signal(self): - result = 10*pq.mV - self.signal1 + result = 10*un.mV - self.signal1 self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -577,8 +577,8 @@ def test__subtract_from_const_should_return_signal(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9, 0], 9*pq.mV) - self.assertEqual(result[9, 0], 1*pq.mV) + self.assertEqual(self.signal1[9, 0], 9*un.mV) + self.assertEqual(result[9, 0], 1*un.mV) assert_array_equal(result.magnitude.flatten(), 10 - self.data1) self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) @@ -591,8 +591,8 @@ def test__mult_by_const_float_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9, 0], 9*pq.mV) - self.assertEqual(result[9, 0], 18*pq.mV) + self.assertEqual(self.signal1[9, 0], 9*un.mV) + self.assertEqual(result[9, 0], 18*un.mV) assert_array_equal(result.magnitude.flatten(), self.data1*2) self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) @@ -605,16 +605,16 @@ def test__divide_by_const_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9, 0], 9*pq.mV) - self.assertEqual(result[9, 0], 18*pq.mV) + self.assertEqual(self.signal1[9, 0], 9*un.mV) + self.assertEqual(result[9, 0], 18*un.mV) assert_array_equal(result.magnitude.flatten(), self.data1/0.5) self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) class TestAnalogSignalFunctions(unittest.TestCase): def test__pickle(self): - signal1 = AnalogSignal([1, 2, 3, 4], sampling_period=1*pq.ms, - units=pq.S) + signal1 = AnalogSignal([1, 2, 3, 4], sampling_period=1*un.ms, + units=un.S) signal1.annotations['index'] = 2 fobj = open('./pickle', 'wb') @@ -641,28 +641,28 @@ def test___get_sampling_rate__period_none_rate_none_ValueError(self): def test___get_sampling_rate__period_quant_rate_none(self): sampling_rate = None - sampling_period = pq.Quantity(10., units=pq.s) + sampling_period = un.Quantity(10., units=un.s) targ_rate = 1/sampling_period out_rate = _get_sampling_rate(sampling_rate, sampling_period) self.assertEqual(targ_rate, out_rate) def test___get_sampling_rate__period_none_rate_quant(self): - sampling_rate = pq.Quantity(10., units=pq.Hz) + sampling_rate = un.Quantity(10., units=un.Hz) sampling_period = None targ_rate = sampling_rate out_rate = _get_sampling_rate(sampling_rate, sampling_period) self.assertEqual(targ_rate, out_rate) def test___get_sampling_rate__period_rate_equivalent(self): - sampling_rate = pq.Quantity(10., units=pq.Hz) - sampling_period = pq.Quantity(0.1, units=pq.s) + sampling_rate = un.Quantity(10., units=un.Hz) + sampling_period = un.Quantity(0.1, units=un.s) targ_rate = sampling_rate out_rate = _get_sampling_rate(sampling_rate, sampling_period) self.assertEqual(targ_rate, out_rate) def test___get_sampling_rate__period_rate_not_equivalent_ValueError(self): - sampling_rate = pq.Quantity(10., units=pq.Hz) - sampling_period = pq.Quantity(10, units=pq.s) + sampling_rate = un.Quantity(10., units=un.Hz) + sampling_period = un.Quantity(10, units=un.s) self.assertRaises(ValueError, _get_sampling_rate, sampling_rate, sampling_period) diff --git a/neo/test/coretest/test_analogsignalarray.py b/neo/test/coretest/test_analogsignalarray.py index 240dfdaec..2ab24adcc 100644 --- a/neo/test/coretest/test_analogsignalarray.py +++ b/neo/test/coretest/test_analogsignalarray.py @@ -12,7 +12,8 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un + try: from IPython.lib.pretty import pretty @@ -39,10 +40,10 @@ def setUp(self): def test__get_fake_values(self): self.annotations['seed'] = 0 - signal = get_fake_value('signal', pq.Quantity, seed=0, dim=2) - sampling_rate = get_fake_value('sampling_rate', pq.Quantity, + signal = get_fake_value('signal', un.Quantity, seed=0, dim=2) + sampling_rate = get_fake_value('sampling_rate', un.Quantity, seed=1, dim=0) - t_start = get_fake_value('t_start', pq.Quantity, seed=2, dim=0) + t_start = get_fake_value('t_start', un.Quantity, seed=2, dim=0) name = get_fake_value('name', str, seed=3, obj=AnalogSignal) description = get_fake_value('description', str, seed=4, obj='AnalogSignal') @@ -102,64 +103,64 @@ def test__fake_neo__nocascade(self): class TestAnalogSignalArrayConstructor(unittest.TestCase): def test__create_from_list(self): data = [(i, i, i) for i in range(10)] # 3 signals each with 10 samples - rate = 1000*pq.Hz + rate = 1000*un.Hz signal = AnalogSignal(data, sampling_rate=rate, units="mV") assert_neo_object_is_compliant(signal) self.assertEqual(signal.shape, (10, 3)) - self.assertEqual(signal.t_start, 0*pq.ms) + self.assertEqual(signal.t_start, 0*un.ms) self.assertEqual(signal.t_stop, len(data)/rate) - self.assertEqual(signal[9, 0], 9000*pq.uV) + self.assertEqual(signal[9, 0], 9000*un.uV) def test__create_from_numpy_array(self): data = np.arange(20.0).reshape((10, 2)) - rate = 1*pq.kHz + rate = 1*un.kHz signal = AnalogSignal(data, sampling_rate=rate, units="uV") assert_neo_object_is_compliant(signal) - self.assertEqual(signal.t_start, 0*pq.ms) + self.assertEqual(signal.t_start, 0*un.ms) self.assertEqual(signal.t_stop, data.shape[0]/rate) - self.assertEqual(signal[9, 0], 0.018*pq.mV) - self.assertEqual(signal[9, 1], 19*pq.uV) + self.assertEqual(signal[9, 0], 0.018*un.mV) + self.assertEqual(signal[9, 1], 19*un.uV) def test__create_from_quantities_array(self): - data = np.arange(20.0).reshape((10, 2)) * pq.mV - rate = 5000*pq.Hz + data = np.arange(20.0).reshape((10, 2)) * un.mV + rate = 5000*un.Hz signal = AnalogSignal(data, sampling_rate=rate) assert_neo_object_is_compliant(signal) - self.assertEqual(signal.t_start, 0*pq.ms) + self.assertEqual(signal.t_start, 0*un.ms) self.assertEqual(signal.t_stop, data.shape[0]/rate) - self.assertEqual(signal[9, 0], 18000*pq.uV) + self.assertEqual(signal[9, 0], 18000*un.uV) def test__create_from_quantities_with_inconsistent_units_ValueError(self): - data = np.arange(20.0).reshape((10, 2)) * pq.mV + data = np.arange(20.0).reshape((10, 2)) * un.mV self.assertRaises(ValueError, AnalogSignal, data, - sampling_rate=1*pq.kHz, units="nA") + sampling_rate=1*un.kHz, units="nA") def test__create_with_copy_true_should_return_copy(self): - data = np.arange(20.0).reshape((10, 2)) * pq.mV - rate = 5000*pq.Hz + data = np.arange(20.0).reshape((10, 2)) * un.mV + rate = 5000*un.Hz signal = AnalogSignal(data, copy=True, sampling_rate=rate) assert_neo_object_is_compliant(signal) - data[3, 0] = 0.099*pq.V - self.assertNotEqual(signal[3, 0], 99*pq.mV) + data[3, 0] = 0.099*un.V + self.assertNotEqual(signal[3, 0], 99*un.mV) def test__create_with_copy_false_should_return_view(self): - data = np.arange(20.0).reshape((10, 2)) * pq.mV - rate = 5000*pq.Hz + data = np.arange(20.0).reshape((10, 2)) * un.mV + rate = 5000*un.Hz signal = AnalogSignal(data, copy=False, sampling_rate=rate) assert_neo_object_is_compliant(signal) - data[3, 0] = 99*pq.mV - self.assertEqual(signal[3, 0], 99000*pq.uV) + data[3, 0] = 99*un.mV + self.assertEqual(signal[3, 0], 99000*un.uV) # signal must not be 1D - should raise Exception if 1D class TestAnalogSignalArrayProperties(unittest.TestCase): def setUp(self): - self.t_start = [0.0*pq.ms, 100*pq.ms, -200*pq.ms] - self.rates = [1*pq.kHz, 420*pq.Hz, 999*pq.Hz] - self.data = [np.arange(10.0).reshape((5, 2))*pq.nA, - np.arange(-100.0, 100.0, 10.0).reshape((4, 5))*pq.mV, - np.random.uniform(size=(100, 4))*pq.uV] + self.t_start = [0.0*un.ms, 100*un.ms, -200*un.ms] + self.rates = [1*un.kHz, 420*un.Hz, 999*un.Hz] + self.data = [np.arange(10.0).reshape((5, 2))*un.nA, + np.arange(-100.0, 100.0, 10.0).reshape((4, 5))*un.mV, + np.random.uniform(size=(100, 4))*un.uV] self.signals = [AnalogSignal(D, sampling_rate=r, t_start=t) for r, D, t in zip(self.rates, self.data, @@ -188,7 +189,7 @@ def test__times(self): for i, signal in enumerate(self.signals): targ = np.arange(self.data[i].shape[0]) targ = targ/self.rates[i] + self.t_start[i] - assert_arrays_almost_equal(signal.times, targ, 1e-12*pq.ms) + assert_arrays_almost_equal(signal.times, targ, 1e-12*un.ms) def test__children(self): signal = self.signals[0] @@ -234,16 +235,16 @@ def test__repr(self): class TestAnalogSignalArrayArrayMethods(unittest.TestCase): def setUp(self): self.data1 = np.arange(55.0).reshape((11, 5)) - self.data1quant = self.data1 * pq.nA + self.data1quant = self.data1 * un.nA self.signal1 = AnalogSignal(self.data1quant, - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') self.data2 = np.array([[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]).T - self.data2quant = self.data2 * pq.mV + self.data2quant = self.data2 * un.mV self.signal2 = AnalogSignal(self.data2quant, - sampling_rate=1.0*pq.Hz, + sampling_rate=1.0*un.Hz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') @@ -297,7 +298,7 @@ def test__index_dim1_and_slice_dim0_should_return_single_channel_analogsignalarr def test__index_dim0_should_return_quantity_array(self): # i.e. values from all signals for a single point in time result = self.signal1[3, :] - self.assertIsInstance(result, pq.Quantity) + self.assertIsInstance(result, un.Quantity) self.assertFalse(hasattr(result, 'name')) self.assertFalse(hasattr(result, 'description')) self.assertFalse(hasattr(result, 'file_origin')) @@ -305,13 +306,13 @@ def test__index_dim0_should_return_quantity_array(self): self.assertEqual(result.shape, (5,)) self.assertFalse(hasattr(result, "t_start")) - self.assertEqual(result.units, pq.nA) + self.assertEqual(result.units, un.nA) assert_arrays_equal(result, self.data1[3, :]) def test__index_dim0_and_slice_dim1_should_return_quantity_array(self): # i.e. values from a subset of signals for a single point in time result = self.signal1[3, 2:5] - self.assertIsInstance(result, pq.Quantity) + self.assertIsInstance(result, un.Quantity) self.assertFalse(hasattr(result, 'name')) self.assertFalse(hasattr(result, 'description')) self.assertFalse(hasattr(result, 'file_origin')) @@ -319,7 +320,7 @@ def test__index_dim0_and_slice_dim1_should_return_quantity_array(self): self.assertEqual(result.shape, (3,)) self.assertFalse(hasattr(result, "t_start")) - self.assertEqual(result.units, pq.nA) + self.assertEqual(result.units, un.nA) assert_arrays_equal(result, self.data1[3, 2:5]) def test__index_as_string_IndexError(self): @@ -336,7 +337,7 @@ def test__slice_both_dimensions_should_return_analogsignalarray(self): targ = AnalogSignal([[0, 1, 2], [5, 6, 7], [10, 11, 12]], dtype=float, units="nA", - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(targ) @@ -367,34 +368,34 @@ def test__slice_only_first_dimension_should_return_analogsignalarray(self): def test__getitem_should_return_single_quantity(self): # quantities drops the units in this case - self.assertEqual(self.signal1[9, 3], 48000*pq.pA) + self.assertEqual(self.signal1[9, 3], 48000*un.pA) self.assertEqual(self.signal1[9][3], self.signal1[9, 3]) self.assertTrue(hasattr(self.signal1[9, 3], 'units')) self.assertRaises(IndexError, self.signal1.__getitem__, (99, 73)) def test_comparison_operators(self): - assert_arrays_equal(self.signal1[0:3, 0:3] >= 5*pq.nA, + assert_arrays_equal(self.signal1[0:3, 0:3] >= 5*un.nA, np.array([[False, False, False], [True, True, True], [True, True, True]])) - assert_arrays_equal(self.signal1[0:3, 0:3] >= 5*pq.pA, + assert_arrays_equal(self.signal1[0:3, 0:3] >= 5*un.pA, np.array([[False, True, True], [True, True, True], [True, True, True]])) def test__comparison_with_inconsistent_units_should_raise_Exception(self): - self.assertRaises(ValueError, self.signal1.__gt__, 5*pq.mV) + self.assertRaises(ValueError, self.signal1.__gt__, 5*un.mV) def test__simple_statistics(self): - self.assertEqual(self.signal1.max(), 54000*pq.pA) - self.assertEqual(self.signal1.min(), 0*pq.nA) - self.assertEqual(self.signal1.mean(), 27*pq.nA) - self.assertEqual(self.signal1.std(), self.signal1.magnitude.std()*pq.nA) - self.assertEqual(self.signal1.var(), self.signal1.magnitude.var()*pq.nA**2) + self.assertEqual(self.signal1.max(), 54000*un.pA) + self.assertEqual(self.signal1.min(), 0*un.nA) + self.assertEqual(self.signal1.mean(), 27*un.nA) + self.assertEqual(self.signal1.std(), self.signal1.magnitude.std()*un.nA) + self.assertEqual(self.signal1.var(), self.signal1.magnitude.var()*un.nA**2) def test__rescale_same(self): result = self.signal1.copy() - result = result.rescale(pq.nA) + result = result.rescale(un.nA) self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) @@ -403,13 +404,13 @@ def test__rescale_same(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(result.units, 1*pq.nA) + self.assertEqual(result.units, 1*un.nA) assert_arrays_equal(result, self.data1) assert_same_sub_schema(result, self.signal1) def test__rescale_new(self): result = self.signal1.copy() - result = result.rescale(pq.pA) + result = result.rescale(un.pA) self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) @@ -418,12 +419,12 @@ def test__rescale_new(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(result.units, 1*pq.pA) + self.assertEqual(result.units, 1*un.pA) assert_arrays_almost_equal(np.array(result), self.data1*1000., 1e-10) def test__time_slice(self): - t_start = 2 * pq.s - t_stop = 4 * pq.s + t_start = 2 * un.s + t_stop = 4 * un.s result = self.signal2.time_slice(t_start, t_stop) self.assertIsInstance(result, AnalogSignal) @@ -434,7 +435,7 @@ def test__time_slice(self): self.assertEqual(result.annotations, {'arg1': 'test'}) targ = AnalogSignal(np.array([[2., 3.], [2., 3.]]).T, - sampling_rate=1.0*pq.Hz, units='mV', + sampling_rate=1.0*un.Hz, units='mV', t_start=t_start, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') @@ -447,10 +448,10 @@ def test__time_slice(self): assert_same_sub_schema(result, targ) def test__time_slice__out_of_bounds_ValueError(self): - t_start_good = 2 * pq.s - t_stop_good = 4 * pq.s - t_start_bad = -2 * pq.s - t_stop_bad = 40 * pq.s + t_start_good = 2 * un.s + t_stop_good = 4 * un.s + t_start_bad = -2 * un.s + t_stop_bad = 40 * un.s self.assertRaises(ValueError, self.signal2.time_slice, t_start_good, t_stop_bad) @@ -460,8 +461,8 @@ def test__time_slice__out_of_bounds_ValueError(self): t_start_bad, t_stop_bad) def test__time_equal(self): - t_start = 0 * pq.s - t_stop = 6 * pq.s + t_start = 0 * un.s + t_stop = 6 * un.s result = self.signal2.time_slice(t_start, t_stop) self.assertIsInstance(result, AnalogSignal) @@ -477,11 +478,11 @@ def test__time_equal(self): assert_same_sub_schema(result, self.signal2) def test__time_slice__offset(self): - self.signal2.t_start = 10.0 * pq.s + self.signal2.t_start = 10.0 * un.s assert_neo_object_is_compliant(self.signal2) - t_start = 12 * pq.s - t_stop = 14 * pq.s + t_start = 12 * un.s + t_stop = 14 * un.s result = self.signal2.time_slice(t_start, t_stop) self.assertIsInstance(result, AnalogSignal) @@ -492,13 +493,13 @@ def test__time_slice__offset(self): self.assertEqual(result.annotations, {'arg1': 'test'}) targ = AnalogSignal(np.array([[2., 3.], [2., 3.]]).T, - t_start=12.0*pq.ms, - sampling_rate=1.0*pq.Hz, units='mV', + t_start=12.0*un.ms, + sampling_rate=1.0*un.Hz, units='mV', name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(result) - self.assertEqual(self.signal2.t_start, 10.0 * pq.s) + self.assertEqual(self.signal2.t_start, 10.0 * un.s) self.assertEqual(result.t_stop, t_stop) self.assertEqual(result.t_start, t_start) self.assertEqual(result.sampling_rate, targ.sampling_rate) @@ -506,11 +507,11 @@ def test__time_slice__offset(self): assert_same_sub_schema(result, targ) def test__time_slice__different_units(self): - self.signal2.t_start = 10.0 * pq.ms + self.signal2.t_start = 10.0 * un.ms assert_neo_object_is_compliant(self.signal2) - t_start = 2 * pq.s + 10.0 * pq.ms - t_stop = 4 * pq.s + 10.0 * pq.ms + t_start = 2 * un.s + 10.0 * un.ms + t_stop = 4 * un.s + 10.0 * un.ms result = self.signal2.time_slice(t_start, t_stop) self.assertIsInstance(result, AnalogSignal) @@ -521,27 +522,27 @@ def test__time_slice__different_units(self): self.assertEqual(result.annotations, {'arg1': 'test'}) targ = AnalogSignal(np.array([[2., 3.], [2., 3.]]).T, - t_start=t_start.rescale(pq.ms), - sampling_rate=1.0*pq.Hz, units='mV', + t_start=t_start.rescale(un.ms), + sampling_rate=1.0*un.Hz, units='mV', name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(result) assert_neo_object_is_compliant(self.signal2) - self.assertEqual(self.signal2.t_start, 10.0 * pq.ms) - self.assertAlmostEqual(result.t_stop, t_stop, delta=1e-12*pq.ms) - self.assertAlmostEqual(result.t_start, t_start, delta=1e-12*pq.ms) - assert_arrays_almost_equal(result.times, targ.times, 1e-12*pq.ms) + self.assertEqual(self.signal2.t_start, 10.0 * un.ms) + self.assertAlmostEqual(result.t_stop, t_stop, delta=1e-12*un.ms) + self.assertAlmostEqual(result.t_start, t_start, delta=1e-12*un.ms) + assert_arrays_almost_equal(result.times, targ.times, 1e-12*un.ms) self.assertEqual(result.sampling_rate, targ.sampling_rate) assert_arrays_equal(result, targ) assert_same_sub_schema(result, targ) def test__time_slice__no_explicit_time(self): - self.signal2.t_start = 10.0 * pq.ms + self.signal2.t_start = 10.0 * un.ms assert_neo_object_is_compliant(self.signal2) - t1 = 2 * pq.s + 10.0 * pq.ms - t2 = 4 * pq.s + 10.0 * pq.ms + t1 = 2 * un.s + 10.0 * un.ms + t2 = 4 * un.s + 10.0 * un.ms for t_start,t_stop in [(t1,None),(None,None),(None,t2)]: @@ -561,17 +562,17 @@ def test__time_slice__no_explicit_time(self): targ_array = self.signal2.magnitude[targ_ind] targ = AnalogSignal(targ_array, - t_start=t_start_targ.rescale(pq.ms), - sampling_rate=1.0*pq.Hz, units='mV', + t_start=t_start_targ.rescale(un.ms), + sampling_rate=1.0*un.Hz, units='mV', name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(result) assert_neo_object_is_compliant(self.signal2) - self.assertEqual(self.signal2.t_start, 10.0 * pq.ms) - self.assertAlmostEqual(result.t_stop, t_stop_targ, delta=1e-12*pq.ms) - self.assertAlmostEqual(result.t_start, t_start_targ, delta=1e-12*pq.ms) - assert_arrays_almost_equal(result.times, targ.times, 1e-12*pq.ms) + self.assertEqual(self.signal2.t_start, 10.0 * un.ms) + self.assertAlmostEqual(result.t_stop, t_stop_targ, delta=1e-12*un.ms) + self.assertAlmostEqual(result.t_start, t_start_targ, delta=1e-12*un.ms) + assert_arrays_almost_equal(result.times, targ.times, 1e-12*un.ms) self.assertEqual(result.sampling_rate, targ.sampling_rate) assert_array_equal(result.magnitude, targ.magnitude) assert_same_sub_schema(result, targ) @@ -580,9 +581,9 @@ def test__time_slice__no_explicit_time(self): class TestAnalogSignalArrayEquality(unittest.TestCase): def test__signals_with_different_data_complement_should_be_not_equal(self): signal1 = AnalogSignal(np.arange(55.0).reshape((11, 5)), - units="mV", sampling_rate=1*pq.kHz) + units="mV", sampling_rate=1*un.kHz) signal2 = AnalogSignal(np.arange(55.0).reshape((11, 5)), - units="mV", sampling_rate=2*pq.kHz) + units="mV", sampling_rate=2*un.kHz) self.assertNotEqual(signal1, signal2) assert_neo_object_is_compliant(signal1) assert_neo_object_is_compliant(signal2) @@ -591,16 +592,16 @@ def test__signals_with_different_data_complement_should_be_not_equal(self): class TestAnalogSignalArrayCombination(unittest.TestCase): def setUp(self): self.data1 = np.arange(55.0).reshape((11, 5)) - self.data1quant = self.data1 * pq.mV + self.data1quant = self.data1 * un.mV self.signal1 = AnalogSignal(self.data1quant, - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') self.data2 = np.arange(100.0, 155.0).reshape((11, 5)) - self.data2quant = self.data2 * pq.mV + self.data2quant = self.data2 * un.mV self.signal2 = AnalogSignal(self.data2quant, - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') @@ -619,7 +620,7 @@ def test__compliant(self): self.assertEqual(self.signal2.annotations, {'arg1': 'test'}) def test__add_const_quantity_should_preserve_data_complement(self): - result = self.signal1 + 0.065*pq.V + result = self.signal1 + 0.065*un.V self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -629,8 +630,8 @@ def test__add_const_quantity_should_preserve_data_complement(self): # time zero, signal index 4 assert_arrays_equal(result, self.data1 + 65) - self.assertEqual(self.signal1[0, 4], 4*pq.mV) - self.assertEqual(result[0, 4], 69000*pq.uV) + self.assertEqual(self.signal1[0, 4], 4*un.mV) + self.assertEqual(result[0, 4], 69000*un.uV) self.assertEqual(self.signal1.t_start, result.t_start) self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) @@ -645,7 +646,7 @@ def test__add_two_consistent_signals_should_preserve_data_complement(self): targdata = np.arange(100.0, 210.0, 2.0).reshape((11, 5)) targ = AnalogSignal(targdata, units="mV", - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='spam', description='eggs', file_origin='testfile.txt', arg1='test') assert_neo_object_is_compliant(targ) @@ -654,13 +655,13 @@ def test__add_two_consistent_signals_should_preserve_data_complement(self): assert_same_sub_schema(result, targ) def test__add_signals_with_inconsistent_data_complement_ValueError(self): - self.signal2.sampling_rate = 0.5*pq.kHz + self.signal2.sampling_rate = 0.5*un.kHz assert_neo_object_is_compliant(self.signal2) self.assertRaises(ValueError, self.signal1.__add__, self.signal2) def test__subtract_const_should_preserve_data_complement(self): - result = self.signal1 - 65*pq.mV + result = self.signal1 - 65*un.mV self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -674,7 +675,7 @@ def test__subtract_const_should_preserve_data_complement(self): self.assertEqual(self.signal1.sampling_rate, result.sampling_rate) def test__subtract_from_const_should_return_signal(self): - result = 10*pq.mV - self.signal1 + result = 10*un.mV - self.signal1 self.assertIsInstance(result, AnalogSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -720,21 +721,21 @@ def test__merge(self): self.signal1.file_origin = None assert_neo_object_is_compliant(self.signal1) - data3 = np.arange(1000.0, 1066.0).reshape((11, 6)) * pq.uV + data3 = np.arange(1000.0, 1066.0).reshape((11, 6)) * un.uV data3scale = data3.rescale(self.data1quant.units) signal2 = AnalogSignal(self.data1quant, - sampling_rate=1*pq.kHz, + sampling_rate=1*un.kHz, name='signal2', description='test signal', file_origin='testfile.txt') signal3 = AnalogSignal(data3, - units="uV", sampling_rate=1*pq.kHz, + units="uV", sampling_rate=1*un.kHz, name='signal3', description='test signal', file_origin='testfile.txt') signal4 = AnalogSignal(data3, - units="uV", sampling_rate=1*pq.kHz, + units="uV", sampling_rate=1*un.kHz, name='signal4', description='test signal', file_origin='testfile.txt') @@ -756,12 +757,12 @@ def test__merge(self): assert_neo_object_is_compliant(merged23) assert_neo_object_is_compliant(merged24) - self.assertEqual(merged13[0, 4], 4*pq.mV) - self.assertEqual(merged23[0, 4], 4*pq.mV) - self.assertEqual(merged13[0, 5], 1*pq.mV) - self.assertEqual(merged23[0, 5], 1*pq.mV) - self.assertEqual(merged13[10, 10], 1.065*pq.mV) - self.assertEqual(merged23[10, 10], 1.065*pq.mV) + self.assertEqual(merged13[0, 4], 4*un.mV) + self.assertEqual(merged23[0, 4], 4*un.mV) + self.assertEqual(merged13[0, 5], 1*un.mV) + self.assertEqual(merged23[0, 5], 1*un.mV) + self.assertEqual(merged13[10, 10], 1.065*un.mV) + self.assertEqual(merged23[10, 10], 1.065*un.mV) self.assertEqual(merged13.t_stop, self.signal1.t_stop) self.assertEqual(merged23.t_stop, self.signal1.t_stop) @@ -780,7 +781,7 @@ def test__merge(self): class TestAnalogSignalArrayFunctions(unittest.TestCase): def test__pickle(self): signal1 = AnalogSignal(np.arange(55.0).reshape((11, 5)), - units="mV", sampling_rate=1*pq.kHz) + units="mV", sampling_rate=1*un.kHz) fobj = open('./pickle', 'wb') pickle.dump(signal1, fobj) diff --git a/neo/test/coretest/test_base.py b/neo/test/coretest/test_base.py index c144c0c2e..f5f445247 100644 --- a/neo/test/coretest/test_base.py +++ b/neo/test/coretest/test_base.py @@ -14,7 +14,8 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un + try: from IPython.lib.pretty import pretty @@ -985,28 +986,28 @@ def setUp(self): def test_quantities_array_int(self): '''test to make sure int type quantites arrays are accepted''' - value = pq.Quantity([1, 2, 3, 4, 5], dtype=np.int, units=pq.s) + value = un.Quantity([1, 2, 3, 4, 5], dtype=np.int, units=un.s) self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) def test_quantities_array_uint(self): '''test to make sure uint type quantites arrays are accepted''' - value = pq.Quantity([1, 2, 3, 4, 5], dtype=np.uint, units=pq.meter) + value = un.Quantity([1, 2, 3, 4, 5], dtype=np.uint, units=un.meter) self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) def test_quantities_array_float(self): '''test to make sure float type quantites arrays are accepted''' - value = [1, 2, 3, 4, 5] * pq.kg + value = [1, 2, 3, 4, 5] * un.kg self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) def test_quantities_array_str(self): '''test to make sure str type quantites arrays are accepted''' - value = pq.Quantity([1, 2, 3, 4, 5], dtype=np.str, units=pq.meter) + value = un.Quantity([1, 2, 3, 4, 5], dtype=np.str, units=un.meter) self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) @@ -1023,28 +1024,28 @@ def setUp(self): def test_quantities_scalar_int(self): '''test to make sure int type quantites scalars are accepted''' - value = pq.Quantity(99, dtype=np.int, units=pq.s) + value = un.Quantity(99, dtype=np.int, units=un.s) self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) def test_quantities_scalar_uint(self): '''test to make sure uint type quantites scalars are accepted''' - value = pq.Quantity(99, dtype=np.uint, units=pq.meter) + value = un.Quantity(99, dtype=np.uint, units=un.meter) self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) def test_quantities_scalar_float(self): '''test to make sure float type quantites scalars are accepted''' - value = 99 * pq.kg + value = 99 * un.kg self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) def test_quantities_scalar_str(self): '''test to make sure str type quantites scalars are accepted''' - value = pq.Quantity(99, dtype=np.str, units=pq.meter) + value = un.Quantity(99, dtype=np.str, units=un.meter) self.base.annotate(data=value) result = {'data': value} self.assertDictEqual(result, self.base.annotations) diff --git a/neo/test/coretest/test_epoch.py b/neo/test/coretest/test_epoch.py index 53ce9877c..761235280 100644 --- a/neo/test/coretest/test_epoch.py +++ b/neo/test/coretest/test_epoch.py @@ -9,7 +9,8 @@ import unittest import numpy as np -import quantities as pq + +from neo import units as un import pickle import os from numpy.testing import assert_array_equal @@ -38,8 +39,8 @@ def setUp(self): def test__get_fake_values(self): self.annotations['seed'] = 0 - times = get_fake_value('times', pq.Quantity, seed=0, dim=1) - durations = get_fake_value('durations', pq.Quantity, seed=1, dim=1) + times = get_fake_value('times', un.Quantity, seed=0, dim=1) + durations = get_fake_value('durations', un.Quantity, seed=1, dim=1) labels = get_fake_value('labels', np.ndarray, seed=2, dim=1, dtype='S') name = get_fake_value('name', str, seed=3, obj=Epoch) description = get_fake_value('description', str, @@ -100,7 +101,7 @@ def test__fake_neo__nocascade(self): class TestEpoch(unittest.TestCase): def test_Epoch_creation(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -110,8 +111,8 @@ def test_Epoch_creation(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - assert_arrays_equal(epc.times, [1.1, 1.5, 1.7]*pq.ms) - assert_arrays_equal(epc.durations, [20, 40, 60]*pq.ns) + assert_arrays_equal(epc.times, [1.1, 1.5, 1.7]*un.ms) + assert_arrays_equal(epc.durations, [20, 40, 60]*un.ns) assert_arrays_equal(epc.labels, np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S')) @@ -125,7 +126,7 @@ def test_Epoch_creation(self): def test_Epoch_repr(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -149,24 +150,24 @@ def test_Epoch_merge(self): paramstarg = {'test2': 'yes;no', 'test3': True, 'test4': False} - epc1 = Epoch([1.1, 1.5, 1.7]*pq.ms, - durations=[20, 40, 60]*pq.us, + epc1 = Epoch([1.1, 1.5, 1.7]*un.ms, + durations=[20, 40, 60]*un.us, labels=np.array(['test epoch 1 1', 'test epoch 1 2', 'test epoch 1 3'], dtype='S'), name='test', description='tester 1', file_origin='test.file', test1=1, **params1) - epc2 = Epoch([2.1, 2.5, 2.7]*pq.us, - durations=[3, 5, 7]*pq.ms, + epc2 = Epoch([2.1, 2.5, 2.7]*un.us, + durations=[3, 5, 7]*un.ms, labels=np.array(['test epoch 2 1', 'test epoch 2 2', 'test epoch 2 3'], dtype='S'), name='test', description='tester 2', file_origin='test.file', test1=1, **params2) - epctarg = Epoch([1.1, 1.5, 1.7, .0021, .0025, .0027]*pq.ms, - durations=[20, 40, 60, 3000, 5000, 7000]*pq.ns, + epctarg = Epoch([1.1, 1.5, 1.7, .0021, .0025, .0027]*un.ms, + durations=[20, 40, 60, 3000, 5000, 7000]*un.ns, labels=np.array(['test epoch 1 1', 'test epoch 1 2', 'test epoch 1 3', @@ -187,7 +188,7 @@ def test_Epoch_merge(self): def test__children(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -217,7 +218,7 @@ def test__children(self): @unittest.skipUnless(HAVE_IPYTHON, "requires IPython") def test__pretty(self): - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -233,19 +234,19 @@ def test__pretty(self): self.assertEqual(prepr, targ) def test__time_slice(self): - epc = Epoch(times=[10, 20, 30] * pq.s, durations=[10, 5, 7] * pq.ms, + epc = Epoch(times=[10, 20, 30] * un.s, durations=[10, 5, 7] * un.ms, labels=np.array(['btn0', 'btn1', 'btn2'], dtype='S'), foo='bar') - epc2 = epc.time_slice(10 * pq.s, 20 * pq.s) - assert_arrays_equal(epc2.times, [10, 20] * pq.s) - assert_arrays_equal(epc2.durations, [10, 5] * pq.ms) + epc2 = epc.time_slice(10 * un.s, 20 * un.s) + assert_arrays_equal(epc2.times, [10, 20] * un.s) + assert_arrays_equal(epc2.durations, [10, 5] * un.ms) assert_arrays_equal(epc2.labels, np.array(['btn0','btn1'], dtype='S')) self.assertEqual(epc.annotations, epc2.annotations) def test_time_slice2(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -255,7 +256,7 @@ def test_time_slice2(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([1.5]*pq.ms, durations=[40]*pq.ns, + targ = Epoch([1.5]*un.ms, durations=[40]*un.ns, labels=np.array(['test epoch 2'], dtype='S'), name='test', description='tester', file_origin='test.file', @@ -279,7 +280,7 @@ def test_time_slice2(self): def test_time_slice_out_of_boundries(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -289,7 +290,7 @@ def test_time_slice_out_of_boundries(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + targ = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -316,7 +317,7 @@ def test_time_slice_out_of_boundries(self): def test_time_slice_empty(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([]*pq.ms, durations=[]*pq.ns, + epc = Epoch([]*un.ms, durations=[]*un.ns, labels=np.array([], dtype='S'), name='test', description='tester', file_origin='test.file', @@ -324,7 +325,7 @@ def test_time_slice_empty(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([]*pq.ms, durations=[]*pq.ns, + targ = Epoch([]*un.ms, durations=[]*un.ns, labels=np.array([], dtype='S'), name='test', description='tester', file_origin='test.file', @@ -348,7 +349,7 @@ def test_time_slice_empty(self): def test_time_slice_none_stop(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -358,7 +359,7 @@ def test_time_slice_none_stop(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([1.5, 1.7]*pq.ms, durations=[40, 60]*pq.ns, + targ = Epoch([1.5, 1.7]*un.ms, durations=[40, 60]*un.ns, labels=np.array(['test epoch 2', 'test epoch 3'], dtype='S'), name='test', description='tester', @@ -383,7 +384,7 @@ def test_time_slice_none_stop(self): def test_time_slice_none_start(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -393,7 +394,7 @@ def test_time_slice_none_start(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([1.1, 1.5]*pq.ms, durations=[20, 40]*pq.ns, + targ = Epoch([1.1, 1.5]*un.ms, durations=[20, 40]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2'], dtype='S'), name='test', description='tester', file_origin='test.file', @@ -417,7 +418,7 @@ def test_time_slice_none_start(self): def test_time_slice_none_both(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -427,7 +428,7 @@ def test_time_slice_none_both(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + targ = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -453,7 +454,7 @@ def test_time_slice_none_both(self): def test_time_slice_differnt_units(self): params = {'test2': 'y1', 'test3': True} - epc = Epoch([1.1, 1.5, 1.7]*pq.ms, durations=[20, 40, 60]*pq.ns, + epc = Epoch([1.1, 1.5, 1.7]*un.ms, durations=[20, 40, 60]*un.ns, labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'), @@ -463,7 +464,7 @@ def test_time_slice_differnt_units(self): epc.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(epc) - targ = Epoch([1.5]*pq.ms, durations=[40]*pq.ns, + targ = Epoch([1.5]*un.ms, durations=[40]*un.ns, labels=np.array(['test epoch 2'], dtype='S'), name='test', description='tester', file_origin='test.file', @@ -471,8 +472,8 @@ def test_time_slice_differnt_units(self): targ.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(targ) - t_start = 0.0012 * pq.s - t_stop = 0.0016 * pq.s + t_start = 0.0012 * un.s + t_stop = 0.0016 * un.s result = epc.time_slice(t_start, t_stop) assert_arrays_equal(result.times, targ.times) @@ -492,13 +493,13 @@ class TestDuplicateWithNewData(unittest.TestCase): def setUp(self): self.data = np.array([0.1, 0.5, 1.2, 3.3, 6.4, 7]) self.durations = np.array([0.2, 0.4, 1.1, 2.4, 0.2, 2.0]) - self.quant = pq.ms + self.quant = un.ms self.epoch = Epoch(self.data*self.quant, durations=self.durations*self.quant) def test_duplicate_with_new_data(self): signal1 = self.epoch - new_data = np.sort(np.random.uniform(0, 100, (self.epoch))) * pq.ms + new_data = np.sort(np.random.uniform(0, 100, (self.epoch))) * un.ms signal1b = signal1.duplicate_with_new_data(new_data) assert_arrays_almost_equal(np.asarray(signal1b), np.asarray(new_data), 1e-12) @@ -509,7 +510,7 @@ class TestEventFunctions(unittest.TestCase): def test__pickle(self): - epoch1 = Epoch(np.arange(0, 30, 10)*pq.s, labels=np.array(['t0', 't1', 't2'], dtype='S'), + epoch1 = Epoch(np.arange(0, 30, 10)*un.s, labels=np.array(['t0', 't1', 't2'], dtype='S'), units='s') fobj = open('./pickle', 'wb') pickle.dump(epoch1, fobj) diff --git a/neo/test/coretest/test_event.py b/neo/test/coretest/test_event.py index a491a6fb2..d9ab78f74 100644 --- a/neo/test/coretest/test_event.py +++ b/neo/test/coretest/test_event.py @@ -9,11 +9,13 @@ import unittest import numpy as np -import quantities as pq + +from neo import units as un import pickle import os from numpy.testing import assert_array_equal + try: from IPython.lib.pretty import pretty except ImportError as err: @@ -39,7 +41,7 @@ def setUp(self): def test__get_fake_values(self): self.annotations['seed'] = 0 - times = get_fake_value('times', pq.Quantity, seed=0, dim=1) + times = get_fake_value('times', un.Quantity, seed=0, dim=1) labels = get_fake_value('labels', np.ndarray, seed=1, dim=1, dtype='S') name = get_fake_value('name', str, seed=2, obj=Event) description = get_fake_value('description', str, @@ -95,7 +97,7 @@ def test__fake_neo__nocascade(self): class TestEvent(unittest.TestCase): def test_Event_creation(self): params = {'test2': 'y1', 'test3': True} - evt = Event([1.1, 1.5, 1.7]*pq.ms, + evt = Event([1.1, 1.5, 1.7]*un.ms, labels=np.array(['test event 1', 'test event 2', 'test event 3'], dtype='S'), @@ -105,7 +107,7 @@ def test_Event_creation(self): evt.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(evt) - assert_arrays_equal(evt.times, [1.1, 1.5, 1.7]*pq.ms) + assert_arrays_equal(evt.times, [1.1, 1.5, 1.7]*un.ms) assert_arrays_equal(evt.labels, np.array(['test event 1', 'test event 2', 'test event 3'], dtype='S')) @@ -119,14 +121,14 @@ def test_Event_creation(self): def tests_time_slice (self): params = {'test2': 'y1', 'test3': True} - evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*pq.ms, + evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) evt.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(evt) - targ = Event([ 2.2, 2.9, 3.0 ]*pq.ms) + targ = Event([ 2.2, 2.9, 3.0 ]*un.ms) result = evt.time_slice(t_start=2.0, t_stop=3.0 ) assert_arrays_equal(targ, result) @@ -139,7 +141,7 @@ def tests_time_slice (self): def test_time_slice_out_of_boundries(self): params = {'test2': 'y1', 'test3': True} - evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*pq.ms, + evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) @@ -159,7 +161,7 @@ def test_time_slice_out_of_boundries(self): def test_time_slice_empty(self): params = {'test2': 'y1', 'test3': True} - evt = Event([]*pq.ms, + evt = Event([]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) @@ -177,12 +179,12 @@ def test_time_slice_empty(self): def test_time_slice_none_stop(self): params = {'test2': 'y1', 'test3': True} - evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*pq.ms, + evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) evt.annotate(test1=1.1, test0=[1, 2]) - targ = Event([ 2.2, 2.9, 3.0, 3.1, 3.3 ]*pq.ms) + targ = Event([ 2.2, 2.9, 3.0, 3.1, 3.3 ]*un.ms) assert_neo_object_is_compliant(evt) t_start = 2.0 @@ -199,14 +201,14 @@ def test_time_slice_none_stop(self): def test_time_slice_none_start(self): params = {'test2': 'y1', 'test3': True} - evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*pq.ms, + evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) evt.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(evt) - targ = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0]*pq.ms) + targ = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0]*un.ms) t_start = None t_stop = 3.0 result = evt.time_slice(t_start, t_stop) @@ -221,7 +223,7 @@ def test_time_slice_none_start(self): def test_time_slice_none_both(self): params = {'test2': 'y1', 'test3': True} - evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*pq.ms, + evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.0, 3.1, 3.3]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) @@ -242,22 +244,22 @@ def test_time_slice_none_both(self): def test_time_slice_differnt_units(self): params = {'test2': 'y1', 'test3': True} - evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.1, 3.3]*pq.ms, + evt = Event([0.1, 0.5, 1.1, 1.5, 1.7, 2.2, 2.9, 3.1, 3.3]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) assert_neo_object_is_compliant(evt) evt.annotate(test1=1.1, test0=[1, 2]) - targ = Event([ 2.2, 2.9 ]*pq.ms, + targ = Event([ 2.2, 2.9 ]*un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) assert_neo_object_is_compliant(targ) targ.annotate(test1=1.1, test0=[1, 2]) - t_start = 0.002 * pq.s - t_stop = 0.003 * pq.s + t_start = 0.002 * un.s + t_stop = 0.003 * un.s result = evt.time_slice(t_start, t_stop) @@ -271,7 +273,7 @@ def test_time_slice_differnt_units(self): def test_Event_repr(self): params = {'test2': 'y1', 'test3': True} - evt = Event([1.1, 1.5, 1.7]*pq.ms, + evt = Event([1.1, 1.5, 1.7]*un.ms, labels=np.array(['test event 1', 'test event 2', 'test event 3'], dtype='S'), @@ -294,21 +296,21 @@ def test_Event_merge(self): paramstarg = {'test2': 'yes;no', 'test3': True, 'test4': False} - evt1 = Event([1.1, 1.5, 1.7]*pq.ms, + evt1 = Event([1.1, 1.5, 1.7]*un.ms, labels=np.array(['test event 1 1', 'test event 1 2', 'test event 1 3'], dtype='S'), name='test', description='tester 1', file_origin='test.file', test1=1, **params1) - evt2 = Event([2.1, 2.5, 2.7]*pq.us, + evt2 = Event([2.1, 2.5, 2.7]*un.us, labels=np.array(['test event 2 1', 'test event 2 2', 'test event 2 3'], dtype='S'), name='test', description='tester 2', file_origin='test.file', test1=1, **params2) - evttarg = Event([1.1, 1.5, 1.7, .0021, .0025, .0027]*pq.ms, + evttarg = Event([1.1, 1.5, 1.7, .0021, .0025, .0027]*un.ms, labels=np.array(['test event 1 1', 'test event 1 2', 'test event 1 3', @@ -329,7 +331,7 @@ def test_Event_merge(self): def test__children(self): params = {'test2': 'y1', 'test3': True} - evt = Event([1.1, 1.5, 1.7]*pq.ms, + evt = Event([1.1, 1.5, 1.7]*un.ms, labels=np.array(['test event 1', 'test event 2', 'test event 3'], dtype='S'), @@ -359,7 +361,7 @@ def test__children(self): @unittest.skipUnless(HAVE_IPYTHON, "requires IPython") def test__pretty(self): - evt = Event([1.1, 1.5, 1.7]*pq.ms, + evt = Event([1.1, 1.5, 1.7]*un.ms, labels=np.array(['test event 1', 'test event 2', 'test event 3'], dtype='S'), @@ -375,28 +377,28 @@ def test__pretty(self): self.assertEqual(prepr, targ) def test__time_slice(self): - data = [2, 3, 4, 5] * pq.ms + data = [2, 3, 4, 5] * un.ms evt = Event(data, foo='bar') - evt1 = evt.time_slice(2.2 * pq.ms, 4.2 * pq.ms) - assert_arrays_equal(evt1.times, [3, 4] * pq.ms) + evt1 = evt.time_slice(2.2 * un.ms, 4.2 * un.ms) + assert_arrays_equal(evt1.times, [3, 4] * un.ms) self.assertEqual(evt.annotations, evt1.annotations) - evt2 = evt.time_slice(None, 4.2 * pq.ms) - assert_arrays_equal(evt2.times, [2, 3, 4] * pq.ms) + evt2 = evt.time_slice(None, 4.2 * un.ms) + assert_arrays_equal(evt2.times, [2, 3, 4] * un.ms) - evt3 = evt.time_slice(2.2 * pq.ms, None) - assert_arrays_equal(evt3.times, [3, 4, 5] * pq.ms) + evt3 = evt.time_slice(2.2 * un.ms, None) + assert_arrays_equal(evt3.times, [3, 4, 5] * un.ms) class TestDuplicateWithNewData(unittest.TestCase): def setUp(self): self.data = np.array([0.1, 0.5, 1.2, 3.3, 6.4, 7]) - self.dataquant = self.data*pq.ms + self.dataquant = self.data*un.ms self.event = Event(self.dataquant) def test_duplicate_with_new_data(self): signal1 = self.event - new_data = np.sort(np.random.uniform(0, 100, (self.event))) * pq.ms + new_data = np.sort(np.random.uniform(0, 100, (self.event))) * un.ms signal1b = signal1.duplicate_with_new_data(new_data) assert_arrays_almost_equal(np.asarray(signal1b), np.asarray(new_data), 1e-12) @@ -404,7 +406,7 @@ class TestEventFunctions(unittest.TestCase): def test__pickle(self): - event1 = Event(np.arange(0, 30, 10)*pq.s, labels=np.array(['t0', 't1', 't2'], dtype='S'), + event1 = Event(np.arange(0, 30, 10)*un.s, labels=np.array(['t0', 't1', 't2'], dtype='S'), units='s') fobj = open('./pickle', 'wb') pickle.dump(event1, fobj) diff --git a/neo/test/coretest/test_generate_datasets.py b/neo/test/coretest/test_generate_datasets.py index 4ee1815eb..cce0bb804 100644 --- a/neo/test/coretest/test_generate_datasets.py +++ b/neo/test/coretest/test_generate_datasets.py @@ -14,7 +14,7 @@ from datetime import datetime import numpy as np -import quantities as pq +from neo import units as un from neo.core import (class_by_name, Block, Segment, ChannelIndex, Unit, @@ -334,12 +334,12 @@ def setUp(self): def test__t_start(self): name = 't_start' - datatype = pq.Quantity - targ = 0.0 * pq.millisecond + datatype = un.Quantity + targ = 0.0 * un.millisecond res = get_fake_value(name, datatype) - self.assertTrue(isinstance(res, pq.Quantity)) - self.assertEqual(res.units, pq.millisecond) + self.assertTrue(isinstance(res, un.Quantity)) + self.assertEqual(res.units, un.millisecond) assert_arrays_equal(targ, res) self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1) @@ -347,12 +347,12 @@ def test__t_start(self): def test__t_stop(self): name = 't_stop' - datatype = pq.Quantity - targ = 1.0 * pq.millisecond + datatype = un.Quantity + targ = 1.0 * un.millisecond res = get_fake_value(name, datatype) - self.assertTrue(isinstance(res, pq.Quantity)) - self.assertEqual(res.units, pq.millisecond) + self.assertTrue(isinstance(res, un.Quantity)) + self.assertEqual(res.units, un.millisecond) assert_arrays_equal(targ, res) self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1) @@ -360,12 +360,12 @@ def test__t_stop(self): def test__sampling_rate(self): name = 'sampling_rate' - datatype = pq.Quantity - targ = 10000.0 * pq.Hz + datatype = un.Quantity + targ = 10000.0 * un.Hz res = get_fake_value(name, datatype) - self.assertTrue(isinstance(res, pq.Quantity)) - self.assertEqual(res.units, pq.Hz) + self.assertTrue(isinstance(res, un.Quantity)) + self.assertEqual(res.units, un.Hz) assert_arrays_equal(targ, res) self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1) @@ -447,30 +447,30 @@ def test__datetime(self): def test__quantity(self): name = 'test__quantity' - datatype = pq.Quantity + datatype = un.Quantity dim = 2 size = [] units = np.random.choice(['nA', 'mA', 'A', 'mV', 'V']) for i in range(int(dim)): size.append(np.random.randint(5) + 1) - targ = pq.Quantity(np.random.random(size)*1000, units=units) + targ = un.Quantity(np.random.random(size)*1000, units=units) res = get_fake_value(name, datatype, dim=dim, seed=0) - self.assertTrue(isinstance(res, pq.Quantity)) - self.assertEqual(res.units, getattr(pq, units)) + self.assertTrue(isinstance(res, un.Quantity)) + self.assertEqual(res.units, getattr(un, units)) assert_arrays_equal(targ, res) def test__quantity_force_units(self): name = 'test__quantity' datatype = np.ndarray dim = 2 - units = pq.ohm + units = un.ohm size = [] for i in range(int(dim)): size.append(np.random.randint(5) + 1) - targ = pq.Quantity(np.random.random(size)*1000, units=units) + targ = un.Quantity(np.random.random(size)*1000, units=units) res = get_fake_value(name, datatype, dim=dim, seed=0, units=units) self.assertTrue(isinstance(res, np.ndarray)) diff --git a/neo/test/coretest/test_irregularysampledsignal.py b/neo/test/coretest/test_irregularysampledsignal.py index 055810cde..d4cf0bdf6 100644 --- a/neo/test/coretest/test_irregularysampledsignal.py +++ b/neo/test/coretest/test_irregularysampledsignal.py @@ -11,7 +11,7 @@ import os import pickle import numpy as np -import quantities as pq +from neo import units as un from numpy.testing import assert_array_equal try: @@ -38,8 +38,8 @@ def setUp(self): def test__get_fake_values(self): self.annotations['seed'] = 0 - times = get_fake_value('times', pq.Quantity, seed=0, dim=1) - signal = get_fake_value('signal', pq.Quantity, seed=1, dim=2) + times = get_fake_value('times', un.Quantity, seed=0, dim=1) + signal = get_fake_value('signal', un.Quantity, seed=1, dim=2) name = get_fake_value('name', str, seed=2, obj=IrregularlySampledSignal) description = get_fake_value('description', str, seed=3, @@ -99,17 +99,17 @@ def test__fake_neo__nocascade(self): class TestIrregularlySampledSignalConstruction(unittest.TestCase): def test_IrregularlySampledSignal_creation_times_units_signal_units(self): params = {'test2': 'y1', 'test3': True} - sig = IrregularlySampledSignal([1.1, 1.5, 1.7]*pq.ms, - signal=[20., 40., 60.]*pq.mV, + sig = IrregularlySampledSignal([1.1, 1.5, 1.7]*un.ms, + signal=[20., 40., 60.]*un.mV, name='test', description='tester', file_origin='test.file', test1=1, **params) sig.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(sig) - assert_array_equal(sig.times, [1.1, 1.5, 1.7]*pq.ms) + assert_array_equal(sig.times, [1.1, 1.5, 1.7]*un.ms) assert_array_equal(np.asarray(sig).flatten(), np.array([20., 40., 60.])) - self.assertEqual(sig.units, pq.mV) + self.assertEqual(sig.units, un.mV) self.assertEqual(sig.name, 'test') self.assertEqual(sig.description, 'tester') self.assertEqual(sig.file_origin, 'test.file') @@ -122,16 +122,16 @@ def test_IrregularlySampledSignal_creation_units_arg(self): params = {'test2': 'y1', 'test3': True} sig = IrregularlySampledSignal([1.1, 1.5, 1.7], signal=[20., 40., 60.], - units=pq.V, time_units=pq.s, + units=un.V, time_units=un.s, name='test', description='tester', file_origin='test.file', test1=1, **params) sig.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(sig) - assert_array_equal(sig.times, [1.1, 1.5, 1.7]*pq.s) + assert_array_equal(sig.times, [1.1, 1.5, 1.7]*un.s) assert_array_equal(np.asarray(sig).flatten(), np.array([20., 40., 60.])) - self.assertEqual(sig.units, pq.V) + self.assertEqual(sig.units, un.V) self.assertEqual(sig.name, 'test') self.assertEqual(sig.description, 'tester') self.assertEqual(sig.file_origin, 'test.file') @@ -142,18 +142,18 @@ def test_IrregularlySampledSignal_creation_units_arg(self): def test_IrregularlySampledSignal_creation_units_rescale(self): params = {'test2': 'y1', 'test3': True} - sig = IrregularlySampledSignal([1.1, 1.5, 1.7]*pq.s, - signal=[2., 4., 6.]*pq.V, - units=pq.mV, time_units=pq.ms, + sig = IrregularlySampledSignal([1.1, 1.5, 1.7]*un.s, + signal=[2., 4., 6.]*un.V, + units=un.mV, time_units=un.ms, name='test', description='tester', file_origin='test.file', test1=1, **params) sig.annotate(test1=1.1, test0=[1, 2]) assert_neo_object_is_compliant(sig) - assert_array_equal(sig.times, [1100, 1500, 1700]*pq.ms) + assert_array_equal(sig.times, [1100, 1500, 1700]*un.ms) assert_array_equal(np.asarray(sig).flatten(), np.array([2000., 4000., 6000.])) - self.assertEqual(sig.units, pq.mV) + self.assertEqual(sig.units, un.mV) self.assertEqual(sig.name, 'test') self.assertEqual(sig.description, 'tester') self.assertEqual(sig.file_origin, 'test.file') @@ -163,29 +163,29 @@ def test_IrregularlySampledSignal_creation_units_rescale(self): self.assertTrue(sig.annotations['test3']) def test_IrregularlySampledSignal_different_lens_ValueError(self): - times = [1.1, 1.5, 1.7]*pq.ms - signal = [20., 40., 60., 70.]*pq.mV + times = [1.1, 1.5, 1.7]*un.ms + signal = [20., 40., 60., 70.]*un.mV self.assertRaises(ValueError, IrregularlySampledSignal, times, signal) def test_IrregularlySampledSignal_no_signal_units_ValueError(self): - times = [1.1, 1.5, 1.7]*pq.ms + times = [1.1, 1.5, 1.7]*un.ms signal = [20., 40., 60.] self.assertRaises(ValueError, IrregularlySampledSignal, times, signal) def test_IrregularlySampledSignal_no_time_units_ValueError(self): times = [1.1, 1.5, 1.7] - signal = [20., 40., 60.]*pq.mV + signal = [20., 40., 60.]*un.mV self.assertRaises(ValueError, IrregularlySampledSignal, times, signal) class TestIrregularlySampledSignalProperties(unittest.TestCase): def setUp(self): - self.times = [np.arange(10.0)*pq.s, - np.arange(-100.0, 100.0, 10.0)*pq.ms, - np.arange(100)*pq.ns] - self.data = [np.arange(10.0)*pq.nA, - np.arange(-100.0, 100.0, 10.0)*pq.mV, - np.random.uniform(size=100)*pq.uV] + self.times = [np.arange(10.0)*un.s, + np.arange(-100.0, 100.0, 10.0)*un.ms, + np.arange(100)*un.ns] + self.data = [np.arange(10.0)*un.nA, + np.arange(-100.0, 100.0, 10.0)*un.mV, + np.random.uniform(size=100)*un.uV] self.signals = [IrregularlySampledSignal(t, signal=D, testattr='test') for D, t in zip(self.data, self.times)] @@ -219,8 +219,8 @@ def test__sampling_intervals_getter(self): threshold=1e-15) def test_IrregularlySampledSignal_repr(self): - sig = IrregularlySampledSignal([1.1, 1.5, 1.7]*pq.s, - signal=[2., 4., 6.]*pq.V, + sig = IrregularlySampledSignal([1.1, 1.5, 1.7]*un.s, + signal=[2., 4., 6.]*un.V, name='test', description='tester', file_origin='test.file', test1=1) @@ -265,9 +265,9 @@ def test_IrregularlySampledSignal_repr(self): class TestIrregularlySampledSignalArrayMethods(unittest.TestCase): def setUp(self): self.data1 = np.arange(10.0) - self.data1quant = self.data1 * pq.mV + self.data1quant = self.data1 * un.mV self.time1 = np.logspace(1, 5, 10) - self.time1quant = self.time1*pq.ms + self.time1quant = self.time1*un.ms self.signal1 = IrregularlySampledSignal(self.time1quant, signal=self.data1quant, name='spam', @@ -304,26 +304,26 @@ def test__slice_should_return_IrregularlySampledSignal(self): self.assertEqual(result.annotations, self.signal1.annotations) def test__getitem_should_return_single_quantity(self): - self.assertEqual(self.signal1[0], 0*pq.mV) - self.assertEqual(self.signal1[9], 9*pq.mV) + self.assertEqual(self.signal1[0], 0*un.mV) + self.assertEqual(self.signal1[9], 9*un.mV) self.assertRaises(IndexError, self.signal1.__getitem__, 10) def test__getitem_out_of_bounds_IndexError(self): self.assertRaises(IndexError, self.signal1.__getitem__, 10) def test_comparison_operators(self): - assert_array_equal(self.signal1 >= 5*pq.mV, + assert_array_equal(self.signal1 >= 5*un.mV, np.array([[False, False, False, False, False, True, True, True, True, True]]).T) def test__comparison_with_inconsistent_units_should_raise_Exception(self): - self.assertRaises(ValueError, self.signal1.__gt__, 5*pq.nA) + self.assertRaises(ValueError, self.signal1.__gt__, 5*un.nA) def test_simple_statistics(self): targmean = self.signal1[:-1]*np.diff(self.time1quant).reshape(-1, 1) targmean = targmean.sum()/(self.time1quant[-1] - self.time1quant[0]) - self.assertEqual(self.signal1.max(), 9*pq.mV) - self.assertEqual(self.signal1.min(), 0*pq.mV) + self.assertEqual(self.signal1.max(), 9*un.mV) + self.assertEqual(self.signal1.min(), 0*un.mV) self.assertEqual(self.signal1.mean(), targmean) def test_mean_interpolation_NotImplementedError(self): @@ -334,7 +334,7 @@ def test_resample_NotImplementedError(self): def test__rescale_same(self): result = self.signal1.copy() - result = result.rescale(pq.mV) + result = result.rescale(un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) @@ -343,14 +343,14 @@ def test__rescale_same(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) assert_array_equal(result.magnitude, self.data1.reshape(-1, 1)) assert_array_equal(result.times, self.time1quant) assert_same_sub_schema(result, self.signal1) def test__rescale_new(self): result = self.signal1.copy() - result = result.rescale(pq.uV) + result = result.rescale(un.uV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) @@ -359,17 +359,17 @@ def test__rescale_new(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(result.units, 1*pq.uV) + self.assertEqual(result.units, 1*un.uV) assert_arrays_almost_equal(np.array(result), self.data1.reshape(-1, 1)*1000., 1e-10) assert_array_equal(result.times, self.time1quant) def test__rescale_new_incompatible_ValueError(self): - self.assertRaises(ValueError, self.signal1.rescale, pq.nA) + self.assertRaises(ValueError, self.signal1.rescale, un.nA) def test_time_slice(self): - targdataquant = [[1.0], [2.0], [3.0]] * pq.mV + targdataquant = [[1.0], [2.0], [3.0]] * un.mV targtime = np.logspace(1, 5, 10) - targtimequant = targtime [1:4] *pq.ms + targtimequant = targtime [1:4] *un.ms targ_signal = IrregularlySampledSignal(targtimequant, signal=targdataquant, name='spam', @@ -383,7 +383,7 @@ def test_time_slice(self): assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -407,7 +407,7 @@ def test_time_slice_out_of_boundries(self): assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -416,8 +416,8 @@ def test_time_slice_out_of_boundries(self): self.assertEqual(result.annotations, {'arg1': 'test'}) def test_time_slice_empty(self): - targdataquant = [] * pq.mV - targtimequant = [] *pq.ms + targdataquant = [] * un.mV + targtimequant = [] *un.ms targ_signal = IrregularlySampledSignal(targtimequant, signal=targdataquant, name='spam', @@ -431,7 +431,7 @@ def test_time_slice_empty(self): assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -440,9 +440,9 @@ def test_time_slice_empty(self): self.assertEqual(result.annotations, {'arg1': 'test'}) def test_time_slice_none_stop(self): - targdataquant = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0]] * pq.mV + targdataquant = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0]] * un.mV targtime = np.logspace(1, 5, 10) - targtimequant = targtime [1:10] *pq.ms + targtimequant = targtime [1:10] *un.ms targ_signal = IrregularlySampledSignal(targtimequant, signal=targdataquant, name='spam', @@ -456,7 +456,7 @@ def test_time_slice_none_stop(self): assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -465,9 +465,9 @@ def test_time_slice_none_stop(self): self.assertEqual(result.annotations, {'arg1': 'test'}) def test_time_slice_none_start(self): - targdataquant = [[0.0], [1.0], [2.0], [3.0]] * pq.mV + targdataquant = [[0.0], [1.0], [2.0], [3.0]] * un.mV targtime = np.logspace(1, 5, 10) - targtimequant = targtime [0:4] *pq.ms + targtimequant = targtime [0:4] *un.ms targ_signal = IrregularlySampledSignal(targtimequant, signal=targdataquant, name='spam', @@ -481,7 +481,7 @@ def test_time_slice_none_start(self): assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -490,9 +490,9 @@ def test_time_slice_none_start(self): self.assertEqual(result.annotations, {'arg1': 'test'}) def test_time_slice_none_both(self): - targdataquant = [[0.0], [1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0]] * pq.mV + targdataquant = [[0.0], [1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0]] * un.mV targtime = np.logspace(1, 5, 10) - targtimequant = targtime [0:10] *pq.ms + targtimequant = targtime [0:10] *un.ms targ_signal = IrregularlySampledSignal(targtimequant, signal=targdataquant, name='spam', @@ -506,7 +506,7 @@ def test_time_slice_none_both(self): assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -515,9 +515,9 @@ def test_time_slice_none_both(self): self.assertEqual(result.annotations, {'arg1': 'test'}) def test_time_slice_differnt_units(self): - targdataquant = [[1.0], [2.0], [3.0]] * pq.mV + targdataquant = [[1.0], [2.0], [3.0]] * un.mV targtime = np.logspace(1, 5, 10) - targtimequant = targtime [1:4] *pq.ms + targtimequant = targtime [1:4] *un.ms targ_signal = IrregularlySampledSignal(targtimequant, signal=targdataquant, name='spam', @@ -528,14 +528,14 @@ def test_time_slice_differnt_units(self): t_start = 15 t_stop = 250 - t_start = 0.015 * pq.s - t_stop = .250 * pq.s + t_start = 0.015 * un.s + t_stop = .250 * un.s result = self.signal1.time_slice(t_start, t_stop) assert_array_equal(result, targ_signal) assert_array_equal(result.times, targtimequant) - self.assertEqual(result.units, 1*pq.mV) + self.assertEqual(result.units, 1*un.mV) self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -546,9 +546,9 @@ def test_time_slice_differnt_units(self): class TestIrregularlySampledSignalCombination(unittest.TestCase): def setUp(self): self.data1 = np.arange(10.0) - self.data1quant = self.data1 * pq.mV + self.data1quant = self.data1 * un.mV self.time1 = np.logspace(1, 5, 10) - self.time1quant = self.time1*pq.ms + self.time1quant = self.time1*un.ms self.signal1 = IrregularlySampledSignal(self.time1quant, signal=self.data1quant, name='spam', @@ -564,7 +564,7 @@ def test__compliant(self): self.assertEqual(self.signal1.annotations, {'arg1': 'test'}) def test__add_const_quantity_should_preserve_data_complement(self): - result = self.signal1 + 0.065*pq.V + result = self.signal1 + 0.065*un.V self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -574,12 +574,12 @@ def test__add_const_quantity_should_preserve_data_complement(self): assert_array_equal(result.magnitude, self.data1.reshape(-1, 1) + 65) assert_array_equal(result.times, self.time1quant) - self.assertEqual(self.signal1[9], 9*pq.mV) - self.assertEqual(result[9], 74*pq.mV) + self.assertEqual(self.signal1[9], 9*un.mV) + self.assertEqual(result[9], 74*un.mV) def test__add_two_consistent_signals_should_preserve_data_complement(self): data2 = np.arange(10.0, 20.0) - data2quant = data2*pq.mV + data2quant = data2*un.mV signal2 = IrregularlySampledSignal(self.time1quant, signal=data2quant) assert_neo_object_is_compliant(signal2) @@ -617,7 +617,7 @@ def test__add_signals_with_inconsistent_dimension_ValueError(self): self.assertRaises(ValueError, self.signal1.__add__, signal2) def test__subtract_const_should_preserve_data_complement(self): - result = self.signal1 - 65*pq.mV + result = self.signal1 - 65*un.mV self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -625,13 +625,13 @@ def test__subtract_const_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9], 9*pq.mV) - self.assertEqual(result[9], -56*pq.mV) + self.assertEqual(self.signal1[9], 9*un.mV) + self.assertEqual(result[9], -56*un.mV) assert_array_equal(result.magnitude, (self.data1 - 65).reshape(-1, 1)) assert_array_equal(result.times, self.time1quant) def test__subtract_from_const_should_return_signal(self): - result = 10*pq.mV - self.signal1 + result = 10*un.mV - self.signal1 self.assertIsInstance(result, IrregularlySampledSignal) assert_neo_object_is_compliant(result) self.assertEqual(result.name, 'spam') @@ -639,8 +639,8 @@ def test__subtract_from_const_should_return_signal(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9], 9*pq.mV) - self.assertEqual(result[9], 1*pq.mV) + self.assertEqual(self.signal1[9], 9*un.mV) + self.assertEqual(result[9], 1*un.mV) assert_array_equal(result.magnitude, (10 - self.data1).reshape(-1, 1)) assert_array_equal(result.times, self.time1quant) @@ -653,8 +653,8 @@ def test__mult_signal_by_const_float_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9], 9*pq.mV) - self.assertEqual(result[9], 18*pq.mV) + self.assertEqual(self.signal1[9], 9*un.mV) + self.assertEqual(result[9], 18*un.mV) assert_array_equal(result.magnitude, self.data1.reshape(-1, 1)*2) assert_array_equal(result.times, self.time1quant) @@ -667,8 +667,8 @@ def test__mult_signal_by_const_array_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9], 9*pq.mV) - self.assertEqual(result[9], 18*pq.mV) + self.assertEqual(self.signal1[9], 9*un.mV) + self.assertEqual(result[9], 18*un.mV) assert_array_equal(result.magnitude, self.data1.reshape(-1, 1)*2) assert_array_equal(result.times, self.time1quant) @@ -681,8 +681,8 @@ def test__divide_signal_by_const_should_preserve_data_complement(self): self.assertEqual(result.file_origin, 'testfile.txt') self.assertEqual(result.annotations, {'arg1': 'test'}) - self.assertEqual(self.signal1[9], 9*pq.mV) - self.assertEqual(result[9], 18*pq.mV) + self.assertEqual(self.signal1[9], 9*un.mV) + self.assertEqual(result[9], 18*un.mV) assert_array_equal(result.magnitude, self.data1.reshape(-1, 1)/0.5) assert_array_equal(result.times, self.time1quant) @@ -700,7 +700,7 @@ def test__pretty(self): class TestAnalogSignalFunctions(unittest.TestCase): def test__pickle(self): - signal1 = IrregularlySampledSignal(np.arange(10.0)/100*pq.s, + signal1 = IrregularlySampledSignal(np.arange(10.0)/100*un.s, np.arange(10.0), units="mV") fobj = open('./pickle', 'wb') @@ -720,9 +720,9 @@ def test__pickle(self): class TestIrregularlySampledSignalEquality(unittest.TestCase): def test__signals_with_different_times_should_be_not_equal(self): - signal1 = IrregularlySampledSignal(np.arange(10.0)/100*pq.s, + signal1 = IrregularlySampledSignal(np.arange(10.0)/100*un.s, np.arange(10.0), units="mV") - signal2 = IrregularlySampledSignal(np.arange(10.0)/100*pq.ms, + signal2 = IrregularlySampledSignal(np.arange(10.0)/100*un.ms, np.arange(10.0), units="mV") self.assertNotEqual(signal1, signal2) diff --git a/neo/test/coretest/test_segment.py b/neo/test/coretest/test_segment.py index bd90bb949..838ff2bee 100644 --- a/neo/test/coretest/test_segment.py +++ b/neo/test/coretest/test_segment.py @@ -14,7 +14,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un try: from IPython.lib.pretty import pretty @@ -720,9 +720,9 @@ def test__construct_subsegment_by_unit(self): # Unit all_unit = [] for u in range(nb_unit): - un = Unit(name='Unit #%d' % u, channel_indexes=np.array([u])) - assert_neo_object_is_compliant(un) - all_unit.append(un) + uni = Unit(name='Unit #%d' % u, channel_indexes=np.array([u])) + assert_neo_object_is_compliant(uni) + all_unit.append(uni) blk = Block() blk.channel_indexes = chxs @@ -737,7 +737,7 @@ def test__construct_subsegment_by_unit(self): anasigarr = AnalogSignal(np.zeros((sig_len, len(unit_with_sig))), units='nA', - sampling_rate=1000.*pq.Hz, + sampling_rate=1000. * un.Hz, channel_indexes=unit_with_sig) seg.analogsignals.append(anasigarr) diff --git a/neo/test/coretest/test_spiketrain.py b/neo/test/coretest/test_spiketrain.py index 9f6a7da2c..548eb905d 100644 --- a/neo/test/coretest/test_spiketrain.py +++ b/neo/test/coretest/test_spiketrain.py @@ -14,7 +14,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un try: from IPython.lib.pretty import pretty @@ -41,13 +41,15 @@ def setUp(self): def test__get_fake_values(self): self.annotations['seed'] = 0 - waveforms = get_fake_value('waveforms', pq.Quantity, seed=3, dim=3) + + waveforms = get_fake_value('waveforms', un.Quantity, seed=3, dim=3) shape = waveforms.shape[0] - times = get_fake_value('times', pq.Quantity, seed=0, dim=1, shape=waveforms.shape[0]) - t_start = get_fake_value('t_start', pq.Quantity, seed=1, dim=0) - t_stop = get_fake_value('t_stop', pq.Quantity, seed=2, dim=0) - left_sweep = get_fake_value('left_sweep', pq.Quantity, seed=4, dim=0) - sampling_rate = get_fake_value('sampling_rate', pq.Quantity, + times = get_fake_value('times', un.Quantity, seed=0, dim=1, shape=waveforms.shape[0]) + t_start = get_fake_value('t_start', un.Quantity, seed=1, dim=0) + t_stop = get_fake_value('t_stop', un.Quantity, seed=2, dim=0) + left_sweep = get_fake_value('left_sweep', un.Quantity, seed=4, dim=0) + sampling_rate = get_fake_value('sampling_rate', un.Quantity, + seed=5, dim=0) name = get_fake_value('name', str, seed=6, obj=SpikeTrain) description = get_fake_value('description', str, @@ -122,10 +124,10 @@ def test__fake_neo__nocascade(self): class Testcheck_has_dimensions_time(unittest.TestCase): def test__check_has_dimensions_time(self): - a = np.arange(3) * pq.ms - b = np.arange(3) * pq.mV - c = np.arange(3) * pq.mA - d = np.arange(3) * pq.minute + a = np.arange(3) * un.ms + b = np.arange(3) * un.mV + c = np.arange(3) * un.mA + d = np.arange(3) * un.minute check_has_dimensions_time(a) self.assertRaises(ValueError, check_has_dimensions_time, b) self.assertRaises(ValueError, check_has_dimensions_time, c) @@ -136,39 +138,39 @@ def test__check_has_dimensions_time(self): class Testcheck_time_in_range(unittest.TestCase): def test__check_time_in_range_empty_array(self): value = np.array([]) - t_start = 0*pq.s - t_stop = 10*pq.s + t_start = 0*un.s + t_stop = 10*un.s _check_time_in_range(value, t_start=t_start, t_stop=t_stop) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=False) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=True) def test__check_time_in_range_exact(self): - value = np.array([0., 5., 10.])*pq.s - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([0., 5., 10.])*un.s + t_start = 0.*un.s + t_stop = 10.*un.s _check_time_in_range(value, t_start=t_start, t_stop=t_stop) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=False) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=True) def test__check_time_in_range_scale(self): - value = np.array([0., 5000., 10000.])*pq.ms - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([0., 5000., 10000.])*un.ms + t_start = 0.*un.s + t_stop = 10.*un.s _check_time_in_range(value, t_start=t_start, t_stop=t_stop) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=False) def test__check_time_in_range_inside(self): - value = np.array([0.1, 5., 9.9])*pq.s - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([0.1, 5., 9.9])*un.s + t_start = 0.*un.s + t_stop = 10.*un.s _check_time_in_range(value, t_start=t_start, t_stop=t_stop) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=False) _check_time_in_range(value, t_start=t_start, t_stop=t_stop, view=True) def test__check_time_in_range_below(self): - value = np.array([-0.1, 5., 10.])*pq.s - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([-0.1, 5., 10.])*un.s + t_start = 0.*un.s + t_stop = 10.*un.s self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _check_time_in_range, value, @@ -177,18 +179,18 @@ def test__check_time_in_range_below(self): t_start=t_start, t_stop=t_stop, view=True) def test__check_time_in_range_below_scale(self): - value = np.array([-1., 5000., 10000.])*pq.ms - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([-1., 5000., 10000.])*un.ms + t_start = 0.*un.s + t_stop = 10.*un.s self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop, view=False) def test__check_time_in_range_above(self): - value = np.array([0., 5., 10.1])*pq.s - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([0., 5., 10.1])*un.s + t_start = 0.*un.s + t_stop = 10.*un.s self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _check_time_in_range, value, @@ -197,18 +199,18 @@ def test__check_time_in_range_above(self): t_start=t_start, t_stop=t_stop, view=True) def test__check_time_in_range_above_scale(self): - value = np.array([0., 5000., 10001.])*pq.ms - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([0., 5000., 10001.])*un.ms + t_start = 0.*un.s + t_stop = 10.*un.s self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop, view=False) def test__check_time_in_range_above_below(self): - value = np.array([-0.1, 5., 10.1])*pq.s - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([-0.1, 5., 10.1])*un.s + t_start = 0.*un.s + t_stop = 10.*un.s self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _check_time_in_range, value, @@ -217,9 +219,9 @@ def test__check_time_in_range_above_below(self): t_start=t_start, t_stop=t_stop, view=True) def test__check_time_in_range_above_below_scale(self): - value = np.array([-1., 5000., 10001.])*pq.ms - t_start = 0.*pq.s - t_stop = 10.*pq.s + value = np.array([-1., 5000., 10001.])*un.ms + t_start = 0.*un.s + t_stop = 10.*un.s self.assertRaises(ValueError, _check_time_in_range, value, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _check_time_in_range, value, @@ -255,11 +257,11 @@ def result_spike_check(self, train, st_out, t_start_out, t_stop_out, def test__create_minimal(self): t_start = 0.0 t_stop = 10.0 - train1 = SpikeTrain([]*pq.s, t_stop) - train2 = _new_spiketrain(SpikeTrain, []*pq.s, t_stop) + train1 = SpikeTrain([]*un.s, t_stop) + train2 = _new_spiketrain(SpikeTrain, []*un.s, t_stop) dtype = np.float64 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start * units t_stop_out = t_stop * units st_out = [] * units @@ -276,7 +278,7 @@ def test__create_empty(self): t_stop=t_stop, units='s') dtype = np.float64 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start * units t_stop_out = t_stop * units st_out = [] * units @@ -292,7 +294,7 @@ def test__create_empty_no_t_start(self): train2 = _new_spiketrain(SpikeTrain, [], t_stop=t_stop, units='s') dtype = np.float64 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start * units t_stop_out = t_stop * units st_out = [] * units @@ -303,14 +305,14 @@ def test__create_empty_no_t_start(self): def test__create_from_list(self): times = range(10) - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units="ms") train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop, units="ms") dtype = np.float64 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start t_stop_out = t_stop st_out = times * units @@ -321,8 +323,8 @@ def test__create_from_list(self): def test__create_from_list_set_dtype(self): times = range(10) - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units="ms", dtype='f4') train2 = _new_spiketrain(SpikeTrain, times, @@ -330,10 +332,10 @@ def test__create_from_list_set_dtype(self): units="ms", dtype='f4') dtype = np.float32 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start.astype(dtype) t_stop_out = t_stop.astype(dtype) - st_out = pq.Quantity(times, units=units, dtype=dtype) + st_out = un.Quantity(times, units=units, dtype=dtype) self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) self.result_spike_check(train2, st_out, t_start_out, t_stop_out, @@ -348,7 +350,7 @@ def test__create_from_list_no_start_stop_units(self): t_start=t_start, t_stop=t_stop, units="ms") dtype = np.float64 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start * units t_stop_out = t_stop * units st_out = times * units @@ -368,10 +370,10 @@ def test__create_from_list_no_start_stop_units_set_dtype(self): units="ms", dtype='f4') dtype = np.float32 - units = 1 * pq.ms - t_start_out = pq.Quantity(t_start, units=units, dtype=dtype) - t_stop_out = pq.Quantity(t_stop, units=units, dtype=dtype) - st_out = pq.Quantity(times, units=units, dtype=dtype) + units = 1 * un.ms + t_start_out = un.Quantity(t_start, units=units, dtype=dtype) + t_stop_out = un.Quantity(t_stop, units=units, dtype=dtype) + st_out = un.Quantity(times, units=units, dtype=dtype) self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) self.result_spike_check(train2, st_out, t_start_out, t_stop_out, @@ -379,14 +381,14 @@ def test__create_from_list_no_start_stop_units_set_dtype(self): def test__create_from_array(self): times = np.arange(10) - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units="s") train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop, units="s") dtype = np.int - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start t_stop_out = t_stop st_out = times * units @@ -397,14 +399,14 @@ def test__create_from_array(self): def test__create_from_array_with_dtype(self): times = np.arange(10, dtype='f4') - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units="s") train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop, units="s") dtype = times.dtype - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start t_stop_out = t_stop st_out = times * units @@ -415,8 +417,8 @@ def test__create_from_array_with_dtype(self): def test__create_from_array_set_dtype(self): times = np.arange(10) - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units="s", dtype='f4') train2 = _new_spiketrain(SpikeTrain, times, @@ -424,7 +426,7 @@ def test__create_from_array_set_dtype(self): units="s", dtype='f4') dtype = np.float32 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start.astype(dtype) t_stop_out = t_stop.astype(dtype) st_out = times.astype(dtype) * units @@ -442,7 +444,7 @@ def test__create_from_array_no_start_stop_units(self): t_start=t_start, t_stop=t_stop, units="s") dtype = np.int - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start * units t_stop_out = t_stop * units st_out = times * units @@ -460,7 +462,7 @@ def test__create_from_array_no_start_stop_units_with_dtype(self): t_start=t_start, t_stop=t_stop, units="s") dtype = np.float32 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start * units t_stop_out = t_stop * units st_out = times * units @@ -480,9 +482,9 @@ def test__create_from_array_no_start_stop_units_set_dtype(self): units="s", dtype='f4') dtype = np.float32 - units = 1 * pq.s - t_start_out = pq.Quantity(t_start, units=units, dtype=dtype) - t_stop_out = pq.Quantity(t_stop, units=units, dtype=dtype) + units = 1 * un.s + t_start_out = un.Quantity(t_start, units=units, dtype=dtype) + t_stop_out = un.Quantity(t_stop, units=units, dtype=dtype) st_out = times.astype(dtype) * units self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) @@ -490,15 +492,15 @@ def test__create_from_array_no_start_stop_units_set_dtype(self): dtype, units) def test__create_from_quantity_array(self): - times = np.arange(10) * pq.ms - t_start = 0.0*pq.s - t_stop = 12.0*pq.ms + times = np.arange(10) * un.ms + t_start = 0.0*un.s + t_stop = 12.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop) train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop) dtype = np.float64 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start t_stop_out = t_stop st_out = times @@ -508,15 +510,15 @@ def test__create_from_quantity_array(self): dtype, units) def test__create_from_quantity_array_with_dtype(self): - times = np.arange(10, dtype='f4') * pq.ms - t_start = 0.0*pq.s - t_stop = 12.0*pq.ms + times = np.arange(10, dtype='f4') * un.ms + t_start = 0.0*un.s + t_stop = 12.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop) train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop) dtype = np.float32 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start.astype(dtype) t_stop_out = t_stop.astype(dtype) st_out = times.astype(dtype) @@ -526,9 +528,9 @@ def test__create_from_quantity_array_with_dtype(self): dtype, units) def test__create_from_quantity_array_set_dtype(self): - times = np.arange(10) * pq.ms - t_start = 0.0*pq.s - t_stop = 12.0*pq.ms + times = np.arange(10) * un.ms + t_start = 0.0*un.s + t_stop = 12.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, dtype='f4') train2 = _new_spiketrain(SpikeTrain, times, @@ -536,7 +538,7 @@ def test__create_from_quantity_array_set_dtype(self): dtype='f4') dtype = np.float32 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start.astype(dtype) t_stop_out = t_stop.astype(dtype) st_out = times.astype(dtype) @@ -546,7 +548,7 @@ def test__create_from_quantity_array_set_dtype(self): dtype, units) def test__create_from_quantity_array_no_start_stop_units(self): - times = np.arange(10) * pq.ms + times = np.arange(10) * un.ms t_start = 0.0 t_stop = 12.0 train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop) @@ -554,7 +556,7 @@ def test__create_from_quantity_array_no_start_stop_units(self): t_start=t_start, t_stop=t_stop) dtype = np.float64 - units = 1 * pq.ms + units = 1 * un.ms t_start_out = t_start * units t_stop_out = t_stop * units st_out = times @@ -564,7 +566,7 @@ def test__create_from_quantity_array_no_start_stop_units(self): dtype, units) def test__create_from_quantity_array_no_start_stop_units_with_dtype(self): - times = np.arange(10, dtype='f4') * pq.ms + times = np.arange(10, dtype='f4') * un.ms t_start = 0.0 t_stop = 12.0 train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop) @@ -572,9 +574,9 @@ def test__create_from_quantity_array_no_start_stop_units_with_dtype(self): t_start=t_start, t_stop=t_stop) dtype = np.float32 - units = 1 * pq.ms - t_start_out = pq.Quantity(t_start, units=units, dtype=dtype) - t_stop_out = pq.Quantity(t_stop, units=units, dtype=dtype) + units = 1 * un.ms + t_start_out = un.Quantity(t_start, units=units, dtype=dtype) + t_stop_out = un.Quantity(t_stop, units=units, dtype=dtype) st_out = times.astype(dtype) self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) @@ -582,7 +584,7 @@ def test__create_from_quantity_array_no_start_stop_units_with_dtype(self): dtype, units) def test__create_from_quantity_array_no_start_stop_units_set_dtype(self): - times = np.arange(10) * pq.ms + times = np.arange(10) * un.ms t_start = 0.0 t_stop = 12.0 train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, @@ -592,9 +594,9 @@ def test__create_from_quantity_array_no_start_stop_units_set_dtype(self): dtype='f4') dtype = np.float32 - units = 1 * pq.ms - t_start_out = pq.Quantity(t_start, units=units, dtype=dtype) - t_stop_out = pq.Quantity(t_stop, units=units, dtype=dtype) + units = 1 * un.ms + t_start_out = un.Quantity(t_start, units=units, dtype=dtype) + t_stop_out = un.Quantity(t_stop, units=units, dtype=dtype) st_out = times.astype(dtype) self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) @@ -602,15 +604,15 @@ def test__create_from_quantity_array_no_start_stop_units_set_dtype(self): dtype, units) def test__create_from_quantity_array_units(self): - times = np.arange(10) * pq.ms - t_start = 0.0*pq.s - t_stop = 12.0*pq.ms + times = np.arange(10) * un.ms + t_start = 0.0*un.s + t_stop = 12.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units='s') train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop, units='s') dtype = np.float64 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start t_stop_out = t_stop st_out = times @@ -620,16 +622,16 @@ def test__create_from_quantity_array_units(self): dtype, units) def test__create_from_quantity_array_units_with_dtype(self): - times = np.arange(10, dtype='f4') * pq.ms - t_start = 0.0*pq.s - t_stop = 12.0*pq.ms + times = np.arange(10, dtype='f4') * un.ms + t_start = 0.0*un.s + t_stop = 12.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units='s') train2 = _new_spiketrain(SpikeTrain, times, t_start=t_start, t_stop=t_stop, units='s') dtype = np.float32 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start.astype(dtype) t_stop_out = t_stop.rescale(units).astype(dtype) st_out = times.rescale(units).astype(dtype) @@ -639,9 +641,9 @@ def test__create_from_quantity_array_units_with_dtype(self): dtype, units) def test__create_from_quantity_array_units_set_dtype(self): - times = np.arange(10) * pq.ms - t_start = 0.0*pq.s - t_stop = 12.0*pq.ms + times = np.arange(10) * un.ms + t_start = 0.0*un.s + t_stop = 12.0*un.ms train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units='s', dtype='f4') train2 = _new_spiketrain(SpikeTrain, times, @@ -649,7 +651,7 @@ def test__create_from_quantity_array_units_set_dtype(self): units='s', dtype='f4') dtype = np.float32 - units = 1 * pq.s + units = 1 * un.s t_start_out = t_start.astype(dtype) t_stop_out = t_stop.rescale(units).astype(dtype) st_out = times.rescale(units).astype(dtype) @@ -659,7 +661,7 @@ def test__create_from_quantity_array_units_set_dtype(self): dtype, units) def test__create_from_quantity_array_units_no_start_stop_units(self): - times = np.arange(10) * pq.ms + times = np.arange(10) * un.ms t_start = 0.0 t_stop = 12.0 train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, units='s') @@ -667,9 +669,9 @@ def test__create_from_quantity_array_units_no_start_stop_units(self): t_start=t_start, t_stop=t_stop, units='s') dtype = np.float64 - units = 1 * pq.s - t_start_out = pq.Quantity(t_start, units=units, dtype=dtype) - t_stop_out = pq.Quantity(t_stop, units=units, dtype=dtype) + units = 1 * un.s + t_start_out = un.Quantity(t_start, units=units, dtype=dtype) + t_stop_out = un.Quantity(t_stop, units=units, dtype=dtype) st_out = times self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) @@ -677,7 +679,7 @@ def test__create_from_quantity_array_units_no_start_stop_units(self): dtype, units) def test__create_from_quantity_units_no_start_stop_units_set_dtype(self): - times = np.arange(10) * pq.ms + times = np.arange(10) * un.ms t_start = 0.0 t_stop = 12.0 train1 = SpikeTrain(times, t_start=t_start, t_stop=t_stop, @@ -687,9 +689,9 @@ def test__create_from_quantity_units_no_start_stop_units_set_dtype(self): units='s', dtype='f4') dtype = np.float32 - units = 1 * pq.s - t_start_out = pq.Quantity(t_start, units=units, dtype=dtype) - t_stop_out = pq.Quantity(t_stop, units=units, dtype=dtype) + units = 1 * un.s + t_start_out = un.Quantity(t_start, units=units, dtype=dtype) + t_stop_out = un.Quantity(t_stop, units=units, dtype=dtype) st_out = times.rescale(units).astype(dtype) self.result_spike_check(train1, st_out, t_start_out, t_stop_out, dtype, units) @@ -698,8 +700,8 @@ def test__create_from_quantity_units_no_start_stop_units_set_dtype(self): def test__create_from_list_without_units_should_raise_ValueError(self): times = range(10) - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms self.assertRaises(ValueError, SpikeTrain, times, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _new_spiketrain, SpikeTrain, times, @@ -707,17 +709,17 @@ def test__create_from_list_without_units_should_raise_ValueError(self): def test__create_from_array_without_units_should_raise_ValueError(self): times = np.arange(10) - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + t_start = 0.0*un.s + t_stop = 10000.0*un.ms self.assertRaises(ValueError, SpikeTrain, times, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _new_spiketrain, SpikeTrain, times, t_start=t_start, t_stop=t_stop) def test__create_from_array_with_incompatible_units_ValueError(self): - times = np.arange(10) * pq.km - t_start = 0.0*pq.s - t_stop = 10000.0*pq.ms + times = np.arange(10) * un.km + t_start = 0.0*un.s + t_stop = 10000.0*un.ms self.assertRaises(ValueError, SpikeTrain, times, t_start=t_start, t_stop=t_stop) self.assertRaises(ValueError, _new_spiketrain, SpikeTrain, times, @@ -760,8 +762,8 @@ def test_defaults(self): assert_neo_object_is_compliant(train2) self.assertEqual(train1.dtype, np.float) self.assertEqual(train2.dtype, np.float) - self.assertEqual(train1.sampling_rate, 1.0 * pq.Hz) - self.assertEqual(train2.sampling_rate, 1.0 * pq.Hz) + self.assertEqual(train1.sampling_rate, 1.0 * un.Hz) + self.assertEqual(train2.sampling_rate, 1.0 * un.Hz) self.assertEqual(train1.waveforms, None) self.assertEqual(train2.waveforms, None) self.assertEqual(train1.left_sweep, None) @@ -769,71 +771,71 @@ def test_defaults(self): def test_default_tstart(self): # t start defaults to zero - train11 = SpikeTrain([3, 4, 5]*pq.s, t_stop=8000*pq.ms) - train21 = _new_spiketrain(SpikeTrain, [3, 4, 5]*pq.s, - t_stop=8000*pq.ms) + train11 = SpikeTrain([3, 4, 5]*un.s, t_stop=8000*un.ms) + train21 = _new_spiketrain(SpikeTrain, [3, 4, 5]*un.s, + t_stop=8000*un.ms) assert_neo_object_is_compliant(train11) assert_neo_object_is_compliant(train21) - self.assertEqual(train11.t_start, 0.*pq.s) - self.assertEqual(train21.t_start, 0.*pq.s) + self.assertEqual(train11.t_start, 0.*un.s) + self.assertEqual(train21.t_start, 0.*un.s) # unless otherwise specified - train12 = SpikeTrain([3, 4, 5]*pq.s, t_start=2.0, t_stop=8) - train22 = _new_spiketrain(SpikeTrain, [3, 4, 5]*pq.s, + train12 = SpikeTrain([3, 4, 5]*un.s, t_start=2.0, t_stop=8) + train22 = _new_spiketrain(SpikeTrain, [3, 4, 5]*un.s, t_start=2.0, t_stop=8) assert_neo_object_is_compliant(train12) assert_neo_object_is_compliant(train22) - self.assertEqual(train12.t_start, 2.*pq.s) - self.assertEqual(train22.t_start, 2.*pq.s) + self.assertEqual(train12.t_start, 2.*un.s) + self.assertEqual(train22.t_start, 2.*un.s) def test_tstop_units_conversion(self): - train11 = SpikeTrain([3, 5, 4]*pq.s, t_stop=10) - train21 = _new_spiketrain(SpikeTrain, [3, 5, 4]*pq.s, t_stop=10) + train11 = SpikeTrain([3, 5, 4]*un.s, t_stop=10) + train21 = _new_spiketrain(SpikeTrain, [3, 5, 4]*un.s, t_stop=10) assert_neo_object_is_compliant(train11) assert_neo_object_is_compliant(train21) - self.assertEqual(train11.t_stop, 10.*pq.s) - self.assertEqual(train21.t_stop, 10.*pq.s) + self.assertEqual(train11.t_stop, 10.*un.s) + self.assertEqual(train21.t_stop, 10.*un.s) - train12 = SpikeTrain([3, 5, 4]*pq.s, t_stop=10000.*pq.ms) - train22 = _new_spiketrain(SpikeTrain, [3, 5, 4]*pq.s, - t_stop=10000.*pq.ms) + train12 = SpikeTrain([3, 5, 4]*un.s, t_stop=10000.*un.ms) + train22 = _new_spiketrain(SpikeTrain, [3, 5, 4]*un.s, + t_stop=10000.*un.ms) assert_neo_object_is_compliant(train12) assert_neo_object_is_compliant(train22) - self.assertEqual(train12.t_stop, 10.*pq.s) - self.assertEqual(train22.t_stop, 10.*pq.s) + self.assertEqual(train12.t_stop, 10.*un.s) + self.assertEqual(train22.t_stop, 10.*un.s) - train13 = SpikeTrain([3, 5, 4], units='sec', t_stop=10000.*pq.ms) + train13 = SpikeTrain([3, 5, 4], units='sec', t_stop=10000.*un.ms) train23 = _new_spiketrain(SpikeTrain, [3, 5, 4], - units='sec', t_stop=10000.*pq.ms) + units='sec', t_stop=10000.*un.ms) assert_neo_object_is_compliant(train13) assert_neo_object_is_compliant(train23) - self.assertEqual(train13.t_stop, 10.*pq.s) - self.assertEqual(train23.t_stop, 10.*pq.s) + self.assertEqual(train13.t_stop, 10.*un.s) + self.assertEqual(train23.t_stop, 10.*un.s) class TestSorting(unittest.TestCase): def test_sort(self): - waveforms = np.array([[[0., 1.]], [[2., 3.]], [[4., 5.]]]) * pq.mV - train = SpikeTrain([3, 4, 5]*pq.s, waveforms=waveforms, name='n', + waveforms = np.array([[[0., 1.]], [[2., 3.]], [[4., 5.]]]) * un.mV + train = SpikeTrain([3, 4, 5]*un.s, waveforms=waveforms, name='n', t_stop=10.0) assert_neo_object_is_compliant(train) train.sort() assert_neo_object_is_compliant(train) - assert_arrays_equal(train, [3, 4, 5]*pq.s) + assert_arrays_equal(train, [3, 4, 5]*un.s) assert_arrays_equal(train.waveforms, waveforms) self.assertEqual(train.name, 'n') - self.assertEqual(train.t_stop, 10.0 * pq.s) + self.assertEqual(train.t_stop, 10.0 * un.s) - train = SpikeTrain([3, 5, 4]*pq.s, waveforms=waveforms, name='n', + train = SpikeTrain([3, 5, 4]*un.s, waveforms=waveforms, name='n', t_stop=10.0) assert_neo_object_is_compliant(train) train.sort() assert_neo_object_is_compliant(train) - assert_arrays_equal(train, [3, 4, 5]*pq.s) + assert_arrays_equal(train, [3, 4, 5]*un.s) assert_arrays_equal(train.waveforms, waveforms[[0, 2, 1]]) self.assertEqual(train.name, 'n') - self.assertEqual(train.t_start, 0.0 * pq.s) - self.assertEqual(train.t_stop, 10.0 * pq.s) + self.assertEqual(train.t_start, 0.0 * un.s) + self.assertEqual(train.t_stop, 10.0 * un.s) class TestSlice(unittest.TestCase): @@ -843,9 +845,9 @@ def setUp(self): [[2., 3.], [2.1, 3.1]], [[4., 5.], - [4.1, 5.1]]]) * pq.mV + [4.1, 5.1]]]) * un.mV self.data1 = np.array([3, 4, 5]) - self.data1quant = self.data1*pq.s + self.data1quant = self.data1*un.s self.train1 = SpikeTrain(self.data1quant, waveforms=self.waveforms1, name='n', arb='arbb', t_stop=10.0) @@ -880,7 +882,7 @@ def test_slice_to_end(self): targwaveforms = np.array([[[2., 3.], [2.1, 3.1]], [[4., 5.], - [4.1, 5.1]]]) * pq.mV + [4.1, 5.1]]]) * un.mV # but keep everything else pristine assert_neo_object_is_compliant(result) @@ -903,7 +905,7 @@ def test_slice_from_beginning(self): targwaveforms = np.array([[[0., 1.], [0.1, 1.1]], [[2., 3.], - [2.1, 3.1]]]) * pq.mV + [2.1, 3.1]]]) * un.mV # but keep everything else pristine assert_neo_object_is_compliant(result) @@ -926,7 +928,7 @@ def test_slice_negative_idxs(self): targwaveforms = np.array([[[0., 1.], [0.1, 1.1]], [[2., 3.], - [2.1, 3.1]]]) * pq.mV + [2.1, 3.1]]]) * un.mV # but keep everything else pristine assert_neo_object_is_compliant(result) @@ -956,10 +958,10 @@ def setUp(self): [[8., 9.], [8.1, 9.1]], [[10., 11.], - [10.1, 11.1]]]) * pq.mV + [10.1, 11.1]]]) * un.mV self.data1 = np.array([0.1, 0.5, 1.2, 3.3, 6.4, 7]) - self.data1quant = self.data1*pq.ms - self.train1 = SpikeTrain(self.data1quant, t_stop=10.0*pq.ms, + self.data1quant = self.data1*un.ms + self.train1 = SpikeTrain(self.data1quant, t_stop=10.0*un.ms, waveforms=self.waveforms1) def test_compliant(self): @@ -969,17 +971,17 @@ def test_time_slice_typical(self): # time_slice spike train, keep sliced spike times # this is the typical time slice falling somewhere # in the middle of spikes - t_start = 0.12 * pq.ms - t_stop = 3.5 * pq.ms + t_start = 0.12 * un.ms + t_stop = 3.5 * un.ms result = self.train1.time_slice(t_start, t_stop) - targ = SpikeTrain([0.5, 1.2, 3.3] * pq.ms, t_stop=3.3) + targ = SpikeTrain([0.5, 1.2, 3.3] * un.ms, t_stop=3.3) assert_arrays_equal(result, targ) targwaveforms = np.array([[[2., 3.], [2.1, 3.1]], [[4., 5.], [4.1, 5.1]], [[6., 7.], - [6.1, 7.1]]]) * pq.mV + [6.1, 7.1]]]) * un.mV assert_arrays_equal(targwaveforms, result.waveforms) # but keep everything else pristine @@ -994,17 +996,17 @@ def test_time_slice_typical(self): def test_time_slice_differnt_units(self): # time_slice spike train, keep sliced spike times - t_start = 0.00012 * pq.s - t_stop = 0.0035 * pq.s + t_start = 0.00012 * un.s + t_stop = 0.0035 * un.s result = self.train1.time_slice(t_start, t_stop) - targ = SpikeTrain([0.5, 1.2, 3.3] * pq.ms, t_stop=3.3) + targ = SpikeTrain([0.5, 1.2, 3.3] * un.ms, t_stop=3.3) assert_arrays_equal(result, targ) targwaveforms = np.array([[[2., 3.], [2.1, 3.1]], [[4., 5.], [4.1, 5.1]], [[6., 7.], - [6.1, 7.1]]]) * pq.mV + [6.1, 7.1]]]) * un.mV assert_arrays_equal(targwaveforms, result.waveforms) # but keep everything else pristine @@ -1019,8 +1021,8 @@ def test_time_slice_differnt_units(self): def test_time_slice_matching_ends(self): # time_slice spike train, keep sliced spike times - t_start = 0.1 * pq.ms - t_stop = 7.0 * pq.ms + t_start = 0.1 * un.ms + t_stop = 7.0 * un.ms result = self.train1.time_slice(t_start, t_stop) assert_arrays_equal(self.train1, result) assert_arrays_equal(self.waveforms1, result.waveforms) @@ -1036,12 +1038,12 @@ def test_time_slice_matching_ends(self): self.assertEqual(t_stop, result.t_stop) def test_time_slice_out_of_boundries(self): - self.train1.t_start = 0.1*pq.ms + self.train1.t_start = 0.1*un.ms assert_neo_object_is_compliant(self.train1) # time_slice spike train, keep sliced spike times - t_start = 0.01 * pq.ms - t_stop = 70.0 * pq.ms + t_start = 0.01 * un.ms + t_stop = 70.0 * un.ms result = self.train1.time_slice(t_start, t_stop) assert_arrays_equal(self.train1, result) assert_arrays_equal(self.waveforms1, result.waveforms) @@ -1057,13 +1059,13 @@ def test_time_slice_out_of_boundries(self): self.assertEqual(self.train1.t_stop, result.t_stop) def test_time_slice_empty(self): - waveforms = np.array([[[]]]) * pq.mV - train = SpikeTrain([] * pq.ms, t_stop=10.0, waveforms=waveforms) + waveforms = np.array([[[]]]) * un.mV + train = SpikeTrain([] * un.ms, t_stop=10.0, waveforms=waveforms) assert_neo_object_is_compliant(train) # time_slice spike train, keep sliced spike times - t_start = 0.01 * pq.ms - t_stop = 70.0 * pq.ms + t_start = 0.01 * un.ms + t_stop = 70.0 * un.ms result = train.time_slice(t_start, t_stop) assert_arrays_equal(train, result) assert_arrays_equal(waveforms[:-1], result.waveforms) @@ -1080,9 +1082,9 @@ def test_time_slice_empty(self): def test_time_slice_none_stop(self): # time_slice spike train, keep sliced spike times - t_start = 1 * pq.ms + t_start = 1 * un.ms result = self.train1.time_slice(t_start, None) - assert_arrays_equal([1.2, 3.3, 6.4, 7] * pq.ms, result) + assert_arrays_equal([1.2, 3.3, 6.4, 7] * un.ms, result) targwaveforms = np.array([[[4., 5.], [4.1, 5.1]], [[6., 7.], @@ -1090,7 +1092,7 @@ def test_time_slice_none_stop(self): [[8., 9.], [8.1, 9.1]], [[10., 11.], - [10.1, 11.1]]]) * pq.mV + [10.1, 11.1]]]) * un.mV assert_arrays_equal(targwaveforms, result.waveforms) # but keep everything else pristine @@ -1105,13 +1107,13 @@ def test_time_slice_none_stop(self): def test_time_slice_none_start(self): # time_slice spike train, keep sliced spike times - t_stop = 1 * pq.ms + t_stop = 1 * un.ms result = self.train1.time_slice(None, t_stop) - assert_arrays_equal([0.1, 0.5] * pq.ms, result) + assert_arrays_equal([0.1, 0.5] * un.ms, result) targwaveforms = np.array([[[0., 1.], [0.1, 1.1]], [[2., 3.], - [2.1, 3.1]]]) * pq.mV + [2.1, 3.1]]]) * un.mV assert_arrays_equal(targwaveforms, result.waveforms) # but keep everything else pristine @@ -1125,7 +1127,7 @@ def test_time_slice_none_start(self): self.assertEqual(t_stop, result.t_stop) def test_time_slice_none_both(self): - self.train1.t_start = 0.1*pq.ms + self.train1.t_start = 0.1*un.ms assert_neo_object_is_compliant(self.train1) # time_slice spike train, keep sliced spike times @@ -1156,19 +1158,19 @@ def setUp(self): [[8., 9.], [8.1, 9.1]], [[10., 11.], - [10.1, 11.1]]]) * pq.mV + [10.1, 11.1]]]) * un.mV self.data = np.array([0.1, 0.5, 1.2, 3.3, 6.4, 7]) - self.dataquant = self.data*pq.ms - self.train = SpikeTrain(self.dataquant, t_stop=10.0*pq.ms, + self.dataquant = self.data*un.ms + self.train = SpikeTrain(self.dataquant, t_stop=10.0*un.ms, waveforms=self.waveforms) def test_duplicate_with_new_data(self): signal1 = self.train - new_t_start = -10*pq.s - new_t_stop = 10*pq.s + new_t_start = -10*un.s + new_t_stop = 10*un.s new_data = np.sort(np.random.uniform(new_t_start.magnitude, new_t_stop.magnitude, - len(self.train))) * pq.ms + len(self.train))) * un.ms signal1b = signal1.duplicate_with_new_data(new_data, t_start=new_t_start, @@ -1190,18 +1192,18 @@ def test_set_universally_recommended_attributes(self): self.assertEqual(train.file_origin, 'crack.txt') def test_autoset_universally_recommended_attributes(self): - train = SpikeTrain([3, 4, 5]*pq.s, t_stop=10.0) + train = SpikeTrain([3, 4, 5]*un.s, t_stop=10.0) assert_neo_object_is_compliant(train) self.assertEqual(train.name, None) self.assertEqual(train.description, None) self.assertEqual(train.file_origin, None) def test_annotations(self): - train = SpikeTrain([3, 4, 5]*pq.s, t_stop=11.1) + train = SpikeTrain([3, 4, 5]*un.s, t_stop=11.1) assert_neo_object_is_compliant(train) self.assertEqual(train.annotations, {}) - train = SpikeTrain([3, 4, 5]*pq.s, t_stop=11.1, ratname='Phillippe') + train = SpikeTrain([3, 4, 5]*un.s, t_stop=11.1, ratname='Phillippe') assert_neo_object_is_compliant(train) self.assertEqual(train.annotations, {'ratname': 'Phillippe'}) @@ -1211,58 +1213,58 @@ def test_change_with_copy_default(self): # Default is copy = True # Changing spike train does not change data # Data source is quantity - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s train = SpikeTrain(data, t_stop=100.0) - train[0] = 99 * pq.s + train[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99*pq.s) - self.assertEqual(data[0], 3*pq.s) + self.assertEqual(train[0], 99*un.s) + self.assertEqual(data[0], 3*un.s) def test_change_with_copy_false(self): # Changing spike train also changes data, because it is a view # Data source is quantity - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s train = SpikeTrain(data, copy=False, t_stop=100.0) - train[0] = 99 * pq.s + train[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99*pq.s) - self.assertEqual(data[0], 99*pq.s) + self.assertEqual(train[0], 99*un.s) + self.assertEqual(data[0], 99*un.s) def test_change_with_copy_false_and_fake_rescale(self): # Changing spike train also changes data, because it is a view # Data source is quantity - data = [3000, 4000, 5000] * pq.ms + data = [3000, 4000, 5000] * un.ms # even though we specify units, it still returns a view train = SpikeTrain(data, units='ms', copy=False, t_stop=100000) - train[0] = 99000 * pq.ms + train[0] = 99000 * un.ms assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99000*pq.ms) - self.assertEqual(data[0], 99000*pq.ms) + self.assertEqual(train[0], 99000*un.ms) + self.assertEqual(data[0], 99000*un.ms) def test_change_with_copy_false_and_rescale_true(self): # When rescaling, a view cannot be returned # Changing spike train also changes data, because it is a view - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s self.assertRaises(ValueError, SpikeTrain, data, units='ms', copy=False, t_stop=10000) def test_init_with_rescale(self): - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s train = SpikeTrain(data, units='ms', t_stop=6000) assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 3000*pq.ms) - self.assertEqual(train._dimensionality, pq.ms._dimensionality) - self.assertEqual(train.t_stop, 6000*pq.ms) + self.assertEqual(train[0], 3000*un.ms) + self.assertEqual(train._dimensionality, un.ms._dimensionality) + self.assertEqual(train.t_stop, 6000*un.ms) def test_change_with_copy_true(self): # Changing spike train does not change data # Data source is quantity - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s train = SpikeTrain(data, copy=True, t_stop=100) - train[0] = 99 * pq.s + train[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99*pq.s) - self.assertEqual(data[0], 3*pq.s) + self.assertEqual(train[0], 99*un.s) + self.assertEqual(data[0], 3*un.s) def test_change_with_copy_default_and_data_not_quantity(self): # Default is copy = True @@ -1272,10 +1274,10 @@ def test_change_with_copy_default_and_data_not_quantity(self): # is different for these two. data = [3, 4, 5] train = SpikeTrain(data, units='sec', t_stop=100) - train[0] = 99 * pq.s + train[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99*pq.s) - self.assertEqual(data[0], 3*pq.s) + self.assertEqual(train[0], 99*un.s) + self.assertEqual(data[0], 3*un.s) def test_change_with_copy_false_and_data_not_quantity(self): # Changing spike train also changes data, because it is a view @@ -1285,9 +1287,9 @@ def test_change_with_copy_false_and_data_not_quantity(self): data = np.array([3, 4, 5]) train = SpikeTrain(data, units='sec', copy=False, dtype=np.int, t_stop=101) - train[0] = 99 * pq.s + train[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99*pq.s) + self.assertEqual(train[0], 99*un.s) self.assertEqual(data[0], 99) def test_change_with_copy_false_and_dtype_change(self): @@ -1303,9 +1305,9 @@ def test_change_with_copy_true_and_data_not_quantity(self): # is different for these two. data = [3, 4, 5] train = SpikeTrain(data, units='sec', copy=True, t_stop=123.4) - train[0] = 99 * pq.s + train[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[0], 99*pq.s) + self.assertEqual(train[0], 99*un.s) self.assertEqual(data[0], 3) def test_changing_slice_changes_original_spiketrain(self): @@ -1314,14 +1316,14 @@ def test_changing_slice_changes_original_spiketrain(self): # Whether the original data source changes is dependent on the # copy parameter. # This is compatible with both np and quantity default behavior. - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s train = SpikeTrain(data, copy=True, t_stop=99.9) result = train[1:3] - result[0] = 99 * pq.s + result[0] = 99 * un.s assert_neo_object_is_compliant(train) - self.assertEqual(train[1], 99*pq.s) - self.assertEqual(result[0], 99*pq.s) - self.assertEqual(data[1], 4*pq.s) + self.assertEqual(train[1], 99*un.s) + self.assertEqual(result[0], 99*un.s) + self.assertEqual(data[1], 4*un.s) def test_changing_slice_changes_original_spiketrain_with_copy_false(self): # If we slice a spiketrain and then change the slice, the @@ -1329,96 +1331,96 @@ def test_changing_slice_changes_original_spiketrain_with_copy_false(self): # Whether the original data source changes is dependent on the # copy parameter. # This is compatible with both np and quantity default behavior. - data = [3, 4, 5] * pq.s + data = [3, 4, 5] * un.s train = SpikeTrain(data, copy=False, t_stop=100.0) result = train[1:3] - result[0] = 99 * pq.s + result[0] = 99 * un.s assert_neo_object_is_compliant(train) assert_neo_object_is_compliant(result) - self.assertEqual(train[1], 99*pq.s) - self.assertEqual(result[0], 99*pq.s) - self.assertEqual(data[1], 99*pq.s) + self.assertEqual(train[1], 99*un.s) + self.assertEqual(result[0], 99*un.s) + self.assertEqual(data[1], 99*un.s) def test__changing_spiketime_should_check_time_in_range(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, copy=False, t_start=0.5, t_stop=10.0) assert_neo_object_is_compliant(train) - self.assertRaises(ValueError, train.__setitem__, 0, 10.1*pq.ms) - self.assertRaises(ValueError, train.__setitem__, 1, 5.0*pq.s) - self.assertRaises(ValueError, train.__setitem__, 2, 5.0*pq.s) + self.assertRaises(ValueError, train.__setitem__, 0, 10.1*un.ms) + self.assertRaises(ValueError, train.__setitem__, 1, 5.0*un.s) + self.assertRaises(ValueError, train.__setitem__, 2, 5.0*un.s) self.assertRaises(ValueError, train.__setitem__, 0, 0) def test__changing_multiple_spiketimes(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, copy=False, t_start=0.5, t_stop=10.0) - train[:] = [7, 8, 9] * pq.ms + train[:] = [7, 8, 9] * un.ms assert_neo_object_is_compliant(train) assert_arrays_equal(train, np.array([7, 8, 9])) def test__changing_multiple_spiketimes_should_check_time_in_range(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, copy=False, t_start=0.5, t_stop=10.0) assert_neo_object_is_compliant(train) if sys.version_info[0] == 2: self.assertRaises(ValueError, train.__setslice__, - 0, 3, [3, 4, 11] * pq.ms) + 0, 3, [3, 4, 11] * un.ms) self.assertRaises(ValueError, train.__setslice__, - 0, 3, [0, 4, 5] * pq.ms) + 0, 3, [0, 4, 5] * un.ms) def test__adding_time(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, copy=False, t_start=0.5, t_stop=10.0) assert_neo_object_is_compliant(train) - self.assertRaises(ValueError, train.__add__, 10 * pq.ms) - assert_arrays_equal(train + 1 * pq.ms, data + 1 * pq.ms) + self.assertRaises(ValueError, train.__add__, 10 * un.ms) + assert_arrays_equal(train + 1 * un.ms, data + 1 * un.ms) def test__subtracting_time(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, copy=False, t_start=0.5, t_stop=10.0) assert_neo_object_is_compliant(train) - self.assertRaises(ValueError, train.__sub__, 10 * pq.ms) - assert_arrays_equal(train - 1 * pq.ms, data - 1 * pq.ms) + self.assertRaises(ValueError, train.__sub__, 10 * un.ms) + assert_arrays_equal(train - 1 * un.ms, data - 1 * un.ms) def test__rescale(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, t_start=0.5, t_stop=10.0) - result = train.rescale(pq.s) + result = train.rescale(un.s) assert_neo_object_is_compliant(train) assert_neo_object_is_compliant(result) assert_arrays_equal(train, result) - self.assertEqual(result.units, 1 * pq.s) + self.assertEqual(result.units, 1 * un.s) def test__rescale_same_units(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, t_start=0.5, t_stop=10.0) - result = train.rescale(pq.ms) + result = train.rescale(un.ms) assert_neo_object_is_compliant(train) assert_arrays_equal(train, result) - self.assertEqual(result.units, 1 * pq.ms) + self.assertEqual(result.units, 1 * un.ms) def test__rescale_incompatible_units_ValueError(self): - data = [3, 4, 5] * pq.ms + data = [3, 4, 5] * un.ms train = SpikeTrain(data, t_start=0.5, t_stop=10.0) assert_neo_object_is_compliant(train) - self.assertRaises(ValueError, train.rescale, pq.m) + self.assertRaises(ValueError, train.rescale, un.m) class TestPropertiesMethods(unittest.TestCase): def setUp(self): self.data1 = [3, 4, 5] - self.data1quant = self.data1 * pq.ms + self.data1quant = self.data1 * un.ms self.waveforms1 = np.array([[[0., 1.], [0.1, 1.1]], [[2., 3.], [2.1, 3.1]], [[4., 5.], - [4.1, 5.1]]]) * pq.mV + [4.1, 5.1]]]) * un.mV self.t_start1 = 0.5 self.t_stop1 = 10.0 - self.t_start1quant = self.t_start1 * pq.ms - self.t_stop1quant = self.t_stop1 * pq.ms - self.sampling_rate1 = .1*pq.Hz - self.left_sweep1 = 2.*pq.s + self.t_start1quant = self.t_start1 * un.ms + self.t_stop1quant = self.t_stop1 * un.ms + self.sampling_rate1 = .1*un.Hz + self.left_sweep1 = 2.*un.s self.name1 = 'train 1' self.description1 = 'a test object' self.ann1 = {'targ0': [1, 2], 'targ1': 1.1} @@ -1451,8 +1453,8 @@ def test__duration(self): assert_neo_object_is_compliant(self.train1) result3 = self.train1.duration - self.assertEqual(result1, 9.5 * pq.ms) - self.assertEqual(result1.units, 1. * pq.ms) + self.assertEqual(result1, 9.5 * un.ms) + self.assertEqual(result1.units, 1. * un.ms) self.assertEqual(result2, None) self.assertEqual(result3, None) @@ -1468,8 +1470,8 @@ def test__spike_duration(self): assert_neo_object_is_compliant(self.train1) result3 = self.train1.spike_duration - self.assertEqual(result1, 20./pq.Hz) - self.assertEqual(result1.units, 1./pq.Hz) + self.assertEqual(result1, 20./un.Hz) + self.assertEqual(result1.units, 1./un.Hz) self.assertEqual(result2, None) self.assertEqual(result3, None) @@ -1481,7 +1483,7 @@ def test__sampling_period(self): result2 = self.train1.sampling_period self.train1.sampling_rate = self.sampling_rate1 - self.train1.sampling_period = 10.*pq.ms + self.train1.sampling_period = 10.*un.ms assert_neo_object_is_compliant(self.train1) result3a = self.train1.sampling_period result3b = self.train1.sampling_rate @@ -1490,13 +1492,13 @@ def test__sampling_period(self): result4a = self.train1.sampling_period result4b = self.train1.sampling_rate - self.assertEqual(result1, 10./pq.Hz) - self.assertEqual(result1.units, 1./pq.Hz) + self.assertEqual(result1, 10./un.Hz) + self.assertEqual(result1.units, 1./un.Hz) self.assertEqual(result2, None) - self.assertEqual(result3a, 10.*pq.ms) - self.assertEqual(result3a.units, 1.*pq.ms) - self.assertEqual(result3b, .1/pq.ms) - self.assertEqual(result3b.units, 1./pq.ms) + self.assertEqual(result3a, 10.*un.ms) + self.assertEqual(result3a.units, 1.*un.ms) + self.assertEqual(result3b, .1/un.ms) + self.assertEqual(result3b.units, 1./un.ms) self.assertEqual(result4a, None) self.assertEqual(result4b, None) @@ -1517,8 +1519,8 @@ def test__right_sweep(self): assert_neo_object_is_compliant(self.train1) result4 = self.train1.right_sweep - self.assertEqual(result1, 22.*pq.s) - self.assertEqual(result1.units, 1.*pq.s) + self.assertEqual(result1, 22.*un.s) + self.assertEqual(result1.units, 1.*un.s) self.assertEqual(result2, None) self.assertEqual(result3, None) self.assertEqual(result4, None) @@ -1562,7 +1564,7 @@ def test__pretty(self): class TestMiscellaneous(unittest.TestCase): def test__different_dtype_for_t_start_and_array(self): - data = np.array([0, 9.9999999], dtype=np.float64) * pq.s + data = np.array([0, 9.9999999], dtype=np.float64) * un.s data16 = data.astype(np.float16) data32 = data.astype(np.float32) data64 = data.astype(np.float64) diff --git a/neo/test/generate_datasets.py b/neo/test/generate_datasets.py index 53ff22167..927dd5802 100644 --- a/neo/test/generate_datasets.py +++ b/neo/test/generate_datasets.py @@ -10,7 +10,7 @@ import numpy as np from numpy.random import rand -import quantities as pq +from neo import units as un from neo.core import (AnalogSignal, Block, @@ -51,12 +51,12 @@ def generate_one_simple_block(block_name='block_0', nb_segment=3, def generate_one_simple_segment(seg_name='segment 0', supported_objects=[], nb_analogsignal=4, - t_start=0.*pq.s, - sampling_rate=10*pq.kHz, - duration=6.*pq.s, + t_start=0.*un.s, + sampling_rate=10*un.kHz, + duration=6.*un.s, nb_spiketrain=6, - spikerate_range=[.5*pq.Hz, 12*pq.Hz], + spikerate_range=[.5*un.Hz, 12*un.Hz], event_types={'stim': ['a', 'b', 'c', 'd'], @@ -84,7 +84,7 @@ def generate_one_simple_segment(seg_name='segment 0', for a in range(nb_analogsignal): anasig = AnalogSignal(rand(int(sampling_rate * duration)), sampling_rate=sampling_rate, t_start=t_start, - units=pq.mV, channel_index=a, + units=un.mV, channel_index=a, name='sig %d for segment %s' % (a, seg.name)) seg.analogsignals.append(anasig) @@ -126,9 +126,9 @@ def generate_one_simple_segment(seg_name='segment 0', t = t+dur labels = np.array(labels, dtype='S') labels = labels[(rand(len(times))*len(labels)).astype('i')] - epc = Epoch(times=pq.Quantity(times, units=pq.s), - durations=pq.Quantity([x[0] for x in durations], - units=pq.s), + epc = Epoch(times=un.Quantity(times, units=un.s), + durations=un.Quantity([x[0] for x in durations], + units=un.s), labels=labels, ) seg.epochs.append(epc) @@ -198,7 +198,7 @@ def get_fake_value(name, datatype, dim=0, dtype='float', seed=None, return datetime.fromtimestamp(1000000000*np.random.random()) if (name in ['t_start', 't_stop', 'sampling_rate'] and - (datatype != pq.Quantity or dim)): + (datatype != un.Quantity or dim)): raise ValueError('%s must be a 0D Quantity, not a %sD %s' % (name, dim, datatype)) @@ -209,12 +209,12 @@ def get_fake_value(name, datatype, dim=0, dtype='float', seed=None, elif name in ['t_start', 't_stop', 'time', 'times', 'duration', 'durations']: - units = pq.millisecond + units = un.millisecond elif name == 'sampling_rate': - units = pq.Hz - elif datatype == pq.Quantity: + units = un.Hz + elif datatype == un.Quantity: units = np.random.choice(['nA', 'mA', 'A', 'mV', 'V']) - units = getattr(pq, units) + units = getattr(un, units) if name == 'sampling_rate': data = np.array(10000.0) @@ -254,7 +254,7 @@ def get_fake_value(name, datatype, dim=0, dtype='float', seed=None, return data if datatype == list: return data.tolist() - if datatype == pq.Quantity: + if datatype == un.Quantity: return data * units # set the units # we have gone through everything we know, so it must be something invalid @@ -296,7 +296,7 @@ def get_fake_values(cls, annotate=True, seed=None, n=None): np.random.seed(0) new_times = np.concatenate([new_times, np.random.random(dif)]) - kwargs["times"] = pq.Quantity(new_times, units=pq.ms) + kwargs["times"] = un.Quantity(new_times, units=un.ms) else : kwargs['times'] = kwargs['times'][:kwargs["waveforms"].shape[0]] diff --git a/neo/test/iotest/test_blackrockio.py b/neo/test/iotest/test_blackrockio.py index 73bd0f9a0..0c3aab9c4 100644 --- a/neo/test/iotest/test_blackrockio.py +++ b/neo/test/iotest/test_blackrockio.py @@ -19,7 +19,7 @@ from numpy.testing import assert_equal import numpy as np -import quantities as pq +from neo import units as un from neo.io.blackrockio import BlackrockIO @@ -92,9 +92,9 @@ def test_inputs_V23(self): # Load data using a negative time and a time exceeding the end of the # recording - too_large_tstop = block.segments[0].analogsignals[0].t_stop + 1 * pq.s + too_large_tstop = block.segments[0].analogsignals[0].t_stop + 1 * un.s block = b.read_block( - n_starts=[-100 * pq.ms], n_stops=[too_large_tstop], + n_starts=[-100 * un.ms], n_stops=[too_large_tstop], channels=range(1, 9), nsx_to_load=[5], units='all', load_events=False, load_waveforms=False) lenb = len(block.segments[0].analogsignals[0]) @@ -144,7 +144,7 @@ def test_inputs_V23(self): # NOTE: channel 6 does not contain any unit block = b.read_block( - n_starts=[None, 3000 * pq.ms], n_stops=[1000 * pq.ms, None], + n_starts=[None, 3000 * un.ms], n_stops=[1000 * un.ms, None], channels=range(1, 9), nsx_to_load='none', units={1: 0, 5: 0, 6: 0}, load_events=True, load_waveforms=True) diff --git a/neo/test/iotest/test_brainwaredamio.py b/neo/test/iotest/test_brainwaredamio.py index 22bbe4510..a404728af 100644 --- a/neo/test/iotest/test_brainwaredamio.py +++ b/neo/test/iotest/test_brainwaredamio.py @@ -15,7 +15,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un from neo.core import (AnalogSignal, Block, ChannelIndex, Segment) @@ -73,10 +73,10 @@ def proc_dam(filename): fulldam = zip(stimIndexes, timestamps, signals, stims) for stimIndex, timestamp, signal, stim in fulldam: - sig = AnalogSignal(signal=signal*pq.mV, - t_start=timestamp*pq.d, + sig = AnalogSignal(signal=signal*un.mV, + t_start=timestamp*un.d, file_origin=filename, - sampling_period=1.*pq.s) + sampling_period=1.*un.s) segment = Segment(file_origin=filename, index=stimIndex, **stim) diff --git a/neo/test/iotest/test_brainwaref32io.py b/neo/test/iotest/test_brainwaref32io.py index c592b2db2..62531f1ff 100644 --- a/neo/test/iotest/test_brainwaref32io.py +++ b/neo/test/iotest/test_brainwaref32io.py @@ -15,7 +15,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un from neo.core import Block, ChannelIndex, Segment, SpikeTrain, Unit from neo.io import BrainwareF32IO @@ -85,7 +85,7 @@ def proc_f32(filename): paramnames = ['Param%s' % i for i in range(len(stim))] params = dict(zip(paramnames, stim)) - train = SpikeTrain(trainpts, units=pq.ms, + train = SpikeTrain(trainpts, units=un.ms, t_start=0, t_stop=sweeplength, file_origin=filenameorig) diff --git a/neo/test/iotest/test_brainwaresrcio.py b/neo/test/iotest/test_brainwaresrcio.py index e9fa07072..d85562d54 100644 --- a/neo/test/iotest/test_brainwaresrcio.py +++ b/neo/test/iotest/test_brainwaresrcio.py @@ -16,7 +16,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un from neo.core import (Block, Event, ChannelIndex, Segment, SpikeTrain, Unit) @@ -111,7 +111,7 @@ def proc_src_comments(srcfile, filename): timeStamps = np.array(timeStamps, dtype=np.float32) t_start = timeStamps.min() - timeStamps = pq.Quantity(timeStamps-t_start, units=pq.d).rescale(pq.s) + timeStamps = un.Quantity(timeStamps-t_start, units=un.d).rescale(un.s) texts = np.array(texts, dtype='S') senders = np.array(senders, dtype='S') t_start = brainwaresrcio.convert_brainwaresrc_timestamp(t_start.tolist()) @@ -256,12 +256,12 @@ def proc_src_condition_unit_repetition(sweep, damaIndex, timeStamp, sweepLen, shapes = np.array([[[]]]) trig2 = np.array([]) - times = pq.Quantity(times, units=pq.ms, dtype=np.float32) - t_start = pq.Quantity(0, units=pq.ms, dtype=np.float32) - t_stop = pq.Quantity(sweepLen, units=pq.ms, dtype=np.float32) - trig2 = pq.Quantity(trig2, units=pq.ms, dtype=np.uint8) - waveforms = pq.Quantity(shapes, dtype=np.int8, units=pq.mV) - sampling_period = pq.Quantity(ADperiod, units=pq.us) + times = un.Quantity(times, units=un.ms, dtype=np.float32) + t_start = un.Quantity(0, units=un.ms, dtype=np.float32) + t_stop = un.Quantity(sweepLen, units=un.ms, dtype=np.float32) + trig2 = un.Quantity(trig2, units=un.ms, dtype=np.uint8) + waveforms = un.Quantity(shapes, dtype=np.int8, units=un.mV) + sampling_period = un.Quantity(ADperiod, units=un.us) train = SpikeTrain(times=times, t_start=t_start, t_stop=t_stop, trig2=trig2, dtype=np.float32, timestamp=timeStamp, diff --git a/neo/test/iotest/test_hdf5io.py b/neo/test/iotest/test_hdf5io.py index 08c45be68..1ec49c179 100644 --- a/neo/test/iotest/test_hdf5io.py +++ b/neo/test/iotest/test_hdf5io.py @@ -11,7 +11,7 @@ import unittest import numpy as np from numpy.testing import assert_array_equal -from quantities import kHz, mV, ms, second, nA +from neo.units import kHz, mV, ms, second, nA try: import h5py HAVE_H5PY = True diff --git a/neo/test/iotest/test_klustakwikio.py b/neo/test/iotest/test_klustakwikio.py index 3fb4909ee..fb88d26a5 100644 --- a/neo/test/iotest/test_klustakwikio.py +++ b/neo/test/iotest/test_klustakwikio.py @@ -17,7 +17,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un import neo from neo.test.iotest.common_io_test import BaseTestIO @@ -103,7 +103,7 @@ def test1(self): self.assertEqual(len(seg.spiketrains), 4) for st in seg.spiketrains: - self.assertEqual(st.units, np.array(1.0) * pq.s) + self.assertEqual(st.units, np.array(1.0) * un.s) self.assertEqual(st.t_start, 0.0) self.assertEqual(seg.spiketrains[0].name, 'unit 1 from group 0') diff --git a/neo/test/iotest/test_nestio.py b/neo/test/iotest/test_nestio.py index 60c5bf7cd..605950c6f 100644 --- a/neo/test/iotest/test_nestio.py +++ b/neo/test/iotest/test_nestio.py @@ -12,7 +12,7 @@ except ImportError: import unittest -import quantities as pq +import quantities as un import numpy as np from neo.io.nestio import ColumnIO @@ -51,12 +51,12 @@ def test_read_analogsignal(self): filename='0gid-1time-2gex-3Vm-1261-0.dat', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_analogsignal(gid=1, t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, + r.read_analogsignal(gid=1, t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column=0, time_column=1, value_column=2, value_type='V_m') - r.read_segment(gid_list=[1], t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, id_column_dat=0, + r.read_segment(gid_list=[1], t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -65,14 +65,14 @@ def test_read_analogsignal(self): filename='0gid-1time_in_steps-2Vm-1263-0.dat', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_analogsignal(gid=1, t_stop=1000. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), - sampling_period=pq.ms, lazy=False, + r.read_analogsignal(gid=1, t_stop=1000. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), + sampling_period=un.ms, lazy=False, id_column=0, time_column=1, value_column=2, value_type='V_m') - r.read_segment(gid_list=[1], t_stop=1000. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), - sampling_period=pq.ms, lazy=False, id_column_dat=0, + r.read_segment(gid_list=[1], t_stop=1000. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -81,14 +81,14 @@ def test_read_analogsignal(self): filename='0gid-1time-2Vm-1259-0.dat', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_analogsignal(gid=1, t_stop=1000. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), - sampling_period=pq.ms, lazy=False, + r.read_analogsignal(gid=1, t_stop=1000. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), + sampling_period=un.ms, lazy=False, id_column=0, time_column=1, value_column=2, value_type='V_m') - r.read_segment(gid_list=[1], t_stop=1000. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), - sampling_period=pq.ms, lazy=False, id_column_dat=0, + r.read_segment(gid_list=[1], t_stop=1000. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -105,12 +105,12 @@ def test_id_column_none_multiple_neurons(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(ValueError): - r.read_analogsignal(t_stop=1000. * pq.ms, lazy=False, - sampling_period=pq.ms, + r.read_analogsignal(t_stop=1000. * un.ms, lazy=False, + sampling_period=un.ms, id_column=None, time_column=0, value_column=1) - r.read_segment(t_stop=1000. * pq.ms, lazy=False, - sampling_period=pq.ms, id_column_gdf=None, + r.read_segment(t_stop=1000. * un.ms, lazy=False, + sampling_period=un.ms, id_column_gdf=None, time_column_gdf=0) def test_values(self): @@ -126,8 +126,8 @@ def test_values(self): id_to_test = 1 r = NestIO(filenames=filename) seg = r.read_segment(gid_list=[id_to_test], - t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, + t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -150,8 +150,8 @@ def test_read_segment(self): id_list_to_test = range(1, 10) seg = r.read_segment(gid_list=id_list_to_test, - t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, + t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -159,8 +159,8 @@ def test_read_segment(self): id_list_to_test = [] seg = r.read_segment(gid_list=id_list_to_test, - t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, + t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -179,8 +179,8 @@ def test_read_block(self): id_list_to_test = range(1, 10) blk = r.read_block(gid_list=id_list_to_test, - t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, + t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') @@ -203,19 +203,19 @@ def test_wrong_input(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(ValueError): - r.read_segment(t_stop=1000. * pq.ms, lazy=False, + r.read_segment(t_stop=1000. * un.ms, lazy=False, id_column_dat=0, time_column_dat=1) with self.assertRaises(ValueError): r.read_segment() with self.assertRaises(ValueError): - r.read_segment(gid_list=[1], t_stop=1000. * pq.ms, - sampling_period=1. * pq.ms, lazy=False, + r.read_segment(gid_list=[1], t_stop=1000. * un.ms, + sampling_period=1. * un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='V_m') with self.assertRaises(ValueError): - r.read_segment(gid_list=[1], t_stop=1000. * pq.ms, - sampling_period=pq.ms, lazy=False, + r.read_segment(gid_list=[1], t_stop=1000. * un.ms, + sampling_period=un.ms, lazy=False, id_column_dat=0, time_column_dat=1, value_columns_dat=2, value_types='U_mem') @@ -229,8 +229,8 @@ def test_t_start_t_stop(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - t_start_targ = 450. * pq.ms - t_stop_targ = 480. * pq.ms + t_start_targ = 450. * un.ms + t_stop_targ = 480. * un.ms seg = r.read_segment(gid_list=[], t_start=t_start_targ, t_stop=t_stop_targ, lazy=False, @@ -252,9 +252,9 @@ def test_notimeid(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - t_start_targ = 450. * pq.ms - t_stop_targ = 460. * pq.ms - sampling_period = pq.CompoundUnit('5*ms') + t_start_targ = 450. * un.ms + t_stop_targ = 460. * un.ms + sampling_period = un.CompoundUnit('5*ms') with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. @@ -269,9 +269,9 @@ def test_notimeid(self): self.assertIn("no time column id", str(w[0].message)) sts = seg.analogsignals for st in sts: - self.assertTrue(st.t_start == 1 * 5 * pq.ms) + self.assertTrue(st.t_start == 1 * 5 * un.ms) self.assertTrue( - st.t_stop == len(st) * sampling_period + 1 * 5 * pq.ms) + st.t_stop == len(st) * sampling_period + 1 * 5 * un.ms) def test_multiple_value_columns(self): """ @@ -284,7 +284,7 @@ def test_multiple_value_columns(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - sampling_period = pq.CompoundUnit('5*ms') + sampling_period = un.CompoundUnit('5*ms') seg = r.read_segment(gid_list=[1001], value_columns_dat=[2, 3], sampling_period=sampling_period) @@ -297,9 +297,9 @@ def test_single_gid(self): filename='N1-0gid-1time-2Vm-1265-0.dat', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - anasig = r.read_analogsignal(gid=1, t_stop=1000. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), - sampling_period=pq.ms, lazy=False, + anasig = r.read_analogsignal(gid=1, t_stop=1000. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), + sampling_period=un.ms, lazy=False, id_column=0, time_column=1, value_column=2, value_type='V_m') assert anasig.annotations['id'] == 1 @@ -310,9 +310,9 @@ def test_no_gid(self): filename='N1-0time-1Vm-1266-0.dat', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - anasig = r.read_analogsignal(gid=None, t_stop=1000. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), - sampling_period=pq.ms, lazy=False, + anasig = r.read_analogsignal(gid=None, t_stop=1000. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), + sampling_period=un.ms, lazy=False, id_column=None, time_column=0, value_column=1, value_type='V_m') self.assertEqual(anasig.annotations['id'], None) @@ -325,7 +325,7 @@ def test_no_gid_no_time(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) anasig = r.read_analogsignal(gid=None, - sampling_period=pq.ms, lazy=False, + sampling_period=un.ms, lazy=False, id_column=None, time_column=None, value_column=0, value_type='V_m') self.assertEqual(anasig.annotations['id'], None) @@ -350,9 +350,9 @@ def test_read_spiketrain(self): filename='0time-1255-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_spiketrain(t_start=400. * pq.ms, t_stop=500. * pq.ms, lazy=False, + r.read_spiketrain(t_start=400. * un.ms, t_stop=500. * un.ms, lazy=False, id_column=None, time_column=0) - r.read_segment(t_start=400. * pq.ms, t_stop=500. * pq.ms, lazy=False, + r.read_segment(t_start=400. * un.ms, t_stop=500. * un.ms, lazy=False, id_column_gdf=None, time_column_gdf=0) filename = get_test_file_full_path( @@ -360,11 +360,11 @@ def test_read_spiketrain(self): filename='0time_in_steps-1257-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_spiketrain(t_start=400. * pq.ms, t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), lazy=False, + r.read_spiketrain(t_start=400. * un.ms, t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column=None, time_column=0) - r.read_segment(t_start=400. * pq.ms, t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), lazy=False, + r.read_segment(t_start=400. * un.ms, t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column_gdf=None, time_column_gdf=0) filename = get_test_file_full_path( @@ -372,9 +372,9 @@ def test_read_spiketrain(self): filename='0gid-1time-1256-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_spiketrain(gdf_id=1, t_start=400. * pq.ms, t_stop=500. * pq.ms, + r.read_spiketrain(gdf_id=1, t_start=400. * un.ms, t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) - r.read_segment(gid_list=[1], t_start=400. * pq.ms, t_stop=500. * pq.ms, + r.read_segment(gid_list=[1], t_start=400. * un.ms, t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) filename = get_test_file_full_path( @@ -382,11 +382,11 @@ def test_read_spiketrain(self): filename='0gid-1time_in_steps-1258-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - r.read_spiketrain(gdf_id=1, t_start=400. * pq.ms, t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), lazy=False, + r.read_spiketrain(gdf_id=1, t_start=400. * un.ms, t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column=0, time_column=1) - r.read_segment(gid_list=[1], t_start=400. * pq.ms, t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), lazy=False, + r.read_segment(gid_list=[1], t_start=400. * un.ms, t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column_gdf=0, time_column_gdf=1) def test_read_integer(self): @@ -399,14 +399,14 @@ def test_read_integer(self): filename='0time_in_steps-1257-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - st = r.read_spiketrain(gdf_id=None, t_start=400. * pq.ms, - t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), + st = r.read_spiketrain(gdf_id=None, t_start=400. * un.ms, + t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column=None, time_column=0) self.assertTrue(st.magnitude.dtype == np.int32) - seg = r.read_segment(gid_list=[None], t_start=400. * pq.ms, - t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), + seg = r.read_segment(gid_list=[None], t_start=400. * un.ms, + t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column_gdf=None, time_column_gdf=0) sts = seg.spiketrains self.assertTrue(all([st.magnitude.dtype == np.int32 for st in sts])) @@ -417,14 +417,14 @@ def test_read_integer(self): directory=self.local_test_dir, clean=False) r = NestIO( filenames=filename) - st = r.read_spiketrain(gdf_id=1, t_start=400. * pq.ms, - t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), + st = r.read_spiketrain(gdf_id=1, t_start=400. * un.ms, + t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column=0, time_column=1) self.assertTrue(st.magnitude.dtype == np.int32) - seg = r.read_segment(gid_list=[1], t_start=400. * pq.ms, - t_stop=500. * pq.ms, - time_unit=pq.CompoundUnit('0.1*ms'), + seg = r.read_segment(gid_list=[1], t_start=400. * un.ms, + t_stop=500. * un.ms, + time_unit=un.CompoundUnit('0.1*ms'), lazy=False, id_column_gdf=0, time_column_gdf=1) sts = seg.spiketrains self.assertTrue(all([st.magnitude.dtype == np.int32 for st in sts])) @@ -439,12 +439,12 @@ def test_read_float(self): filename='0gid-1time-1256-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - st = r.read_spiketrain(gdf_id=1, t_start=400. * pq.ms, - t_stop=500. * pq.ms, + st = r.read_spiketrain(gdf_id=1, t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column=0, time_column=1) self.assertTrue(st.magnitude.dtype == np.float) - seg = r.read_segment(gid_list=[1], t_start=400. * pq.ms, - t_stop=500. * pq.ms, + seg = r.read_segment(gid_list=[1], t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) sts = seg.spiketrains self.assertTrue(all([s.magnitude.dtype == np.float for s in sts])) @@ -460,8 +460,8 @@ def test_values(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) seg = r.read_segment(gid_list=[id_to_test], - t_start=400. * pq.ms, - t_stop=500. * pq.ms, lazy=False, + t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) dat = np.loadtxt(filename) @@ -481,14 +481,14 @@ def test_read_segment(self): r = NestIO(filenames=filename) id_list_to_test = range(1, 10) - seg = r.read_segment(gid_list=id_list_to_test, t_start=400. * pq.ms, - t_stop=500. * pq.ms, lazy=False, + seg = r.read_segment(gid_list=id_list_to_test, t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) self.assertTrue(len(seg.spiketrains) == len(id_list_to_test)) id_list_to_test = [] - seg = r.read_segment(gid_list=id_list_to_test, t_start=400. * pq.ms, - t_stop=500. * pq.ms, lazy=False, + seg = r.read_segment(gid_list=id_list_to_test, t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) self.assertTrue(len(seg.spiketrains) == 50) @@ -502,8 +502,8 @@ def test_read_segment_accepts_range(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - seg = r.read_segment(gid_list=(10, 39), t_start=400. * pq.ms, - t_stop=500. * pq.ms, lazy=False, + seg = r.read_segment(gid_list=(10, 39), t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) self.assertEqual(len(seg.spiketrains), 30) @@ -518,13 +518,13 @@ def test_read_segment_range_is_reasonable(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - seg = r.read_segment(gid_list=(10, 10), t_start=400. * pq.ms, - t_stop=500. * pq.ms, lazy=False, + seg = r.read_segment(gid_list=(10, 10), t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) self.assertEqual(len(seg.spiketrains), 1) with self.assertRaises(ValueError): - r.read_segment(gid_list=(10, 9), t_start=400. * pq.ms, - t_stop=500. * pq.ms, lazy=False, + r.read_segment(gid_list=(10, 9), t_start=400. * un.ms, + t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) def test_read_spiketrain_annotates(self): @@ -537,8 +537,8 @@ def test_read_spiketrain_annotates(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) ID = 7 - st = r.read_spiketrain(gdf_id=ID, t_start=400. * pq.ms, - t_stop=500. * pq.ms) + st = r.read_spiketrain(gdf_id=ID, t_start=400. * un.ms, + t_stop=500. * un.ms) self.assertEqual(ID, st.annotations['id']) def test_read_segment_annotates(self): @@ -551,8 +551,8 @@ def test_read_segment_annotates(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) IDs = (5, 11) - sts = r.read_segment(gid_list=(5, 11), t_start=400. * pq.ms, - t_stop=500. * pq.ms) + sts = r.read_segment(gid_list=(5, 11), t_start=400. * un.ms, + t_stop=500. * un.ms) for ID in np.arange(5, 12): self.assertEqual(ID, sts.spiketrains[ID - 5].annotations['id']) @@ -565,8 +565,8 @@ def test_adding_custom_annotation(self): filename='0gid-1time-1256-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - st = r.read_spiketrain(gdf_id=0, t_start=400. * pq.ms, - t_stop=500. * pq.ms, + st = r.read_spiketrain(gdf_id=0, t_start=400. * un.ms, + t_stop=500. * un.ms, layer='L23', population='I') self.assertEqual(0, st.annotations.pop('id')) self.assertEqual('L23', st.annotations.pop('layer')) @@ -585,7 +585,7 @@ def test_wrong_input(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(ValueError): - r.read_segment(t_start=400. * pq.ms, t_stop=500. * pq.ms, + r.read_segment(t_start=400. * un.ms, t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) with self.assertRaises(ValueError): @@ -601,8 +601,8 @@ def test_t_start_t_stop(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - t_stop_targ = 490. * pq.ms - t_start_targ = 410. * pq.ms + t_stop_targ = 490. * un.ms + t_start_targ = 410. * un.ms seg = r.read_segment(gid_list=[], t_start=t_start_targ, t_stop=t_stop_targ, lazy=False, @@ -625,10 +625,10 @@ def test_t_start_undefined_raises_error(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(ValueError): - r.read_spiketrain(gdf_id=1, t_stop=500. * pq.ms, lazy=False, + r.read_spiketrain(gdf_id=1, t_stop=500. * un.ms, lazy=False, id_column=0, time_column=1) with self.assertRaises(ValueError): - r.read_segment(gid_list=[1, 2, 3], t_stop=500. * pq.ms, lazy=False, + r.read_segment(gid_list=[1, 2, 3], t_stop=500. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) def test_t_stop_undefined_raises_error(self): @@ -641,10 +641,10 @@ def test_t_stop_undefined_raises_error(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(ValueError): - r.read_spiketrain(gdf_id=1, t_start=400. * pq.ms, lazy=False, + r.read_spiketrain(gdf_id=1, t_start=400. * un.ms, lazy=False, id_column=0, time_column=1) with self.assertRaises(ValueError): - r.read_segment(gid_list=[1, 2, 3], t_start=400. * pq.ms, lazy=False, + r.read_segment(gid_list=[1, 2, 3], t_start=400. * un.ms, lazy=False, id_column_gdf=0, time_column_gdf=1) def test_gdf_id_illdefined_raises_error(self): @@ -658,13 +658,13 @@ def test_gdf_id_illdefined_raises_error(self): directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) with self.assertRaises(ValueError): - r.read_spiketrain(gdf_id=[], t_start=400. * pq.ms, - t_stop=500. * pq.ms) + r.read_spiketrain(gdf_id=[], t_start=400. * un.ms, + t_stop=500. * un.ms) with self.assertRaises(ValueError): - r.read_spiketrain(gdf_id=[1], t_start=400. * pq.ms, - t_stop=500. * pq.ms) + r.read_spiketrain(gdf_id=[1], t_start=400. * un.ms, + t_stop=500. * un.ms) with self.assertRaises(ValueError): - r.read_spiketrain(t_start=400. * pq.ms, t_stop=500. * pq.ms) + r.read_spiketrain(t_start=400. * un.ms, t_stop=500. * un.ms) def test_read_segment_can_return_empty_spiketrains(self): """ @@ -676,8 +676,8 @@ def test_read_segment_can_return_empty_spiketrains(self): filename='0gid-1time-1256-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - seg = r.read_segment(gid_list=[], t_start=400. * pq.ms, - t_stop=1. * pq.ms) + seg = r.read_segment(gid_list=[], t_start=400. * un.ms, + t_stop=1. * un.ms) for st in seg.spiketrains: self.assertEqual(st.size, 0) @@ -691,11 +691,11 @@ def test_read_spiketrain_can_return_empty_spiketrain(self): filename='0gid-1time-1256-0.gdf', directory=self.local_test_dir, clean=False) r = NestIO(filenames=filename) - st = r.read_spiketrain(gdf_id=0, t_start=400. * pq.ms, - t_stop=1. * pq.ms) + st = r.read_spiketrain(gdf_id=0, t_start=400. * un.ms, + t_stop=1. * un.ms) self.assertEqual(st.size, 0) - + class TestNestIO_multiple_signal_types(BaseTestIO, unittest.TestCase): ioclass = NestIO files_to_test = [] @@ -714,8 +714,8 @@ def test_read_analogsignal_and_spiketrain(self): clean=False) for file in files] r = NestIO(filenames=filenames) - seg = r.read_segment(gid_list=[], t_start=400 * pq.ms, - t_stop=600 * pq.ms, + seg = r.read_segment(gid_list=[], t_start=400 * un.ms, + t_stop=600 * un.ms, id_column_gdf=0, time_column_gdf=1, id_column_dat=0, time_column_dat=1, value_columns_dat=2) diff --git a/neo/test/iotest/test_nixio.py b/neo/test/iotest/test_nixio.py index 757309fb0..8d7a71a60 100644 --- a/neo/test/iotest/test_nixio.py +++ b/neo/test/iotest/test_nixio.py @@ -27,7 +27,7 @@ import itertools import numpy as np -import quantities as pq +from neo import units as un from neo.core import (Block, Segment, ChannelIndex, AnalogSignal, IrregularlySampledSignal, Unit, SpikeTrain, Event, Epoch) @@ -191,7 +191,7 @@ def compare_signal_dalist(self, neosig, nixdalist): if isinstance(neosig, AnalogSignal): self.assertIsInstance(timedim, nix.pycore.SampledDimension) self.assertEqual( - pq.Quantity(timedim.sampling_interval, timedim.unit), + un.Quantity(timedim.sampling_interval, timedim.unit), neosig.sampling_period ) self.assertEqual(timedim.offset, neosig.t_start.magnitude) @@ -286,7 +286,7 @@ def compare_attr(self, neoobj, nixobj): if neoobj.annotations: nixmd = nixobj.metadata for k, v, in neoobj.annotations.items(): - if isinstance(v, pq.Quantity): + if isinstance(v, un.Quantity): self.assertEqual(nixmd.props[str(k)].unit, str(v.dimensionality)) np.testing.assert_almost_equal(nixmd[str(k)], @@ -562,8 +562,8 @@ def rquant(shape, unit, incr=False): @classmethod def create_all_annotated(cls): - times = cls.rquant(1, pq.s) - signal = cls.rquant(1, pq.V) + times = cls.rquant(1, un.s) + signal = cls.rquant(1, un.V) blk = Block() blk.annotate(**cls.rdict(3)) @@ -571,12 +571,12 @@ def create_all_annotated(cls): seg.annotate(**cls.rdict(4)) blk.segments.append(seg) - asig = AnalogSignal(signal=signal, sampling_rate=pq.Hz) + asig = AnalogSignal(signal=signal, sampling_rate=un.Hz) asig.annotate(**cls.rdict(2)) seg.analogsignals.append(asig) isig = IrregularlySampledSignal(times=times, signal=signal, - time_units=pq.s) + time_units=un.s) isig.annotate(**cls.rdict(2)) seg.irregularlysampledsignals.append(isig) @@ -588,10 +588,10 @@ def create_all_annotated(cls): event.annotate(**cls.rdict(4)) seg.events.append(event) - spiketrain = SpikeTrain(times=times, t_stop=pq.s, units=pq.s) + spiketrain = SpikeTrain(times=times, t_stop=un.s, units=un.s) d = cls.rdict(6) - d["quantity"] = pq.Quantity(10, "mV") - d["qarray"] = pq.Quantity(range(10), "mA") + d["quantity"] = un.Quantity(10, "mV") + d["qarray"] = un.Quantity(range(10), "mA") spiketrain.annotate(**d) seg.spiketrains.append(spiketrain) @@ -658,8 +658,8 @@ def test_signals_write(self): seg = Segment() block.segments.append(seg) - asig = AnalogSignal(signal=self.rquant((10, 3), pq.mV), - sampling_rate=pq.Quantity(10, "Hz")) + asig = AnalogSignal(signal=self.rquant((10, 3), un.mV), + sampling_rate=un.Quantity(10, "Hz")) seg.analogsignals.append(asig) self.write_and_compare([block]) @@ -668,18 +668,18 @@ def test_signals_write(self): anotherblock.segments.append(seg) irsig = IrregularlySampledSignal( signal=np.random.random((20, 3)), - times=self.rquant(20, pq.ms, True), - units=pq.A + times=self.rquant(20, un.ms, True), + units=un.A ) seg.irregularlysampledsignals.append(irsig) self.write_and_compare([anotherblock]) block.segments[0].analogsignals.append( - AnalogSignal(signal=[10.0, 1.0, 3.0], units=pq.S, - sampling_period=pq.Quantity(3, "s"), + AnalogSignal(signal=[10.0, 1.0, 3.0], units=un.S, + sampling_period=un.Quantity(3, "s"), dtype=np.double, name="signal42", description="this is an analogsignal", - t_start=45 * pq.ms), + t_start=45 * un.ms), ) self.write_and_compare([block, anotherblock]) @@ -698,7 +698,7 @@ def test_epoch_write(self): seg = Segment() block.segments.append(seg) - epoch = Epoch(times=[1, 1, 10, 3]*pq.ms, durations=[3, 3, 3, 1]*pq.ms, + epoch = Epoch(times=[1, 1, 10, 3]*un.ms, durations=[3, 3, 3, 1]*un.ms, labels=np.array(["one", "two", "three", "four"]), name="test epoch", description="an epoch for testing") @@ -710,7 +710,7 @@ def test_event_write(self): seg = Segment() block.segments.append(seg) - event = Event(times=np.arange(0, 30, 10)*pq.s, + event = Event(times=np.arange(0, 30, 10)*un.s, labels=np.array(["0", "1", "2"]), name="event name", description="event description") @@ -722,13 +722,13 @@ def test_spiketrain_write(self): seg = Segment() block.segments.append(seg) - spiketrain = SpikeTrain(times=[3, 4, 5]*pq.s, t_stop=10.0, + spiketrain = SpikeTrain(times=[3, 4, 5]*un.s, t_stop=10.0, name="spikes!", description="sssssspikes") seg.spiketrains.append(spiketrain) self.write_and_compare([block]) - waveforms = self.rquant((3, 5, 10), pq.mV) - spiketrain = SpikeTrain(times=[1, 1.1, 1.2]*pq.ms, t_stop=1.5*pq.s, + waveforms = self.rquant((3, 5, 10), un.mV) + spiketrain = SpikeTrain(times=[1, 1.1, 1.2]*un.ms, t_stop=1.5*un.s, name="spikes with wf", description="spikes for waveform test", waveforms=waveforms) @@ -736,7 +736,7 @@ def test_spiketrain_write(self): seg.spiketrains.append(spiketrain) self.write_and_compare([block]) - spiketrain.left_sweep = np.random.random(10)*pq.ms + spiketrain.left_sweep = np.random.random(10)*un.ms self.write_and_compare([block]) def test_metadata_structure_write(self): @@ -776,8 +776,8 @@ def test_anonymous_objects_write(self): nchx = 5 nunits = 10 - times = self.rquant(1, pq.s) - signal = self.rquant(1, pq.V) + times = self.rquant(1, un.s) + signal = self.rquant(1, un.V) blocks = [] for blkidx in range(nblocks): blk = Block() @@ -787,20 +787,20 @@ def test_anonymous_objects_write(self): blk.segments.append(seg) for anaidx in range(nanasig): seg.analogsignals.append(AnalogSignal(signal=signal, - sampling_rate=pq.Hz)) + sampling_rate=un.Hz)) for irridx in range(nirrseg): seg.irregularlysampledsignals.append( IrregularlySampledSignal(times=times, signal=signal, - time_units=pq.s) + time_units=un.s) ) for epidx in range(nepochs): seg.epochs.append(Epoch(times=times, durations=times)) for evidx in range(nevents): seg.events.append(Event(times=times)) for stidx in range(nspiketrains): - seg.spiketrains.append(SpikeTrain(times=times, t_stop=pq.s, - units=pq.s)) + seg.spiketrains.append(SpikeTrain(times=times, t_stop=un.s, + units=un.s)) for chidx in range(nchx): chx = ChannelIndex(name="chx{}".format(chidx), index=[1, 2]) @@ -817,7 +817,7 @@ def test_to_value(self): writeprop = self.io._write_property # quantity - qvalue = pq.Quantity(10, "mV") + qvalue = un.Quantity(10, "mV") writeprop(section, "qvalue", qvalue) self.assertEqual(section["qvalue"], 10) self.assertEqual(section.props["qvalue"].unit, "mV") @@ -997,7 +997,7 @@ def test_block_seg_hash(self): "file_datetime": self.rdate, # annotations self.rword(): self.rword, - self.rword(): lambda: self.rquant((10, 10), pq.mV)} + self.rword(): lambda: self.rquant((10, 10), un.mV)} self._hash_test(Block, argfuncs) self._hash_test(Segment, argfuncs) self._hash_test(Unit, argfuncs) @@ -1007,58 +1007,58 @@ def test_chx_hash(self): "description": self.rsentence, "index": lambda: np.random.random(10).tolist(), "channel_names": lambda: self.rsentence(10).split(" "), - "coordinates": lambda: [(np.random.random() * pq.cm, - np.random.random() * pq.cm, - np.random.random() * pq.cm)]*10, + "coordinates": lambda: [(np.random.random() * un.cm, + np.random.random() * un.cm, + np.random.random() * un.cm)]*10, # annotations self.rword(): self.rword, - self.rword(): lambda: self.rquant((10, 10), pq.mV)} + self.rword(): lambda: self.rquant((10, 10), un.mV)} self._hash_test(ChannelIndex, argfuncs) def test_analogsignal_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, - "signal": lambda: self.rquant((10, 10), pq.mV), - "sampling_rate": lambda: np.random.random() * pq.Hz, - "t_start": lambda: np.random.random() * pq.sec, - "t_stop": lambda: np.random.random() * pq.sec, + "signal": lambda: self.rquant((10, 10), un.mV), + "sampling_rate": lambda: np.random.random() * un.Hz, + "t_start": lambda: np.random.random() * un.sec, + "t_stop": lambda: np.random.random() * un.sec, # annotations self.rword(): self.rword, - self.rword(): lambda: self.rquant((10, 10), pq.mV)} + self.rword(): lambda: self.rquant((10, 10), un.mV)} self._hash_test(AnalogSignal, argfuncs) def test_irregularsignal_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, - "signal": lambda: self.rquant((10, 10), pq.mV), - "times": lambda: self.rquant(10, pq.ms, True), + "signal": lambda: self.rquant((10, 10), un.mV), + "times": lambda: self.rquant(10, un.ms, True), # annotations self.rword(): self.rword, - self.rword(): lambda: self.rquant((10, 10), pq.mV)} + self.rword(): lambda: self.rquant((10, 10), un.mV)} self._hash_test(IrregularlySampledSignal, argfuncs) def test_event_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, - "times": lambda: self.rquant(10, pq.ms), - "durations": lambda: self.rquant(10, pq.ms), + "times": lambda: self.rquant(10, un.ms), + "durations": lambda: self.rquant(10, un.ms), "labels": lambda: self.rsentence(10).split(" "), # annotations self.rword(): self.rword, - self.rword(): lambda: self.rquant((10, 10), pq.mV)} + self.rword(): lambda: self.rquant((10, 10), un.mV)} self._hash_test(Event, argfuncs) self._hash_test(Epoch, argfuncs) def test_spiketrain_hash(self): argfuncs = {"name": self.rword, "description": self.rsentence, - "times": lambda: self.rquant(10, pq.ms, True), - "t_start": lambda: -np.random.random() * pq.sec, - "t_stop": lambda: np.random.random() * 100 * pq.sec, - "waveforms": lambda: self.rquant((10, 10, 20), pq.mV), + "times": lambda: self.rquant(10, un.ms, True), + "t_start": lambda: -np.random.random() * un.sec, + "t_stop": lambda: np.random.random() * 100 * un.sec, + "waveforms": lambda: self.rquant((10, 10, 20), un.mV), # annotations self.rword(): self.rword, - self.rword(): lambda: self.rquant((10, 10), pq.mV)} + self.rword(): lambda: self.rquant((10, 10), un.mV)} self._hash_test(SpikeTrain, argfuncs) diff --git a/neo/test/iotest/test_pynnio.py b/neo/test/iotest/test_pynnio.py index 9d7a580ff..e25c21f48 100644 --- a/neo/test/iotest/test_pynnio.py +++ b/neo/test/iotest/test_pynnio.py @@ -14,7 +14,7 @@ import unittest import numpy as np -import quantities as pq +from neo import units as un from neo.core import Segment, AnalogSignal, SpikeTrain from neo.io import PyNNNumpyIO, PyNNTextIO @@ -105,16 +105,16 @@ def test_read_segment_containing_analogsignals_using_eager_cascade(self): self.assertEqual(as0.shape, (101, NCELLS)) assert_array_equal(as0[:, 0], AnalogSignal(np.arange(0, 101, dtype=float), - sampling_period=0.1*pq.ms, - t_start=0*pq.s, - units=pq.mV)) + sampling_period=0.1*un.ms, + t_start=0*un.s, + units=un.mV)) as4 = as0[:, 4] self.assertIsInstance(as4, AnalogSignal) assert_array_equal(as4, AnalogSignal(np.arange(4, 105, dtype=float), - sampling_period=0.1*pq.ms, - t_start=0*pq.s, - units=pq.mV)) + sampling_period=0.1*un.ms, + t_start=0*un.s, + units=un.mV)) # test annotations (stuff from file metadata) def test_read_analogsignal_using_eager(self): @@ -123,9 +123,9 @@ def test_read_analogsignal_using_eager(self): self.assertIsInstance(sig, AnalogSignal) assert_array_equal(sig[:, 3], AnalogSignal(np.arange(3, 104, dtype=float), - sampling_period=0.1*pq.ms, - t_start=0*pq.s, - units=pq.mV)) + sampling_period=0.1*un.ms, + t_start=0*un.s, + units=un.mV)) # should test annotations: 'channel_index', etc. def test_read_spiketrain_should_fail_with_analogsignal_file(self): @@ -147,16 +147,16 @@ def test_read_segment_containing_spiketrains_using_eager_cascade(self): self.assertIsInstance(st0, SpikeTrain) assert_arrays_equal(st0, SpikeTrain(np.arange(0, 101, dtype=float), - t_start=0*pq.s, - t_stop=101*pq.ms, - units=pq.ms)) + t_start=0*un.s, + t_stop=101*un.ms, + units=un.ms)) st4 = segment.spiketrains[4] self.assertIsInstance(st4, SpikeTrain) assert_arrays_equal(st4, SpikeTrain(np.arange(4, 105, dtype=float), - t_start=0*pq.s, - t_stop=105*pq.ms, - units=pq.ms)) + t_start=0*un.s, + t_stop=105*un.ms, + units=un.ms)) # test annotations (stuff from file metadata) def test_read_spiketrain_using_eager(self): @@ -165,9 +165,9 @@ def test_read_spiketrain_using_eager(self): self.assertIsInstance(st3, SpikeTrain) assert_arrays_equal(st3, SpikeTrain(np.arange(3, 104, dtype=float), - t_start=0*pq.s, - t_stop=104*pq.s, - units=pq.ms)) + t_start=0*un.s, + t_stop=104*un.s, + units=un.ms)) # should test annotations: 'channel_index', etc. def test_read_analogsignal_should_fail_with_spiketrain_file(self): diff --git a/neo/test/testfile_partialwrite.h5 b/neo/test/testfile_partialwrite.h5 new file mode 100644 index 000000000..0d370d393 Binary files /dev/null and b/neo/test/testfile_partialwrite.h5 differ diff --git a/neo/test/testfile_readtest.h5 b/neo/test/testfile_readtest.h5 new file mode 100644 index 000000000..f254900c6 Binary files /dev/null and b/neo/test/testfile_readtest.h5 differ diff --git a/neo/test/tools.py b/neo/test/tools.py index 91ac4d0bf..0d8c4d3b4 100644 --- a/neo/test/tools.py +++ b/neo/test/tools.py @@ -7,7 +7,7 @@ import os import numpy as np -import quantities as pq +from neo import units as un import neo from neo.core import objectlist @@ -121,7 +121,7 @@ def assert_neo_object_is_compliant(ob): if (hasattr(ob, '_quantity_attr') and ob._quantity_attr == attrname and - (attrtype == pq.Quantity or attrtype == np.ndarray)): + (attrtype == un.Quantity or attrtype == np.ndarray)): # object inherits from Quantity (AnalogSignal, SpikeTrain, ...) ndim = ioattr[2] assert ob.ndim == ndim, \ @@ -139,7 +139,7 @@ def assert_neo_object_is_compliant(ob): assert issubclass(type(obattr), attrtype), \ '%s in %s is %s should be %s' % \ (attrname, classname, type(obattr), attrtype) - if attrtype == pq.Quantity or attrtype == np.ndarray: + if attrtype == un.Quantity or attrtype == np.ndarray: ndim = ioattr[2] assert obattr.ndim == ndim, \ '%s.%s dimension is %d should be %d' % \ @@ -313,7 +313,7 @@ def assert_same_attributes(ob1, ob2, equal_almost=True, threshold=1e-10, getattr(ob2, attrname)) continue - if attrtype == pq.Quantity: + if attrtype == un.Quantity: # Compare magnitudes mag1 = getattr(ob1, attrname).magnitude mag2 = getattr(ob2, attrname).magnitude @@ -425,7 +425,7 @@ def assert_sub_schema_is_lazy_loaded(ob): if not hasattr(ob, attrname) or getattr(ob, attrname) is None: continue #~ print 'hjkjh' - if (attrtype == pq.Quantity or attrtype == np.ndarray): + if (attrtype == un.Quantity or attrtype == np.ndarray): # FIXME: it is a workaround for recordingChannelGroup.channel_names # which is nupy.array but allowed to be loaded when lazy == True diff --git a/neo/units.py b/neo/units.py new file mode 100644 index 000000000..7bad10e59 --- /dev/null +++ b/neo/units.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +""" +This module defines aim to replace the quantities module for others neo modules. + +""" + +# needed for python 3 compatibility +from __future__ import absolute_import, division, print_function + +from quantities import * +