BrainPyObject#

class brainpy.math.BrainPyObject(name=None)[source]#

The BrainPyObject class for the whole BrainPy ecosystem.

The subclass of BrainPyObject includes but not limited to:

  • DynamicalSystem in brainpy.dyn.base.py

  • Integrator in brainpy.integrators.base.py

  • Optimizer in brainpy.optimizers.py

  • Scheduler in brainpy.optimizers.py

Note

Note a variable created in the BrainPyObject will never be replaced.

For example, if here we create an object which has an attribute a:

>>> import brainpy as bp
>>> import brainpy.math as bm
>>>
>>> class MyObj(bp.BrainPyObject):
>>>   def __init__(self):
>>>     super().__init__()
>>>     self.a = bm.Variable(bm.ones(1))
>>>
>>>   def reset1(self):
>>>     self.a = bm.asarray([10.])
>>>
>>>   def reset2(self):
>>>     self.a = 1.
>>>
>>> ob = MyObj()
>>> id(ob.a)
2643434845056

After we call ob.reset1() function, ob.a is still the original Variable. what’s change is its value.

>>> ob.reset1()
>>> id(ob.a)
2643434845056

What’s really happend when we call self.a = bm.asarray([10.]) is self.a.value = bm.asarray([10.]). Therefore we when call ob.reset2(), there will be an error.

>>> ob.reset2()
brainpy.errors.MathError: The shape of the original data is (1,), while we got () with batch_axis=None.
cpu()[source]#

Move all variable into the CPU device.

cuda()[source]#

Move all variables into the GPU device.

load_state(state_dict, **kwargs)[source]#

Load states from a dictionary.

Return type:

Optional[Tuple[Sequence[str], Sequence[str]]]

load_state_dict(state_dict, warn=True, compatible='v2', **kwargs)[source]#

Copy parameters and buffers from state_dict into this module and its descendants.

Parameters:
  • state_dict (Dict[str, Any]) – A dict containing parameters and persistent buffers.

  • warn (bool) – Warnings when there are missing keys or unexpected keys in the external state_dict.

  • compatible (str) – The version of API for compatibility.

Returns:

outNamedTuple with missing_keys and unexpected_keys fields:

  • missing_keys is a list of str containing the missing keys

  • unexpected_keys is a list of str containing the unexpected keys

Return type:

StateLoadResult

property name#

Name of the model.

nodes(method='absolute', level=-1, include_self=True)[source]#

Collect all children nodes.

Parameters:
  • method (str) – The method to access the nodes.

  • level (int) – The hierarchy level to find nodes.

  • include_self (bool) – Whether include the self.

Returns:

gather – The collection contained (the path, the node).

Return type:

Collector

save_state(**kwargs)[source]#

Save states as a dictionary.

Return type:

Dict

state_dict(**kwargs)[source]#

Returns a dictionary containing a whole state of the module.

Returns:

out – A dictionary containing a whole state of the module.

Return type:

dict

to(device)[source]#

Moves all variables into the given device.

Parameters:

device (Optional[Any]) – The device.

tpu()[source]#

Move all variables into the TPU device.

tracing_variable(name, init, shape, batch_or_mode=None, batch_axis=0, axis_names=None, batch_axis_name='batch')[source]#

Initialize a variable that can be traced during computations and transformations.

Deprecated since version 3.0.0: This feature is no longer supported. Since BrainPy 3.0.0 the library has been rewritten on top of brainstate and variable tracing is handled by brainstate directly. Calling this method always raises NotImplementedError.

Parameters:
  • name (str) – The variable name.

  • init (Union[Callable, Array, Array]) – The data to be initialized as a Variable.

  • shape (Union[int, Sequence[int]]) – The shape of the variable.

  • batch_or_mode (Union[int, bool, Mode]) – The batch size of this variable.

  • batch_axis (int) – The batch axis, if batch size is given.

  • axis_names (Optional[Sequence[str]]) – The name for each axis.

  • batch_axis_name (Optional[str]) – The name for the batch axis.

Raises:

NotImplementedError – Always, because this feature is unsupported since 3.0.0.

Return type:

Variable

train_vars(method='absolute', level=-1, include_self=True)[source]#

The shortcut for retrieving all trainable variables.

Parameters:
  • method (str) – The method to access the variables. Support ‘absolute’ and ‘relative’.

  • level (int) – The hierarchy level to find TrainVar instances.

  • include_self (bool) – Whether include the TrainVar instances in the self.

Returns:

gather – The collection contained (the path, the trainable variable).

Return type:

ArrayCollector

tree_flatten()[source]#

Flattens the object as a PyTree.

The flattening order is determined by attributes added order.

Added in version 2.3.1.

Returns:

res – A tuple of dynamical values and static values.

Return type:

tuple

classmethod tree_unflatten(aux, dynamic_values)[source]#

Unflatten the data to construct an object of this class.

Added in version 2.3.1.

unique_name(name=None, type_=None)[source]#

Get the unique name for this object.

Parameters:
  • name (str, optional) – The expected name. If None, the default unique name will be returned. Otherwise, the provided name will be checked to guarantee its uniqueness.

  • type_ – The name of this class, used for object naming.

Returns:

name – The unique name for this object.

Return type:

str

vars(method='absolute', level=-1, include_self=True, exclude_types=None)[source]#

Collect all variables in this node and the children nodes.

Parameters:
  • method (str) – The method to access the variables.

  • level (int) – The hierarchy level to find variables.

  • include_self (bool) – Whether include the variables in the self.

  • exclude_types (Tuple[type, ...]) – The type to exclude.

Returns:

gather – The collection contained (the path, the variable).

Return type:

ArrayCollector