devices.dynapse.DynapseSamna

class devices.dynapse.DynapseSamna(*args, **kwargs)[source]

Bases: Module

DynapseSamna bridges the gap between the chip and the computer. Provides a simulation-like interface for users, but executes all the operations on the hardware under the hood. Use devices.dynapse.find_dynapse_boards to find the HDK. Use devices.dynapse.config_from_specification to obtain a configuration object.

Example usage
# Connect
se2_devices = find_dynapse_boards()
se2 = DynapseSamna(se2_devices[0], **config)
out, state, rec = se2(raster, record=True)
Parameters:
  • shape (Tuple[int]) – Two dimensions (Nin, Nout), which defines a input and output conections of Dynap-SE2 neurons.

  • device (DeviceInfo) – the Dynan-SE2 the device object to open and configure

  • config (Dynapse2Configuration) – a Dynan-SE2 samna configuration object

  • input_channel_map (Dict[int, List[Dynapse2Destination]]) – the mapping between input timeseries channels and the destinations

  • dt (float, optional) – the simulation timestep resolution, defaults to 1e-3

  • dt_fpga (float, optional) – the FPGA timestep resolution, defaults to 1e-6

  • control_tag (int, optional) – a tag used in special occacions such as current time reading. Do not capture events with this tag and control_hop, defaults to 2047

  • control_hop (int, optional) – a chip position (-7 means x_hop=-7, y_hop=-7) which does not really exist, works in cooperation with control_tag. Do not capture events coming from this hop and control tag, defauts to -7.

Attributes overview

class_name

Class name of self

config

the configuration object stored on the Dynap-SE2 board

full_name

The full name of this module (class plus module name)

model

the HDK model object that can be used to configure the device

name

The name of this module, or an empty string if None

shape

The shape of this module

size

(DEPRECATED) The output size of this module

size_in

The input size of this module

size_out

The output size of this module

spiking_input

If True, this module receives spiking input.

spiking_output

If True, this module sends spiking output.

dt

the simulation timestep resolution

dt_fpga

the FPGA timestep resolution

control_tag

a tag used in special occacions such as current time reading.

control_hop

a chip position (-7 means x_hop=-7, y_hop=-7) which does not really exist, works in cooperation with control_tag.

input_channel_map

the mapping between input timeseries channels and the destinations

board

a configured samna Dynan-SE2 interface node Dynapse2Interface

app_config

the samna configuration object deployed to the chip

leaky_config

a dummy object to discharge all the capacitors on chip

Methods overview

__init__(device,Β config,Β input_channel_map)

__init__ initializes DynapseSamna module.

apply_config()

apply_config writes the configuration object to the device

as_graph()

Convert this module to a computational graph

attributes_named(name)

Search for attributes of this or submodules by time

current_timestamp([timeout,Β poll_step])

current_timestamp bounces a dummy event from FPGA to get the exact FPGA time at that moment.

discharge_capacitors()

discharge_capacitors applies the leaky configuration object to the hardware model in order to discharge all the capacitors

disconnect()

disconnect breaks the connection between CPU and the device

evolve(input_data[,Β read_timeout,Β offset,Β ...])

evolve simulates the network on Dynap-SE2 HDK in real-time The function first converts raster plot to a sequence of AER packages and dispatches to the device.

modules()

Return a dictionary of all sub-modules of this module

parameters([family])

Return a nested dictionary of module and submodule Parameters

reset_parameters()

Reset all parameters in this module

reset_state()

Reset the state of this module

set_attributes(new_attributes)

Set the attributes and sub-module attributes from a dictionary

simulation_parameters([family])

Return a nested dictionary of module and submodule SimulationParameters

state([family])

Return a nested dictionary of module and submodule States

timed([output_num,Β dt,Β add_events])

Convert this module to a TimedModule

__aer_to_raster(buffer: List[NormalGridEvent], stop_time: float, start_time: float = 0) Tuple[ndarray, Dict[int, Dynapse2Destination]]

__aer_to_raster converts a list of Dynap-SE2 AER packages to a discrete raster record The events does not meet the start and stop time criteria are descarded

Parameters:
  • buffer (List[NormalGridEvent]) – the event buffer, a list of Dynap-SE2 AER packages

  • stop_time (float) – the stop time cut-off for the events.

  • start_time – the start time cut-off for the events, defaults to 0

