Scheduled service maintenance on November 22


On Friday, November 22, 2024, between 06:00 CET and 18:00 CET, GIN services will undergo planned maintenance. Extended service interruptions should be expected. We will try to keep downtimes to a minimum, but recommend that users avoid critical tasks, large data uploads, or DOI requests during this time.

We apologize for any inconvenience.

spiketrain.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. # -*- coding: utf-8 -*-
  2. '''
  3. This module implements :class:`SpikeTrain`, an array of spike times.
  4. :class:`SpikeTrain` derives from :class:`BaseNeo`, from
  5. :module:`neo.core.baseneo`, and from :class:`quantites.Quantity`, which
  6. inherits from :class:`numpy.array`.
  7. Inheritance from :class:`numpy.array` is explained here:
  8. http://docs.scipy.org/doc/numpy/user/basics.subclassing.html
  9. In brief:
  10. * Initialization of a new object from constructor happens in :meth:`__new__`.
  11. This is where user-specified attributes are set.
  12. * :meth:`__array_finalize__` is called for all new objects, including those
  13. created by slicing. This is where attributes are copied over from
  14. the old object.
  15. '''
  16. # needed for python 3 compatibility
  17. from __future__ import absolute_import, division, print_function
  18. import sys
  19. import copy
  20. import numpy as np
  21. import quantities as pq
  22. from neo.core.baseneo import BaseNeo, MergeError, merge_annotations
  23. def check_has_dimensions_time(*values):
  24. '''
  25. Verify that all arguments have a dimensionality that is compatible
  26. with time.
  27. '''
  28. errmsgs = []
  29. for value in values:
  30. dim = value.dimensionality
  31. if (len(dim) != 1 or list(dim.values())[0] != 1 or
  32. not isinstance(list(dim.keys())[0], pq.UnitTime)):
  33. errmsgs.append("value %s has dimensions %s, not [time]" %
  34. (value, dim.simplified))
  35. if errmsgs:
  36. raise ValueError("\n".join(errmsgs))
  37. def _check_time_in_range(value, t_start, t_stop, view=False):
  38. '''
  39. Verify that all times in :attr:`value` are between :attr:`t_start`
  40. and :attr:`t_stop` (inclusive.
  41. If :attr:`view` is True, vies are used for the test.
  42. Using drastically increases the speed, but is only safe if you are
  43. certain that the dtype and units are the same
  44. '''
  45. if not value.size:
  46. return
  47. if view:
  48. value = value.view(np.ndarray)
  49. t_start = t_start.view(np.ndarray)
  50. t_stop = t_stop.view(np.ndarray)
  51. if value.min() < t_start:
  52. raise ValueError("The first spike (%s) is before t_start (%s)" %
  53. (value, t_start))
  54. if value.max() > t_stop:
  55. raise ValueError("The last spike (%s) is after t_stop (%s)" %
  56. (value, t_stop))
  57. def _check_waveform_dimensions(spiketrain):
  58. '''
  59. Verify that waveform is compliant with the waveform definition as
  60. quantity array 3D (spike, channel_index, time)
  61. '''
  62. if not spiketrain.size:
  63. return
  64. waveforms = spiketrain.waveforms
  65. if (waveforms is None) or (not waveforms.size):
  66. return
  67. if waveforms.shape[0] != len(spiketrain):
  68. raise ValueError("Spiketrain length (%s) does not match to number of "
  69. "waveforms present (%s)" % (len(spiketrain),
  70. waveforms.shape[0]))
  71. def _new_spiketrain(cls, signal, t_stop, units=None, dtype=None,
  72. copy=True, sampling_rate=1.0 * pq.Hz,
  73. t_start=0.0 * pq.s, waveforms=None, left_sweep=None,
  74. name=None, file_origin=None, description=None,
  75. annotations=None, segment=None, unit=None):
  76. '''
  77. A function to map :meth:`BaseAnalogSignal.__new__` to function that
  78. does not do the unit checking. This is needed for :module:`pickle` to work.
  79. '''
  80. if annotations is None:
  81. annotations = {}
  82. obj = SpikeTrain(signal, t_stop, units, dtype, copy, sampling_rate,
  83. t_start, waveforms, left_sweep, name, file_origin,
  84. description, **annotations)
  85. obj.segment = segment
  86. obj.unit = unit
  87. return obj
  88. class SpikeTrain(BaseNeo, pq.Quantity):
  89. '''
  90. :class:`SpikeTrain` is a :class:`Quantity` array of spike times.
  91. It is an ensemble of action potentials (spikes) emitted by the same unit
  92. in a period of time.
  93. *Usage*::
  94. >>> from neo.core import SpikeTrain
  95. >>> from quantities import s
  96. >>>
  97. >>> train = SpikeTrain([3, 4, 5]*s, t_stop=10.0)
  98. >>> train2 = train[1:3]
  99. >>>
  100. >>> train.t_start
  101. array(0.0) * s
  102. >>> train.t_stop
  103. array(10.0) * s
  104. >>> train
  105. <SpikeTrain(array([ 3., 4., 5.]) * s, [0.0 s, 10.0 s])>
  106. >>> train2
  107. <SpikeTrain(array([ 4., 5.]) * s, [0.0 s, 10.0 s])>
  108. *Required attributes/properties*:
  109. :times: (quantity array 1D, numpy array 1D, or list) The times of
  110. each spike.
  111. :units: (quantity units) Required if :attr:`times` is a list or
  112. :class:`~numpy.ndarray`, not if it is a
  113. :class:`~quantites.Quantity`.
  114. :t_stop: (quantity scalar, numpy scalar, or float) Time at which
  115. :class:`SpikeTrain` ended. This will be converted to the
  116. same units as :attr:`times`. This argument is required because it
  117. specifies the period of time over which spikes could have occurred.
  118. Note that :attr:`t_start` is highly recommended for the same
  119. reason.
  120. Note: If :attr:`times` contains values outside of the
  121. range [t_start, t_stop], an Exception is raised.
  122. *Recommended attributes/properties*:
  123. :name: (str) A label for the dataset.
  124. :description: (str) Text description.
  125. :file_origin: (str) Filesystem path or URL of the original data file.
  126. :t_start: (quantity scalar, numpy scalar, or float) Time at which
  127. :class:`SpikeTrain` began. This will be converted to the
  128. same units as :attr:`times`.
  129. Default: 0.0 seconds.
  130. :waveforms: (quantity array 3D (spike, channel_index, time))
  131. The waveforms of each spike.
  132. :sampling_rate: (quantity scalar) Number of samples per unit time
  133. for the waveforms.
  134. :left_sweep: (quantity array 1D) Time from the beginning
  135. of the waveform to the trigger time of the spike.
  136. :sort: (bool) If True, the spike train will be sorted by time.
  137. *Optional attributes/properties*:
  138. :dtype: (numpy dtype or str) Override the dtype of the signal array.
  139. :copy: (bool) Whether to copy the times array. True by default.
  140. Must be True when you request a change of units or dtype.
  141. Note: Any other additional arguments are assumed to be user-specific
  142. metadata and stored in :attr:`annotations`.
  143. *Properties available on this object*:
  144. :sampling_period: (quantity scalar) Interval between two samples.
  145. (1/:attr:`sampling_rate`)
  146. :duration: (quantity scalar) Duration over which spikes can occur,
  147. read-only.
  148. (:attr:`t_stop` - :attr:`t_start`)
  149. :spike_duration: (quantity scalar) Duration of a waveform, read-only.
  150. (:attr:`waveform`.shape[2] * :attr:`sampling_period`)
  151. :right_sweep: (quantity scalar) Time from the trigger times of the
  152. spikes to the end of the waveforms, read-only.
  153. (:attr:`left_sweep` + :attr:`spike_duration`)
  154. :times: (:class:`SpikeTrain`) Returns the :class:`SpikeTrain` without
  155. modification or copying.
  156. *Slicing*:
  157. :class:`SpikeTrain` objects can be sliced. When this occurs, a new
  158. :class:`SpikeTrain` (actually a view) is returned, with the same
  159. metadata, except that :attr:`waveforms` is also sliced in the same way
  160. (along dimension 0). Note that t_start and t_stop are not changed
  161. automatically, although you can still manually change them.
  162. '''
  163. _single_parent_objects = ('Segment', 'Unit')
  164. _quantity_attr = 'times'
  165. _necessary_attrs = (('times', pq.Quantity, 1),
  166. ('t_start', pq.Quantity, 0),
  167. ('t_stop', pq.Quantity, 0))
  168. _recommended_attrs = ((('waveforms', pq.Quantity, 3),
  169. ('left_sweep', pq.Quantity, 0),
  170. ('sampling_rate', pq.Quantity, 0)) +
  171. BaseNeo._recommended_attrs)
  172. def __new__(cls, times, t_stop, units=None, dtype=None, copy=True,
  173. sampling_rate=1.0 * pq.Hz, t_start=0.0 * pq.s, waveforms=None,
  174. left_sweep=None, name=None, file_origin=None, description=None,
  175. **annotations):
  176. '''
  177. Constructs a new :clas:`Spiketrain` instance from data.
  178. This is called whenever a new :class:`SpikeTrain` is created from the
  179. constructor, but not when slicing.
  180. '''
  181. if len(times) != 0 and waveforms is not None and len(times) != \
  182. waveforms.shape[
  183. 0]: # len(times)!=0 has been used to workaround a bug occuring during neo import)
  184. raise ValueError(
  185. "the number of waveforms should be equal to the number of spikes")
  186. # Make sure units are consistent
  187. # also get the dimensionality now since it is much faster to feed
  188. # that to Quantity rather than a unit
  189. if units is None:
  190. # No keyword units, so get from `times`
  191. try:
  192. dim = times.units.dimensionality
  193. except AttributeError:
  194. raise ValueError('you must specify units')
  195. else:
  196. if hasattr(units, 'dimensionality'):
  197. dim = units.dimensionality
  198. else:
  199. dim = pq.quantity.validate_dimensionality(units)
  200. if hasattr(times, 'dimensionality'):
  201. if times.dimensionality.items() == dim.items():
  202. units = None # units will be taken from times, avoids copying
  203. else:
  204. if not copy:
  205. raise ValueError("cannot rescale and return view")
  206. else:
  207. # this is needed because of a bug in python-quantities
  208. # see issue # 65 in python-quantities github
  209. # remove this if it is fixed
  210. times = times.rescale(dim)
  211. if dtype is None:
  212. if not hasattr(times, 'dtype'):
  213. dtype = np.float
  214. elif hasattr(times, 'dtype') and times.dtype != dtype:
  215. if not copy:
  216. raise ValueError("cannot change dtype and return view")
  217. # if t_start.dtype or t_stop.dtype != times.dtype != dtype,
  218. # _check_time_in_range can have problems, so we set the t_start
  219. # and t_stop dtypes to be the same as times before converting them
  220. # to dtype below
  221. # see ticket #38
  222. if hasattr(t_start, 'dtype') and t_start.dtype != times.dtype:
  223. t_start = t_start.astype(times.dtype)
  224. if hasattr(t_stop, 'dtype') and t_stop.dtype != times.dtype:
  225. t_stop = t_stop.astype(times.dtype)
  226. # check to make sure the units are time
  227. # this approach is orders of magnitude faster than comparing the
  228. # reference dimensionality
  229. if (len(dim) != 1 or list(dim.values())[0] != 1 or
  230. not isinstance(list(dim.keys())[0], pq.UnitTime)):
  231. ValueError("Unit has dimensions %s, not [time]" % dim.simplified)
  232. # Construct Quantity from data
  233. obj = pq.Quantity(times, units=units, dtype=dtype, copy=copy).view(cls)
  234. # if the dtype and units match, just copy the values here instead
  235. # of doing the much more expensive creation of a new Quantity
  236. # using items() is orders of magnitude faster
  237. if (hasattr(t_start, 'dtype') and t_start.dtype == obj.dtype and
  238. hasattr(t_start, 'dimensionality') and
  239. t_start.dimensionality.items() == dim.items()):
  240. obj.t_start = t_start.copy()
  241. else:
  242. obj.t_start = pq.Quantity(t_start, units=dim, dtype=obj.dtype)
  243. if (hasattr(t_stop, 'dtype') and t_stop.dtype == obj.dtype and
  244. hasattr(t_stop, 'dimensionality') and
  245. t_stop.dimensionality.items() == dim.items()):
  246. obj.t_stop = t_stop.copy()
  247. else:
  248. obj.t_stop = pq.Quantity(t_stop, units=dim, dtype=obj.dtype)
  249. # Store attributes
  250. obj.waveforms = waveforms
  251. obj.left_sweep = left_sweep
  252. obj.sampling_rate = sampling_rate
  253. # parents
  254. obj.segment = None
  255. obj.unit = None
  256. # Error checking (do earlier?)
  257. _check_time_in_range(obj, obj.t_start, obj.t_stop, view=True)
  258. return obj
  259. def __init__(self, times, t_stop, units=None, dtype=np.float,
  260. copy=True, sampling_rate=1.0 * pq.Hz, t_start=0.0 * pq.s,
  261. waveforms=None, left_sweep=None, name=None, file_origin=None,
  262. description=None, **annotations):
  263. '''
  264. Initializes a newly constructed :class:`SpikeTrain` instance.
  265. '''
  266. # This method is only called when constructing a new SpikeTrain,
  267. # not when slicing or viewing. We use the same call signature
  268. # as __new__ for documentation purposes. Anything not in the call
  269. # signature is stored in annotations.
  270. # Calls parent __init__, which grabs universally recommended
  271. # attributes and sets up self.annotations
  272. BaseNeo.__init__(self, name=name, file_origin=file_origin,
  273. description=description, **annotations)
  274. def rescale(self, units):
  275. '''
  276. Return a copy of the :class:`SpikeTrain` converted to the specified
  277. units
  278. '''
  279. if self.dimensionality == pq.quantity.validate_dimensionality(units):
  280. return self.copy()
  281. spikes = self.view(pq.Quantity)
  282. obj = SpikeTrain(times=spikes, t_stop=self.t_stop, units=units,
  283. sampling_rate=self.sampling_rate,
  284. t_start=self.t_start, waveforms=self.waveforms,
  285. left_sweep=self.left_sweep, name=self.name,
  286. file_origin=self.file_origin,
  287. description=self.description, **self.annotations)
  288. obj.segment = self.segment
  289. obj.unit = self.unit
  290. return obj
  291. def __reduce__(self):
  292. '''
  293. Map the __new__ function onto _new_BaseAnalogSignal, so that pickle
  294. works
  295. '''
  296. import numpy
  297. return _new_spiketrain, (self.__class__, numpy.array(self),
  298. self.t_stop, self.units, self.dtype, True,
  299. self.sampling_rate, self.t_start,
  300. self.waveforms, self.left_sweep,
  301. self.name, self.file_origin, self.description,
  302. self.annotations, self.segment, self.unit)
  303. def __array_finalize__(self, obj):
  304. '''
  305. This is called every time a new :class:`SpikeTrain` is created.
  306. It is the appropriate place to set default values for attributes
  307. for :class:`SpikeTrain` constructed by slicing or viewing.
  308. User-specified values are only relevant for construction from
  309. constructor, and these are set in __new__. Then they are just
  310. copied over here.
  311. Note that the :attr:`waveforms` attibute is not sliced here. Nor is
  312. :attr:`t_start` or :attr:`t_stop` modified.
  313. '''
  314. # This calls Quantity.__array_finalize__ which deals with
  315. # dimensionality
  316. super(SpikeTrain, self).__array_finalize__(obj)
  317. # Supposedly, during initialization from constructor, obj is supposed
  318. # to be None, but this never happens. It must be something to do
  319. # with inheritance from Quantity.
  320. if obj is None:
  321. return
  322. # Set all attributes of the new object `self` from the attributes
  323. # of `obj`. For instance, when slicing, we want to copy over the
  324. # attributes of the original object.
  325. self.t_start = getattr(obj, 't_start', None)
  326. self.t_stop = getattr(obj, 't_stop', None)
  327. self.waveforms = getattr(obj, 'waveforms', None)
  328. self.left_sweep = getattr(obj, 'left_sweep', None)
  329. self.sampling_rate = getattr(obj, 'sampling_rate', None)
  330. self.segment = getattr(obj, 'segment', None)
  331. self.unit = getattr(obj, 'unit', None)
  332. # The additional arguments
  333. self.annotations = getattr(obj, 'annotations', {})
  334. # Globally recommended attributes
  335. self.name = getattr(obj, 'name', None)
  336. self.file_origin = getattr(obj, 'file_origin', None)
  337. self.description = getattr(obj, 'description', None)
  338. if hasattr(obj, 'lazy_shape'):
  339. self.lazy_shape = obj.lazy_shape
  340. def __repr__(self):
  341. '''
  342. Returns a string representing the :class:`SpikeTrain`.
  343. '''
  344. return '<SpikeTrain(%s, [%s, %s])>' % (
  345. super(SpikeTrain, self).__repr__(), self.t_start, self.t_stop)
  346. def sort(self):
  347. '''
  348. Sorts the :class:`SpikeTrain` and its :attr:`waveforms`, if any,
  349. by time.
  350. '''
  351. # sort the waveforms by the times
  352. sort_indices = np.argsort(self)
  353. if self.waveforms is not None and self.waveforms.any():
  354. self.waveforms = self.waveforms[sort_indices]
  355. # now sort the times
  356. # We have sorted twice, but `self = self[sort_indices]` introduces
  357. # a dependency on the slicing functionality of SpikeTrain.
  358. super(SpikeTrain, self).sort()
  359. def __getslice__(self, i, j):
  360. '''
  361. Get a slice from :attr:`i` to :attr:`j`.
  362. Doesn't get called in Python 3, :meth:`__getitem__` is called instead
  363. '''
  364. return self.__getitem__(slice(i, j))
  365. def __add__(self, time):
  366. '''
  367. Shifts the time point of all spikes by adding the amount in
  368. :attr:`time` (:class:`Quantity`)
  369. Raises an exception if new time points fall outside :attr:`t_start` or
  370. :attr:`t_stop`
  371. '''
  372. spikes = self.view(pq.Quantity)
  373. check_has_dimensions_time(time)
  374. _check_time_in_range(spikes + time, self.t_start, self.t_stop)
  375. return SpikeTrain(times=spikes + time, t_stop=self.t_stop,
  376. units=self.units, sampling_rate=self.sampling_rate,
  377. t_start=self.t_start, waveforms=self.waveforms,
  378. left_sweep=self.left_sweep, name=self.name,
  379. file_origin=self.file_origin,
  380. description=self.description, **self.annotations)
  381. def __sub__(self, time):
  382. '''
  383. Shifts the time point of all spikes by subtracting the amount in
  384. :attr:`time` (:class:`Quantity`)
  385. Raises an exception if new time points fall outside :attr:`t_start` or
  386. :attr:`t_stop`
  387. '''
  388. spikes = self.view(pq.Quantity)
  389. check_has_dimensions_time(time)
  390. _check_time_in_range(spikes - time, self.t_start, self.t_stop)
  391. return SpikeTrain(times=spikes - time, t_stop=self.t_stop,
  392. units=self.units, sampling_rate=self.sampling_rate,
  393. t_start=self.t_start, waveforms=self.waveforms,
  394. left_sweep=self.left_sweep, name=self.name,
  395. file_origin=self.file_origin,
  396. description=self.description, **self.annotations)
  397. def __getitem__(self, i):
  398. '''
  399. Get the item or slice :attr:`i`.
  400. '''
  401. obj = super(SpikeTrain, self).__getitem__(i)
  402. if hasattr(obj, 'waveforms') and obj.waveforms is not None:
  403. obj.waveforms = obj.waveforms.__getitem__(i)
  404. return obj
  405. def __setitem__(self, i, value):
  406. '''
  407. Set the value the item or slice :attr:`i`.
  408. '''
  409. if not hasattr(value, "units"):
  410. value = pq.Quantity(value, units=self.units)
  411. # or should we be strict: raise ValueError("Setting a value
  412. # requires a quantity")?
  413. # check for values outside t_start, t_stop
  414. _check_time_in_range(value, self.t_start, self.t_stop)
  415. super(SpikeTrain, self).__setitem__(i, value)
  416. def __setslice__(self, i, j, value):
  417. if not hasattr(value, "units"):
  418. value = pq.Quantity(value, units=self.units)
  419. _check_time_in_range(value, self.t_start, self.t_stop)
  420. super(SpikeTrain, self).__setslice__(i, j, value)
  421. def _copy_data_complement(self, other, deep_copy=False):
  422. '''
  423. Copy the metadata from another :class:`SpikeTrain`.
  424. '''
  425. for attr in ("left_sweep", "sampling_rate", "name", "file_origin",
  426. "description", "annotations"):
  427. attr_value = getattr(other, attr, None)
  428. if deep_copy:
  429. attr_value = copy.deepcopy(attr_value)
  430. setattr(self, attr, attr_value)
  431. def duplicate_with_new_data(self, signal, t_start=None, t_stop=None,
  432. waveforms=None, deep_copy=True):
  433. '''
  434. Create a new :class:`SpikeTrain` with the same metadata
  435. but different data (times, t_start, t_stop)
  436. '''
  437. # using previous t_start and t_stop if no values are provided
  438. if t_start is None:
  439. t_start = self.t_start
  440. if t_stop is None:
  441. t_stop = self.t_stop
  442. if waveforms is None:
  443. waveforms = self.waveforms
  444. new_st = self.__class__(signal, t_start=t_start, t_stop=t_stop,
  445. waveforms=waveforms, units=self.units)
  446. new_st._copy_data_complement(self, deep_copy=deep_copy)
  447. # overwriting t_start and t_stop with new values
  448. new_st.t_start = t_start
  449. new_st.t_stop = t_stop
  450. # consistency check
  451. _check_time_in_range(new_st, new_st.t_start, new_st.t_stop, view=False)
  452. _check_waveform_dimensions(new_st)
  453. return new_st
  454. def time_slice(self, t_start, t_stop):
  455. '''
  456. Creates a new :class:`SpikeTrain` corresponding to the time slice of
  457. the original :class:`SpikeTrain` between (and including) times
  458. :attr:`t_start` and :attr:`t_stop`. Either parameter can also be None
  459. to use infinite endpoints for the time interval.
  460. '''
  461. _t_start = t_start
  462. _t_stop = t_stop
  463. if t_start is None:
  464. _t_start = -np.inf
  465. if t_stop is None:
  466. _t_stop = np.inf
  467. indices = (self >= _t_start) & (self <= _t_stop)
  468. new_st = self[indices]
  469. new_st.t_start = max(_t_start, self.t_start)
  470. new_st.t_stop = min(_t_stop, self.t_stop)
  471. if self.waveforms is not None:
  472. new_st.waveforms = self.waveforms[indices]
  473. return new_st
  474. def merge(self, other):
  475. '''
  476. Merge another :class:`SpikeTrain` into this one.
  477. The times of the :class:`SpikeTrain` objects combined in one array
  478. and sorted.
  479. If the attributes of the two :class:`SpikeTrain` are not
  480. compatible, an Exception is raised.
  481. '''
  482. if self.sampling_rate != other.sampling_rate:
  483. raise MergeError("Cannot merge, different sampling rates")
  484. if self.t_start != other.t_start:
  485. raise MergeError("Cannot merge, different t_start")
  486. if self.t_stop != other.t_stop:
  487. raise MemoryError("Cannot merge, different t_stop")
  488. if self.left_sweep != other.left_sweep:
  489. raise MemoryError("Cannot merge, different left_sweep")
  490. if self.segment != other.segment:
  491. raise MergeError("Cannot merge these two signals as they belong to"
  492. " different segments.")
  493. if hasattr(self, "lazy_shape"):
  494. if hasattr(other, "lazy_shape"):
  495. merged_lazy_shape = (self.lazy_shape[0] + other.lazy_shape[0])
  496. else:
  497. raise MergeError("Cannot merge a lazy object with a real"
  498. " object.")
  499. if other.units != self.units:
  500. other = other.rescale(self.units)
  501. wfs = [self.waveforms is not None, other.waveforms is not None]
  502. if any(wfs) and not all(wfs):
  503. raise MergeError("Cannot merge signal with waveform and signal "
  504. "without waveform.")
  505. stack = np.concatenate((np.asarray(self), np.asarray(other)))
  506. sorting = np.argsort(stack)
  507. stack = stack[sorting]
  508. kwargs = {}
  509. for name in ("name", "description", "file_origin"):
  510. attr_self = getattr(self, name)
  511. attr_other = getattr(other, name)
  512. if attr_self == attr_other:
  513. kwargs[name] = attr_self
  514. else:
  515. kwargs[name] = "merge(%s, %s)" % (attr_self, attr_other)
  516. merged_annotations = merge_annotations(self.annotations,
  517. other.annotations)
  518. kwargs.update(merged_annotations)
  519. train = SpikeTrain(stack, units=self.units, dtype=self.dtype,
  520. copy=False, t_start=self.t_start,
  521. t_stop=self.t_stop,
  522. sampling_rate=self.sampling_rate,
  523. left_sweep=self.left_sweep, **kwargs)
  524. if all(wfs):
  525. wfs_stack = np.vstack((self.waveforms, other.waveforms))
  526. wfs_stack = wfs_stack[sorting]
  527. train.waveforms = wfs_stack
  528. train.segment = self.segment
  529. if train.segment is not None:
  530. self.segment.spiketrains.append(train)
  531. if hasattr(self, "lazy_shape"):
  532. train.lazy_shape = merged_lazy_shape
  533. return train
  534. @property
  535. def times(self):
  536. '''
  537. Returns the :class:`SpikeTrain` without modification or copying.
  538. '''
  539. return self
  540. @property
  541. def duration(self):
  542. '''
  543. Duration over which spikes can occur,
  544. (:attr:`t_stop` - :attr:`t_start`)
  545. '''
  546. if self.t_stop is None or self.t_start is None:
  547. return None
  548. return self.t_stop - self.t_start
  549. @property
  550. def spike_duration(self):
  551. '''
  552. Duration of a waveform.
  553. (:attr:`waveform`.shape[2] * :attr:`sampling_period`)
  554. '''
  555. if self.waveforms is None or self.sampling_rate is None:
  556. return None
  557. return self.waveforms.shape[2] / self.sampling_rate
  558. @property
  559. def sampling_period(self):
  560. '''
  561. Interval between two samples.
  562. (1/:attr:`sampling_rate`)
  563. '''
  564. if self.sampling_rate is None:
  565. return None
  566. return 1.0 / self.sampling_rate
  567. @sampling_period.setter
  568. def sampling_period(self, period):
  569. '''
  570. Setter for :attr:`sampling_period`
  571. '''
  572. if period is None:
  573. self.sampling_rate = None
  574. else:
  575. self.sampling_rate = 1.0 / period
  576. @property
  577. def right_sweep(self):
  578. '''
  579. Time from the trigger times of the spikes to the end of the waveforms.
  580. (:attr:`left_sweep` + :attr:`spike_duration`)
  581. '''
  582. dur = self.spike_duration
  583. if self.left_sweep is None or dur is None:
  584. return None
  585. return self.left_sweep + dur
  586. def as_array(self, units=None):
  587. """
  588. Return the spike times as a plain NumPy array.
  589. If `units` is specified, first rescale to those units.
  590. """
  591. if units:
  592. return self.rescale(units).magnitude
  593. else:
  594. return self.magnitude
  595. def as_quantity(self):
  596. """
  597. Return the spike times as a quantities array.
  598. """
  599. return self.view(pq.Quantity)