Debian Codegraph @

brian2/core/network.py

raw
1 """
2 Module defining the `Network` object, the basis of all simulation runs.
3
4 Preferences
5 -----------
6
7 .. document_brian_prefs:: core.network
8
9 """
10
11 import gc
12 import os
13 import pickle as pickle
14 import sys
15 import time
16 from collections import Counter, defaultdict, namedtuple
17 from collections.abc import Mapping, Sequence
18
19 from brian2.core.base import BrianObject, BrianObjectException
20 from brian2.core.clocks import defaultclock
21 from brian2.core.names import Nameable
22 from brian2.core.namespace import get_local_namespace
23 from brian2.core.preferences import BrianPreference, prefs
24 from brian2.devices.device import all_devices, get_device
25 from brian2.groups.group import Group
26 from brian2.synapses.synapses import SummedVariableUpdater
27 from brian2.units.allunits import msecond, second
28 from brian2.units.fundamentalunits import Quantity, check_units
29 from brian2.utils.logger import get_logger
30
31 from .base import device_override
32
33 __all__ = ["Network", "profiling_summary", "scheduling_summary"]
34
35
36 logger = get_logger(__name__)
37
38
39 prefs.register_preferences(
40 "core.network",
41 "Network preferences",
42 default_schedule=BrianPreference(
43 default=[
44 "start",
45 "groups",
46 "thresholds",
47 "synapses",
48 "resets",
49 "end",
50 ],
51 docs="""
52 Default schedule used for networks that
53 don't specify a schedule.
54 """,
55 ),
56 )
57
58
59 def _format_time(time_in_s):
60 """
61 Helper function to format time in seconds, minutes, hours, days, depending
62 on the magnitude.
63
64 Examples
65 --------
66 >>> from brian2.core.network import _format_time
67 >>> _format_time(12345)
68 '3h 25m 45s'
69 >>> _format_time(123)
70 '2m 3s'
71 >>> _format_time(12.5)
72 '12s'
73 >>> _format_time(.5)
74 '< 1s'
75
76 """
77 divisors = [24 * 60 * 60, 60 * 60, 60, 1]
78 letters = ["d", "h", "m", "s"]
79 remaining = time_in_s
80 text = ""
81 for divisor, letter in zip(divisors, letters, strict=True):
82 time_to_represent = int(remaining / divisor)
83 remaining -= time_to_represent * divisor
84 if time_to_represent > 0 or len(text):
85 if len(text):
86 text += " "
87 text += f"{int(time_to_represent)}{letter}"
88
89 # less than one second
90 if len(text) == 0:
91 text = "< 1s"
92
93 return text
94
95
96 class TextReport:
97 """
98 Helper object to report simulation progress in `Network.run`.
99
100 Parameters
101 ----------
102 stream : file
103 The stream to write to, commonly `sys.stdout` or `sys.stderr`.
104 """
105
106 def __init__(self, stream):
107 self.stream = stream
108
109 def __call__(self, elapsed, completed, start, duration):
110 if completed == 0.0:
111 self.stream.write(
112 f"Starting simulation at t={start} for a duration of {duration}\n"
113 )
114 else:
115 t = str(completed * duration)
116 percent = int(completed * 100.0)
117 real_t = _format_time(float(elapsed))
118 report_msg = f"{t} ({percent}%) simulated in {real_t}"
119 if completed < 1.0:
120 remaining = int(round((1 - completed) / completed * float(elapsed)))
121 remaining_msg = f", estimated {_format_time(remaining)} remaining.\n"
122 else:
123 remaining_msg = "\n"
124
125 self.stream.write(report_msg + remaining_msg)
126
127 # Flush the stream, this is useful if stream is a file
128 self.stream.flush()
129
130
131 def _format_table(header, values, cell_formats):
132 # table = [header] + values
133 table_format = len(values) * [cell_formats]
134 col_widths = [
135 max(
136 len(format.format(cell, 0))
137 for format, cell in zip(col_format, col, strict=True)
138 )
139 for col_format, col in zip(
140 list(zip(*([len(header) * ["{}"]] + table_format), strict=True)),
141 list(zip(*([header] + values), strict=True)),
142 strict=True,
143 )
144 ]
145 line = "-+-".join("-" * width for width in col_widths)
146 content = [
147 " | ".join(
148 format.format(cell, width)
149 for format, cell, width in zip(row_format, row, col_widths, strict=True)
150 )
151 for row_format, row in zip(table_format, values, strict=True)
152 ]
153 formatted_header = " | ".join(
154 "{:^{}}".format(h, width) for h, width in zip(header, col_widths, strict=True)
155 )
156
157 return "\n".join([formatted_header, line] + content)
158
159
160 class SchedulingSummary:
161 """
162 Object representing the schedule that is used to simulate the objects in a
163 network. Objects of this type are returned by `scheduling_summary`, they
164 should not be created manually by the user.
165
166 Parameters
167 ----------
168 objects : list of `BrianObject`
169 The sorted list of objects that are simulated by the network.
170 """
171
172 def __init__(self, objects):
173 # Map each dt to a rank (i.e. smallest dt=0, second smallest=1, etc.)
174 self.dts = {
175 dt: rank
176 for rank, dt in enumerate(sorted({float(obj.clock.dt) for obj in objects}))
177 }
178 ScheduleEntry = namedtuple(
179 "ScheduleEntry",
180 field_names=[
181 "when",
182 "order",
183 "dt",
184 "name",
185 "type",
186 "active",
187 "owner_name",
188 "owner_type",
189 ],
190 )
191 entries = []
192 for obj in objects:
193 if len(obj.contained_objects):
194 continue
195 owner = getattr(obj, "group", None)
196 if owner is None:
197 owner_name, owner_type = None, None
198 else:
199 owner_name = owner.name
200 owner_type = owner.__class__.__name__
201 entries.append(
202 ScheduleEntry(
203 when=obj.when,
204 order=obj.order,
205 dt=obj.clock.dt,
206 name=obj.name,
207 type=obj.__class__.__name__,
208 active=obj.active,
209 owner_name=owner_name,
210 owner_type=owner_type,
211 )
212 )
213 self.entries = entries
214
215 self.all_dts = sorted({float(entry.dt) for entry in self.entries})
216 # How many steps compared to the fastest clock?
217 self.steps = {float(dt): int(dt / self.all_dts[0]) for dt in self.all_dts}
218
219 def __repr__(self):
220 return _format_table(
221 ["object", "part of", "Clock dt", "when", "order", "active"],
222 [
223 [
224 f"{entry.name} ({entry.type})",
225 (
226 f"{entry.owner_name} ({entry.owner_type})"
227 if entry.owner_name is not None
228 else "--"
229 ),
230 "{} (every {})".format(
231 str(entry.dt),
232 (
233 "step"
234 if self.steps[float(entry.dt)] == 1
235 else f"{self.steps[float(entry.dt)]} steps"
236 ),
237 ),
238 entry.when,
239 entry.order,
240 "yes" if entry.active else "no",
241 ]
242 for entry in self.entries
243 ],
244 ["{:<{}}", "{:<{}}", "{:<{}}", "{:<{}}", "{:{}d}", "{:^{}}"],
245 )
246
247 def _repr_html_(self):
248 rows = [
249 """\
250 <tr>
251 <td style="text-align: left;">{}</td>
252 <td style="text-align: left;">{}</td>
253 <td style="text-align: left;">{}</td>
254 <td style="text-align: left;">{}</td>
255 <td style="text-align: right;">{}</td>
256 <td style="text-align: center;">{}</td>
257 </tr>
258 """.format(
259 f"<b>{entry.name}</b> (<em>{entry.type}</em>)",
260 (
261 f"{entry.owner_name} (<em>{entry.owner_type}</em>)"
262 if entry.owner_name is not None
263 else "&ndash;"
264 ),
265 "{} (every {})".format(
266 str(entry.dt),
267 (
268 "step"
269 if self.steps[float(entry.dt)] == 1
270 else f"{self.steps[float(entry.dt)]} steps"
271 ),
272 ),
273 entry.when,
274 entry.order,
275 "yes" if entry.active else "no",
276 )
277 for entry in self.entries
278 ]
279 html_code = """
280 <table>
281 <thead>
282 <tr>
283 <th style="text-align: center;">object</th>
284 <th style="text-align: center;">part of</th>
285 <th style="text-align: center;">Clock dt</th>
286 <th style="text-align: center;">when</th>
287 <th style="text-align: center;">order</th>
288 <th style="text-align: center;">active</th>
289 </tr>
290 </thead>
291 <tbody>
292 {rows}
293 </tbody>
294 </table>
295 """.format(rows="\n".join(rows))
296 return html_code
297
298
299 def _check_multiple_summed_updaters(objects):
300 """
301 Helper function that checks whether multiple `SummedVariableUpdater` target
302 the same target variable. Raises a `NotImplementedError` if this is the
303 case (and problematic, i.e. not when using non-overlapping subgroups).
304
305 Parameters
306 ----------
307 objects : list of `BrianObject`
308 The list of objects in the network.
309 """
310 summed_targets = {}
311 for obj in objects:
312 if isinstance(obj, SummedVariableUpdater):
313 if obj.target_var in summed_targets:
314 other_target = summed_targets[obj.target_var]
315 if obj.target == other_target:
316 # We raise an error, even though this could be ok in
317 # principle (e.g. two Synapses could target different
318 # subsets of the target groups, without using subgroups)
319 msg = (
320 "Multiple 'summed variables' target the "
321 f"variable '{obj.target_var.name}' in group "
322 f"'{obj.target.name}'. Use multiple variables in "
323 "the target group instead."
324 )
325 raise NotImplementedError(msg)
326 elif (
327 obj.target.start < other_target.stop
328 and other_target.start < obj.target.stop
329 ):
330 # Overlapping subgroups
331 msg = (
332 "Multiple 'summed variables' target the "
333 f"variable '{obj.target_var.name}' in overlapping "
334 f"groups '{other_target.name}' and '{obj.target.name}'. "
335 "Use separate variables in the target groups instead."
336 )
337 raise NotImplementedError(msg)
338 summed_targets[obj.target_var] = obj.target
339
340
341 def _get_all_objects(objs):
342 """
343 Helper function to get all objects of a 'Network' along with their
344 corresponding ``contained_objects``.
345
346 Parameters
347 ----------
348 objs : Iterable
349 List or set of objects
350
351 Returns
352 -------
353 all_objects : set
354 A set of all Network's objects and respective child objects.
355 """
356 all_objects = set()
357 for obj in objs:
358 all_objects.add(obj)
359 all_objects |= _get_all_objects(obj.contained_objects)
360 return all_objects
361
362
363 class Network(Nameable):
364 """
365 Network(*objs, name='network*')
366
367 The main simulation controller in Brian
368
369 `Network` handles the running of a simulation. It contains a set of Brian
370 objects that are added with `~Network.add`. The `~Network.run` method
371 actually runs the simulation. The main run loop, determining which
372 objects get called in what order is described in detail in the notes below.
373 The objects in the `Network` are accesible via their names, e.g.
374 `net['neurongroup']` would return the `NeuronGroup` with this name.
375
376 Parameters
377 ----------
378 objs : (`BrianObject`, container), optional
379 A list of objects to be added to the `Network` immediately, see
380 `~Network.add`.
381 name : str, optional
382 An explicit name, if not specified gives an automatically generated name
383
384 Notes
385 -----
386
387 The main run loop performs the following steps:
388
389 1. Prepare the objects if necessary, see `~Network.prepare`.
390 2. Determine the end time of the simulation as `~Network.t`+``duration``.
391 3. Determine which set of clocks to update. This will be the clock with the
392 smallest value of `~Clock.t`. If there are several with the same value,
393 then all objects with these clocks will be updated simultaneously.
394 Set `~Network.t` to the clock time.
395 4. If the `~Clock.t` value of these clocks is past the end time of the
396 simulation, stop running. If the `Network.stop` method or the
397 `stop` function have been called, stop running. Set `~Network.t` to the
398 end time of the simulation.
399 5. For each object whose `~BrianObject.clock` is set to one of the clocks from the
400 previous steps, call the `~BrianObject.update` method. This method will
401 not be called if the `~BrianObject.active` flag is set to ``False``.
402 The order in which the objects are called is described below.
403 6. Increase `Clock.t` by `Clock.dt` for each of the clocks and return to
404 step 2.
405
406 The order in which the objects are updated in step 4 is determined by
407 the `Network.schedule` and the objects `~BrianObject.when` and
408 `~BrianObject.order` attributes. The `~Network.schedule` is a list of
409 string names. Each `~BrianObject.when` attribute should be one of these
410 strings, and the objects will be updated in the order determined by the
411 schedule. The default schedule is
412 ``['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']``. In
413 addition to the names provided in the schedule, automatic names starting
414 with ``before_`` and ``after_`` can be used. That means that all objects
415 with ``when=='before_start'`` will be updated first, then
416 those with ``when=='start'``, ``when=='after_start'``,
417 ``when=='before_groups'``, ``when=='groups'`` and so forth. If several
418 objects have the same `~BrianObject.when` attribute, then the order is
419 determined by the `~BrianObject.order` attribute (lower first).
420
421 See Also
422 --------
423
424 MagicNetwork, run, stop
425 """
426
427 def __init__(self, *objs, **kwds):
428 #: The set of objects in the Network, should not normally be modified
429 #: directly.
430 #: Note that in a `MagicNetwork`, this attribute only contains the
431 #: objects during a run: it is filled in `before_run` and emptied in
432 #: `after_run`
433 self.objects = set()
434
435 name = kwds.pop("name", "network*")
436
437 if kwds:
438 raise TypeError("Only keyword argument to Network is 'name'.")
439
440 Nameable.__init__(self, name=name)
441
442 #: Current time as a float
443 self.t_ = 0.0
444
445 for obj in objs:
446 self.add(obj)
447
448 #: Stored state of objects (store/restore)
449 self._stored_state = {}
450
451 # Stored profiling information (if activated via the keyword option)
452 self._profiling_info = None
453
454 self._schedule = None
455
456 t = property(
457 fget=lambda self: Quantity(self.t_, dim=second.dim),
458 doc="Current simulation time in seconds (`Quantity`)",
459 )
460
461 @device_override("network_get_profiling_info")
462 def get_profiling_info(self):
463 """
464 The only reason this is not directly implemented in `profiling_info`
465 is to allow devices (e.g. `CPPStandaloneDevice`) to overwrite this.
466 """
467 if self._profiling_info is None:
468 raise ValueError(
469 "No profiling info collected (did you run with 'profile=True?')"
470 )
471 return sorted(self._profiling_info, key=lambda item: item[1], reverse=True)
472
473 @property
474 def profiling_info(self):
475 """
476 The time spent in executing the various `CodeObject` s.
477
478 A list of ``(name, time)`` tuples, containing the name of the
479 `CodeObject` and the total execution time for simulations of this object
480 (as a `Quantity` with unit `second`). The list is sorted descending
481 with execution time.
482
483 Profiling has to be activated using the ``profile`` keyword in `run` or
484 `Network.run`.
485 """
486 return self.get_profiling_info()
487
488 _globally_stopped = False
489 _globally_running = False
490
491 def __getitem__(self, item):
492 if not isinstance(item, str):
493 raise TypeError(
494 f"Need a name to access objects in a Network, got {type(item)} instead"
495 )
496 all_objects = _get_all_objects(self.objects)
497 for obj in all_objects:
498 if obj.name == item:
499 return obj
500
501 raise KeyError(f'No object with name "{item}" found')
502
503 def __delitem__(self, key):
504 if not isinstance(key, str):
505 raise TypeError(
506 "Need a name to access objects in a Network, got {type(key)} instead"
507 )
508 for obj in self.objects:
509 if obj.name == key:
510 self.remove(obj)
511 return
512
513 raise KeyError(f"No object with name '{key}' found")
514
515 def __contains__(self, item):
516 all_objects = _get_all_objects(self.objects)
517 for obj in all_objects:
518 if obj.name == item:
519 return True
520 return False
521
522 def __len__(self):
523 all_objects = _get_all_objects(self.objects)
524 return len(all_objects)
525
526 def __iter__(self):
527 all_objects = _get_all_objects(self.objects)
528 return iter(all_objects)
529
530 def add(self, *objs):
531 """
532 Add objects to the `Network`
533
534 Parameters
535 ----------
536
537 objs : (`BrianObject`, container)
538 The `BrianObject` or container of Brian objects to be added. Specify
539 multiple objects, or lists (or other containers) of objects.
540 Containers will be added recursively. If the container is a `dict`
541 then it will add the values from the dictionary but not the keys.
542 If you want to add the keys, do ``add(objs.keys())``.
543 """
544 for obj in objs:
545 if isinstance(obj, BrianObject):
546 if obj._network is not None:
547 raise RuntimeError(
548 f"{obj.name} has already been simulated, cannot "
549 "add it to the network. If you were "
550 "trying to remove and add an object to "
551 "temporarily stop it from being run, "
552 "set its active flag to False instead."
553 )
554 self.objects.add(obj)
555 else:
556 # allow adding values from dictionaries
557 if isinstance(obj, Mapping):
558 self.add(*list(obj.values()))
559 else:
560 try:
561 for o in obj:
562 # The following "if" looks silly but avoids an infinite
563 # recursion if a string is provided as an argument
564 # (which might occur during testing)
565 if o is obj:
566 raise TypeError()
567 self.add(o)
568 except TypeError as ex:
569 raise TypeError(
570 "Can only add objects of type BrianObject, "
571 "or containers of such objects to Network"
572 ) from ex
573
574 def remove(self, *objs):
575 """
576 Remove an object or sequence of objects from a `Network`.
577
578 Parameters
579 ----------
580
581 objs : (`BrianObject`, container)
582 The `BrianObject` or container of Brian objects to be removed. Specify
583 multiple objects, or lists (or other containers) of objects.
584 Containers will be removed recursively.
585 """
586 for obj in objs:
587 if isinstance(obj, BrianObject):
588 self.objects.remove(obj)
589 else:
590 try:
591 for o in obj:
592 self.remove(o)
593 except TypeError as ex:
594 raise TypeError(
595 "Can only remove objects of type "
596 "BrianObject, or containers of such "
597 "objects from Network"
598 ) from ex
599
600 def _full_state(self):
601 all_objects = _get_all_objects(self.objects)
602 state = {}
603 for obj in all_objects:
604 if hasattr(obj, "_full_state"):
605 state[obj.name] = obj._full_state()
606 clocks = {obj.clock for obj in all_objects}
607 for clock in clocks:
608 state[clock.name] = clock._full_state()
609 # Store the time as "0_t" -- this name is guaranteed not to clash with
610 # the name of an object as names are not allowed to start with a digit
611 state["0_t"] = self.t_
612 return state
613
614 @device_override("network_store")
615 def store(self, name="default", filename=None):
616 """
617 store(name='default', filename=None)
618
619 Store the state of the network and all included objects.
620
621 Parameters
622 ----------
623 name : str, optional
624 A name for the snapshot, if not specified uses ``'default'``.
625 filename : str, optional
626 A filename where the state should be stored. If not specified, the
627 state will be stored in memory.
628
629 Notes
630 -----
631 The state stored to disk can be restored with the `Network.restore`
632 function. Note that it will only restore the *internal state* of all
633 the objects (including undelivered spikes) -- the objects have to
634 exist already and they need to have the same name as when they were
635 stored. Equations, thresholds, etc. are *not* stored -- this is
636 therefore not a general mechanism for object serialization. Also, the
637 format of the file is not guaranteed to work across platforms or
638 versions. If you are interested in storing the state of a network for
639 documentation or analysis purposes use `Network.get_states` instead.
640 """
641 clocks = {obj.clock for obj in _get_all_objects(self.objects)}
642 # Make sure that all clocks are up to date
643 for clock in clocks:
644 clock._set_t_update_dt(target_t=self.t)
645
646 state = self._full_state()
647 # Store the state of the random number generator
648 dev = get_device()
649 state["_random_generator_state"] = dev.get_random_state()
650
651 if filename is None:
652 self._stored_state[name] = state
653 else:
654 # A single file can contain several states, so we'll read in the
655 # existing file first if it exists
656 if os.path.exists(filename):
657 with open(filename, "rb") as f:
658 store_state = pickle.load(f)
659 else:
660 store_state = {}
661 store_state[name] = state
662
663 with open(filename, "wb") as f:
664 pickle.dump(store_state, f, protocol=pickle.HIGHEST_PROTOCOL)
665
666 @device_override("network_restore")
667 def restore(self, name="default", filename=None, restore_random_state=False):
668 """
669 restore(name='default', filename=None, restore_random_state=False)
670
671 Retore the state of the network and all included objects.
672
673 Parameters
674 ----------
675 name : str, optional
676 The name of the snapshot to restore, if not specified uses
677 ``'default'``.
678 filename : str, optional
679 The name of the file from where the state should be restored. If
680 not specified, it is expected that the state exist in memory
681 (i.e. `Network.store` was previously called without the ``filename``
682 argument).
683 restore_random_state : bool, optional
684 Whether to restore the state of the random number generator. If set
685 to ``True``, going back to an earlier state of the simulation will
686 continue exactly where it left off, even if the simulation is
687 stochastic. If set to ``False`` (the default), random numbers are
688 independent between runs (except for explicitly set random seeds),
689 regardless of whether `store`/`restore` has been used or not. Note
690 that this also restores numpy's random number generator (since it is
691 used internally by Brian), but it does *not* restore Python's
692 builtin random number generator in the ``random`` module.
693 """
694 all_objects = _get_all_objects(self.objects)
695 if filename is None:
696 state = self._stored_state[name]
697 else:
698 with open(filename, "rb") as f:
699 state = pickle.load(f)[name]
700 self.t_ = state["0_t"]
701 if restore_random_state:
702 dev = get_device()
703 dev.set_random_state(state["_random_generator_state"])
704 clocks = {obj.clock for obj in all_objects}
705 restored_objects = set()
706 for obj in all_objects:
707 if obj.name in state:
708 obj._restore_from_full_state(state[obj.name])
709 restored_objects.add(obj.name)
710 elif hasattr(obj, "_restore_from_full_state"):
711 raise KeyError(
712 "Stored state does not have a stored state for "
713 f"'{obj.name}'. Note that the names of all objects have "
714 "to be identical to the names when they were "
715 "stored."
716 )
717 for clock in clocks:
718 clock._restore_from_full_state(state[clock.name])
719 clock_names = {c.name for c in clocks}
720
721 unnused = (
722 set(state.keys())
723 - restored_objects
724 - clock_names
725 - {"0_t", "_random_generator_state"}
726 )
727 if len(unnused):
728 raise KeyError(
729 "The stored state contains the state of the "
730 "following objects which were not present in the "
731 f"network: {', '.join(unnused)}. Note that the names of all "
732 "objects have to be identical to the names when they "
733 "were stored."
734 )
735
736 def get_states(
737 self,
738 units=True,
739 format="dict",
740 subexpressions=False,
741 read_only_variables=True,
742 level=0,
743 ):
744 """
745 Return a copy of the current state variable values of objects in the
746 network.. The returned arrays are copies of the actual arrays that
747 store the state variable values, therefore changing the values in the
748 returned dictionary will not affect the state variables.
749
750 Parameters
751 ----------
752 vars : list of str, optional
753 The names of the variables to extract. If not specified, extract
754 all state variables (except for internal variables, i.e. names that
755 start with ``'_'``). If the ``subexpressions`` argument is ``True``,
756 the current values of all subexpressions are returned as well.
757 units : bool, optional
758 Whether to include the physical units in the return value. Defaults
759 to ``True``.
760 format : str, optional
761 The output format. Defaults to ``'dict'``.
762 subexpressions: bool, optional
763 Whether to return subexpressions when no list of variable names
764 is given. Defaults to ``False``. This argument is ignored if an
765 explicit list of variable names is given in ``vars``.
766 read_only_variables : bool, optional
767 Whether to return read-only variables (e.g. the number of neurons,
768 the time, etc.). Setting it to ``False`` will assure that the
769 returned state can later be used with `set_states`. Defaults to
770 ``True``.
771 level : int, optional
772 How much higher to go up the stack to resolve external variables.
773 Only relevant if extracting subexpressions that refer to external
774 variables.
775
776 Returns
777 -------
778 values : dict
779 A dictionary mapping object names to the state variables of that
780 object, in the specified ``format``.
781
782 See Also
783 --------
784 VariableOwner.get_states
785 """
786 states = dict()
787 for obj in self.sorted_objects:
788 if hasattr(obj, "get_states"):
789 states[obj.name] = obj.get_states(
790 vars=None,
791 units=units,
792 format=format,
793 subexpressions=subexpressions,
794 read_only_variables=read_only_variables,
795 level=level + 1,
796 )
797 return states
798
799 def set_states(self, values, units=True, format="dict", level=0):
800 """
801 Set the state variables of objects in the network.
802
803 Parameters
804 ----------
805 values : dict
806 A dictionary mapping object names to objects of ``format``, setting
807 the states of this object.
808 units : bool, optional
809 Whether the ``values`` include physical units. Defaults to ``True``.
810 format : str, optional
811 The format of ``values``. Defaults to ``'dict'``
812 level : int, optional
813 How much higher to go up the stack to _resolve external variables.
814 Only relevant when using string expressions to set values.
815
816 See Also
817 --------
818 Group.set_states
819 """
820 # For the moment, 'dict' is the only supported format -- later this will
821 # be made into an extensible system, see github issue #306
822 for obj_name, obj_values in values.items():
823 if obj_name not in self:
824 raise KeyError(
825 "Network does not include a network with name '%s'." % obj_name
826 )
827 self[obj_name].set_states(
828 obj_values, units=units, format=format, level=level + 1
829 )
830
831 def _get_schedule(self):
832 if self._schedule is None:
833 return list(prefs.core.network.default_schedule)
834 else:
835 return list(self._schedule)
836
837 def _set_schedule(self, schedule):
838 if schedule is None:
839 self._schedule = None
840 logger.debug("Resetting network {self.name} schedule to default schedule")
841 else:
842 if not isinstance(schedule, Sequence) or not all(
843 isinstance(slot, str) for slot in schedule
844 ):
845 raise TypeError(
846 "Schedule has to be None or a sequence of scheduling slots"
847 )
848 if any(
849 slot.startswith("before_") or slot.startswith("after_")
850 for slot in schedule
851 ):
852 raise ValueError(
853 "Slot names are not allowed to start with "
854 "'before_' or 'after_' -- such slot names "
855 "are created automatically based on the "
856 "existing slot names."
857 )
858 self._schedule = list(schedule)
859 logger.debug(
860 f"Setting network '{self.name}' schedule to {self._schedule}",
861 "_set_schedule",
862 )
863
864 schedule = property(
865 fget=_get_schedule,
866 fset=_set_schedule,
867 doc="""
868 List of ``when`` slots in the order they will be updated, can be modified.
869
870 See notes on scheduling in `Network`. Note that additional ``when``
871 slots can be added, but the schedule should contain at least all of the
872 names in the default schedule:
873 ``['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']``.
874
875 The schedule can also be set to ``None``, resetting it to the default
876 schedule set by the `core.network.default_schedule` preference.
877 """,
878 )
879
880 @property
881 def sorted_objects(self):
882 """
883 The sorted objects of this network in the order defined by the schedule.
884
885 Objects are sorted first by their ``when`` attribute, and secondly
886 by the ``order`` attribute. The order of the ``when`` attribute is
887 defined by the ``schedule``. In addition to the slot names defined in
888 the schedule, automatic slot names starting with ``before_`` and
889 ``after_`` can be used (e.g. the slots ``['groups', 'thresholds']``
890 allow to use ``['before_groups', 'groups', 'after_groups',
891 'before_thresholds', 'thresholds', 'after_thresholds']``).
892
893 Final ties are resolved using the objects' names, leading to an
894 arbitrary but deterministic sorting.
895 """
896 # Provided slot names are assigned positions 1, 4, 7, ...
897 # before_... names are assigned positions 0, 3, 6, ...
898 # after_... names are assigned positions 2, 5, 8, ...
899 all_objects = _get_all_objects(self.objects)
900 when_to_int = {when: 1 + i * 3 for i, when in enumerate(self.schedule)}
901 when_to_int.update(
902 (f"before_{when}", i * 3) for i, when in enumerate(self.schedule)
903 )
904 when_to_int.update(
905 (f"after_{when}", 2 + i * 3) for i, when in enumerate(self.schedule)
906 )
907 return sorted(
908 all_objects, key=lambda obj: (when_to_int[obj.when], obj.order, obj.name)
909 )
910
911 def scheduling_summary(self):
912 """
913 Return a `SchedulingSummary` object, representing the scheduling
914 information for all objects included in the network.
915
916 Returns
917 -------
918 summary : `SchedulingSummary`
919 Object representing the scheduling information.
920 """
921 return SchedulingSummary(self.sorted_objects)
922
923 def check_dependencies(self):
924 all_objects = _get_all_objects(self.objects)
925 all_ids = [obj.id for obj in all_objects]
926 for obj in all_objects:
927 for dependency in obj._dependencies:
928 if dependency not in all_ids:
929 raise ValueError(
930 f"'{obj.name}' has been included in the network "
931 "but not the object on which it "
932 "depends."
933 )
934
935 @device_override("network_before_run")
936 def before_run(self, run_namespace):
937 """
938 before_run(namespace)
939
940 Prepares the `Network` for a run.
941
942 Objects in the `Network` are sorted into the correct running order, and
943 their `BrianObject.before_run` methods are called.
944
945 Parameters
946 ----------
947 run_namespace : dict-like, optional
948 A namespace in which objects which do not define their own
949 namespace will be run.
950 """
951 all_objects = self.sorted_objects
952 prefs.check_all_validated()
953
954 # Check names in the network for uniqueness
955 names = [obj.name for obj in all_objects]
956 non_unique_names = [name for name, count in Counter(names).items() if count > 1]
957 if len(non_unique_names):
958 formatted_names = ", ".join(f"'{name}'" for name in non_unique_names)
959 raise ValueError(
960 "All objects in a network need to have unique "
961 "names, the following name(s) were used more than "
962 f"once: {formatted_names}"
963 )
964
965 # Check that there are no SummedVariableUpdaters targeting the same
966 # target variable
967 _check_multiple_summed_updaters(all_objects)
968
969 self._stopped = False
970 Network._globally_stopped = False
971
972 device = get_device()
973 if device.network_schedule is not None:
974 # The device defines a fixed network schedule
975 if device.network_schedule != self.schedule:
976 # TODO: The human-readable name of a device should be easier to get
977 device_name = list(all_devices.keys())[
978 list(all_devices.values()).index(device)
979 ]
980 logger.warn(
981 f"The selected device '{device_name}' only "
982 "supports a fixed schedule, but this schedule is "
983 "not consistent with the network's schedule. The "
984 "simulation will use the device's schedule.\n"
985 f"Device schedule: {device.network_schedule}\n"
986 f"Network schedule: {self.schedule}\n"
987 "Set the network schedule explicitly or set the "
988 "core.network.default_schedule preference to "
989 "avoid this warning.",
990 name_suffix="schedule_conflict",
991 once=True,
992 )
993
994 objnames = ", ".join(obj.name for obj in all_objects)
995 logger.debug(
996 f"Preparing network '{self.name}' with {len(all_objects)} "
997 f"objects: {objnames}",
998 "before_run",
999 )
1000
1001 self.check_dependencies()
1002
1003 for obj in all_objects:
1004 if obj.active:
1005 try:
1006 obj.before_run(run_namespace)
1007 except Exception as ex:
1008 raise BrianObjectException(
1009 "An error occurred when preparing an object.", obj
1010 ) from ex
1011
1012 # Check that no object has been run as part of another network before
1013 for obj in all_objects:
1014 if obj._network is None:
1015 obj._network = self.id
1016 elif obj._network != self.id:
1017 raise RuntimeError(
1018 f"'{obj.name}' has already been run in the "
1019 "context of another network. Use "
1020 "add/remove to change the objects "
1021 "in a simulated network instead of "
1022 "creating a new one."
1023 )
1024
1025 clocknames = ", ".join(f"{obj.name}" for obj in self._clocks)
1026 logger.debug(
1027 f"Network '{self.name}' uses {len(self._clocks)} clocks: {clocknames}",
1028 "before_run",
1029 )
1030
1031 @device_override("network_after_run")
1032 def after_run(self):
1033 """
1034 after_run()
1035 """
1036 for obj in self.sorted_objects:
1037 if obj.active:
1038 obj.after_run()
1039
1040 def _nextclocks(self):
1041 minclock = min(self._clocks, key=lambda c: c.variables["t"].get_value().item())
1042
1043 curclocks = {clock for clock in self._clocks if clock.same_time(minclock)}
1044
1045 return minclock, curclocks
1046
1047 @device_override("network_run")
1048 @check_units(duration=second, report_period=second)
1049 def run(
1050 self,
1051 duration,
1052 report=None,
1053 report_period=10 * second,
1054 namespace=None,
1055 profile=None,
1056 level=0,
1057 ):
1058 """
1059 run(duration, report=None, report_period=60*second, namespace=None, level=0)
1060
1061 Runs the simulation for the given duration.
1062
1063 Parameters
1064 ----------
1065 duration : `Quantity`
1066 The amount of simulation time to run for.
1067 report : {None, 'text', 'stdout', 'stderr', function}, optional
1068 How to report the progress of the simulation. If ``None``, do not
1069 report progress. If ``'text'`` or ``'stdout'`` is specified, print
1070 the progress to stdout. If ``'stderr'`` is specified, print the
1071 progress to stderr. Alternatively, you can specify a callback
1072 ``callable(elapsed, completed, start, duration)`` which will be passed
1073 the amount of time elapsed as a `Quantity`, the fraction ``completed``
1074 from 0.0 to 1.0, the ``start`` time of the simulation as a `Quantity`
1075 and the total duration of the simulation (in biological time)
1076 as a `Quantity`.
1077 The function will always be called at the beginning and the end
1078 (i.e. for fractions 0.0 and 1.0), regardless of the ``report_period``.
1079 report_period : `Quantity`
1080 How frequently (in real time) to report progress.
1081 namespace : dict-like, optional
1082 A namespace that will be used in addition to the group-specific
1083 namespaces (if defined). If not specified, the locals
1084 and globals around the run function will be used.
1085 profile : bool, optional
1086 Whether to record profiling information (see
1087 `Network.profiling_info`). Defaults to ``None`` (which will use the
1088 value set by ``set_device``, if any).
1089 level : int, optional
1090 How deep to go up the stack frame to look for the locals/global
1091 (see `namespace` argument). Only used by run functions that call
1092 this run function, e.g. `MagicNetwork.run` to adjust for the
1093 additional nesting.
1094
1095 Notes
1096 -----
1097 The simulation can be stopped by calling `Network.stop` or the
1098 global `stop` function.
1099
1100 Raises
1101 ------
1102 ValueError
1103 Error raised when duration passed in run function is negative.
1104 """
1105 if duration < 0:
1106 raise ValueError(
1107 f"Function 'run' expected a non-negative duration but got '{duration}'"
1108 )
1109 # This will trigger warnings for objects that have not been included in a network
1110 gc.collect()
1111 device = get_device() # Do not use the ProxyDevice -- slightly faster
1112
1113 if profile is None:
1114 profile = device.build_options.get("profile", False)
1115
1116 all_objects = self.sorted_objects
1117 self._clocks = {obj.clock for obj in all_objects}
1118 single_clock = len(self._clocks) == 1
1119
1120 t_start = self.t
1121 t_end = self.t + duration
1122
1123 if single_clock:
1124 clock = list(self._clocks)[0]
1125 clock.set_interval(self.t, t_end)
1126 else:
1127 # We get direct references to the underlying variables for all clocks
1128 # to avoid expensive access during the run loop
1129 self._clock_variables = {
1130 c: (
1131 c.variables["timestep"].get_value(),
1132 c.variables["t"].get_value(),
1133 )
1134 for c in self._clocks
1135 }
1136 for clock in self._clocks:
1137 clock.set_interval(self.t, t_end)
1138
1139 # Get the local namespace
1140 if namespace is None:
1141 namespace = get_local_namespace(level=level + 3)
1142
1143 self.before_run(namespace)
1144
1145 if len(all_objects) == 0:
1146 return # TODO: raise an error? warning?
1147
1148 start_time = time.time()
1149
1150 logger.debug(
1151 f"Simulating network '{self.name}' from time {t_start} to {t_end}.", "run"
1152 )
1153
1154 if report is not None:
1155 report_period = float(report_period)
1156 next_report_time = start_time + report_period
1157 if report == "text" or report == "stdout":
1158 report_callback = TextReport(sys.stdout)
1159 elif report == "stderr":
1160 report_callback = TextReport(sys.stderr)
1161 elif isinstance(report, str):
1162 raise ValueError(
1163 f'Do not know how to handle report argument "{report}".'
1164 )
1165 elif callable(report):
1166 report_callback = report
1167 else:
1168 raise TypeError(
1169 "Do not know how to handle report argument, "
1170 "it has to be one of 'text', 'stdout', "
1171 "'stderr', or a callable function/object, "
1172 f"but it is of type {type(report)}"
1173 )
1174 report_callback(0 * second, 0.0, t_start, duration)
1175
1176 profiling_info = defaultdict(float)
1177
1178 if single_clock:
1179 timestep, t = (
1180 clock.variables["timestep"].get_value(),
1181 clock.variables["t"].get_value(),
1182 )
1183
1184 else:
1185 # Find the first clock to be updated (see note below)
1186 clock, curclocks = self._nextclocks()
1187 timestep, t = self._clock_variables[clock]
1188
1189 running = timestep[0] < clock._i_end
1190
1191 active_objects = [obj for obj in all_objects if obj.active]
1192
1193 Network._globally_running = True
1194 while running and not self._stopped and not Network._globally_stopped:
1195 if not single_clock:
1196 timestep, t = self._clock_variables[clock]
1197 # update the network time to this clock's time
1198 self.t_ = t[0]
1199 if report is not None:
1200 current = time.time()
1201 if current > next_report_time:
1202 report_callback(
1203 (current - start_time) * second,
1204 (self.t_ - float(t_start)) / float(t_end - t_start),
1205 t_start,
1206 duration,
1207 )
1208 next_report_time = current + report_period
1209
1210 # update the objects and tick forward the clock(s)
1211 if single_clock:
1212 if profile:
1213 for obj in active_objects:
1214 obj_time = time.time()
1215 obj.run()
1216 profiling_info[obj.name] += time.time() - obj_time
1217 else:
1218 for obj in active_objects:
1219 obj.run()
1220
1221 clock.advance()
1222
1223 else:
1224 if profile:
1225 for obj in active_objects:
1226 if obj._clock in curclocks:
1227 obj_time = time.time()
1228 obj.run()
1229 profiling_info[obj.name] += time.time() - obj_time
1230 else:
1231 for obj in active_objects:
1232 if obj._clock in curclocks:
1233 obj.run()
1234
1235 for c in curclocks:
1236 c.advance()
1237 # find the next clocks to be updated. The < operator for Clock
1238 # determines that the first clock to be updated should be the one
1239 # with the smallest t value, unless there are several with the
1240 # same t value in which case we update all of them
1241 clock, curclocks = self._nextclocks()
1242 timestep, t = self._clock_variables[clock]
1243
1244 if (
1245 device._maximum_run_time is not None
1246 and time.time() - start_time > float(device._maximum_run_time)
1247 ):
1248 self._stopped = True
1249 else:
1250 running = timestep[0] < clock._i_end
1251
1252 end_time = time.time()
1253 Network._globally_running = False
1254 if self._stopped or Network._globally_stopped:
1255 self.t_ = clock.t_
1256 else:
1257 self.t_ = float(t_end)
1258
1259 device._last_run_time = end_time - start_time
1260 if duration > 0:
1261 device._last_run_completed_fraction = (self.t - t_start) / duration
1262 else:
1263 device._last_run_completed_fraction = 1.0
1264
1265 # check for nans
1266 for obj in all_objects:
1267 if isinstance(obj, Group):
1268 obj._check_for_invalid_states()
1269
1270 if report is not None:
1271 report_callback(
1272 (end_time - start_time) * second,
1273 device._last_run_completed_fraction,
1274 t_start,
1275 duration,
1276 )
1277 self.after_run()
1278
1279 logger.debug(
1280 f"Finished simulating network '{self.name}' "
1281 f"(took {end_time - start_time:.2f}s)",
1282 "run",
1283 )
1284 # Store profiling info (or erase old info to avoid confusion)
1285 if profile:
1286 self._profiling_info = [
1287 (name, t * second) for name, t in profiling_info.items()
1288 ]
1289 # Dump a profiling summary to the log
1290 logger.debug(f"\n{str(profiling_summary(self))}")
1291 else:
1292 self._profiling_info = None
1293
1294 @device_override("network_stop")
1295 def stop(self):
1296 """
1297 stop()
1298
1299 Stops the network from running, this is reset the next time `Network.run` is called.
1300 """
1301 self._stopped = True
1302
1303 def __repr__(self):
1304 objects = ", ".join(obj.__repr__() for obj in _get_all_objects(self.objects))
1305 return (
1306 f"<{self.__class__.__name__} at time t={self.t!s}, containing "
1307 f"objects: {objects}>"
1308 )
1309
1310
1311 class ProfilingSummary:
1312 """
1313 Class to nicely display the results of profiling. Objects of this class are
1314 returned by `profiling_summary`.
1315
1316 Parameters
1317 ----------
1318
1319 net : `Network`
1320 The `Network` object to profile.
1321 show : int, optional
1322 The number of results to show (the longest results will be shown). If
1323 not specified, all results will be shown.
1324
1325 See Also
1326 --------
1327 Network.profiling_info
1328 """
1329
1330 def __init__(self, net, show=None):
1331 prof = net.profiling_info
1332 if len(prof):
1333 names, times = list(zip(*prof, strict=True))
1334 else: # Can happen if a network has been run for 0ms
1335 # Use a dummy entry to prevent problems with empty lists later
1336 names = ["no code objects have been run"]
1337 times = [0 * second]
1338 self.total_time = sum(times)
1339 self.time_unit = msecond
1340 if self.total_time > 1 * second:
1341 self.time_unit = second
1342 if show is not None:
1343 names = names[:show]
1344 times = times[:show]
1345 if self.total_time > 0 * second:
1346 self.percentages = [100.0 * time / self.total_time for time in times]
1347 else:
1348 self.percentages = [0.0 for _ in times]
1349 self.names_maxlen = max(len(name) for name in names)
1350 self.names = [name + " " * (self.names_maxlen - len(name)) for name in names]
1351 self.times = times
1352
1353 def __repr__(self):
1354 times = [f"{time / self.time_unit:.2f} {self.time_unit}" for time in self.times]
1355 times_maxlen = max(len(time) for time in times)
1356 times = [" " * (times_maxlen - len(time)) + time for time in times]
1357 percentages = [f"{percentage:.2f} %" for percentage in self.percentages]
1358 percentages_maxlen = max(len(percentage) for percentage in percentages)
1359 percentages = [
1360 (" " * (percentages_maxlen - len(percentage))) + percentage
1361 for percentage in percentages
1362 ]
1363
1364 s = "Profiling summary"
1365 s += f"\n{'=' * len(s)}\n"
1366 for name, t, percentage in zip(self.names, times, percentages, strict=True):
1367 s += f"{name} {t} {percentage}\n"
1368 return s
1369
1370 def _repr_html_(self):
1371 times = [f"{time / self.time_unit:.2f} {self.time_unit}" for time in self.times]
1372 percentages = [f"{percentage:.2f} %" for percentage in self.percentages]
1373 s = '<h2 class="brian_prof_summary_header">Profiling summary</h2>\n'
1374 s += '<table class="brian_prof_summary_table">\n'
1375 for name, t, percentage in zip(self.names, times, percentages, strict=True):
1376 s += "<tr>"
1377 s += f"<td>{name}</td>"
1378 s += f'<td style="text-align: right">{t}</td>'
1379 s += f'<td style="text-align: right">{percentage}</td>'
1380 s += "</tr>\n"
1381 s += "</table>"
1382 return s
1383
1384
1385 def profiling_summary(net=None, show=None):
1386 """
1387 Returns a `ProfilingSummary` of the profiling info for a run. This object
1388 can be transformed to a string explicitly but on an interactive console
1389 simply calling `profiling_summary` is enough since it will
1390 automatically convert the `ProfilingSummary` object.
1391
1392 Parameters
1393 ----------
1394
1395 net : {`Network`, None} optional
1396 The `Network` object to profile, or `magic_network` if not specified.
1397 show : int
1398 The number of results to show (the longest results will be shown). If
1399 not specified, all results will be shown.
1400 """
1401 if net is None:
1402 from .magic import magic_network
1403
1404 net = magic_network
1405 return ProfilingSummary(net, show)
1406
1407
1408 def scheduling_summary(net=None):
1409 """
1410 Returns a `SchedulingSummary` object, representing the scheduling
1411 information for all objects included in the given `Network` (or the
1412 "magic" network, if none is specified). The returned objects can be
1413 printed or converted to a string to give an ASCII table representation of
1414 the schedule. In a Jupyter notebook, the output can be displayed as a
1415 HTML table.
1416
1417 Parameters
1418 ----------
1419 net : `Network`, optional
1420 The network for which the scheduling information should be displayed.
1421 Defaults to the "magic" network.
1422
1423 Returns
1424 -------
1425 summary : `SchedulingSummary`
1426 An object that represents the scheduling information.
1427 """
1428 if net is None:
1429 from .magic import magic_network
1430
1431 magic_network._update_magic_objects(level=1)
1432 net = magic_network
1433 return net.scheduling_summary()
1434
1435
1436 def schedule_propagation_offset(net=None):
1437 """
1438 Returns the minimal time difference for a post-synaptic effect after a
1439 spike. With the default schedule, this time difference is 0, since the
1440 ``thresholds`` slot precedes the ``synapses`` slot. For the GeNN device,
1441 however, a post-synaptic effect will occur in the following time step, this
1442 function therefore returns one ``dt``.
1443
1444 Parameters
1445 ----------
1446 net : `Network`
1447 The network to check (uses the magic network if not specified).
1448
1449 Returns
1450 -------
1451 offset : `Quantity`
1452 The minimum spike propagation delay: ``0*ms`` for the standard schedule
1453 but ``dt`` for schedules where ``synapses`` precedes ``thresholds``.
1454
1455 Notes
1456 -----
1457 This function always returns ``0*ms`` or ``defaultclock.dt`` -- no attempt
1458 is made to deal with other clocks.
1459 """
1460 from brian2.core.magic import magic_network
1461
1462 device = get_device()
1463 if device.network_schedule is not None:
1464 schedule = device.network_schedule
1465 else:
1466 if net is None:
1467 net = magic_network
1468 schedule = net.schedule
1469
1470 if schedule.index("thresholds") < schedule.index("synapses"):
1471 return 0 * second
1472 else:
1473 return defaultclock.dt