| 1 |
""" |
| 2 |
Clocks for the simulator. |
| 3 |
""" |
| 4 |
|
| 5 |
__docformat__ = "restructuredtext en" |
| 6 |
|
| 7 |
from abc import ABC, abstractmethod |
| 8 |
|
| 9 |
import numpy as np |
| 10 |
|
| 11 |
from brian2.core.names import Nameable |
| 12 |
from brian2.core.variables import Variables |
| 13 |
from brian2.groups.group import VariableOwner |
| 14 |
from brian2.units.allunits import second |
| 15 |
from brian2.units.fundamentalunits import Quantity, check_units |
| 16 |
from brian2.units.stdunits import ms |
| 17 |
from brian2.utils.logger import get_logger |
| 18 |
|
| 19 |
__all__ = ["BaseClock", "Clock", "defaultclock", "EventClock"] |
| 20 |
|
| 21 |
logger = get_logger(__name__) |
| 22 |
|
| 23 |
|
| 24 |
def check_dt(new_dt, old_dt, target_t): |
| 25 |
""" |
| 26 |
Check that the target time can be represented equally well with the new |
| 27 |
dt. |
| 28 |
|
| 29 |
Parameters |
| 30 |
---------- |
| 31 |
new_dt : float |
| 32 |
The new dt value |
| 33 |
old_dt : float |
| 34 |
The old dt value |
| 35 |
target_t : float |
| 36 |
The target time |
| 37 |
|
| 38 |
Raises |
| 39 |
------ |
| 40 |
ValueError |
| 41 |
If using the new dt value would lead to a difference in the target |
| 42 |
time of more than `Clock.epsilon_dt` times ``new_dt`` (by default, |
| 43 |
0.01% of the new dt). |
| 44 |
|
| 45 |
Examples |
| 46 |
-------- |
| 47 |
>>> from brian2 import * |
| 48 |
>>> check_dt(float(17*ms), float(0.1*ms), float(0*ms)) # For t=0s, every dt is fine |
| 49 |
>>> check_dt(float(0.05*ms), float(0.1*ms), float(10*ms)) # t=10*ms can be represented with the new dt |
| 50 |
>>> check_dt(float(0.2*ms), float(0.1*ms), float(10.1*ms)) # t=10.1ms cannot be represented with dt=0.2ms # doctest: +ELLIPSIS |
| 51 |
Traceback (most recent call last): |
| 52 |
... |
| 53 |
ValueError: Cannot set dt from 100. us to 200. us, the time 10.1 ms is not a multiple of 200. us. |
| 54 |
""" |
| 55 |
old_t = np.int64(np.round(target_t / old_dt)) * old_dt |
| 56 |
new_t = np.int64(np.round(target_t / new_dt)) * new_dt |
| 57 |
error_t = target_t |
| 58 |
if abs(new_t - old_t) / new_dt > Clock.epsilon_dt: |
| 59 |
old = str(old_dt * second) |
| 60 |
new = str(new_dt * second) |
| 61 |
t = str(error_t * second) |
| 62 |
raise ValueError( |
| 63 |
f"Cannot set dt from {old} to {new}, the " |
| 64 |
f"time {t} is not a multiple of {new}." |
| 65 |
) |
| 66 |
|
| 67 |
|
| 68 |
class BaseClock(VariableOwner, ABC): |
| 69 |
""" |
| 70 |
Abstract base class for all clocks in the simulator. |
| 71 |
|
| 72 |
This class should never be instantiated directly, use one of the subclasses |
| 73 |
like Clock or EventClock instead. |
| 74 |
|
| 75 |
Parameters |
| 76 |
---------- |
| 77 |
name : str, optional |
| 78 |
An explicit name, if not specified gives an automatically generated name |
| 79 |
""" |
| 80 |
|
| 81 |
epsilon = 1e-14 |
| 82 |
|
| 83 |
def __init__(self, name): |
| 84 |
# We need a name right away because some devices (e.g. cpp_standalone) |
| 85 |
# need a name for the object when creating the variables |
| 86 |
Nameable.__init__(self, name=name) |
| 87 |
self.variables = Variables(self) |
| 88 |
self.variables.add_array( |
| 89 |
"timestep", size=1, dtype=np.int64, read_only=True, scalar=True |
| 90 |
) |
| 91 |
self.variables.add_array( |
| 92 |
"t", |
| 93 |
dimensions=second.dim, |
| 94 |
size=1, |
| 95 |
dtype=np.float64, |
| 96 |
read_only=True, |
| 97 |
scalar=True, |
| 98 |
) |
| 99 |
self.variables["timestep"].set_value(0) |
| 100 |
|
| 101 |
self.variables.add_constant("N", value=1) |
| 102 |
|
| 103 |
self._enable_group_attributes() |
| 104 |
|
| 105 |
self._i_end = None |
| 106 |
logger.diagnostic(f"Created clock {self.name}") |
| 107 |
|
| 108 |
@abstractmethod |
| 109 |
def advance(self): |
| 110 |
""" |
| 111 |
Advance the clock to the next time step. |
| 112 |
Must be implemented by subclasses. |
| 113 |
""" |
| 114 |
pass |
| 115 |
|
| 116 |
@abstractmethod |
| 117 |
@check_units(start=second, end=second) |
| 118 |
def set_interval(self, start, end): |
| 119 |
""" |
| 120 |
Set the start and end time of the simulation. |
| 121 |
Must be implemented by subclasses. |
| 122 |
""" |
| 123 |
pass |
| 124 |
|
| 125 |
@abstractmethod |
| 126 |
def same_time(self, other): |
| 127 |
""" |
| 128 |
Check if two clocks are at the same time (within epsilon). |
| 129 |
|
| 130 |
Parameters |
| 131 |
---------- |
| 132 |
other : BaseClock |
| 133 |
The other clock to compare with |
| 134 |
|
| 135 |
Returns |
| 136 |
------- |
| 137 |
bool |
| 138 |
True if both clocks are at the same time |
| 139 |
""" |
| 140 |
pass |
| 141 |
|
| 142 |
|
| 143 |
class EventClock(BaseClock): |
| 144 |
""" |
| 145 |
A clock that advances through a predefined sequence of times. |
| 146 |
|
| 147 |
Parameters |
| 148 |
---------- |
| 149 |
times : array-like |
| 150 |
The sequence of times for the clock to advance through |
| 151 |
name : str, optional |
| 152 |
An explicit name, if not specified gives an automatically generated name |
| 153 |
""" |
| 154 |
|
| 155 |
def __init__(self, times, name="eventclock*"): |
| 156 |
super().__init__(name=name) |
| 157 |
times = Quantity(times) |
| 158 |
from brian2.units.fundamentalunits import fail_for_dimension_mismatch |
| 159 |
|
| 160 |
fail_for_dimension_mismatch( |
| 161 |
times, |
| 162 |
second.dim, |
| 163 |
error_message="'times' must have dimensions of time", |
| 164 |
dim=times, |
| 165 |
) |
| 166 |
|
| 167 |
times_array = np.asarray(times, dtype=float) |
| 168 |
unique_times = np.unique(times_array) |
| 169 |
if len(unique_times) != len(times_array): |
| 170 |
raise ValueError( |
| 171 |
"The times provided to EventClock must not contain duplicates." |
| 172 |
) |
| 173 |
|
| 174 |
self._times = sorted(times) |
| 175 |
self._times.append(np.inf * ms) |
| 176 |
self.variables.add_array( |
| 177 |
"times", |
| 178 |
dimensions=second.dim, |
| 179 |
size=len(self._times), |
| 180 |
values=self._times, |
| 181 |
dtype=np.float64, |
| 182 |
read_only=True, |
| 183 |
) |
| 184 |
self.variables["t"].set_value(self._times[0]) |
| 185 |
|
| 186 |
logger.diagnostic(f"Created event clock {self.name}") |
| 187 |
|
| 188 |
def advance(self): |
| 189 |
""" |
| 190 |
Advance to the next time in the sequence. |
| 191 |
""" |
| 192 |
new_ts = self.variables["timestep"].get_value().item() |
| 193 |
if self._i_end is not None and new_ts + 1 > self._i_end: |
| 194 |
raise StopIteration( |
| 195 |
"EventClock has reached the end of its available times." |
| 196 |
) |
| 197 |
new_ts += 1 |
| 198 |
self.variables["timestep"].set_value(new_ts) |
| 199 |
self.variables["t"].set_value(self._times[new_ts]) |
| 200 |
|
| 201 |
@check_units(start=second, end=second) |
| 202 |
def set_interval(self, start, end): |
| 203 |
""" |
| 204 |
Set the start and end time of the simulation. |
| 205 |
|
| 206 |
Parameters |
| 207 |
---------- |
| 208 |
start : second |
| 209 |
The start time of the simulation |
| 210 |
end : second |
| 211 |
The end time of the simulation |
| 212 |
""" |
| 213 |
start = float(start) |
| 214 |
end = float(end) |
| 215 |
|
| 216 |
start_idx = np.searchsorted(self._times, start) |
| 217 |
end_idx = np.searchsorted(self._times, end) |
| 218 |
|
| 219 |
self.variables["timestep"].set_value(start_idx) |
| 220 |
self.variables["t"].set_value(self._times[start_idx]) |
| 221 |
|
| 222 |
self._i_end = end_idx |
| 223 |
|
| 224 |
def __getitem__(self, timestep): |
| 225 |
""" |
| 226 |
Get the time at a specific timestep. |
| 227 |
|
| 228 |
Parameters |
| 229 |
---------- |
| 230 |
timestep : int |
| 231 |
The timestep to get the time for |
| 232 |
|
| 233 |
Returns |
| 234 |
------- |
| 235 |
float |
| 236 |
The time at the specified timestep |
| 237 |
""" |
| 238 |
return self._times[timestep] |
| 239 |
|
| 240 |
def same_time(self, other): |
| 241 |
""" |
| 242 |
Check if two clocks are at the same time. |
| 243 |
|
| 244 |
For comparisons with `Clock` objects, uses the Clock's dt and epsilon_dt. |
| 245 |
For comparisons with other `EventClock` or `BaseClock` objects, uses the base |
| 246 |
epsilon value. |
| 247 |
|
| 248 |
Parameters |
| 249 |
---------- |
| 250 |
other : BaseClock |
| 251 |
The other clock to compare with |
| 252 |
|
| 253 |
Returns |
| 254 |
------- |
| 255 |
bool |
| 256 |
True if both clocks are at the same time |
| 257 |
""" |
| 258 |
t1 = self.variables["t"].get_value().item() |
| 259 |
t2 = other.variables["t"].get_value().item() |
| 260 |
|
| 261 |
if isinstance(other, Clock): |
| 262 |
return abs(t1 - t2) / other.dt_ < other.epsilon_dt |
| 263 |
else: |
| 264 |
# Both are pure EventClocks without dt. |
| 265 |
return abs(t1 - t2) < self.epsilon |
| 266 |
|
| 267 |
|
| 268 |
class Clock(BaseClock): |
| 269 |
""" |
| 270 |
An object that holds the simulation time and the time step. |
| 271 |
|
| 272 |
Parameters |
| 273 |
---------- |
| 274 |
dt : float |
| 275 |
The time step of the simulation as a float |
| 276 |
name : str, optional |
| 277 |
An explicit name, if not specified gives an automatically generated name |
| 278 |
|
| 279 |
Notes |
| 280 |
----- |
| 281 |
Clocks are run in the same `Network.run` iteration if `~Clock.t` is the |
| 282 |
same. The condition for two |
| 283 |
clocks to be considered as having the same time is |
| 284 |
``abs(t1-t2)<epsilon*abs(t1)``, a standard test for equality of floating |
| 285 |
point values. The value of ``epsilon`` is ``1e-14``. |
| 286 |
""" |
| 287 |
|
| 288 |
#: The relative difference for times (in terms of dt) so that they are |
| 289 |
#: considered identical. |
| 290 |
epsilon_dt = 1e-4 |
| 291 |
|
| 292 |
def __init__(self, dt, name="clock*"): |
| 293 |
super().__init__(name=name) |
| 294 |
|
| 295 |
self._old_dt = None |
| 296 |
|
| 297 |
self.variables.add_array( |
| 298 |
"dt", |
| 299 |
dimensions=second.dim, |
| 300 |
size=1, |
| 301 |
values=float(dt), |
| 302 |
dtype=np.float64, |
| 303 |
read_only=True, |
| 304 |
constant=True, |
| 305 |
scalar=True, |
| 306 |
) |
| 307 |
|
| 308 |
self.dt = dt |
| 309 |
|
| 310 |
logger.diagnostic(f"Created clock {self.name} with dt={self.dt}") |
| 311 |
|
| 312 |
def __repr__(self): |
| 313 |
return f"Clock(dt={self.dt!r}, name={self.name!r})" |
| 314 |
|
| 315 |
def advance(self): |
| 316 |
""" |
| 317 |
Advance to the next time step. |
| 318 |
""" |
| 319 |
new_ts = self.variables["timestep"].get_value().item() + 1 |
| 320 |
if self._i_end is not None and new_ts > self._i_end: |
| 321 |
raise StopIteration("Clock has reached the end of its available times.") |
| 322 |
|
| 323 |
self.variables["timestep"].set_value(new_ts) |
| 324 |
new_t = new_ts * self.dt_ |
| 325 |
self.variables["t"].set_value(new_t) |
| 326 |
|
| 327 |
def _get_dt_(self): |
| 328 |
return self.variables["dt"].get_value().item() |
| 329 |
|
| 330 |
@check_units(dt_=1) |
| 331 |
def _set_dt_(self, dt_): |
| 332 |
self._old_dt = self._get_dt_() |
| 333 |
self.variables["dt"].set_value(dt_) |
| 334 |
|
| 335 |
@check_units(dt=second) |
| 336 |
def _set_dt(self, dt): |
| 337 |
self._set_dt_(float(dt)) |
| 338 |
|
| 339 |
dt = property( |
| 340 |
fget=lambda self: Quantity(self.dt_, dim=second.dim), |
| 341 |
fset=_set_dt, |
| 342 |
doc="""The time step of the simulation in seconds.""", |
| 343 |
) |
| 344 |
dt_ = property( |
| 345 |
fget=_get_dt_, |
| 346 |
fset=_set_dt_, |
| 347 |
doc="""The time step of the simulation as a float (in seconds)""", |
| 348 |
) |
| 349 |
|
| 350 |
def _calc_timestep(self, target_t): |
| 351 |
""" |
| 352 |
Calculate the integer time step for the target time. If it cannot be |
| 353 |
exactly represented (up to epsilon_dt of dt), round up. |
| 354 |
|
| 355 |
Parameters |
| 356 |
---------- |
| 357 |
target_t : float |
| 358 |
The target time in seconds |
| 359 |
|
| 360 |
Returns |
| 361 |
------- |
| 362 |
timestep : int |
| 363 |
The target time in integers (based on dt) |
| 364 |
""" |
| 365 |
new_i = np.int64(np.round(target_t / self.dt_)) |
| 366 |
new_t = new_i * self.dt_ |
| 367 |
if new_t == target_t or np.abs(new_t - target_t) / self.dt_ <= Clock.epsilon_dt: |
| 368 |
new_timestep = new_i |
| 369 |
else: |
| 370 |
new_timestep = np.int64(np.ceil(target_t / self.dt_)) |
| 371 |
return new_timestep |
| 372 |
|
| 373 |
@check_units(target_t=second) |
| 374 |
def _set_t_update_dt(self, target_t=0 * second): |
| 375 |
""" |
| 376 |
Set the time to a specific value, checking if dt has changed. |
| 377 |
|
| 378 |
Parameters |
| 379 |
---------- |
| 380 |
target_t : second |
| 381 |
The target time to set |
| 382 |
""" |
| 383 |
new_dt = self.dt_ |
| 384 |
old_dt = self._old_dt |
| 385 |
target_t = float(target_t) |
| 386 |
|
| 387 |
if old_dt is not None and new_dt != old_dt: |
| 388 |
self._old_dt = None |
| 389 |
check_dt(new_dt, old_dt, target_t) |
| 390 |
|
| 391 |
new_timestep = self._calc_timestep(target_t) |
| 392 |
|
| 393 |
self.variables["timestep"].set_value(new_timestep) |
| 394 |
self.variables["t"].set_value(new_timestep * self.dt_) |
| 395 |
set_t = self.variables["t"].get_value().item() |
| 396 |
|
| 397 |
logger.diagnostic(f"Setting Clock {self.name} to t={set_t}, dt={new_dt}") |
| 398 |
|
| 399 |
@check_units(start=second, end=second) |
| 400 |
def set_interval(self, start, end): |
| 401 |
""" |
| 402 |
Set the start and end time of the simulation. |
| 403 |
|
| 404 |
Sets the start and end value of the clock precisely if |
| 405 |
possible (using epsilon_dt) or rounding up if not. This assures that |
| 406 |
multiple calls to `Network.run` will not re-run the same time step. |
| 407 |
|
| 408 |
Parameters |
| 409 |
---------- |
| 410 |
start : second |
| 411 |
The start time of the simulation |
| 412 |
end : second |
| 413 |
The end time of the simulation |
| 414 |
""" |
| 415 |
self._set_t_update_dt(target_t=start) |
| 416 |
end = float(end) |
| 417 |
self._i_end = self._calc_timestep(end) |
| 418 |
|
| 419 |
if self._i_end > 2**40: |
| 420 |
logger.warn( |
| 421 |
"The end time of the simulation has been set to " |
| 422 |
f"{str(end * second)}, which based on the dt value of " |
| 423 |
f"{str(self.dt)} means that {self._i_end} " |
| 424 |
"time steps will be simulated. This can lead to " |
| 425 |
"numerical problems, e.g. the times t will not " |
| 426 |
"correspond to exact multiples of " |
| 427 |
"dt.", |
| 428 |
"many_timesteps", |
| 429 |
) |
| 430 |
|
| 431 |
def same_time(self, other): |
| 432 |
""" |
| 433 |
Check if two clocks are at the same time (within epsilon_dt * dt). |
| 434 |
|
| 435 |
Parameters |
| 436 |
---------- |
| 437 |
other : BaseClock |
| 438 |
The other clock to compare with |
| 439 |
|
| 440 |
Returns |
| 441 |
------- |
| 442 |
bool |
| 443 |
True if both clocks are at the same time |
| 444 |
""" |
| 445 |
t1 = self.variables["t"].get_value().item() |
| 446 |
t2 = other.variables["t"].get_value().item() |
| 447 |
|
| 448 |
if isinstance(other, Clock): |
| 449 |
# Both are pure Clocks with dt so we take the min. |
| 450 |
dt = min(self.dt_, other.dt_) |
| 451 |
return abs(t1 - t2) / dt < self.epsilon_dt |
| 452 |
else: |
| 453 |
return abs(t1 - t2) / self.dt_ < self.epsilon_dt |
| 454 |
|
| 455 |
def __le__(self, other): |
| 456 |
return self.__lt__(other) or self.same_time(other) |
| 457 |
|
| 458 |
def __ge__(self, other): |
| 459 |
return self.__gt__(other) or self.same_time(other) |
| 460 |
|
| 461 |
|
| 462 |
class DefaultClockProxy: |
| 463 |
""" |
| 464 |
Method proxy to access the defaultclock of the currently active device |
| 465 |
""" |
| 466 |
|
| 467 |
def __getattr__(self, name): |
| 468 |
if name == "_is_proxy": |
| 469 |
return True |
| 470 |
from brian2.devices.device import active_device |
| 471 |
|
| 472 |
return getattr(active_device.defaultclock, name) |
| 473 |
|
| 474 |
def __setattr__(self, key, value): |
| 475 |
from brian2.devices.device import active_device |
| 476 |
|
| 477 |
setattr(active_device.defaultclock, key, value) |
| 478 |
|
| 479 |
|
| 480 |
#: The standard clock, used for objects that do not specify any clock or dt |
| 481 |
defaultclock = DefaultClockProxy() |