| 1 |
import numbers |
| 2 |
from collections.abc import Sequence |
| 3 |
|
| 4 |
import numpy as np |
| 5 |
|
| 6 |
from brian2.core.variables import Variables, get_dtype |
| 7 |
from brian2.groups.group import CodeRunner, Group |
| 8 |
from brian2.units.allunits import second |
| 9 |
from brian2.units.fundamentalunits import Quantity |
| 10 |
from brian2.utils.logger import get_logger |
| 11 |
|
| 12 |
__all__ = ["StateMonitor"] |
| 13 |
|
| 14 |
logger = get_logger(__name__) |
| 15 |
|
| 16 |
|
| 17 |
class StateMonitorView: |
| 18 |
def __init__(self, monitor, item): |
| 19 |
self.monitor = monitor |
| 20 |
self.item = item |
| 21 |
self.indices = self._calc_indices(item) |
| 22 |
self._group_attribute_access_active = True |
| 23 |
|
| 24 |
def __getattr__(self, item): |
| 25 |
# We do this because __setattr__ and __getattr__ are not active until |
| 26 |
# _group_attribute_access_active attribute is set, and if it is set, |
| 27 |
# then __getattr__ will not be called. Therefore, if getattr is called |
| 28 |
# with this name, it is because it hasn't been set yet and so this |
| 29 |
# method should raise an AttributeError to agree that it hasn't been |
| 30 |
# called yet. |
| 31 |
if item == "_group_attribute_access_active": |
| 32 |
raise AttributeError |
| 33 |
if not hasattr(self, "_group_attribute_access_active"): |
| 34 |
raise AttributeError |
| 35 |
|
| 36 |
mon = self.monitor |
| 37 |
if item == "t": |
| 38 |
return Quantity(mon.variables["t"].get_value(), dim=second.dim) |
| 39 |
elif item == "t_": |
| 40 |
return mon.variables["t"].get_value() |
| 41 |
elif item in mon.record_variables: |
| 42 |
dims = mon.variables[item].dim |
| 43 |
return Quantity( |
| 44 |
mon.variables[item].get_value().T[self.indices], dim=dims, copy=True |
| 45 |
) |
| 46 |
elif item.endswith("_") and item[:-1] in mon.record_variables: |
| 47 |
return mon.variables[item[:-1]].get_value().T[self.indices].copy() |
| 48 |
else: |
| 49 |
raise AttributeError(f"Unknown attribute {item}") |
| 50 |
|
| 51 |
def _calc_indices(self, item): |
| 52 |
""" |
| 53 |
Convert the neuron indices to indices into the stored values. For example, if neurons [0, 5, 10] have been |
| 54 |
recorded, [5, 10] is converted to [1, 2]. |
| 55 |
""" |
| 56 |
dtype = get_dtype(item) |
| 57 |
# scalar value |
| 58 |
if np.issubdtype(dtype, np.signedinteger) and not isinstance(item, np.ndarray): |
| 59 |
indices = np.nonzero(self.monitor.record == item)[0] |
| 60 |
if len(indices) == 0: |
| 61 |
raise IndexError(f"Index number {int(item)} has not been recorded") |
| 62 |
return indices[0] |
| 63 |
|
| 64 |
if self.monitor.record_all: |
| 65 |
return item |
| 66 |
indices = [] |
| 67 |
for index in item: |
| 68 |
if index in self.monitor.record: |
| 69 |
indices.append(np.nonzero(self.monitor.record == index)[0][0]) |
| 70 |
else: |
| 71 |
raise IndexError(f"Index number {int(index)} has not been recorded") |
| 72 |
return np.array(indices) |
| 73 |
|
| 74 |
def __repr__(self): |
| 75 |
classname = self.__class__.__name__ |
| 76 |
return ( |
| 77 |
f"<{classname}, giving access to elements {self.item!r} recorded by " |
| 78 |
f"{self.monitor.name}>" |
| 79 |
) |
| 80 |
|
| 81 |
|
| 82 |
class StateMonitor(Group, CodeRunner): |
| 83 |
""" |
| 84 |
Record values of state variables during a run |
| 85 |
|
| 86 |
To extract recorded values after a run, use the ``t`` attribute for the |
| 87 |
array of times at which values were recorded, and variable name attribute |
| 88 |
for the values. The values will have shape ``(len(indices), len(t))``, |
| 89 |
where ``indices`` are the array indices which were recorded. When indexing |
| 90 |
the `StateMonitor` directly, the returned object can be used to get the |
| 91 |
recorded values for the specified indices, i.e. the indexing semantic |
| 92 |
refers to the indices in ``source``, not to the relative indices of the |
| 93 |
recorded values. For example, when recording only neurons with even numbers, |
| 94 |
`mon[[0, 2]].v` will return the values for neurons 0 and 2, whereas |
| 95 |
`mon.v[[0, 2]]` will return the values for the first and third *recorded* |
| 96 |
neurons, i.e. for neurons 0 and 4. |
| 97 |
|
| 98 |
Parameters |
| 99 |
---------- |
| 100 |
source : `Group` |
| 101 |
Which object to record values from. |
| 102 |
variables : str, sequence of str, True |
| 103 |
Which variables to record, or ``True`` to record all variables |
| 104 |
(note that this may use a great deal of memory). |
| 105 |
record : bool, sequence of ints |
| 106 |
Which indices to record, nothing is recorded for ``False``, |
| 107 |
everything is recorded for ``True`` (warning: may use a great deal of |
| 108 |
memory), or a specified subset of indices. |
| 109 |
dt : `Quantity`, optional |
| 110 |
The time step to be used for the monitor. Cannot be combined with |
| 111 |
the `clock` argument. |
| 112 |
clock : `Clock`, optional |
| 113 |
The update clock to be used. If neither a clock, nor the ``dt`` argument |
| 114 |
is specified, the clock of the `source` will be used. |
| 115 |
when : str, optional |
| 116 |
At which point during a time step the values should be recorded. |
| 117 |
Defaults to ``'start'``. See :ref:`scheduling` for possible values. |
| 118 |
order : int, optional |
| 119 |
The priority of of this group for operations occurring at the same time |
| 120 |
step and in the same scheduling slot. Defaults to 0. |
| 121 |
name : str, optional |
| 122 |
A unique name for the object, otherwise will use |
| 123 |
``source.name+'statemonitor_0'``, etc. |
| 124 |
codeobj_class : `CodeObject`, optional |
| 125 |
The `CodeObject` class to create. |
| 126 |
|
| 127 |
Examples |
| 128 |
-------- |
| 129 |
|
| 130 |
Record all variables, first 5 indices:: |
| 131 |
|
| 132 |
eqs = ''' |
| 133 |
dV/dt = (2-V)/(10*ms) : 1 |
| 134 |
''' |
| 135 |
threshold = 'V>1' |
| 136 |
reset = 'V = 0' |
| 137 |
G = NeuronGroup(100, eqs, threshold=threshold, reset=reset) |
| 138 |
G.V = rand(len(G)) |
| 139 |
M = StateMonitor(G, True, record=range(5)) |
| 140 |
run(100*ms) |
| 141 |
plot(M.t, M.V.T) |
| 142 |
show() |
| 143 |
|
| 144 |
Notes |
| 145 |
----- |
| 146 |
|
| 147 |
Since this monitor by default records in the ``'start'`` time slot, |
| 148 |
recordings of the membrane potential in integrate-and-fire models may look |
| 149 |
unexpected: the recorded membrane potential trace will never be above |
| 150 |
threshold in an integrate-and-fire model, because the reset statement will |
| 151 |
have been applied already. Set the ``when`` keyword to a different value if |
| 152 |
this is not what you want. |
| 153 |
|
| 154 |
Note that ``record=True`` only works in runtime mode for synaptic variables. |
| 155 |
This is because the actual array of indices has to be calculated and this is |
| 156 |
not possible in standalone mode, where the synapses have not been created |
| 157 |
yet at this stage. Consider using an explicit array of indices instead, |
| 158 |
i.e. something like ``record=np.arange(n_synapses)``. |
| 159 |
""" |
| 160 |
|
| 161 |
invalidates_magic_network = False |
| 162 |
add_to_magic_network = True |
| 163 |
|
| 164 |
def __init__( |
| 165 |
self, |
| 166 |
source, |
| 167 |
variables, |
| 168 |
record, |
| 169 |
dt=None, |
| 170 |
clock=None, |
| 171 |
when="start", |
| 172 |
order=0, |
| 173 |
name="statemonitor*", |
| 174 |
codeobj_class=None, |
| 175 |
): |
| 176 |
self.source = source |
| 177 |
# Make the monitor use the explicitly defined namespace of its source |
| 178 |
# group (if it exists) |
| 179 |
self.namespace = getattr(source, "namespace", None) |
| 180 |
self.codeobj_class = codeobj_class |
| 181 |
|
| 182 |
# run by default on source clock at the end |
| 183 |
if dt is None and clock is None: |
| 184 |
clock = source.clock |
| 185 |
|
| 186 |
# variables should always be a list of strings |
| 187 |
if variables is True: |
| 188 |
variables = source.equations.names |
| 189 |
elif isinstance(variables, str): |
| 190 |
variables = [variables] |
| 191 |
#: The variables to record |
| 192 |
self.record_variables = variables |
| 193 |
|
| 194 |
# record should always be an array of ints |
| 195 |
self.record_all = False |
| 196 |
if hasattr(record, "_indices"): |
| 197 |
# The ._indices method always returns absolute indices |
| 198 |
# If the source is already a subgroup of another group, we therefore |
| 199 |
# have to shift the indices to become relative to the subgroup |
| 200 |
record = record._indices() - getattr(source, "_offset", 0) |
| 201 |
if record is True: |
| 202 |
self.record_all = True |
| 203 |
try: |
| 204 |
record = np.arange(len(source), dtype=np.int32) |
| 205 |
except NotImplementedError as ex: |
| 206 |
# In standalone mode, this is not possible for synaptic |
| 207 |
# variables because the number of synapses is not defined yet |
| 208 |
raise NotImplementedError( |
| 209 |
"Cannot determine the actual " |
| 210 |
"indices to record for record=True. " |
| 211 |
"This can occur for example in " |
| 212 |
"standalone mode when trying to " |
| 213 |
"record a synaptic variable. " |
| 214 |
"Consider providing an explicit " |
| 215 |
"array of indices for the record " |
| 216 |
"argument." |
| 217 |
) from ex |
| 218 |
elif record is False: |
| 219 |
record = np.array([], dtype=np.int32) |
| 220 |
elif isinstance(record, numbers.Number): |
| 221 |
record = np.array([record], dtype=np.int32) |
| 222 |
else: |
| 223 |
record = np.asarray(record, dtype=np.int32) |
| 224 |
|
| 225 |
#: The array of recorded indices |
| 226 |
self.record = record |
| 227 |
self.n_indices = len(record) |
| 228 |
|
| 229 |
if not self.record_all: |
| 230 |
try: |
| 231 |
if len(record) and ( |
| 232 |
np.max(record) >= len(source) or np.min(record) < 0 |
| 233 |
): |
| 234 |
# Check whether the values in record make sense |
| 235 |
error_message = ( |
| 236 |
"The indices to record from contain values outside of the" |
| 237 |
f" range [0, {len(source) - 1}] allowed for the group" |
| 238 |
f" '{source.name}'" |
| 239 |
) |
| 240 |
raise IndexError(error_message) |
| 241 |
except NotImplementedError: |
| 242 |
logger.warn( |
| 243 |
"Cannot check whether the indices to record from are valid. This" |
| 244 |
" can happen in standalone mode when recording from synapses that" |
| 245 |
" have been created with a connection pattern. You can avoid this" |
| 246 |
" situation by using synaptic indices in the connect call.", |
| 247 |
name_suffix="cannot_check_statemonitor_indices", |
| 248 |
) |
| 249 |
|
| 250 |
# Some dummy code so that code generation takes care of the indexing |
| 251 |
# and subexpressions |
| 252 |
code = [f"_to_record_{v} = _source_{v}" for v in variables] |
| 253 |
code = "\n".join(code) |
| 254 |
|
| 255 |
CodeRunner.__init__( |
| 256 |
self, |
| 257 |
group=self, |
| 258 |
template="statemonitor", |
| 259 |
code=code, |
| 260 |
name=name, |
| 261 |
clock=clock, |
| 262 |
dt=dt, |
| 263 |
when=when, |
| 264 |
order=order, |
| 265 |
check_units=False, |
| 266 |
) |
| 267 |
|
| 268 |
self.add_dependency(source) |
| 269 |
|
| 270 |
# Setup variables |
| 271 |
self.variables = Variables(self) |
| 272 |
|
| 273 |
self.variables.add_dynamic_array( |
| 274 |
"t", |
| 275 |
size=0, |
| 276 |
dimensions=second.dim, |
| 277 |
constant=False, |
| 278 |
dtype=self._clock.variables["t"].dtype, |
| 279 |
read_only=True, |
| 280 |
) |
| 281 |
self.variables.add_array( |
| 282 |
"N", dtype=np.int32, size=1, scalar=True, read_only=True |
| 283 |
) |
| 284 |
self.variables.add_array( |
| 285 |
"_indices", |
| 286 |
size=len(self.record), |
| 287 |
dtype=self.record.dtype, |
| 288 |
constant=True, |
| 289 |
read_only=True, |
| 290 |
values=self.record, |
| 291 |
) |
| 292 |
self.variables.create_clock_variables(self._clock, prefix="_clock_") |
| 293 |
for varname in variables: |
| 294 |
var = source.variables[varname] |
| 295 |
if var.scalar and len(self.record) > 1: |
| 296 |
logger.warn( |
| 297 |
"Variable %s is a shared variable but it will be " |
| 298 |
"recorded once for every target." % varname, |
| 299 |
once=True, |
| 300 |
) |
| 301 |
index = source.variables.indices[varname] |
| 302 |
self.variables.add_reference( |
| 303 |
f"_source_{varname}", source, varname, index=index |
| 304 |
) |
| 305 |
if index not in ("_idx", "0") and index not in variables: |
| 306 |
self.variables.add_reference(index, source) |
| 307 |
self.variables.add_dynamic_array( |
| 308 |
varname, |
| 309 |
size=(0, len(self.record)), |
| 310 |
resize_along_first=True, |
| 311 |
dimensions=var.dim, |
| 312 |
dtype=var.dtype, |
| 313 |
constant=False, |
| 314 |
read_only=True, |
| 315 |
) |
| 316 |
|
| 317 |
for varname in variables: |
| 318 |
var = self.source.variables[varname] |
| 319 |
self.variables.add_auxiliary_variable( |
| 320 |
f"_to_record_{varname}", |
| 321 |
dimensions=var.dim, |
| 322 |
dtype=var.dtype, |
| 323 |
scalar=var.scalar, |
| 324 |
) |
| 325 |
|
| 326 |
self.recorded_variables = { |
| 327 |
varname: self.variables[varname] for varname in variables |
| 328 |
} |
| 329 |
recorded_names = [varname for varname in variables] |
| 330 |
|
| 331 |
self.needed_variables = recorded_names |
| 332 |
self.template_kwds = {"_recorded_variables": self.recorded_variables} |
| 333 |
self.written_readonly_vars = { |
| 334 |
self.variables[varname] for varname in self.record_variables |
| 335 |
} |
| 336 |
self._enable_group_attributes() |
| 337 |
|
| 338 |
def resize(self, new_size): |
| 339 |
self.variables["N"].set_value(new_size) |
| 340 |
self.variables["t"].resize(new_size) |
| 341 |
|
| 342 |
for var in self.recorded_variables.values(): |
| 343 |
var.resize((new_size, self.n_indices)) |
| 344 |
|
| 345 |
def reinit(self): |
| 346 |
raise NotImplementedError() |
| 347 |
|
| 348 |
def __getitem__(self, item): |
| 349 |
dtype = get_dtype(item) |
| 350 |
if np.issubdtype(dtype, np.signedinteger): |
| 351 |
return StateMonitorView(self, item) |
| 352 |
elif isinstance(item, Sequence): |
| 353 |
index_array = np.array(item) |
| 354 |
if not np.issubdtype(index_array.dtype, np.signedinteger): |
| 355 |
raise TypeError("Index has to be an integer or a sequence of integers") |
| 356 |
return StateMonitorView(self, item) |
| 357 |
elif hasattr(item, "_indices"): |
| 358 |
# objects that support the indexing interface will return absolute |
| 359 |
# indices but here we need relative ones |
| 360 |
# TODO: How to we prevent the use of completely unrelated objects here? |
| 361 |
source_offset = getattr(self.source, "_offset", 0) |
| 362 |
return StateMonitorView(self, item._indices() - source_offset) |
| 363 |
else: |
| 364 |
raise TypeError(f"Cannot use object of type {type(item)} as an index") |
| 365 |
|
| 366 |
def __getattr__(self, item): |
| 367 |
# We do this because __setattr__ and __getattr__ are not active until |
| 368 |
# _group_attribute_access_active attribute is set, and if it is set, |
| 369 |
# then __getattr__ will not be called. Therefore, if getattr is called |
| 370 |
# with this name, it is because it hasn't been set yet and so this |
| 371 |
# method should raise an AttributeError to agree that it hasn't been |
| 372 |
# called yet. |
| 373 |
if item == "_group_attribute_access_active": |
| 374 |
raise AttributeError |
| 375 |
if not hasattr(self, "_group_attribute_access_active"): |
| 376 |
raise AttributeError |
| 377 |
if item in self.record_variables: |
| 378 |
var_dim = self.variables[item].dim |
| 379 |
return Quantity(self.variables[item].get_value().T, dim=var_dim, copy=True) |
| 380 |
elif item.endswith("_") and item[:-1] in self.record_variables: |
| 381 |
return self.variables[item[:-1]].get_value().T |
| 382 |
else: |
| 383 |
return Group.__getattr__(self, item) |
| 384 |
|
| 385 |
def __repr__(self): |
| 386 |
classname = self.__class__.__name__ |
| 387 |
variables = repr(self.record_variables) |
| 388 |
return f"<{classname}, recording {variables} from '{self.source.name}'>" |
| 389 |
|
| 390 |
def record_single_timestep(self): |
| 391 |
""" |
| 392 |
Records a single time step. Useful for recording the values at the end |
| 393 |
of the simulation -- otherwise a `StateMonitor` will not record the |
| 394 |
last simulated values since its ``when`` attribute defaults to |
| 395 |
``'start'``, i.e. the last recording is at the *beginning* of the last |
| 396 |
time step. |
| 397 |
|
| 398 |
Notes |
| 399 |
----- |
| 400 |
This function will only work if the `StateMonitor` has been already run, |
| 401 |
but a run with a length of ``0*ms`` does suffice. |
| 402 |
|
| 403 |
Examples |
| 404 |
-------- |
| 405 |
>>> from brian2 import * |
| 406 |
>>> G = NeuronGroup(1, 'dv/dt = -v/(5*ms) : 1') |
| 407 |
>>> G.v = 1 |
| 408 |
>>> mon = StateMonitor(G, 'v', record=True) |
| 409 |
>>> run(0.5*ms) |
| 410 |
>>> print(np.array_str(mon.v[:], precision=3)) |
| 411 |
[[ 1. 0.98 0.961 0.942 0.923]] |
| 412 |
>>> print(mon.t[:]) |
| 413 |
[ 0. 100. 200. 300. 400.] us |
| 414 |
>>> print(np.array_str(G.v[:], precision=3)) # last value had not been recorded |
| 415 |
[ 0.905] |
| 416 |
>>> mon.record_single_timestep() |
| 417 |
>>> print(mon.t[:]) |
| 418 |
[ 0. 100. 200. 300. 400. 500.] us |
| 419 |
>>> print(np.array_str(mon.v[:], precision=3)) |
| 420 |
[[ 1. 0.98 0.961 0.942 0.923 0.905]] |
| 421 |
""" |
| 422 |
if self.codeobj is None: |
| 423 |
raise TypeError( |
| 424 |
"Can only record a single time step after the " |
| 425 |
"network has been run once." |
| 426 |
) |
| 427 |
self.codeobj() |
| 428 |
|
| 429 |
def after_run(self): |
| 430 |
super().after_run() |
| 431 |
# In Cython runtime mode, we directly update the underlying dynamic array, |
| 432 |
# so the size attribute of the Variable does not get updated automatically |
| 433 |
for var in ["t"] + list(self.record_variables): |
| 434 |
try: |
| 435 |
val = self.variables[var].get_value() |
| 436 |
# Note : For 1D arrays : size = length (integer) |
| 437 |
# For 2D arrays: size = shape( tuple) |
| 438 |
self.variables[var].size = val.shape if val.ndim > 1 else len(val) |
| 439 |
except (KeyError, NotImplementedError): |
| 440 |
pass # Does not apply to standalone mode |