| 1 |
import gc |
| 2 |
import inspect |
| 3 |
import itertools |
| 4 |
import weakref |
| 5 |
|
| 6 |
from brian2.units.allunits import second |
| 7 |
from brian2.units.fundamentalunits import check_units |
| 8 |
from brian2.utils.logger import get_logger |
| 9 |
|
| 10 |
from .base import BrianObject |
| 11 |
from .network import Network |
| 12 |
|
| 13 |
__all__ = [ |
| 14 |
"MagicNetwork", |
| 15 |
"magic_network", |
| 16 |
"MagicError", |
| 17 |
"run", |
| 18 |
"stop", |
| 19 |
"collect", |
| 20 |
"store", |
| 21 |
"restore", |
| 22 |
"start_scope", |
| 23 |
] |
| 24 |
|
| 25 |
logger = get_logger(__name__) |
| 26 |
|
| 27 |
|
| 28 |
def _get_contained_objects(obj): |
| 29 |
""" |
| 30 |
Helper function to recursively get all contained objects. |
| 31 |
|
| 32 |
Parameters |
| 33 |
---------- |
| 34 |
obj : `BrianObject` |
| 35 |
An object that (potentially) contains other objects, e.g. a |
| 36 |
`NeuronGroup` contains a `StateUpdater`, etc. |
| 37 |
|
| 38 |
Returns |
| 39 |
------- |
| 40 |
objects : list of `BrianObject` |
| 41 |
A list of all the objects contained in `obj` |
| 42 |
""" |
| 43 |
objects = [] |
| 44 |
contained_objects = getattr(obj, "contained_objects", []) |
| 45 |
objects.extend(contained_objects) |
| 46 |
for contained_obj in contained_objects: |
| 47 |
objects.extend(_get_contained_objects(contained_obj)) |
| 48 |
|
| 49 |
return objects |
| 50 |
|
| 51 |
|
| 52 |
def get_objects_in_namespace(level): |
| 53 |
r""" |
| 54 |
Get all the objects in the current namespace that derive from `BrianObject`. |
| 55 |
Used to determine the objects for the `MagicNetwork`. |
| 56 |
|
| 57 |
Parameters |
| 58 |
---------- |
| 59 |
level : int, optional |
| 60 |
How far to go back to get the locals/globals. Each function/method |
| 61 |
call should add ``1`` to this argument, functions/method with a |
| 62 |
decorator have to add ``2``. |
| 63 |
|
| 64 |
Returns |
| 65 |
------- |
| 66 |
objects : set |
| 67 |
A set with weak references to the `BrianObject`\ s in the namespace. |
| 68 |
""" |
| 69 |
# Get the locals and globals from the stack frame |
| 70 |
objects = set() |
| 71 |
frame = inspect.stack()[level + 1][0] |
| 72 |
for _, v in itertools.chain(frame.f_globals.items(), frame.f_locals.items()): |
| 73 |
# We are only interested in numbers and functions, not in |
| 74 |
# everything else (classes, modules, etc.) |
| 75 |
if isinstance(v, BrianObject): |
| 76 |
objects.add(weakref.ref(v)) |
| 77 |
del frame |
| 78 |
return objects |
| 79 |
|
| 80 |
|
| 81 |
class MagicError(Exception): |
| 82 |
""" |
| 83 |
Error that is raised when something goes wrong in `MagicNetwork` |
| 84 |
|
| 85 |
See notes to `MagicNetwork` for more details. |
| 86 |
""" |
| 87 |
|
| 88 |
pass |
| 89 |
|
| 90 |
|
| 91 |
class MagicNetwork(Network): |
| 92 |
""" |
| 93 |
`Network` that automatically adds all Brian objects |
| 94 |
|
| 95 |
In order to avoid bugs, this class will occasionally raise |
| 96 |
`MagicError` when the intent of the user is not clear. See the notes |
| 97 |
below for more details on this point. If you persistently see this |
| 98 |
error, then Brian is not able to safely guess what you intend to do, and |
| 99 |
you should use a `Network` object and call `Network.run` explicitly. |
| 100 |
|
| 101 |
Note that this class cannot be instantiated by the user, there can be only |
| 102 |
one instance `magic_network` of `MagicNetwork`. |
| 103 |
|
| 104 |
Notes |
| 105 |
----- |
| 106 |
|
| 107 |
All Brian objects that are visible at the point of the `run` call will be |
| 108 |
included in the network. This class is designed to work in the following |
| 109 |
two major use cases: |
| 110 |
|
| 111 |
1. You create a collection of Brian objects, and call `run` to run the |
| 112 |
simulation. Subsequently, you may call `run` again to run it again for |
| 113 |
a further duration. In this case, the `Network.t` time will start at 0 |
| 114 |
and for the second call to `run` will continue from the end of the |
| 115 |
previous run. |
| 116 |
|
| 117 |
2. You have a loop in which at each iteration, you create some Brian |
| 118 |
objects and run a simulation using them. In this case, time is reset to |
| 119 |
0 for each call to `run`. |
| 120 |
|
| 121 |
In any other case, you will have to explicitly create a `Network` object |
| 122 |
yourself and call `Network.run` on this object. Brian has a built in |
| 123 |
system to guess which of the cases above applies and behave correctly. |
| 124 |
When it is not possible to safely guess which case you are in, it raises |
| 125 |
`MagicError`. The rules for this guessing system are explained below. |
| 126 |
|
| 127 |
If a simulation consists only of objects that have not been run, it will |
| 128 |
assume that you want to start a new simulation. If a simulation only |
| 129 |
consists of objects that have been simulated in the previous `run` call, |
| 130 |
it will continue that simulation at the previous time. |
| 131 |
|
| 132 |
If neither of these two situations apply, i.e., the network consists of a |
| 133 |
mix of previously run objects and new objects, an error will be raised. |
| 134 |
|
| 135 |
In these checks, "non-invalidating" objects (i.e. objects that have |
| 136 |
`BrianObject.invalidates_magic_network` set to ``False``) are ignored, e.g. |
| 137 |
creating new monitors is always possible. |
| 138 |
|
| 139 |
See Also |
| 140 |
-------- |
| 141 |
Network, collect, run, stop, store, restore |
| 142 |
""" |
| 143 |
|
| 144 |
_already_created = False |
| 145 |
|
| 146 |
def __init__(self): |
| 147 |
if MagicNetwork._already_created: |
| 148 |
raise ValueError("There can be only one MagicNetwork.") |
| 149 |
MagicNetwork._already_created = True |
| 150 |
|
| 151 |
super().__init__(name="magicnetwork*") |
| 152 |
|
| 153 |
self._previous_refs = set() |
| 154 |
|
| 155 |
def add(self, *objs): |
| 156 |
""" |
| 157 |
You cannot add objects directly to `MagicNetwork` |
| 158 |
""" |
| 159 |
raise MagicError("Cannot directly modify MagicNetwork") |
| 160 |
|
| 161 |
def remove(self, *objs): |
| 162 |
""" |
| 163 |
You cannot remove objects directly from `MagicNetwork` |
| 164 |
""" |
| 165 |
raise MagicError("Cannot directly modify MagicNetwork") |
| 166 |
|
| 167 |
def _update_magic_objects(self, level): |
| 168 |
objects = collect(level + 1) |
| 169 |
contained_objects = set() |
| 170 |
for obj in objects: |
| 171 |
for contained in _get_contained_objects(obj): |
| 172 |
contained_objects.add(contained) |
| 173 |
objects |= contained_objects |
| 174 |
|
| 175 |
# check whether we should restart time, continue time, or raise an |
| 176 |
# error |
| 177 |
some_known = False |
| 178 |
some_new = False |
| 179 |
for obj in objects: |
| 180 |
if obj._network == self.id: |
| 181 |
some_known = True # we are continuing a previous run |
| 182 |
elif obj._network is None and obj.invalidates_magic_network: |
| 183 |
some_new = True |
| 184 |
# Note that the inclusion of objects that have been run as part of |
| 185 |
# other objects will lead to an error in `Network.before_run`, we |
| 186 |
# do not have to deal with this case here. |
| 187 |
|
| 188 |
if some_known and some_new: |
| 189 |
raise MagicError( |
| 190 |
"The magic network contains a mix of objects " |
| 191 |
"that has been run before and new objects, Brian " |
| 192 |
"does not know whether you want to start a new " |
| 193 |
"simulation or continue an old one. Consider " |
| 194 |
"explicitly creating a Network object. Also note " |
| 195 |
"that you can find out which objects will be " |
| 196 |
"included in a magic network with the " |
| 197 |
"collect() function." |
| 198 |
) |
| 199 |
elif some_new: # all objects are new, start a new simulation |
| 200 |
# reset time |
| 201 |
self.t_ = 0.0 |
| 202 |
# reset id -- think of this as a new Network |
| 203 |
self.assign_id() |
| 204 |
|
| 205 |
for obj in objects: |
| 206 |
if obj._network is None: |
| 207 |
obj._network = self.id |
| 208 |
|
| 209 |
self.objects = objects |
| 210 |
numobjs = len(self.objects) |
| 211 |
names = ", ".join(obj.name for obj in self.objects) |
| 212 |
logger.debug( |
| 213 |
f"Updated MagicNetwork to include {numobjs} objects with names {names}", |
| 214 |
name_suffix="magic_objects", |
| 215 |
) |
| 216 |
|
| 217 |
def check_dependencies(self): |
| 218 |
all_ids = {obj.id for obj in self.objects} |
| 219 |
for obj in self.objects: |
| 220 |
if not obj.active: |
| 221 |
continue # object is already inactive, no need to check it |
| 222 |
for dependency in obj._dependencies: |
| 223 |
if dependency not in all_ids: |
| 224 |
logger.warn( |
| 225 |
f"'{obj.name}' has been included in the network but " |
| 226 |
"not the object on which it depends." |
| 227 |
f"Setting '{obj.name}' to inactive.", |
| 228 |
name_suffix="dependency_warning", |
| 229 |
) |
| 230 |
obj.active = False |
| 231 |
break |
| 232 |
|
| 233 |
def after_run(self): |
| 234 |
super().after_run() |
| 235 |
self.objects.clear() |
| 236 |
gc.collect() # Make sure that all unused objects are cleared |
| 237 |
|
| 238 |
def run( |
| 239 |
self, |
| 240 |
duration, |
| 241 |
report=None, |
| 242 |
report_period=10 * second, |
| 243 |
namespace=None, |
| 244 |
profile=None, |
| 245 |
level=0, |
| 246 |
): |
| 247 |
self._update_magic_objects(level=level + 1) |
| 248 |
Network.run( |
| 249 |
self, |
| 250 |
duration, |
| 251 |
report=report, |
| 252 |
report_period=report_period, |
| 253 |
namespace=namespace, |
| 254 |
profile=profile, |
| 255 |
level=level + 1, |
| 256 |
) |
| 257 |
|
| 258 |
def store(self, name="default", filename=None, level=0): |
| 259 |
""" |
| 260 |
See `Network.store`. |
| 261 |
""" |
| 262 |
self._update_magic_objects(level=level + 1) |
| 263 |
super().store(name=name, filename=filename) |
| 264 |
self.objects.clear() |
| 265 |
|
| 266 |
def restore( |
| 267 |
self, name="default", filename=None, restore_random_state=False, level=0 |
| 268 |
): |
| 269 |
""" |
| 270 |
See `Network.restore`. |
| 271 |
""" |
| 272 |
self._update_magic_objects(level=level + 1) |
| 273 |
super().restore( |
| 274 |
name=name, filename=filename, restore_random_state=restore_random_state |
| 275 |
) |
| 276 |
self.objects.clear() |
| 277 |
|
| 278 |
def get_states(self, units=True, format="dict", subexpressions=False, level=0): |
| 279 |
""" |
| 280 |
See `Network.get_states`. |
| 281 |
""" |
| 282 |
self._update_magic_objects(level=level + 1) |
| 283 |
states = super().get_states(units, format, subexpressions, level=level + 1) |
| 284 |
self.objects.clear() |
| 285 |
return states |
| 286 |
|
| 287 |
def set_states(self, values, units=True, format="dict", level=0): |
| 288 |
""" |
| 289 |
See `Network.set_states`. |
| 290 |
""" |
| 291 |
self._update_magic_objects(level=level + 1) |
| 292 |
super().set_states(values, units, format, level=level + 1) |
| 293 |
self.objects.clear() |
| 294 |
|
| 295 |
def __str__(self): |
| 296 |
return "MagicNetwork()" |
| 297 |
|
| 298 |
__repr__ = __str__ |
| 299 |
|
| 300 |
|
| 301 |
#: Automatically constructed `MagicNetwork` of all Brian objects |
| 302 |
magic_network = MagicNetwork() |
| 303 |
|
| 304 |
|
| 305 |
def collect(level=0): |
| 306 |
r""" |
| 307 |
Return the list of `BrianObject`\ s that will be simulated if `run` is |
| 308 |
called. |
| 309 |
|
| 310 |
Parameters |
| 311 |
---------- |
| 312 |
level : int, optional |
| 313 |
How much further up to go in the stack to find the objects. Needs |
| 314 |
only to be specified if `collect` is called as part of a function |
| 315 |
and should be increased by 1 for every level of nesting. Defaults to 0. |
| 316 |
|
| 317 |
Returns |
| 318 |
------- |
| 319 |
objects : set of `BrianObject` |
| 320 |
The objects that will be simulated. |
| 321 |
""" |
| 322 |
all_objects = set() |
| 323 |
for obj in get_objects_in_namespace(level=level + 1): |
| 324 |
obj = obj() |
| 325 |
if obj.add_to_magic_network: |
| 326 |
gk = BrianObject._scope_current_key |
| 327 |
k = obj._scope_key |
| 328 |
if gk != k: |
| 329 |
continue |
| 330 |
all_objects.add(obj) |
| 331 |
return all_objects |
| 332 |
|
| 333 |
|
| 334 |
@check_units(duration=second, report_period=second) |
| 335 |
def run( |
| 336 |
duration, |
| 337 |
report=None, |
| 338 |
report_period=10 * second, |
| 339 |
namespace=None, |
| 340 |
profile=None, |
| 341 |
level=0, |
| 342 |
): |
| 343 |
""" |
| 344 |
run(duration, report=None, report_period=10*second, namespace=None, level=0) |
| 345 |
|
| 346 |
Runs a simulation with all "visible" Brian objects for the given duration. |
| 347 |
Calls `collect` to gather all the objects, the simulation can |
| 348 |
be stopped by calling the global `stop` function. |
| 349 |
|
| 350 |
In order to avoid bugs, this function will occasionally raise |
| 351 |
`MagicError` when the intent of the user is not clear. See the notes to |
| 352 |
`MagicNetwork` for more details on this point. If you persistently see this |
| 353 |
error, then Brian is not able to safely guess what you intend to do, and |
| 354 |
you should use a `Network` object and call `Network.run` explicitly. |
| 355 |
|
| 356 |
Parameters |
| 357 |
---------- |
| 358 |
|
| 359 |
duration : `Quantity` |
| 360 |
The amount of simulation time to run for. If the network consists of |
| 361 |
new objects since the last time `run` was called, the start time will |
| 362 |
be reset to 0. If `run` is called twice or more without changing the |
| 363 |
set of objects, the second and subsequent runs will start from the |
| 364 |
end time of the previous run. To explicitly reset the time to 0, |
| 365 |
do ``magic_network.t = 0*second``. |
| 366 |
report : {None, 'text', 'stdout', 'stderr', function}, optional |
| 367 |
How to report the progress of the simulation. If ``None``, do not |
| 368 |
report progress. If ``'text'`` or ``'stdout'`` is specified, print |
| 369 |
the progress to stdout. If ``'stderr'`` is specified, print the |
| 370 |
progress to stderr. Alternatively, you can specify a callback |
| 371 |
``callable(elapsed, completed, start, duration)`` which will be passed |
| 372 |
the amount of time elapsed as a `Quantity`, the fraction ``completed`` |
| 373 |
from 0.0 to 1.0, the ``start`` time of the simulation as a `Quantity` |
| 374 |
and the total duration of the simulation (in biological time) |
| 375 |
as a `Quantity`. |
| 376 |
The function will always be called at the beginning and the end |
| 377 |
(i.e. for fractions 0.0 and 1.0), regardless of the ``report_period``. |
| 378 |
report_period : `Quantity` |
| 379 |
How frequently (in real time) to report progress. |
| 380 |
profile : bool, optional |
| 381 |
Whether to record profiling information (see `Network.profiling_info`). |
| 382 |
Defaults to ``None`` (which will use the value set by ``set_device``, |
| 383 |
if any). |
| 384 |
namespace : dict-like, optional |
| 385 |
A namespace in which objects which do not define their own |
| 386 |
namespace will be run. If not namespace is given, the locals and |
| 387 |
globals around the run function will be used. |
| 388 |
level : int, optional |
| 389 |
How deep to go down the stack frame to look for the locals/global |
| 390 |
(see `namespace` argument). Only necessary under particular |
| 391 |
circumstances, e.g. when calling the run function as part of a |
| 392 |
function call or lambda expression. This is used in tests, e.g.: |
| 393 |
``assert_raises(MagicError, lambda: run(1*ms, level=3))``. |
| 394 |
|
| 395 |
See Also |
| 396 |
-------- |
| 397 |
|
| 398 |
Network.run, MagicNetwork, collect, start_scope, stop |
| 399 |
|
| 400 |
Raises |
| 401 |
------ |
| 402 |
|
| 403 |
MagicError |
| 404 |
Error raised when it was not possible for Brian to safely guess the |
| 405 |
intended use. See `MagicNetwork` for more details. |
| 406 |
""" |
| 407 |
return magic_network.run( |
| 408 |
duration, |
| 409 |
report=report, |
| 410 |
report_period=report_period, |
| 411 |
namespace=namespace, |
| 412 |
profile=profile, |
| 413 |
level=2 + level, |
| 414 |
) |
| 415 |
|
| 416 |
|
| 417 |
run.__module__ = __name__ |
| 418 |
|
| 419 |
|
| 420 |
def store(name="default", filename=None): |
| 421 |
""" |
| 422 |
Store the state of the network and all included objects. |
| 423 |
|
| 424 |
Parameters |
| 425 |
---------- |
| 426 |
name : str, optional |
| 427 |
A name for the snapshot, if not specified uses ``'default'``. |
| 428 |
filename : str, optional |
| 429 |
A filename where the state should be stored. If not specified, the |
| 430 |
state will be stored in memory. |
| 431 |
|
| 432 |
See Also |
| 433 |
-------- |
| 434 |
Network.store |
| 435 |
""" |
| 436 |
magic_network.store(name=name, filename=filename, level=1) |
| 437 |
|
| 438 |
|
| 439 |
def restore(name="default", filename=None, restore_random_state=False): |
| 440 |
""" |
| 441 |
Restore the state of the network and all included objects. |
| 442 |
|
| 443 |
Parameters |
| 444 |
---------- |
| 445 |
name : str, optional |
| 446 |
The name of the snapshot to restore, if not specified uses |
| 447 |
``'default'``. |
| 448 |
filename : str, optional |
| 449 |
The name of the file from where the state should be restored. If |
| 450 |
not specified, it is expected that the state exist in memory |
| 451 |
(i.e. `Network.store` was previously called without the ``filename`` |
| 452 |
argument). |
| 453 |
restore_random_state : bool, optional |
| 454 |
Whether to restore the state of the random number generator. If set |
| 455 |
to ``True``, going back to an earlier state of the simulation will |
| 456 |
continue exactly where it left off, even if the simulation is |
| 457 |
stochastic. If set to ``False`` (the default), random numbers are |
| 458 |
independent between runs (except for explicitly set random seeds), |
| 459 |
regardless of whether `store`/`restore` has been used or not. Note |
| 460 |
that this also restores numpy's random number generator (since it is |
| 461 |
used internally by Brian), but it does *not* restore Python's |
| 462 |
builtin random number generator in the ``random`` module. |
| 463 |
See Also |
| 464 |
-------- |
| 465 |
Network.restore |
| 466 |
""" |
| 467 |
magic_network.restore( |
| 468 |
name=name, filename=filename, restore_random_state=restore_random_state, level=1 |
| 469 |
) |
| 470 |
|
| 471 |
|
| 472 |
def stop(): |
| 473 |
""" |
| 474 |
Stops all running simulations. |
| 475 |
|
| 476 |
See Also |
| 477 |
-------- |
| 478 |
|
| 479 |
Network.stop, run, reinit |
| 480 |
""" |
| 481 |
Network._globally_stopped = True |
| 482 |
|
| 483 |
|
| 484 |
def start_scope(): |
| 485 |
""" |
| 486 |
Starts a new scope for magic functions |
| 487 |
|
| 488 |
All objects created before this call will no longer be automatically |
| 489 |
included by the magic functions such as `run`. |
| 490 |
""" |
| 491 |
BrianObject._scope_current_key += 1 |