Returns:

ts, cmap raster_out: the raster record referenced on the event buffer cmap: the mapping between raster channels and the destinations

Return type:

Tuple[np.ndarray, Dict[int, Dynapse2Destination]]

__configure_dynapse2_fpga(device: DeviceInfo, bitfile: str | None = None) Dynapse2Interface

configure_dynapse2_fpga configures the FPGA on board and builds a connection node between CPU and the device. It allows one to configure the device, read or write AER events to bus, and monitor the activity of device neurons

Parameters:
  • device (DeviceInfo) – the device object to open and configure

  • bitfile (Optional[str], optional) – the bitfile path if known, defaults to None

Raises:

IOError – Failed to configure Opal Kelly

Returns:

an open and configured Dynan-SE2 interface node

Return type:

Dynapse2Interface

__control_event(event_time: float = 0.0) NormalGridEvent

__control_event generates a dummy event to be bounced back from the FPGA This event helps to read the current FPGA time or understand the simulation is done

Parameters:

event_time (float) – the time that the event happened in seconds

Returns:

a virtual samna AER package for control

Return type:

NormalGridEvent

__control_sequence(event_time: float = 0.0, num_events: int = 3) List[NormalGridEvent]

__control_sequence creates a sequence of control events. In general, one control event is not enough because it can easily get lost.

Parameters:

num_events (int, optional) – number of event to append to the list, defaults to 3

Returns:

a sequence of control events

Return type:

List[NormalGridEvent]

__default_channel_map(num_channels: int) Dict[int, Dynapse2Destination]

__default_channel_map creates a dummy channel map which helps to bounce the AER events back from the FPGA

Parameters:

num_channels (int) – number of input channels

Returns:

a channel map which assigns the neuron ids as tags, and use the control hop to bounce the neurons

Return type:

Dict[int, Dynapse2Destination]

__event_generator(event_time: float, core: List[bool] = [True, True, True, True], x_hop: int = -7, y_hop: int = -7, tag: uint64 = 2047) NormalGridEvent

__event_generator can be used to generate dummy events

Parameters:
  • event_time (float) – the time that the event happened in seconds

  • core (List[bool], optional) – the core mask used while sending the events, defaults to [True, True, True, True] [1,1,1,1] means all 4 cores are on the target [0,0,1,0] means the event will arrive at core 2 only

  • x_hop (int, optional) – number of chip hops on x axis, defaults -7

  • y_hop (int, optional) – number of chip hops on y axis, defaults to -7

  • tag (np.uint, optional) – globally multiplexed locally unique event tag which is used to identify the connection between two neurons, defaults to 2047

Returns:

a virtual samna AER package for DynapSE2

Return type:

NormalGridEvent

__extract_channel_map(buffer: List[NormalGridEvent]) Dict[int, Dynapse2Destination]

extract_channel_map obtains a channel map from a list of dummy AER packages (samna alias)

Parameters:

buffer (List[NormalGridEvent]) – the list of AER packages

Returns:

the mapping between timeseries channels and the destinations

Return type:

Dict[int, Dynapse2Destination]

__get_leaky_config() Dynapse2Configuration

get_leaky_config returns a configuration object to discharge all the capacitors on chip

__if_control_event(event: NormalGridEvent) bool

__if_control_event returns true if the event is a control event which is bounced back from FPGA

Parameters:

event (NormalGridEvent) – any Dynap-SE2 AER package to check

Returns:

true if the package is a control event bounced back from FPGA

Return type:

bool

__init__(device: DeviceInfo, config: Dynapse2Configuration, input_channel_map: Dict[int, List[Dynapse2Destination]], dt: float = 0.001, dt_fpga: float = 1e-06, control_tag: int = 2047, control_hop: int = -7, *args, **kwargs) None[source]

__init__ initializes DynapseSamna module. Parameters are explained in the class docstring.

__poll_events(duration: float, poll_step: float = 0.001) Tuple[List[NormalGridEvent], bool, float]

__poll_events records the device’s output and stores in an event buffer

Parameters:
  • duration (float) – the maximum duration that the events will be captured

  • poll_step (float, optional) – the pollling step, 1 ms means the CPU fetches events from FPGA in every 1 ms, defaults to 1e-3

