# Network class

(Shortest import: `from brian2 import Network)`

class brian2.core.network.Network(*objs, name='network*')

  Bases: `Nameable`

  The main simulation controller in Brian

  `Network` handles the running of a simulation. It contains a set of Brian objects that are added with `add`. The `run` method actually runs the simulation. The main run loop, determining which objects get called in what order is described in detail in the notes below. The objects in the `Network` are accesible via their names, e.g. `net['neurongroup']` would return the `NeuronGroup` with this name.

  Parameters:

    objs : (`BrianObject`, container), optional

    > A list of objects to be added to the `Network` immediately, see `add`.

    name : str, optional

    > An explicit name, if not specified gives an automatically generated name

  See also

  `MagicNetwork`, `run()`, `stop()`

  Notes

  The main run loop performs the following steps:

  1. Prepare the objects if necessary, see `prepare`.

  2. Determine the end time of the simulation as `t`+``duration``.

  3. Determine which set of clocks to update. This will be the clock with the smallest value of `t`. If there are several with the same value, then all objects with these clocks will be updated simultaneously. Set `t` to the clock time.

  4. If the `t` value of these clocks is past the end time of the simulation, stop running. If the `Network.stop` method or the `stop()` function have been called, stop running. Set `t` to the end time of the simulation.

  5. For each object whose `clock` is set to one of the clocks from the previous steps, call the `update` method. This method will not be called if the `active` flag is set to `False`. The order in which the objects are called is described below.

  6. Increase `Clock.t` by `Clock.dt` for each of the clocks and return to step 2.

  The order in which the objects are updated in step 4 is determined by the `Network.schedule` and the objects `when` and `order` attributes. The `schedule` is a list of string names. Each `when` attribute should be one of these strings, and the objects will be updated in the order determined by the schedule. The default schedule is `['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']`. In addition to the names provided in the schedule, automatic names starting with `before_` and `after_` can be used. That means that all objects with `when=='before_start'` will be updated first, then those with `when=='start'`, `when=='after_start'`, `when=='before_groups'`, `when=='groups'` and so forth. If several objects have the same `when` attribute, then the order is determined by the `order` attribute (lower first).

  Attributes

  `_stored_state` | Stored state of objects (store/restore)
  `objects` | The set of objects in the Network, should not normally be modified directly.
  `profiling_info` | The time spent in executing the various `CodeObject` s.
  `schedule` | List of `when` slots in the order they will be updated, can be modified.
  `sorted_objects` | The sorted objects of this network in the order defined by the schedule.
  `t` | Current simulation time in seconds (`Quantity`)
  `t_` | Current time as a float

  Methods

  `add`(*objs) | Add objects to the `Network`
  `after_run`() |
  `before_run`(namespace) | Prepares the `Network` for a run.
  `check_dependencies`() |
  `get_profiling_info`() | The only reason this is not directly implemented in `profiling_info` is to allow devices (e.g. `CPPStandaloneDevice`) to overwrite this.
  `get_states`([units, format, subexpressions, ...]) | Return a copy of the current state variable values of objects in the network.
  `remove`(*objs) | Remove an object or sequence of objects from a `Network`.
  `restore`([name, filename, restore_random_state]) | Retore the state of the network and all included objects.
  `run`(duration[, report, report_period, ...]) | Runs the simulation for the given duration.
  `scheduling_summary`() | Return a `SchedulingSummary` object, representing the scheduling information for all objects included in the network.
  `set_states`(values[, units, format, level]) | Set the state variables of objects in the network.
  `stop`() | Stops the network from running, this is reset the next time `Network.run` is called.
  `store`([name, filename]) | Store the state of the network and all included objects.

  Details

  _stored_state

    Stored state of objects (store/restore)

  objects

    The set of objects in the Network, should not normally be modified directly. Note that in a `MagicNetwork`, this attribute only contains the objects during a run: it is filled in `before_run` and emptied in `after_run`

  profiling_info

    The time spent in executing the various `CodeObject` s.

    A list of `(name, time)` tuples, containing the name of the `CodeObject` and the total execution time for simulations of this object (as a `Quantity` with unit `second`). The list is sorted descending with execution time.

    Profiling has to be activated using the `profile` keyword in `run()` or `Network.run`.

  schedule

    List of `when` slots in the order they will be updated, can be modified.

    See notes on scheduling in `Network`. Note that additional `when` slots can be added, but the schedule should contain at least all of the names in the default schedule: `['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']`.

    The schedule can also be set to `None`, resetting it to the default schedule set by the core.network.default_schedule preference.

  sorted_objects

    The sorted objects of this network in the order defined by the schedule.

    Objects are sorted first by their `when` attribute, and secondly by the `order` attribute. The order of the `when` attribute is defined by the `schedule`. In addition to the slot names defined in the schedule, automatic slot names starting with `before_` and `after_` can be used (e.g. the slots `['groups', 'thresholds']` allow to use `['before_groups', 'groups', 'after_groups', 'before_thresholds', 'thresholds', 'after_thresholds']`).

    Final ties are resolved using the objects’ names, leading to an arbitrary but deterministic sorting.

  t

    Current simulation time in seconds (`Quantity`)

  t_

    Current time as a float

  add(*objs)

    Add objects to the `Network`

    Parameters:

      objs : (`BrianObject`, container)

      > The `BrianObject` or container of Brian objects to be added. Specify multiple objects, or lists (or other containers) of objects. Containers will be added recursively. If the container is a `dict` then it will add the values from the dictionary but not the keys. If you want to add the keys, do `add(objs.keys())`.

  after_run()
  before_run(namespace)

    Prepares the `Network` for a run.

    Objects in the `Network` are sorted into the correct running order, and their `BrianObject.before_run` methods are called.

    Parameters:

      run_namespace : dict-like, optional

      > A namespace in which objects which do not define their own namespace will be run.

  check_dependencies()
  get_profiling_info()

    The only reason this is not directly implemented in `profiling_info` is to allow devices (e.g. `CPPStandaloneDevice`) to overwrite this.

  get_states(units=True, format='dict', subexpressions=False, read_only_variables=True, level=0)

    Return a copy of the current state variable values of objects in the network.. The returned arrays are copies of the actual arrays that store the state variable values, therefore changing the values in the returned dictionary will not affect the state variables.

    Parameters:

      vars : list of str, optional

      > The names of the variables to extract. If not specified, extract all state variables (except for internal variables, i.e. names that start with `'_'`). If the `subexpressions` argument is `True`, the current values of all subexpressions are returned as well.

      units : bool, optional

      > Whether to include the physical units in the return value. Defaults to `True`.

      format : str, optional

      > The output format. Defaults to `'dict'`.

      subexpressions: bool, optional :

      > Whether to return subexpressions when no list of variable names is given. Defaults to `False`. This argument is ignored if an explicit list of variable names is given in `vars`.

      read_only_variables : bool, optional

      > Whether to return read-only variables (e.g. the number of neurons, the time, etc.). Setting it to `False` will assure that the returned state can later be used with `set_states`. Defaults to `True`.

      level : int, optional

      > How much higher to go up the stack to resolve external variables. Only relevant if extracting subexpressions that refer to external variables.

    Returns:

      values : dict

      > A dictionary mapping object names to the state variables of that object, in the specified `format`.

    See also

    `VariableOwner.get_states`

  remove(*objs)

    Remove an object or sequence of objects from a `Network`.

    Parameters:

      objs : (`BrianObject`, container)

      > The `BrianObject` or container of Brian objects to be removed. Specify multiple objects, or lists (or other containers) of objects. Containers will be removed recursively.

  restore(name='default', filename=None, restore_random_state=False)

    Retore the state of the network and all included objects.

    Parameters:

      name : str, optional

      > The name of the snapshot to restore, if not specified uses `'default'`.

      filename : str, optional

      > The name of the file from where the state should be restored. If not specified, it is expected that the state exist in memory (i.e. `Network.store` was previously called without the `filename` argument).

      restore_random_state : bool, optional

      > Whether to restore the state of the random number generator. If set to `True`, going back to an earlier state of the simulation will continue exactly where it left off, even if the simulation is stochastic. If set to `False` (the default), random numbers are independent between runs (except for explicitly set random seeds), regardless of whether `store()`/`restore()` has been used or not. Note that this also restores numpy’s random number generator (since it is used internally by Brian), but it does not restore Python’s builtin random number generator in the `random` module.

  run(duration, report=None, report_period=60 * second, namespace=None, level=0)

    Runs the simulation for the given duration.

    Parameters:

      duration : `Quantity`

      > The amount of simulation time to run for.

      report : {None, ‘text’, ‘stdout’, ‘stderr’, function}, optional

      > How to report the progress of the simulation. If `None`, do not report progress. If `'text'` or `'stdout'` is specified, print the progress to stdout. If `'stderr'` is specified, print the progress to stderr. Alternatively, you can specify a callback `callable(elapsed, completed, start, duration)` which will be passed the amount of time elapsed as a `Quantity`, the fraction `completed` from 0.0 to 1.0, the `start` time of the simulation as a `Quantity` and the total duration of the simulation (in biological time) as a `Quantity`. The function will always be called at the beginning and the end (i.e. for fractions 0.0 and 1.0), regardless of the `report_period`.

      report_period : `Quantity`

      > How frequently (in real time) to report progress.

      namespace : dict-like, optional

      > A namespace that will be used in addition to the group-specific namespaces (if defined). If not specified, the locals and globals around the run function will be used.

      profile : bool, optional

      > Whether to record profiling information (see `Network.profiling_info`). Defaults to `None` (which will use the value set by `set_device`, if any).

      level : int, optional

      > How deep to go up the stack frame to look for the locals/global (see `namespace` argument). Only used by run functions that call this run function, e.g. `MagicNetwork.run` to adjust for the additional nesting.

    Raises

    `ValueError`

      Error raised when duration passed in run function is negative.

    Notes

    The simulation can be stopped by calling `Network.stop` or the global `stop()` function.

  scheduling_summary()

    Return a `SchedulingSummary` object, representing the scheduling information for all objects included in the network.

    Returns:

      summary : `SchedulingSummary`

      > Object representing the scheduling information.

  set_states(values, units=True, format='dict', level=0)

    Set the state variables of objects in the network.

    Parameters:

      values : dict

      > A dictionary mapping object names to objects of `format`, setting the states of this object.

      units : bool, optional

      > Whether the `values` include physical units. Defaults to `True`.

      format : str, optional

      > The format of `values`. Defaults to `'dict'`

      level : int, optional

      > How much higher to go up the stack to _resolve external variables. Only relevant when using string expressions to set values.

    See also

    `Group.set_states`

  stop()

    Stops the network from running, this is reset the next time `Network.run` is called.

  store(name='default', filename=None)

    Store the state of the network and all included objects.

    Parameters:

      name : str, optional

      > A name for the snapshot, if not specified uses `'default'`.

      filename : str, optional

      > A filename where the state should be stored. If not specified, the state will be stored in memory.

    Notes

    The state stored to disk can be restored with the `Network.restore` function. Note that it will only restore the internal state of all the objects (including undelivered spikes) – the objects have to exist already and they need to have the same name as when they were stored. Equations, thresholds, etc. are not stored – this is therefore not a general mechanism for object serialization. Also, the format of the file is not guaranteed to work across platforms or versions. If you are interested in storing the state of a network for documentation or analysis purposes use `Network.get_states` instead.

## Tutorials and examples using this

- Tutorial 3-intro-to-brian-simulations

- Example IF_curve_Hodgkin_Huxley

- Example IF_curve_LIF

- Example advanced/compare_GSL_to_conventional

- Example advanced/stochastic_odes

- Example frompapers/Brunel_Wang_2001

- Example frompapers/Diehl_Cook_2015

- Example frompapers/Maass_Natschlaeger_Markram_2002

- Example frompapers/Spreizer_et_al_2019/Spreizer_et_al_2019

- Example frompapers/Wang_2002

- Example multiprocessing/02_using_standalone

- Example multiprocessing/03_standalone_joblib

- Example standalone/standalone_multiple_processes

- Example standalone/standalone_multiplerun

- Example synapses/homeostatic_stdp_at_inhibitory_synapes