Skip to content

Commit

Permalink
faster mean_firing_rate for a typical use case (NeuralEnsemble#331)
Browse files Browse the repository at this point in the history
* explicit doc of how the firing rate is computed
  • Loading branch information
dizcza committed Jun 22, 2020
1 parent eb40eb5 commit 1405966
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
17 changes: 14 additions & 3 deletions elephant/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,17 @@ 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`.
The interval over which the firing rate is calculated can be optionally
controlled with `t_start` and `t_stop`.
Parameters
----------
spiketrain : neo.SpikeTrain or pq.Quantity or np.ndarray
Expand Down Expand Up @@ -163,6 +165,15 @@ def mean_firing_rate(spiketrain, t_start=None, t_stop=None, axis=None):
If the input spiketrain is empty.
"""
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):
Expand Down
9 changes: 9 additions & 0 deletions elephant/test/test_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,15 @@ def test_mean_firing_rate_with_spiketrain(self):
res = statistics.mean_firing_rate(st)
assert_array_almost_equal(res, target, decimal=9)

def test_mean_firing_rate_typical_use_case(self):
np.random.seed(92)
st = homogeneous_poisson_process(rate=100*pq.Hz, t_stop=100*pq.s)
rate1 = statistics.mean_firing_rate(st)
rate2 = statistics.mean_firing_rate(st, t_start=st.t_start,
t_stop=st.t_stop)
self.assertEqual(rate1.units, rate2.units)
self.assertAlmostEqual(rate1.item(), rate2.item())

def test_mean_firing_rate_with_spiketrain_set_ends(self):
st = neo.SpikeTrain(self.test_array_1d, units='ms', t_stop=10.0)
target = pq.Quantity(2 / 0.5, '1/ms')
Expand Down

0 comments on commit 1405966

Please sign in to comment.