Returns:

output_events, done, t_done :output_events: the event buffer, a list of Dynap-SE2 AER packages captured :done: a bloolean flag indicating if all the events read or not :t_done: the time in seconds that the reading is done.

Return type:

Tuple[List[NormalGridEvent], bool, float]

__raster_to_aer(raster: ndarray, start_time: float = 0.0) List[NormalGridEvent]

__raster_to_aer converts a discrete raster record to a list of AER packages. It uses a channel map to map the channels to destinations, and by default it returns a list of samna objects.

Parameters:
  • raster (np.ndarray) – the discrete timeseries to be converted into list of Dynap-SE2 AER packages

  • start_time (float) – the start time of the record in seconds, defaults to 0.0

Raises:
  • ValueError – Raster should be 2 dimensional!

  • ValueError – Channel map does not map the channels of the timeseries provided!

Returns:

a list of Dynap-SE2 AER packages

Return type:

List[NormalGridEvent]

_abc_impl = <_abc._abc_data object>
_auto_batch(data: ndarray, states: Tuple = (), target_shapes: Tuple | None = None) Tuple[ndarray, Tuple[ndarray]]

Automatically replicate states over batches and verify input dimensions

Examples

>>> data, (state0, state1, state2) = self._auto_batch(data, (self.state0, self.state1, self.state2))

This will verify that data has the correct final dimension (i.e. self.size_in).

If data has only two dimensions (T, Nin), then it will be augmented to (1, T, Nin). The individual states will be replicated out from shape (a, b, c, ...) to (n_batches, a, b, c, ...) and returned.

If data has only a single dimension (T,), it will be expanded to (1, T, self.size_in).

state0, state1, state2 will be replicated out along the batch dimension.

>>> data, (state0,) = self._auto_batch(data, (self.state0,), ((10, -1, self.size_in),))

Attempt to replicate state0 to a specified size (10, -1, self.size_in).

Parameters:
  • data (np.ndarray) – Input data tensor. Either (batches, T, Nin) or (T, Nin)

  • states (Tuple) – Tuple of state variables. Each will be replicated out over batches by prepending a batch dimension

  • target_shapes (Tuple) – A tuple of target size tuples, each corresponding to each state argument. The individual states will be replicated out to match the corresponding target sizes. If not provided (the default), then states will be only replicated along batches.

Returns:

(np.ndarray, Tuple[np.ndarray]) data, states

_force_set_attributes

(bool) If True, do not sanity-check attributes when setting.

_get_attribute_family(type_name: str, family: Tuple | List | str | None = None) dict

Search for attributes of this module and submodules that match a given family

This method can be used to conveniently get all weights for a network; or all time constants; or any other family of parameters. Parameter families are defined simply by a string: "weights" for weights; "taus" for time constants, etc. These strings are arbitrary, but if you follow the conventions then future developers will thank you (that includes you in six month’s time).

Parameters:
  • type_name (str) – The class of parameters to search for. Must be one of ["Parameter", "SimulationParameter", "State"] or another future subclass of ParameterBase

  • family (Union[str, Tuple[str]]) – A string or list or tuple of strings, that define one or more attribute families to search for

Returns:

A nested dictionary of attributes that match the provided type_name and family

Return type:

dict

_get_attribute_registry() Tuple[Dict, Dict]

Return or initialise the attribute registry for this module

Returns:

registered_attributes, registered_modules

Return type:

(tuple)

_has_registered_attribute(name: str) bool

Check if the module has a registered attribute

Parameters:

name (str) – The name of the attribute to check

Returns:

True if the attribute name is in the attribute registry, False otherwise.

Return type:

bool

_in_Module_init

(bool) If exists and True, indicates that the module is in the __init__ chain.

_name: str | None

Name of this module, if assigned

_register_attribute(name: str, val: ParameterBase)

Record an attribute in the attribute registry

Parameters:
  • name (str) – The name of the attribute to register

  • val (ParameterBase) – The ParameterBase subclass object to register. e.g. Parameter, SimulationParameter or State.

_register_module(name: str, mod: ModuleBase)

Register a sub-module in the module registry

Parameters:
  • name (str) – The name of the module to register

  • mod (ModuleBase) – The ModuleBase object to register

