-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathstatistics.py
1883 lines (1570 loc) · 67.9 KB
/
statistics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Statistical measures of spike trains (e.g., Fano factor) and functions to
estimate firing rates.
Rate estimation
***************
.. autosummary::
:toctree: _toctree/statistics/
mean_firing_rate
instantaneous_rate
time_histogram
optimal_kernel_bandwidth
Spike interval statistics
*************************
.. autosummary::
:toctree: _toctree/statistics/
isi
cv
cv2
lv
lvr
Statistics across spike trains
******************************
.. autosummary::
:toctree: _toctree/statistics/
fanofactor
complexity_pdf
Complexity
Tutorial
========
:doc:`View tutorial <../tutorials/statistics>`
Run tutorial interactively:
.. image:: https://mybinder.org/badge.svg
:target: https://mybinder.org/v2/gh/NeuralEnsemble/elephant/master
?filepath=doc/tutorials/statistics.ipynb
References
----------
.. bibliography::
:keyprefix: statistics-
:copyright: Copyright 2014-2024 by the Elephant team, see `doc/authors.rst`.
:license: Modified BSD, see LICENSE.txt for details.
"""
from __future__ import division, print_function
import math
import warnings
import neo
import numpy as np
import quantities as pq
import scipy.stats
import scipy.signal
from numpy import ndarray
from scipy.special import erf
from typing import Union
import elephant.conversion as conv
import elephant.kernels as kernels
import elephant.trials
from elephant.conversion import BinnedSpikeTrain
from elephant.utils import deprecated_alias, check_neo_consistency, \
is_time_quantity, round_binning_errors, is_list_neo_spiketrains
# do not import unicode_literals
# (quantities rescale does not work with unicodes)
__all__ = [
"isi",
"mean_firing_rate",
"fanofactor",
"cv",
"cv2",
"lv",
"lvr",
"instantaneous_rate",
"time_histogram",
"complexity_pdf",
"Complexity",
"fftkernel",
"optimal_kernel_bandwidth"
]
cv = scipy.stats.variation
def isi(spiketrain, axis=-1):
"""
Return an array containing the inter-spike intervals of the spike train.
Accepts a `neo.SpikeTrain`, a `pq.Quantity` array, a `np.ndarray`, or a
list of time spikes. If either a `neo.SpikeTrain` or `pq.Quantity` is
provided, the return value will be `pq.Quantity`, otherwise `np.ndarray`.
The units of `pq.Quantity` will be the same as `spiketrain`.
Visualization of this function is covered in Viziphant:
:func:`viziphant.statistics.plot_isi_histogram`.
Parameters
----------
spiketrain : neo.SpikeTrain or pq.Quantity or array-like
The spike times.
axis : int, optional
The axis along which the difference is taken.
Default: the last axis
Returns
-------
intervals : np.ndarray or pq.Quantity
The inter-spike intervals of the `spiketrain`.
Warns
-----
UserWarning
When the input array is not sorted, negative intervals are returned
with a warning.
Examples
--------
>>> from elephant import statistics
>>> statistics.isi([0.3, 4.5, 6.7, 9.3])
array([4.2, 2.2, 2.6])
"""
if isinstance(spiketrain, neo.SpikeTrain):
intervals = np.diff(spiketrain.magnitude, axis=axis)
# np.diff makes a copy
intervals = pq.Quantity(intervals, units=spiketrain.units, copy=False)
else:
intervals = np.diff(spiketrain, axis=axis)
if (intervals < 0).any():
warnings.warn("ISI evaluated to negative values. "
"Please sort the input array.")
return intervals
def mean_firing_rate(spiketrain, t_start=None, t_stop=None, axis=None):
"""
Return the firing rate of the spike train.
The firing rate is calculated as the number of spikes in the spike train
in the range `[t_start, t_stop]` divided by the time interval
`t_stop - t_start`. See the description below for cases when `t_start` or
`t_stop` is None.
Accepts a `neo.SpikeTrain`, a `pq.Quantity` array, or a plain
`np.ndarray`. If either a `neo.SpikeTrain` or `pq.Quantity` array is
provided, the return value will be a `pq.Quantity` array, otherwise a
plain `np.ndarray`. The units of the `pq.Quantity` array will be the
inverse of the `spiketrain`.
Parameters
----------
spiketrain : neo.SpikeTrain or pq.Quantity or np.ndarray
The spike times.
t_start : float or pq.Quantity, optional
The start time to use for the interval.
If None, retrieved from the `t_start` attribute of `spiketrain`. If
that is not present, default to 0. All spiketrain's spike times below
this value are ignored.
Default: None
t_stop : float or pq.Quantity, optional
The stop time to use for the time points.
If not specified, retrieved from the `t_stop` attribute of
`spiketrain`. If that is not present, default to the maximum value of
`spiketrain`. All spiketrain's spike times above this value are
ignored.
Default: None
axis : int, optional
The axis over which to do the calculation; has no effect when the
input is a neo.SpikeTrain, because a neo.SpikeTrain is always a 1-d
vector. If None, do the calculation over the flattened array.
Default: None
Returns
-------
float or pq.Quantity or np.ndarray
The firing rate of the `spiketrain`
Raises
------
TypeError
If the input spiketrain is a `np.ndarray` but `t_start` or `t_stop` is
`pq.Quantity`.
If the input spiketrain is a `neo.SpikeTrain` or `pq.Quantity` but
`t_start` or `t_stop` is not `pq.Quantity`.
ValueError
If the input spiketrain is empty.
Examples
--------
>>> from elephant import statistics
>>> statistics.mean_firing_rate([0.3, 4.5, 6.7, 9.3])
0.4301075268817204
"""
if isinstance(spiketrain, neo.SpikeTrain) and t_start is None \
and t_stop is None and axis is None:
# a faster approach for a typical use case
n_spikes = len(spiketrain)
time_interval = spiketrain.t_stop - spiketrain.t_start
time_interval = time_interval.rescale(spiketrain.units)
rate = n_spikes / time_interval
return rate
if isinstance(spiketrain, pq.Quantity):
# Quantity or neo.SpikeTrain
if not is_time_quantity(t_start, allow_none=True):
raise TypeError("'t_start' must be a Quantity or None")
if not is_time_quantity(t_stop, allow_none=True):
raise TypeError("'t_stop' must be a Quantity or None")
units = spiketrain.units
if t_start is None:
t_start = getattr(spiketrain, 't_start', 0 * units)
t_start = t_start.rescale(units).magnitude
if t_stop is None:
t_stop = getattr(spiketrain, 't_stop',
np.max(spiketrain, axis=axis))
t_stop = t_stop.rescale(units).magnitude
# calculate as a numpy array
rates = mean_firing_rate(spiketrain.magnitude, t_start=t_start,
t_stop=t_stop, axis=axis)
rates = pq.Quantity(rates, units=1. / units)
elif isinstance(spiketrain, (np.ndarray, list, tuple)):
if isinstance(t_start, pq.Quantity) or isinstance(t_stop, pq.Quantity):
raise TypeError("'t_start' and 't_stop' cannot be quantities if "
"'spiketrain' is not a Quantity.")
spiketrain = np.asarray(spiketrain)
if len(spiketrain) == 0:
raise ValueError("Empty input spiketrain.")
if t_start is None:
t_start = 0
if t_stop is None:
t_stop = np.max(spiketrain, axis=axis)
time_interval = t_stop - t_start
if axis and isinstance(t_stop, np.ndarray):
t_stop = np.expand_dims(t_stop, axis)
rates = np.sum((spiketrain >= t_start) & (spiketrain <= t_stop),
axis=axis) / time_interval
else:
raise TypeError("Invalid input spiketrain type: '{}'. Allowed: "
"neo.SpikeTrain, Quantity, ndarray".
format(type(spiketrain)))
return rates
def fanofactor(spiketrains, warn_tolerance=0.1 * pq.ms):
r"""
Evaluates the empirical Fano factor F of the spike counts of
a list of `neo.SpikeTrain` objects.
Given the vector v containing the observed spike counts (one per
spike train) in the time window [t0, t1], F is defined as:
.. math::
F := \frac{var(v)}{mean(v)}
The Fano factor is typically computed for spike trains representing the
activity of the same neuron over different trials. The higher F, the
larger the cross-trial non-stationarity. In theory for a time-stationary
Poisson process, F=1.
Parameters
----------
spiketrains : list
List of `neo.SpikeTrain` or `pq.Quantity` or `np.ndarray` or list of
spike times for which to compute the Fano factor of spike counts.
warn_tolerance : pq.Quantity
In case of a list of input neo.SpikeTrains, if their durations vary by
more than `warn_tolerence` in their absolute values, throw a warning
(see Notes).
Default: 0.1 ms
Returns
-------
fano : float
The Fano factor of the spike counts of the input spike trains.
Returns np.NaN if an empty list is specified, or if all spike trains
are empty.
Raises
------
TypeError
If the input spiketrains are neo.SpikeTrain objects, but
`warn_tolerance` is not a quantity.
Notes
-----
The check for the equal duration of the input spike trains is performed
only if the input is of type`neo.SpikeTrain`: if you pass a numpy array,
please make sure that they all have the same duration manually.
Examples
--------
>>> import neo
>>> from elephant import statistics
>>> spiketrains = [
... neo.SpikeTrain([0.3, 4.5, 6.7, 9.3], t_stop=10, units='s'),
... neo.SpikeTrain([1.4, 3.3, 8.2], t_stop=10, units='s')
... ]
>>> statistics.fanofactor(spiketrains)
0.07142857142857142
"""
# Build array of spike counts (one per spike train)
spike_counts = np.array([len(st) for st in spiketrains])
# Compute FF
if all(count == 0 for count in spike_counts):
# empty list of spiketrains reaches this branch, and NaN is returned
return np.nan
if all(isinstance(st, neo.SpikeTrain) for st in spiketrains):
if not is_time_quantity(warn_tolerance):
raise TypeError("'warn_tolerance' must be a time quantity.")
durations = [(st.t_stop - st.t_start).simplified.item()
for st in spiketrains]
durations_min = min(durations)
durations_max = max(durations)
if durations_max - durations_min > warn_tolerance.simplified.item():
warnings.warn("Fano factor calculated for spike trains of "
"different duration (minimum: {_min}s, maximum "
"{_max}s).".format(_min=durations_min,
_max=durations_max))
fano = spike_counts.var() / spike_counts.mean()
return fano
def __variation_check(v, with_nan):
# ensure the input ia a vector
if v.ndim != 1:
raise ValueError("The input must be a vector, not a {}-dim matrix.".
format(v.ndim))
# ensure we have enough entries
if v.size < 2:
if with_nan:
warnings.warn("The input size is too small. Please provide"
"an input with more than 1 entry. Returning `NaN`"
"since the argument `with_nan` is `True`")
return np.NaN
raise ValueError("Input size is too small. Please provide "
"an input with more than 1 entry. Set 'with_nan' "
"to True to replace the error by a warning.")
return None
@deprecated_alias(v='time_intervals')
def cv2(time_intervals, with_nan=False):
r"""
Calculate the measure of Cv2 for a sequence of time intervals between
events :cite:`statistics-Holt1996_1806`.
Given a vector :math:`I` containing a sequence of intervals, the Cv2 is
defined as:
.. math::
Cv2 := \frac{1}{N} \sum_{i=1}^{N-1}
\frac{2|I_{i+1}-I_i|}
{|I_{i+1}+I_i|}
The Cv2 is typically computed as a substitute for the classical
coefficient of variation (Cv) for sequences of events which include some
(relatively slow) rate fluctuation. As with the Cv, Cv2=1 for a sequence
of intervals generated by a Poisson process.
Parameters
----------
time_intervals : pq.Quantity or np.ndarray or list
Vector of consecutive time intervals.
with_nan : bool, optional
If True, `cv2` of a spike train with less than two spikes results in a
np.NaN value and a warning is raised.
If False, `ValueError` exception is raised with a spike train with
less than two spikes.
Default: True
Returns
-------
float
The Cv2 of the inter-spike interval of the input sequence.
Raises
------
ValueError
If an empty list is specified, or if the sequence has less than two
entries and `with_nan` is False.
If a matrix is passed to the function. Only vector inputs are
supported.
Warns
-----
UserWarning
If `with_nan` is True and `cv2` is calculated for a sequence with less
than two entries, generating a np.NaN.
Examples
--------
>>> from elephant import statistics
>>> statistics.cv2([0.3, 4.5, 6.7, 9.3])
0.8226190476190478
"""
# convert to array, cast to float
time_intervals = np.asarray(time_intervals)
np_nan = __variation_check(time_intervals, with_nan)
if np_nan is not None:
return np_nan
# calculate Cv2 and return result
cv_i = np.diff(time_intervals) / (time_intervals[:-1] + time_intervals[1:])
return 2. * np.mean(np.abs(cv_i))
@deprecated_alias(v='time_intervals')
def lv(time_intervals, with_nan=False):
r"""
Calculate the measure of local variation Lv for a sequence of time
intervals between events :cite:`statistics-Shinomoto2003_2823`.
Given a vector :math:`I` containing a sequence of intervals, the Lv is
defined as:
.. math::
Lv := \frac{1}{N} \sum_{i=1}^{N-1}
\frac{3(I_i-I_{i+1})^2}
{(I_i+I_{i+1})^2}
The Lv is typically computed as a substitute for the classical coefficient
of variation for sequences of events which include some (relatively slow)
rate fluctuation. As with the Cv, Lv=1 for a sequence of intervals
generated by a Poisson process.
Parameters
----------
time_intervals : pq.Quantity or np.ndarray or list
Vector of consecutive time intervals.
with_nan : bool, optional
If True, the Lv of a spike train with less than two spikes results in a
`np.NaN` value and a warning is raised.
If False, a `ValueError` exception is raised with a spike train with
less than two spikes.
Default: True
Returns
-------
float
The Lv of the inter-spike interval of the input sequence.
Raises
------
ValueError
If an empty list is specified, or if the sequence has less than two
entries and `with_nan` is False.
If a matrix is passed to the function. Only vector inputs are
supported.
Warns
-----
UserWarning
If `with_nan` is True and the Lv is calculated for a spike train
with less than two spikes, generating a np.NaN.
Examples
--------
>>> from elephant import statistics
>>> statistics.lv([0.3, 4.5, 6.7, 9.3])
0.8306154336734695
"""
# convert to array, cast to float
time_intervals = np.asarray(time_intervals)
np_nan = __variation_check(time_intervals, with_nan)
if np_nan is not None:
return np_nan
cv_i = np.diff(time_intervals) / (time_intervals[:-1] + time_intervals[1:])
return 3. * np.mean(np.power(cv_i, 2))
def lvr(time_intervals, R=5*pq.ms, with_nan=False):
r"""
Calculate the measure of revised local variation LvR for a sequence of time
intervals between events :cite:`statistics-Shinomoto2009_e1000433`.
Given a vector :math:`I` containing a sequence of intervals, the LvR is
defined as:
.. math::
LvR := \frac{3}{N-1} \sum_{i=1}^{N-1}
\left(1-\frac{4 I_i I_{i+1}}
{(I_i+I_{i+1})^2}\right)
\left(1+\frac{4 R}{I_i+I_{i+1}}\right)
The LvR is a revised version of the Lv, with enhanced invariance to firing
rate fluctuations by introducing a refractoriness constant R. The LvR with
`R=5ms` was shown to outperform other ISI variability measures in spike
trains with firing rate fluctuations and sensory stimuli
:cite:`statistics-Shinomoto2009_e1000433`.
Parameters
----------
time_intervals : pq.Quantity or np.ndarray or list
Vector of consecutive time intervals. Must have time units, if not unit
is passed `ms` are assumed.
R : pq.Quantity or int or float
Refractoriness constant (R >= 0). If no quantity is passed `ms` are
assumed.
Default: 5 ms
with_nan : bool, optional
If True, LvR of a spike train with less than two spikes results in a
np.NaN value and a warning is raised.
If False, a `ValueError` exception is raised with a spike train with
less than two spikes.
Default: True
Returns
-------
float
The LvR of the inter-spike interval of the input sequence.
Raises
------
ValueError
If an empty list is specified, or if the sequence has less than two
entries and `with_nan` is False.
If a matrix is passed to the function. Only vector inputs are
supported.
Warns
-----
UserWarning
If `with_nan` is True and the `lvr` is calculated for a spike train
with less than two spikes, generating a np.NaN.
If R is passed without any units attached milliseconds are assumed.
Examples
--------
>>> from elephant import statistics
>>> statistics.lvr([0.3, 4.5, 6.7, 9.3], R=0.005)
0.833907445980624
"""
if isinstance(R, pq.Quantity):
R = R.rescale('ms').magnitude
else:
warnings.warn('No units specified for R, assuming milliseconds (ms)')
if R < 0:
raise ValueError('R must be >= 0')
# check units of intervals if available
if isinstance(time_intervals, pq.Quantity):
time_intervals = time_intervals.rescale('ms').magnitude
else:
warnings.warn('No units specified for time_intervals,'
' assuming milliseconds (ms)')
# convert to array, cast to float
time_intervals = np.asarray(time_intervals)
np_nan = __variation_check(time_intervals, with_nan)
if np_nan is not None:
return np_nan
N = len(time_intervals)
t = time_intervals[:-1] + time_intervals[1:]
frac1 = 4 * time_intervals[:-1] * time_intervals[1:] / t**2
frac2 = 4 * R / t
lvr = (3 / (N-1)) * np.sum((1-frac1) * (1+frac2))
return lvr
@deprecated_alias(spiketrain='spiketrains')
def instantaneous_rate(spiketrains, sampling_period, kernel='auto',
cutoff=5.0, t_start=None, t_stop=None, trim=False,
center_kernel=True, border_correction=False,
pool_trials=False, pool_spike_trains=False):
r"""
Estimates instantaneous firing rate by kernel convolution.
Visualization of this function is covered in Viziphant:
:func:`viziphant.statistics.plot_instantaneous_rates_colormesh`.
Parameters
----------
spiketrains : neo.SpikeTrain, list of neo.SpikeTrain or elephant.trials.Trials
Input spike train(s) for which the instantaneous firing rate is
calculated. If a list of spike trains is supplied, the parameter
pool_spike_trains determines the behavior of the function. If a Trials
object is supplied, the behavior is determined by the parameters
pool_spike_trains (within a trial) and pool_trials (across trials).
sampling_period : pq.Quantity
Time stamp resolution of the spike times. The same resolution will
be assumed for the kernel.
kernel : 'auto' or Kernel, optional
The string 'auto' or callable object of class `kernels.Kernel`.
The kernel is used for convolution with the spike train and its
standard deviation determines the time resolution of the instantaneous
rate estimation. Currently, implemented kernel forms are rectangular,
triangular, epanechnikovlike, gaussian, laplacian, exponential, and
alpha function.
If 'auto', the optimized kernel width for the rate estimation is
calculated according to :cite:`statistics-Shimazaki2010_171` and a
Gaussian kernel is constructed with this width. Automatized calculation
of the kernel width is not available for other than Gaussian kernel
shapes.
Note: The kernel width is not adaptive, i.e., it is calculated as
global optimum across the data.
Default: 'auto'
cutoff : float, optional
This factor determines the cutoff of the probability distribution of
the kernel, i.e., the considered width of the kernel in terms of
multiples of the standard deviation sigma.
Default: 5.0
t_start : pq.Quantity, optional
Start time of the interval used to compute the firing rate.
If None, `t_start` is assumed equal to `t_start` attribute of
`spiketrain`.
Default: None
t_stop : pq.Quantity, optional
End time of the interval used to compute the firing rate.
If None, `t_stop` is assumed equal to `t_stop` attribute of
`spiketrain`.
Default: None
trim : bool, optional
Accounts for the asymmetry of a kernel.
If False, the output of the Fast Fourier Transformation being a longer
vector than the input vector (ouput = input + kernel - 1) is reduced
back to the original size of the considered time interval of the
`spiketrain` using the median of the kernel. False (no trimming) is
equivalent to 'same' convolution mode for symmetrical kernels.
If True, only the region of the convolved signal is returned, where
there is complete overlap between kernel and spike train. This is
achieved by reducing the length of the output of the Fast Fourier
Transformation by a total of two times the size of the kernel, and
`t_start` and `t_stop` are adjusted. True (trimming) is equivalent to
'valid' convolution mode for symmetrical kernels.
Default: False
center_kernel : bool, optional
If set to True, the kernel will be translated such that its median is
centered on the spike, thus putting equal weight before and after the
spike. If False, no adjustment is performed such that the spike sits at
the origin of the kernel.
Default: True
border_correction : bool, optional
Apply a border correction to prevent underestimating the firing rates
at the borders of the spike trains, i.e., close to t_start and t_stop.
The correction is done by estimating the mass of the kernel outside
these spike train borders under the assumption that the rate does not
change strongly.
Only possible in the case of a Gaussian kernel.
Default: False
pool_trials: bool, optional
If true, calculate firing rates averaged over trials if spiketrains is
of type elephant.trials.Trials
Has no effect for single spike train or lists of spike trains.
Default: False
pool_spike_trains: bool, optional
If true, calculate firing rates averaged over spike trains. If the
input is a Trials object, spike trains are pooled across spike trains
within each trial, and pool_trials determines whether spike trains are
additionally pooled across trials.
Has no effect for a single spike train.
Default: False
Returns
-------
rate : neo.AnalogSignal
2D matrix that contains the rate estimation in unit hertz (Hz) of shape
``(time, len(spiketrains))`` or ``(time, 1)`` in case of a single
input spiketrain. `rate.times` contains the time axis of the rate
estimate: the unit of this property is the same as the resolution that
is given via the argument `sampling_period` to the function.
Raises
------
TypeError
* If `spiketrain` is not an instance of `neo.SpikeTrain`.
* If `sampling_period` is not a `pq.Quantity`.
* If `sampling_period` is not larger than zero.
* If `kernel` is neither instance of `kernels.Kernel` nor string
'auto'.
* If `cutoff` is neither `float` nor `int`.
* If `t_start` and `t_stop` are neither None nor a `pq.Quantity`.
* If `trim` is not `bool`.
ValueError
* If `sampling_period` is smaller than zero.
* If `kernel` is 'auto' and the function was unable to calculate
optimal kernel width for instantaneous rate from input data.
Warns
-----
UserWarning
* If `cutoff` is less than `min_cutoff` attribute of `kernel`, the
width of the kernel is adjusted to a minimally allowed width.
Notes
-----
* The resulting instantaneous firing rate values smaller than ``0``, which
may happen due to machine precision errors, are clipped to zero.
* The instantaneous firing rate estimate is calculated based on half-open
intervals ``[)``, except the last one e.g. if ``t_start = 0s``,
``t_stop = 4s`` and ``sampling_period = 1s``, the intervals are:
``[0, 1)`` ``[1, 2)`` ``[2, 3)`` ``[3, 4]``.
This induces a sampling bias, which can lead to a time shift of the
estimated rate, if the `sampling_period` is chosen large relative to the
duration ``(t_stop - t_start)``. One possibility to counteract this is
to choose a smaller `sampling_period`.
* The last interval of the given duration ``(t_stop - t_start)`` is
dropped if it is shorter than `sampling_period`,
e.g. if ``t_start = 0s``, ``t_stop = 4.5s`` and
``sampling_period = 1s``, the intervals considered are:
``[0, 1)`` ``[1, 2)`` ``[2, 3)`` ``[3, 4]``,
the last interval ``[4, 4.5]`` is excluded from all calculations.
Examples
--------
Example 1. Automatic kernel estimation.
>>> import neo
>>> import quantities as pq
>>> from elephant import statistics
>>> spiketrain = neo.SpikeTrain([0.3, 4.5, 6.7, 9.3], t_stop=10, units='s')
>>> rate = statistics.instantaneous_rate(spiketrain,
... sampling_period=10 * pq.ms,
... kernel='auto')
>>> rate.annotations['kernel']
{'type': 'GaussianKernel', 'sigma': '7.273225922958104 s', 'invert': False}
>>> print(rate.sampling_rate)
0.1 1/ms
Example 2. Manually set kernel.
>>> from elephant import kernels
>>> spiketrain = neo.SpikeTrain([0], t_stop=1, units='s')
>>> kernel = kernels.GaussianKernel(sigma=300 * pq.ms)
>>> rate = statistics.instantaneous_rate(spiketrain,
... sampling_period=200 * pq.ms, kernel=kernel, t_start=-1 * pq.s)
>>> rate
<AnalogSignal(array([[0.01007419],
[0.05842767],
[0.22928759],
[0.60883028],
[1.0938699 ],
[1.3298076 ],
[1.0938699 ],
[0.60883028],
[0.22928759],
[0.05842767]]) * Hz, [-1.0 s, 1.0 s], sampling rate: 0.005 1/ms)>
>>> rate.magnitude
array([[0.01007419],
[0.05842767],
[0.22928759],
[0.60883028],
[1.0938699 ],
[1.3298076 ],
[1.0938699 ],
[0.60883028],
[0.22928759],
[0.05842767]])
"""
if isinstance(spiketrains, elephant.trials.Trials):
kwargs = {
'kernel': kernel,
'cutoff': cutoff,
't_start': t_start,
't_stop': t_stop,
'trim': trim,
'center_kernel': center_kernel,
'border_correction': border_correction,
'pool_trials': False,
'pool_spike_trains': False,
}
if pool_trials:
list_of_lists_of_spiketrains = [
spiketrains.get_spiketrains_from_trial_as_list(
trial_id=trial_no)
for trial_no in range(spiketrains.n_trials)]
spiketrains_cross_trials = (
[list_of_lists_of_spiketrains[trial_no][spiketrain_idx]
for trial_no in range(spiketrains.n_trials)]
for spiketrain_idx, spiketrain in
enumerate(list_of_lists_of_spiketrains[0]))
rates_cross_trials = [instantaneous_rate(spiketrain,
sampling_period,
**kwargs)
for spiketrain in spiketrains_cross_trials]
average_rate_cross_trials = (
np.mean(rates, axis=1) for rates in rates_cross_trials)
if pool_spike_trains:
average_rate = np.mean(list(average_rate_cross_trials), axis=0)
analog_signal = rates_cross_trials[0]
return (neo.AnalogSignal(
signal=average_rate,
sampling_period=analog_signal.sampling_period,
units=analog_signal.units,
t_start=analog_signal.t_start,
t_stop=analog_signal.t_stop,
kernel=analog_signal.annotations)
)
list_of_average_rates_cross_trial = neo.AnalogSignal(
signal=np.array(list(average_rate_cross_trials)).transpose(),
sampling_period=rates_cross_trials[0].sampling_period,
units=rates_cross_trials[0].units,
t_start=rates_cross_trials[0].t_start,
t_stop=rates_cross_trials[0].t_stop,
kernel=rates_cross_trials[0].annotations)
return list_of_average_rates_cross_trial
if not pool_trials and not pool_spike_trains:
return [instantaneous_rate(
spiketrains.get_spiketrains_from_trial_as_list(
trial_id=trial_no), sampling_period, **kwargs)
for trial_no in range(spiketrains.n_trials)]
if not pool_trials and pool_spike_trains:
rates = [instantaneous_rate(
spiketrains.get_spiketrains_from_trial_as_list(
trial_id=trial_no), sampling_period, **kwargs)
for trial_no in range(spiketrains.n_trials)]
average_rates = (np.mean(rate, axis=1) for rate in rates)
list_of_average_rates_over_spiketrains = [
neo.AnalogSignal(signal=average_rate,
sampling_period=analog_signal.sampling_period,
units=analog_signal.units,
t_start=analog_signal.t_start,
t_stop=analog_signal.t_stop,
kernel=analog_signal.annotations)
for average_rate, analog_signal in zip(average_rates, rates)]
return list_of_average_rates_over_spiketrains
def optimal_kernel(st):
width_sigma = None
if len(st) > 0:
width_sigma = optimal_kernel_bandwidth(
st.magnitude, times=None, bootstrap=False)['optw']
if width_sigma is None:
raise ValueError("Unable to calculate optimal kernel width for "
"instantaneous rate from input data.")
return kernels.GaussianKernel(width_sigma * st.units)
if border_correction and not \
(kernel == 'auto' or isinstance(kernel, kernels.GaussianKernel)):
raise ValueError(
'The border correction is only implemented'
' for Gaussian kernels.')
if isinstance(spiketrains, neo.SpikeTrain):
if kernel == 'auto':
kernel = optimal_kernel(spiketrains)
spiketrains = [spiketrains]
if not all([isinstance(elem, neo.SpikeTrain) for elem in spiketrains]):
raise TypeError(f"'spiketrains' must be a list of neo.SpikeTrain's or "
f"a single neo.SpikeTrain. Found: {type(spiketrains)}")
if not is_time_quantity(sampling_period):
raise TypeError(f"The 'sampling_period' must be a time Quantity."
f"Found: {type(sampling_period)}")
if sampling_period.magnitude < 0:
raise ValueError(f"The 'sampling_period' ({sampling_period}) "
f"must be non-negative.")
if not (isinstance(kernel, kernels.Kernel) or kernel == 'auto'):
raise TypeError(f"'kernel' must be instance of class "
f"elephant.kernels.Kernel or string 'auto'. Found: "
f"{type(kernel)}, value {str(kernel)}")
if not isinstance(cutoff, (float, int)):
raise TypeError("'cutoff' must be float or integer")
if not is_time_quantity(t_start, allow_none=True):
raise TypeError("'t_start' must be a time Quantity")
if not is_time_quantity(t_stop, allow_none=True):
raise TypeError("'t_stop' must be a time Quantity")
if not isinstance(trim, bool):
raise TypeError("'trim' must be bool")
check_neo_consistency(spiketrains,
object_type=neo.SpikeTrain,
t_start=t_start, t_stop=t_stop)
if kernel == 'auto':
if len(spiketrains) == 1:
kernel = optimal_kernel(spiketrains[0])
else:
raise ValueError("Cannot estimate a kernel for a list of spike "
"trains. Please provide a kernel explicitly "
"rather than 'auto'.")
if t_start is None:
t_start = spiketrains[0].t_start
if t_stop is None:
t_stop = spiketrains[0].t_stop
# Rescale units for consistent calculation
t_start = t_start.rescale(spiketrains[0].units)
t_stop = t_stop.rescale(spiketrains[0].units)
# Calculate parameters for np.histogram
n_bins = int(((t_stop - t_start) / sampling_period).simplified)
hist_range_end = t_start + n_bins * \
sampling_period.rescale(spiketrains[0].units)
hist_range = (t_start.item(), hist_range_end.item())
# Preallocation
histogram_arr = np.zeros((len(spiketrains), n_bins), dtype=np.float64)
for i, st in enumerate(spiketrains):
histogram_arr[i], _ = np.histogram(st.magnitude, bins=n_bins,
range=hist_range)
histogram_arr = histogram_arr.T # make it (time, units)
# Kernel
if cutoff < kernel.min_cutoff:
cutoff = kernel.min_cutoff
warnings.warn("The width of the kernel was adjusted to a minimally "
"allowed width.")
scaling_unit = pq.CompoundUnit(f"{sampling_period.rescale('s').item()}*s")
cutoff_sigma = cutoff * kernel.sigma.rescale(scaling_unit).magnitude
if center_kernel: # t_arr is centered on the kernel median.
median = kernel.icdf(0.5).rescale(scaling_unit).item()
else:
median = 0
# An odd number of points correctly resolves the median index of the
# kernel. This avoids a timeshift in the rate estimate for symmetric
# kernels. A number x given by 'x = 2 * n + 1' with n being an integer is
# always odd. Using `math.ceil` to calculate `t_arr_kernel_half` ensures an
# integer value, hence the number of points for the kernel (num) given by
# `num=2 * t_arr_kernel_half + 1` is always odd.
# (See Issue #360, https://github.com/NeuralEnsemble/elephant/issues/360)
t_arr_kernel_half = math.ceil(
cutoff * (kernel.sigma / sampling_period).simplified.item())
t_arr_kernel_length = 2 * t_arr_kernel_half + 1