| 1 |
""" |
| 2 |
Module defining `PopulationRateMonitor` and the abstract `RateMonitor` class. |
| 3 |
""" |
| 4 |
|
| 5 |
from abc import ABC, abstractmethod |
| 6 |
|
| 7 |
import numpy as np |
| 8 |
|
| 9 |
from brian2.core.functions import timestep |
| 10 |
from brian2.core.variables import Variables |
| 11 |
from brian2.groups.group import CodeRunner, Group |
| 12 |
from brian2.units.allunits import hertz, second |
| 13 |
from brian2.units.fundamentalunits import Quantity, check_units |
| 14 |
from brian2.utils.logger import get_logger |
| 15 |
|
| 16 |
__all__ = ["PopulationRateMonitor", "RateMonitor"] |
| 17 |
|
| 18 |
|
| 19 |
logger = get_logger(__name__) |
| 20 |
|
| 21 |
|
| 22 |
class RateMonitor(CodeRunner, Group, ABC): |
| 23 |
""" |
| 24 |
Abstract base class for monitors that record rates. |
| 25 |
""" |
| 26 |
|
| 27 |
@abstractmethod |
| 28 |
@check_units(bin_size=second) |
| 29 |
def binned_rate(self, bin_size): |
| 30 |
""" |
| 31 |
Return the rate calculated in bins of a certain size. |
| 32 |
|
| 33 |
Parameters |
| 34 |
------------- |
| 35 |
bin_size : `Quantity` |
| 36 |
The size of the bins in seconds. Should be a multiple of dt. |
| 37 |
|
| 38 |
Returns |
| 39 |
------- |
| 40 |
bins : `Quantity` |
| 41 |
The start time of the bins. |
| 42 |
binned_values : `Quantity` |
| 43 |
The binned values. For EventMonitor subclasses, this is a 2D array |
| 44 |
with shape (neurons, bins). For PopulationRateMonitor, this is a 1D array. |
| 45 |
|
| 46 |
Notes |
| 47 |
----- |
| 48 |
The returned bin times represent the **start** of each bin interval, not the center. |
| 49 |
This is consistent with how Brian2 records spike times and other temporal data. |
| 50 |
For example, a spike recorded at time `t` occurred during the interval `[t, t+dt)`. |
| 51 |
|
| 52 |
For plotting purposes, especially with larger bin sizes, you may want to use bin |
| 53 |
centers instead of bin starts for a more intuitive visualization. You can easily |
| 54 |
calculate the bin centers by adding half the bin size:: |
| 55 |
|
| 56 |
>> bins, rates = monitor.binned_rate(10*ms) |
| 57 |
>> bin_centers = bins + 10*ms / 2 |
| 58 |
>> plt.plot(bin_centers, rates) |
| 59 |
|
| 60 |
This adjustment is particularly helpful when the bins are large relative to the |
| 61 |
time scale of interest, as it better represents where the rate measurement applies |
| 62 |
within each time window. |
| 63 |
""" |
| 64 |
raise NotImplementedError() |
| 65 |
|
| 66 |
@check_units(width=second) |
| 67 |
def smooth_rate(self, window="gaussian", width=None): |
| 68 |
""" |
| 69 |
Returns a smoothed out version of the firing rate(s). |
| 70 |
|
| 71 |
Parameters |
| 72 |
---------- |
| 73 |
window : str, ndarray |
| 74 |
The window to use for smoothing. Can be a string to chose a |
| 75 |
predefined window(`flat` for a rectangular, and `gaussian` |
| 76 |
for a Gaussian-shaped window). |
| 77 |
|
| 78 |
In this case the width of the window |
| 79 |
is determined by the `width` argument. Note that for the Gaussian |
| 80 |
window, the `width` parameter specifies the standard deviation of |
| 81 |
the Gaussian, the width of the actual window is `4*width + dt` |
| 82 |
(rounded to the nearest dt). For the flat window, the width is |
| 83 |
rounded to the nearest odd multiple of dt to avoid shifting the rate |
| 84 |
in time. |
| 85 |
Alternatively, an arbitrary window can be given as a numpy array |
| 86 |
(with an odd number of elements). In this case, the width in units |
| 87 |
of time depends on the ``dt`` of the simulation, and no `width` |
| 88 |
argument can be specified. The given window will be automatically |
| 89 |
normalized to a sum of 1. |
| 90 |
width : `Quantity`, optional |
| 91 |
The width of the ``window`` in seconds (for a predefined window). |
| 92 |
|
| 93 |
Returns |
| 94 |
------- |
| 95 |
rate : `Quantity` |
| 96 |
The smoothed firing rate(s) in Hz. For EventMonitor subclasses, |
| 97 |
this returns a 2D array with shape (neurons, time_bins). |
| 98 |
For PopulationRateMonitor, this returns a 1D array. |
| 99 |
Note that the rates are smoothed at the original time step resolution (dt), not re-binned. |
| 100 |
The length of the returned array equals the number of recorded time steps and |
| 101 |
can be plotted against the original time values (e.g., self.t). |
| 102 |
|
| 103 |
Warnings |
| 104 |
-------- |
| 105 |
This method will give incorrect results if the monitor has recorded values with |
| 106 |
varying ``dt`` values. |
| 107 |
""" |
| 108 |
if width is None and isinstance(window, str): |
| 109 |
raise TypeError("Need a width when using a predefined window.") |
| 110 |
if width is not None and not isinstance(window, str): |
| 111 |
raise TypeError("Can only specify a width for a predefined window") |
| 112 |
|
| 113 |
if isinstance(window, str): |
| 114 |
if window == "gaussian": |
| 115 |
# basically Gaussian theoretically spans infinite time, but practically it falls off quickly, |
| 116 |
# So we choose a window of +- 2*(Standard deviations), i.e 95% of gaussian curve |
| 117 |
|
| 118 |
width_dt = int( |
| 119 |
np.round(2 * width / self.clock.dt) |
| 120 |
) # Rounding only for the size of the window, not for the standard |
| 121 |
# deviation of the Gaussian |
| 122 |
window = np.exp( |
| 123 |
-(np.arange(-width_dt, width_dt + 1) ** 2) |
| 124 |
* 1.0 # hack to ensure floating-point division :) |
| 125 |
/ (2 * (width / self.clock.dt) ** 2) |
| 126 |
) |
| 127 |
elif window == "flat": |
| 128 |
width_dt = int(np.round(width / (2 * self.clock.dt))) * 2 + 1 |
| 129 |
used_width = width_dt * self.clock.dt |
| 130 |
if abs(used_width - width) > 1e-6 * self.clock.dt: |
| 131 |
logger.info( |
| 132 |
f"width adjusted from {width} to {used_width}", |
| 133 |
"adjusted_width", |
| 134 |
once=True, |
| 135 |
) |
| 136 |
window = np.ones(width_dt) |
| 137 |
else: |
| 138 |
raise NotImplementedError(f'Unknown pre-defined window "{window}"') |
| 139 |
else: |
| 140 |
try: |
| 141 |
window = np.asarray(window) |
| 142 |
except TypeError as ex: |
| 143 |
raise TypeError(f"Cannot use a window of type {type(window)}") from ex |
| 144 |
if window.ndim != 1: |
| 145 |
raise TypeError("The provided window has to be one-dimensional.") |
| 146 |
if len(window) % 2 != 1: |
| 147 |
raise TypeError("The window has to have an odd number of values.") |
| 148 |
|
| 149 |
# Get the binned rates at the finest resolution |
| 150 |
_, binned_values = self.binned_rate(bin_size=self.clock.dt) |
| 151 |
|
| 152 |
# Normalize the window |
| 153 |
window = window * 1.0 / sum(window) |
| 154 |
|
| 155 |
# Extract the raw numpy array from the Quantity (if it is one) |
| 156 |
binned_array = np.asarray(binned_values) |
| 157 |
|
| 158 |
# So we need to handle for both 1D (PopulationRateMonitor) and 2D (EventMonitor) cases separately as `np.convolve()` only works with 1D arrays |
| 159 |
if binned_values.ndim == 1: |
| 160 |
# PopulationRateMonitor case - 1D convolution |
| 161 |
smoothed = np.convolve(binned_values, window, mode="same") |
| 162 |
else: |
| 163 |
# EventMonitor/SpikeMonitor case - convolve each neuron and then we return the smoothed 2D array ( neuron * bins ) |
| 164 |
num_neurons, num_bins = binned_array.shape |
| 165 |
smoothed = np.zeros((num_neurons, num_bins)) |
| 166 |
for i in range(num_neurons): |
| 167 |
smoothed[i, :] = np.convolve(binned_array[i, :], window, mode="same") |
| 168 |
|
| 169 |
return Quantity(smoothed, dim=hertz.dim) |
| 170 |
|
| 171 |
|
| 172 |
class PopulationRateMonitor(RateMonitor): |
| 173 |
""" |
| 174 |
Record instantaneous firing rates, averaged across neurons from a |
| 175 |
`NeuronGroup` or other spike source. |
| 176 |
|
| 177 |
Parameters |
| 178 |
---------- |
| 179 |
source : (`NeuronGroup`, `SpikeSource`) |
| 180 |
The source of spikes to record. |
| 181 |
name : str, optional |
| 182 |
A unique name for the object, otherwise will use |
| 183 |
``source.name+'_ratemonitor_0'``, etc. |
| 184 |
codeobj_class : class, optional |
| 185 |
The `CodeObject` class to run code with. |
| 186 |
dtype : dtype, optional |
| 187 |
The dtype to use to store the ``rate`` variable. Defaults to |
| 188 |
`~numpy.float64`, i.e. double precision. |
| 189 |
|
| 190 |
Notes |
| 191 |
----- |
| 192 |
Currently, this monitor can only monitor the instantaneous firing rates at |
| 193 |
each time step of the source clock. Any binning/smoothing of the firing |
| 194 |
rates has to be done afterwards using the `binned_rate` or `smooth_rate` |
| 195 |
methods. |
| 196 |
""" |
| 197 |
|
| 198 |
invalidates_magic_network = False |
| 199 |
add_to_magic_network = True |
| 200 |
|
| 201 |
def __init__( |
| 202 |
self, source, name="ratemonitor*", codeobj_class=None, dtype=np.float64 |
| 203 |
): |
| 204 |
#: The group we are recording from |
| 205 |
self.source = source |
| 206 |
|
| 207 |
self.codeobj_class = codeobj_class |
| 208 |
CodeRunner.__init__( |
| 209 |
self, |
| 210 |
group=self, |
| 211 |
code="", |
| 212 |
template="ratemonitor", |
| 213 |
clock=source.clock, |
| 214 |
when="end", |
| 215 |
order=0, |
| 216 |
name=name, |
| 217 |
) |
| 218 |
|
| 219 |
self.add_dependency(source) |
| 220 |
|
| 221 |
self.variables = Variables(self) |
| 222 |
# Handle subgroups correctly |
| 223 |
start = getattr(source, "start", 0) |
| 224 |
stop = getattr(source, "stop", len(source)) |
| 225 |
self.variables.add_constant("_source_start", start) |
| 226 |
self.variables.add_constant("_source_stop", stop) |
| 227 |
self.variables.add_reference("_spikespace", source) |
| 228 |
self.variables.add_dynamic_array( |
| 229 |
"rate", size=0, dimensions=hertz.dim, read_only=True, dtype=dtype |
| 230 |
) |
| 231 |
self.variables.add_dynamic_array( |
| 232 |
"t", |
| 233 |
size=0, |
| 234 |
dimensions=second.dim, |
| 235 |
read_only=True, |
| 236 |
dtype=self._clock.variables["t"].dtype, |
| 237 |
) |
| 238 |
self.variables.add_reference("_num_source_neurons", source, "N") |
| 239 |
self.variables.add_array( |
| 240 |
"N", dtype=np.int32, size=1, scalar=True, read_only=True |
| 241 |
) |
| 242 |
self.variables.create_clock_variables(self._clock, prefix="_clock_") |
| 243 |
self._enable_group_attributes() |
| 244 |
|
| 245 |
def resize(self, new_size): |
| 246 |
# Note that this does not set N, this has to be done in the template |
| 247 |
# since we use a restricted pointer to access it (which promises that |
| 248 |
# we only change the value through this pointer) |
| 249 |
self.variables["rate"].resize(new_size) |
| 250 |
self.variables["t"].resize(new_size) |
| 251 |
|
| 252 |
def reinit(self): |
| 253 |
""" |
| 254 |
Clears all recorded rates |
| 255 |
""" |
| 256 |
raise NotImplementedError() |
| 257 |
|
| 258 |
@check_units(bin_size=second) |
| 259 |
def binned_rate(self, bin_size): |
| 260 |
""" |
| 261 |
Return the population rate binned with the given bin size. |
| 262 |
|
| 263 |
Parameters |
| 264 |
---------- |
| 265 |
bin_size : `Quantity` |
| 266 |
The size of the bins in seconds. Should be a multiple of dt. |
| 267 |
|
| 268 |
Returns |
| 269 |
------- |
| 270 |
bins : `Quantity` |
| 271 |
The start time of the bins. |
| 272 |
binned_values : `Quantity` |
| 273 |
The binned population rates as a 1D array in Hz. |
| 274 |
|
| 275 |
Notes |
| 276 |
----- |
| 277 |
The returned bin times represent the **start** of each bin interval, not the center. |
| 278 |
This is consistent with how Brian2 records spike times and other temporal data. |
| 279 |
For example, a spike recorded at time `t` occurred during the interval `[t, t+dt)`. |
| 280 |
|
| 281 |
For plotting purposes, especially with larger bin sizes, you may want to use bin |
| 282 |
centers instead of bin starts for a more intuitive visualization. You can easily |
| 283 |
calculate the bin centers by adding half the bin size:: |
| 284 |
|
| 285 |
>> bins, rates = monitor.binned_rate(10*ms) |
| 286 |
>> bin_centers = bins + 10*ms / 2 |
| 287 |
>> plt.plot(bin_centers, rates) |
| 288 |
|
| 289 |
This adjustment is particularly helpful when the bins are large relative to the |
| 290 |
time scale of interest, as it better represents where the rate measurement applies |
| 291 |
within each time window. |
| 292 |
|
| 293 |
Warnings |
| 294 |
-------- |
| 295 |
This method will give incorrect results if the monitor has recorded values with |
| 296 |
varying ``dt`` values. |
| 297 |
""" |
| 298 |
if (bin_size / self.clock.dt) % 1 > 1e-6: |
| 299 |
raise ValueError("bin_size has to be a multiple of dt.") |
| 300 |
|
| 301 |
bin_timesteps = timestep( |
| 302 |
bin_size, self.clock.dt |
| 303 |
) # Convert bin_size to integer timestep |
| 304 |
|
| 305 |
if ( |
| 306 |
bin_timesteps == 1 |
| 307 |
): # Early return for dt-sized bins (no binning needed) as bin_size and clock timesteps are same |
| 308 |
return self.t[:], self.rate |
| 309 |
|
| 310 |
# Calculate number of complete bins based on recorded data , Note we don't use `self.clock.timestep` as we want the recorded rates |
| 311 |
num_bins = int( |
| 312 |
len(self.rate) // bin_timesteps |
| 313 |
) # int for type conversion from numpy int |
| 314 |
|
| 315 |
num_values = num_bins * bin_timesteps |
| 316 |
rate_to_bin = self.rate[:num_values] # # Only use complete bins |
| 317 |
|
| 318 |
# No we reshape into (num_bins, bin_timesteps) and take mean over each bin |
| 319 |
binned_values = rate_to_bin.reshape(num_bins, bin_timesteps).mean(axis=1) |
| 320 |
|
| 321 |
# Calculate bin centers based on ACTUAL recorded times |
| 322 |
# Start from when recording began, not from t=0 |
| 323 |
t_start = self.t[0] |
| 324 |
bin_starts_timesteps = (np.arange(num_bins)) * bin_timesteps |
| 325 |
bins = t_start + bin_starts_timesteps * self.clock.dt |
| 326 |
|
| 327 |
return bins, Quantity(binned_values, dim=hertz.dim) |
| 328 |
|
| 329 |
def __repr__(self): |
| 330 |
classname = self.__class__.__name__ |
| 331 |
return f"<{classname}, recording {self.source.name}>" |