_reset_attribute(name: str) ModuleBase

Reset an attribute to its initialisation value

Parameters:

name (str) – The name of the attribute to reset

Returns:

For compatibility with the functional API

Return type:

self (Module)

_shape

The shape of this module

_spiking_input: bool

Whether this module receives spiking input

_spiking_output: bool

Whether this module produces spiking output

_submodulenames: List[str]

Registry of sub-module names

_wrap_recorded_state(recorded_dict: dict, t_start: float) Dict[str, TimeSeries]

Convert a recorded dictionary to a TimeSeries representation

This method is optional, and is provided to make the timed() conversion to a TimedModule work better. You should override this method in your custom Module, to wrap each element of your recorded state dictionary as a TimeSeries

Parameters:
  • state_dict (dict) – A recorded state dictionary as returned by evolve()

  • t_start (float) – The initial time of the recorded state, to use as the starting point of the time series

Returns:

The mapped recorded state dictionary, wrapped as TimeSeries objects

Return type:

Dict[str, TimeSeries]

app_config

the samna configuration object deployed to the chip

apply_config() None[source]

apply_config writes the configuration object to the device

as_graph() GraphModuleBase

Convert this module to a computational graph

Returns:

The computational graph corresponding to this module

Return type:

GraphModuleBase

Raises:

NotImplementedError – If as_graph() is not implemented for this subclass

attributes_named(name: Tuple[str] | List[str] | str) dict

Search for attributes of this or submodules by time

Parameters:

