spiketrain.py 24 KB

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