name (Union[str, Tuple[str]) – The name of the attribute to search for

Returns:

A nested dictionary of attributes that match name

Return type:

dict

board: Dynapse2Interface

a configured samna Dynan-SE2 interface node Dynapse2Interface

property class_name: str

Class name of self

Type:

str

property config: Dynapse2Configuration

the configuration object stored on the Dynap-SE2 board

control_hop

a chip position (-7 means x_hop=-7, y_hop=-7) which does not really exist, works in cooperation with control_tag. Do not capture events coming from this hop and control tag

control_tag

a tag used in special occacions such as current time reading. Do not capture events with this tag and control_hop

current_timestamp(timeout: float = 20.0, poll_step: float = 0.001) float[source]

current_timestamp bounces a dummy event from FPGA to get the exact FPGA time at that moment.

Parameters:
  • timeout (float, optional) – the maximum timeout limit in seconds, defaults to 20.0

  • poll_step (float, optional) – the pollling step, 1 ms means the CPU fetches events from FPGA in every 1 ms, defaults to 1e-3

Raises:

TimeoutError – FPGA could not respond in {timeout} seconds!

Returns:

the current FPGA time in seconds

Return type:

float

discharge_capacitors() None[source]

discharge_capacitors applies the leaky configuration object to the hardware model in order to discharge all the capacitors

disconnect() None[source]

disconnect breaks the connection between CPU and the device

dt

the simulation timestep resolution

dt_fpga

the FPGA timestep resolution

evolve(input_data: ndarray, read_timeout: float = 60.0, offset: float = 0.1, poll_step: float = 0.001, record: bool = False) Tuple[ndarray, Dict, Dict][source]

evolve simulates the network on Dynap-SE2 HDK in real-time The function first converts raster plot to a sequence of AER packages and dispatches to the device. Then reads the output buffers

Parameters:
  • input_data (np.ndarray) – A raster (T, Nin) specifying for each bin the number of input events sent to the corresponding input channel on Dynap-SE2, at the corresponding time point.

  • read_timeout (float, optional) – the maximum time to wait until reading finishes, defaults to 60.0

  • offset (float, optional) – user defined start time offset in seconds, defaults to 100e-3

  • poll_step (float, optional) – the pollling step, 1 ms means the CPU fetches events from FPGA in every 1 ms, defaults to 1e-3

  • record (bool, optional) – record the states in each timestep of evolution or not, defaults to False

Returns:

spikes_ts, states, record_dict :spikes_ts: is an array with shape (T, Nrec) containing the output data(spike raster) produced by the module. :states: is a dictionary containing the updated module state following evolution. :record_dict: is a dictionary containing the recorded state variables during the evolution at each time step, if the record argument is True else empty dictionary {}

Return type:

Tuple[np.ndarray, Dict, Dict]

property full_name: str

The full name of this module (class plus module name)

Type:

str

input_channel_map

the mapping between input timeseries channels and the destinations

leaky_config

a dummy object to discharge all the capacitors on chip

property model: Dynapse2Model

the HDK model object that can be used to configure the device

modules() Dict

Return a dictionary of all sub-modules of this module

Returns:

A dictionary containing all sub-modules. Each item will be named with the sub-module name.

Return type:

dict

property name: str

The name of this module, or an empty string if None

Type:

str

parameters(family: Tuple | List | str | None = None) Dict

Return a nested dictionary of module and submodule Parameters

Use this method to inspect the Parameters from this and all submodules. The optional argument family allows you to search for Parameters in a particular family β€” for example "weights" for all weights of this module and nested submodules.

Although the family argument is an arbitrary string, reasonable choises are "weights", "taus" for time constants, "biases" for biases…

Examples

Obtain a dictionary of all Parameters for this module (including submodules):

>>> mod.parameters()
dict{ ... }

Obtain a dictionary of Parameters from a particular family:

>>> mod.parameters("weights")
dict{ ... }
Parameters:

family (str) – The family of Parameters to search for. Default: None; return all parameters.

Returns:

A nested dictionary of Parameters of this module and all submodules

Return type:

dict

reset_parameters()

Reset all parameters in this module

Returns:

The updated module is returned for compatibility with the functional API

Return type:

Module

reset_state() ModuleBase

Reset the state of this module

Returns:

The updated module is returned for compatibility with the functional API

Return type:

Module

set_attributes(new_attributes: dict) ModuleBase

Set the attributes and sub-module attributes from a dictionary

This method can be used with the dictionary returned from module evolution to set the new state of the module. It can also be used to set multiple parameters of a module and submodules.

Examples

Use the functional API to evolve, obtain new states, and set those states:

>>> _, new_state, _ = mod(input)
>>> mod = mod.set_attributes(new_state)

Obtain a parameter dictionary, modify it, then set the parameters back:

>>> params = mod.parameters()
>>> params['w_input'] *= 0.
>>> mod.set_attributes(params)
Parameters:

new_attributes (dict) – A nested dictionary containing parameters of this module and sub-modules.

property shape: tuple

The shape of this module

Type:

tuple

simulation_parameters(family: Tuple | List | str | None = None) Dict

Return a nested dictionary of module and submodule SimulationParameters

Use this method to inspect the SimulationParameters from this and all submodules. The optional argument family allows you to search for SimulationParameters in a particular family.

Examples

Obtain a dictionary of all SimulationParameters for this module (including submodules):

>>> mod.simulation_parameters()
dict{ ... }
Parameters:

family (str) – The family of SimulationParameters to search for. Default: None; return all SimulationParameter attributes.

Returns:

A nested dictionary of SimulationParameters of this module and all submodules

Return type:

dict

property size: int

(DEPRECATED) The output size of this module

Type:

int

property size_in: int

The input size of this module

Type:

int

property size_out: int

The output size of this module

Type:

int

property spiking_input: bool

If True, this module receives spiking input. If False, this module expects continuous input.

Type:

bool

property spiking_output

If True, this module sends spiking output. If False, this module sends continuous output.

Type:

bool

state(family: Tuple | List | str | None = None) Dict

Return a nested dictionary of module and submodule States

Use this method to inspect the States from this and all submodules. The optional argument family allows you to search for States in a particular family.

Examples

Obtain a dictionary of all States for this module (including submodules):

>>> mod.state()
dict{ ... }
Parameters:

family (str) – The family of States to search for. Default: None; return all State attributes.

Returns:

A nested dictionary of States of this module and all submodules

Return type:

dict

timed(output_num: int = 0, dt: float | None = None, add_events: bool = False)

Convert this module to a TimedModule

Parameters:
  • output_num (int) – Specify which output of the module to take, if the module returns multiple output series. Default: 0, take the first (or only) output.

  • dt (float) – Used to provide a time-step for this module, if the module does not already have one. If self already defines a time-step, then self.dt will be used. Default: None

  • add_events (bool) – Iff True, the TimedModule will add events occurring on a single timestep on input and output. Default: False, don’t add time steps.

Returns: TimedModule: A timed module that wraps this module