Warning

This version of the documentation is NOT an official release. You are looking at ‘latest’, which is in active and ongoing development. You can change versions on the bottom left of the screen.

# PyNEST API¶

The nest module contains methods and attributes to control the NEST kernel. This interface is known as PyNEST.

## Kernel attributes¶

The NEST kernel can be controlled from the PyNEST interface by getting or setting attributes on the nest module:

# set a single kernel attribute
nest.resolution = 0.1

# set multiple attributes at once
nest.set(min_delay=0.1, max_delay=2.0)

# if you have the attributes in a dictionary
params = {'min_delay': 0.1, 'max_delay': 2.0}
nest.set(**params)


Here is a list of attributes that can be get and/or set on the nest module:

class nest.NestModule(name, doc=None)

A module class for the nest root module to control the dynamic generation of module level attributes such as the KernelAttributes and lazy loading some submodules.

T_max

The largest representable time value.

Type

float

T_min

The smallest representable time value.

Type

float

Whether MPI buffers for communication of spikes resize on the fly, defaults to True.

Type

bool

Whether MPI buffers for communication of connections resize on the fly, defaults to True.

Type

bool

biological_time

The current simulation time (in ms).

Type

float

buffer_size_secondary_events

Size of MPI buffers for communicating secondary events (in bytes, per MPI rank, for developers).

Type

int

buffer_size_spike_data

Total size of MPI buffer for communication of spikes, defaults to 2.

Type

int

buffer_size_target_data

Total size of MPI buffer for communication of connections, defaults to 2.

Type

int

data_path

A path, where all data is written to, defaults to current directory.

Type

str

data_prefix

A common prefix for all data files.

Type

str

dict_miss_is_error

Whether missed dictionary entries are treated as errors, defaults to True.

Type

bool

growth_factor_buffer_spike_data

If MPI buffers for communication of spikes resize on the fly, grow them by this factor each round, defaults to 1.5.

Type

float

growth_factor_buffer_target_data

If MPI buffers for communication of connections resize on the fly, grow them by this factor each round, defaults to 1.5.

Type

float

keep_source_table

Whether to keep source table after connection setup is complete, defaults to True.

Type

bool

kernel_status

Get the complete kernel status.

Type

dict

The local number of threads, defaults to 1.

Type

int

local_spike_counter

Number of spikes fired by neurons on a given MPI rank during the most recent call to Simulate(). Only spikes from “normal” neurons are counted, not spikes generated by devices such as poisson_generator.

Type

int

max_buffer_size_spike_data

Maximal size of MPI buffers for communication of spikes, defaults to 8388608.

Type

int

max_buffer_size_target_data

Maximal size of MPI buffers for communication of connections, defaults to 16777216.

Type

int

max_delay

The maximum delay in the network, defaults to 0.1.

Type

float

max_num_syn_models

Maximal number of synapse models supported.

Type

int

max_update_time

Longest wall-clock time measured so far for a full update step [seconds].

Type

float

min_delay

The minimum delay in the network, defaults to 0.1.

Type

float

min_update_time

Shortest wall-clock time measured so far for a full update step [seconds].

Type

float

ms_per_tic

The number of milliseconds per tic, defaults to 0.001.

Type

float

network_size

The number of nodes in the network.

Type

int

num_connections

The number of connections in the network.

Type

int

num_processes

The number of MPI processes.

Type

int

off_grid_spiking

Whether to transmit precise spike times in MPI communication.

Type

bool

overwrite_files

Whether to overwrite existing data files, defaults to False.

Type

bool

print_time

Whether to print progress information during the simulation, defaults to False.

Type

bool

recording_backends

Dict of backends for recording devices. Each recording backend can have a set of global parameters that can be modified through this attribute by passing a dictionary with the name of the recording backend as key and a dictionary with the global parameters to be overwritten as value.

Example

Please note that NEST must be compiled with SionLIB for the sionlib backend to be available.

nest.recording_backends = dict(sionlib=dict(buffer_size=1024))


The valid global parameters are listed in the documentation of each recording backend.

Type

dict[str, dict]

resolution

The resolution of the simulation (in ms), defaults to 0.1.

Type

float

rng_seed

Seed value used as base for seeding NEST random number generators ($$1 \leq s\leq 2^{32}-1$$), defaults to 143202461.

Type

int

rng_type

Name of random number generator type used by NEST, defaults to mt19937_64.

Type

str

rng_types

List of available random number generator types.

Type

list[str]

sort_connections_by_source

Whether to sort connections by their source; increases construction time of presynaptic data structures, decreases simulation time if the average number of outgoing connections per neuron is smaller than the total number of threads, defaults to True.

Type

bool

structural_plasticity_synapses

Defines all synapses which are plastic for the structural plasticity algorithm. Each entry in the dictionary is composed of a synapse model, the presynaptic element and the postsynaptic element.

Type

dict

structural_plasticity_update_interval

Defines the time interval in ms at which the structural plasticity manager will make changes in the structure of the network ( creation and deletion of plastic synapses), defaults to 10000.0.

Type

int

tics_per_ms

The number of tics per millisecond, defaults to 1000.0.

Type

float

tics_per_step

The number of tics per simulation time step, defaults to 100.

Type

int

to_do

The number of steps yet to be simulated.

Type

int

total_num_virtual_procs

The total number of virtual processes, defaults to 1.

Type

int

update_time_limit

Maximum wall-clock time for one full update step [seconds]. This can be used to terminate simulations that slow down significantly. Simulations may still get stuck if the slowdown occurs within a single update step, defaults to inf.

Type

float

use_compressed_spikes

Whether to use spike compression; if a neuron has targets on multiple threads of a process, this switch makes sure that only a single packet is sent to the process instead of one packet per target thread; requires nest.sort_connections_by_source = True, defaults to True.

Type

bool

use_wfr

Whether to use waveform relaxation method, defaults to True.

Type

bool

wfr_comm_interval

Desired waveform relaxation communication interval, defaults to 1.0.

Type

float

wfr_interpolation_order

Interpolation order of polynomial used in wfr iterations, defaults to 3.

Type

int

wfr_max_iterations

Maximal number of iterations used for waveform relaxation, defaults to 15.

Type

int

wfr_tol

Convergence tolerance of waveform relaxation method, defaults to 0.0001.

Type

float

## Functions related to models¶

Functions for model handling

nest.lib.hl_api_models.ConnectionRules()

Return a typle of all available connection rules, sorted by name.

Returns

Available connection rules

Return type

tuple

nest.lib.hl_api_models.CopyModel(existing, new, params=None)

Create a new model by copying an existing one.

Parameters
• existing (str) – Name of existing model

• new (str) – Name of the copied model

• params (dict, optional) – Default parameters assigned to the copy. Not provided parameters are taken from the existing model.

nest.lib.hl_api_models.GetDefaults(model, keys=None, output='')

Return default parameters of the given model, specified by a string.

Parameters
• model (str) – Name of the model

• keys (str or list, optional) – String or a list of strings naming model properties. GetDefaults then returns a single value or a list of values belonging to the keys given.

• output (str, optional) – Whether the returned data should be in a format (output='json'). Default is ‘’.

Returns

• dict – A dictionary of default parameters.

• type – If keys is a string, the corrsponding default parameter is returned.

• list – If keys is a list of strings, a list of corrsponding default parameters is returned.

• str – If output is json, returns parameters in JSON format.

Raises
nest.lib.hl_api_models.Models(mtype='all', sel=None)

Return a tuple of model names, sorted by name.

All available models are neurons, devices and synapses.

Parameters
• mtype (str, optional) – Use 'mtype='nodes' to only see neuron and device models, or 'type='synapses' to only see synapse models.

• sel (str, optional) – String used to filter the result list and only return models containing it.

Returns

Available model names

Return type

tuple

Raises

ValueError – Description

Notes

• Synapse model names ending with '_hpc' provide minimal memory requirements by using thread-local target neuron IDs and fixing the 'rport' to 0.

• Synapse model names ending with '_lbl' allow to assign an individual integer label ('synapse_label') to created synapses at the cost of increased memory requirements.

nest.lib.hl_api_models.SetDefaults(model, params, val=None)

Set the default parameter values of the given model.

New default values are used for all subsequently created instances of the model.

Parameters
• model (str) – Name of the model

• params (str or dict) – Dictionary of new default parameter values

• val (str, optional) – If given, params has to be the name of a model property.

## Functions related to the creation and retrieval of nodes (neurons, devices)¶

Functions for node handling

nest.lib.hl_api_nodes.Create(model, n=1, params=None, positions=None)

Create one or more nodes.

Generates n new network objects of the supplied model type. If n is not given, a single node is created. Note that if setting parameters of the nodes fail, the nodes will still have been created.

Parameters
• model (str) – Name of the model to create

• n (int, optional) – Number of nodes to create

• params (dict or list, optional) –

Parameters for the new nodes. Can be any of the following:

• A dictionary with either single values or lists of size n. The single values will be applied to all nodes, while the lists will be distributed across the nodes. Both single values and lists can be given at the same time.

• A list with n dictionaries, one dictionary for each node.

Values may be Parameter objects. If omitted, the model’s defaults are used.

• positions (spatial.grid or spatial.free object, optional) – Object describing spatial positions of the nodes. If omitted, the nodes have no spatial attachment.

Returns

Object representing the IDs of created nodes, see NodeCollection for more.

Return type

NodeCollection

Raises
• NESTError – If setting node parameters fail. However, the nodes will still have been created.

• TypeError – If the positions object is of wrong type.

nest.lib.hl_api_nodes.GetLocalNodeCollection(nc)

Get local nodes of a NodeCollection as a new NodeCollection.

This function returns the local nodes of a NodeCollection. If there are no local elements, an empty NodeCollection is returned.

Parameters

nc (NodeCollection) – NodeCollection for which to get local nodes

Returns

Object representing the local nodes of the given NodeCollection

Return type

NodeCollection

nest.lib.hl_api_nodes.GetNodes(properties={}, local_only=False)

Return all nodes with the given properties as NodeCollection.

Parameters
• properties (dict, optional) – Only node IDs of nodes matching the properties given in the dictionary exactly will be returned. Matching properties with float values (e.g. the membrane potential) may fail due to tiny numerical discrepancies and should be avoided. Note that when a params dict is present, thread parallelization is not possible, the function will be run thread serial.

• local_only (bool, optional) – If True, only node IDs of nodes simulated on the local MPI process will be returned. By default, node IDs of nodes in the entire simulation will be returned. This requires MPI communication and may slow down the script.

Returns

NodeCollection of nodes

Return type

NodeCollection

nest.lib.hl_api_nodes.PrintNodes()

Print the node ID ranges and model names of all the nodes in the network.

## Functions related to setting and getting parameters¶

Functions to get information on NEST.

nest.lib.hl_api_info.GetStatus(nodes, keys=None, output='')

Return the parameter dictionaries of nodes or connections.

If keys is given, a list of values is returned instead. keys may also be a list, in which case the returned list contains lists of values.

Parameters
• nodes (NodeCollection or SynapseCollection) – Either a NodeCollection representing nodes, or a SynapseCollection of connection handles as returned by GetConnections().

• keys (str or list, optional) – string or a list of strings naming model properties. GetStatus then returns a single value or a list of values belonging to the keys given.

• output (str, optional) – Whether the returned data should be in a selected format (output='json').

Returns

• list of dicts – All parameters in a dict for each node or connection.

• list of values – If keys is a string, the value of the corresponding parameter for each node or connection is returned.

• list of lists of values – If keys is a list of strings, a list of values of the corresponding parameters for each node or connection is returned.

• str – If output is json, the above formats are converted to JSON format before they are returned.

Raises

TypeError – If nodes or keys are on the wrong form.

Examples

For nodes:

>>>    nest.GetStatus(nodes)
({'archiver_length': 0,
'beta_Ca': 0.001,
...
'global_id': 1,
...
'vp': 0},
...
{'archiver_length': 0,
'beta_Ca': 0.001,
...
'global_id': 3,
...
'vp': 0})

>>>    nest.GetStatus(nodes, 'V_m')
(-70.0, -70.0, -70.0)

>>>    nest.GetStatus(nodes, ['V_m', 'C_m'])
((-70.0, 250.0), (-70.0, 250.0), (-70.0, 250.0))

>>>    nest.GetStatus(nodes, ['V_m', 'C_m'], output='json')
'[[-70.0, 250.0], [-70.0, 250.0], [-70.0, 250.0]]'


For connections:

>>>    nest.GetStatus(conns)
({'delay': 1.0,
...
'source': 1,
...
'weight': 1.0},
...
{'delay': 1.0,
...
'source': 3,
...
'weight': 1.0})

>>>    nest.GetStatus(conns, 'weight')
(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)

>>>    nest.GetStatus(conns, ['source', 'delay'])
((1, 1.0),
...
(3, 1.0))

>>>    nest.GetStatus(conns, ['source', 'delay'], output='json')
'[[1, 1.0], [1, 1.0], [1, 1.0], [2, 1.0], [2, 1.0], [2, 1.0],
[3, 1.0], [3, 1.0], [3, 1.0]]'

nest.lib.hl_api_info.SetStatus(nodes, params, val=None)

Set parameters of nodes or connections.

Parameters of nodes or connections, given in nodes, is set as specified by params. If val is given, params has to be a string with the name of an attribute, which is set to val on the nodes/connections. val can be a single value or a list of the same size as nodes.

Parameters
• nodes (NodeCollection or SynapseCollection) – Either a NodeCollection representing nodes, or a SynapseCollection of connection handles as returned by GetConnections().

• params (str or dict or list) – Dictionary of parameters (either lists or single values) or list of dictionaries of parameters of same length as nodes. If val is given, this has to be a string giving the name of a model property.

• val (int, list, optional) – If given, params has to be the name of a model property.

Raises

TypeError – If nodes is not a NodeCollection of nodes, a SynapseCollection of synapses, or if the number of parameters don’t match the number of nodes or synapses.

nest.lib.hl_api_info.authors()

Print the authors of NEST.

nest.lib.hl_api_info.get_argv()

Return argv as seen by NEST.

This is similar to Python sys.argv but might have changed after MPI initialization.

Returns

Argv, as seen by NEST

Return type

tuple

nest.lib.hl_api_info.get_verbosity()

Return verbosity level of NEST’s messages.

• M_ALL=0, display all messages

• M_INFO=10, display information messages and above

• M_DEPRECATED=18, display deprecation warnings and above

• M_WARNING=20, display warning messages and above

• M_ERROR=30, display error messages and above

• M_FATAL=40, display failure messages and above

Returns

The current verbosity level

Return type

int

nest.lib.hl_api_info.help(obj=None, return_text=False)

Display the help page for the given object in a pager.

If return_text is omitted or explicitly given as False, this command opens the help text for object in the default pager using the pydoc module.

If return_text is True, the help text is returned as a string in reStructuredText format instead of displaying it.

Parameters
• obj (object, optional) – Object to display help for

• return_text (bool, optional) – Option for returning the help text

Returns

The help text of the object if return_text is True.

Return type

None or str

nest.lib.hl_api_info.helpdesk()

Open the NEST documentation index in a browser.

This command opens the NEST documentation index page using the system’s default browser.

Please note that the help pages will only be available if you ran make html prior to installing NEST. For more details, see User-level documentation workflow.

nest.lib.hl_api_info.message(level, sender, text)

Print a message using message system of NEST.

Parameters
• level – Level

• sender – Message sender

• text (str) – Text to be sent in the message

nest.lib.hl_api_info.set_verbosity(level)

Change verbosity level for NEST’s messages.

• M_ALL=0, display all messages

• M_INFO=10, display information messages and above

• M_DEPRECATED=18, display deprecation warnings and above

• M_WARNING=20, display warning messages and above

• M_ERROR=30, display error messages and above

• M_FATAL=40, display failure messages and above

Parameters

level (str, default: 'M_INFO') – Can be one of ‘M_FATAL’, ‘M_ERROR’, ‘M_WARNING’, ‘M_DEPRECATED’, ‘M_INFO’ or ‘M_ALL’.

nest.lib.hl_api_info.sysinfo()

Print information on the platform on which NEST was compiled.

## Functions related to connections¶

Functions for connection handling

nest.lib.hl_api_connections.Connect(pre, post, conn_spec=None, syn_spec=None, return_synapsecollection=False)

Connect pre nodes to post nodes.

Nodes in pre and post are connected using the specified connectivity (all-to-all by default) and synapse type (static_synapse by default). Details depend on the connectivity rule.

Parameters
• pre (NodeCollection (or array-like object)) – Presynaptic nodes, as object representing the IDs of the nodes

• post (NodeCollection (or array-like object)) – Postsynaptic nodes, as object representing the IDs of the nodes

• conn_spec (str or dict, optional) – Specifies connectivity rule, see below

• syn_spec (str or dict, optional) – Specifies synapse model, see below

• return_synapsecollection (bool) – Specifies whether or not we should return a SynapseCollection of pre and post connections

Raises

kernel.NESTError

Notes

It is possible to connect NumPy arrays of node IDs one-to-one by passing the arrays as pre and post, specifying ‘one_to_one’ for conn_spec. In that case, the arrays may contain non-unique IDs. You may also specify weight, delay, and receptor type for each connection as NumPy arrays in the syn_spec dictionary. This feature is currently not available when MPI is used; trying to connect arrays with more than one MPI process will raise an error.

If pre and post have spatial positions, a mask can be specified as a dictionary. The mask define which nodes are considered as potential targets for each source node. Connections with spatial nodes can also use nest.spatial_distributions as parameters, for instance for the probability p.

Connectivity specification (conn_spec)

Available rules and associated parameters:

- 'all_to_all' (default)
- 'one_to_one'
- 'fixed_indegree', 'indegree'
- 'fixed_outdegree', 'outdegree'
- 'fixed_total_number', 'N'
- 'pairwise_bernoulli', 'p'
- 'symmetric_pairwise_bernoulli', 'p'


See Connection Rules for more details, including example usage.

Synapse specification (syn_spec)

The synapse model and its properties can be given either as a string identifying a specific synapse model (default: static_synapse) or as a dictionary specifying the synapse model and its parameters.

Available keys in the synapse specification dictionary are:

- 'synapse_model'
- 'weight'
- 'delay'
- 'receptor_type'
- any parameters specific to the selected synapse model.


See Synapse Specification for details, including example usage.

All parameters are optional and if not specified, the default values of the synapse model will be used. The key ‘synapse_model’ identifies the synapse model, this can be one of NEST’s built-in synapse models or a user-defined model created via CopyModel().

If synapse_model is not specified the default model static_synapse will be used.

Distributed parameters can be defined through NEST’s different parametertypes. NEST has various random parameters, spatial parameters and distributions (only accesseable for nodes with spatial positions), logical expressions and mathematical expressions, which can be used to define node and connection parameters.

To see all available parameters, see documentation defined in distributions, logic, math, random and spatial modules.

nest.lib.hl_api_connections.Disconnect(pre, post, conn_spec='one_to_one', syn_spec='static_synapse')

Disconnect pre neurons from post neurons.

Neurons in pre and post are disconnected using the specified disconnection rule (one-to-one by default) and synapse type (static_synapse by default). Details depend on the disconnection rule.

Parameters
• pre (NodeCollection) – Presynaptic nodes, given as NodeCollection

• post (NodeCollection) – Postsynaptic nodes, given as NodeCollection

• conn_spec (str or dict) – Disconnection rule, see below

• syn_spec (str or dict) – Synapse specifications, see below

Notes

conn_spec

Apply the same rules as for connectivity specs in the Connect() method

Possible choices of the conn_spec are

- 'one_to_one'
- 'all_to_all'


syn_spec

The synapse model and its properties can be inserted either as a string describing one synapse model (synapse models are listed in the synapsedict) or as a dictionary as described below.

Note that only the synapse type is checked when we disconnect and that if syn_spec is given as a non-empty dictionary, the ‘synapse_model’ parameter must be present.

If no synapse model is specified the default model static_synapse will be used.

Available keys in the synapse dictionary are:

- 'synapse_model'
- 'weight'
- 'delay',
- 'receptor_type'
- parameters specific to the synapse model chosen


‘synapse_model’ determines the synapse type, taken from pre-defined synapse types in NEST or manually specified synapses created via CopyModel().

All other parameters are not currently implemented.

Notes

Disconnect only disconnects explicitly specified nodes.

nest.lib.hl_api_connections.GetConnections(source=None, target=None, synapse_model=None, synapse_label=None)

Return a SynapseCollection representing the connection identifiers.

Any combination of source, target, synapse_model and synapse_label parameters is permitted.

Parameters
• source (NodeCollection, optional) – Source node IDs, only connections from these pre-synaptic neurons are returned

• target (NodeCollection, optional) – Target node IDs, only connections to these postsynaptic neurons are returned

• synapse_model (str, optional) – Only connections with this synapse type are returned

• synapse_label (int, optional) – (non-negative) only connections with this synapse label are returned

Returns

Object representing the source-node_id, target-node_id, target-thread, synapse-id, port of connections, see SynapseCollection for more.

Return type

SynapseCollection

Raises

Notes

Only connections with targets on the MPI process executing the command are returned.

## Functions related to simulation¶

Functions for simulation control

nest.lib.hl_api_simulation.Cleanup()

Cleans up resources after a Run call. Not needed for Simulate.

Closes state for a series of runs, such as flushing and closing files. A Prepare is needed after a Cleanup before any more calls to Run.

nest.lib.hl_api_simulation.DisableStructuralPlasticity()

Disable structural plasticity for the network simulation

nest.lib.hl_api_simulation.EnableStructuralPlasticity()

Enable structural plasticity for the network simulation

nest.lib.hl_api_simulation.GetKernelStatus(keys=None)

Obtain parameters of the simulation kernel.

Parameters

keys (str or list, optional) – Single parameter name or list of parameter names

Returns

• dict – Parameter dictionary, if called without argument

• type – Single parameter value, if called with single parameter name

• list – List of parameter values, if called with list of parameter names

Raises

TypeError – If keys are of the wrong type.

Notes

See SetKernelStatus for documentation on each parameter key.

nest.lib.hl_api_simulation.Install(module_name)

Parameters

module_name (str) – Name of the dynamically linked module

Returns

Return type

handle

Notes

Dynamically linked modules are searched in the NEST library directory (<prefix>/lib/nest) and in LD_LIBRARY_PATH (on Linux) or DYLD_LIBRARY_PATH (on OSX).

Example

nest.Install("mymodule")

nest.lib.hl_api_simulation.Prepare()

Calibrate the system before a Run call. Not needed for Simulate.

Call before the first Run call, or before calling Run after changing the system, calling SetStatus or Cleanup.

nest.lib.hl_api_simulation.ResetKernel()

Reset the simulation kernel.

This will destroy the network as well as all custom models created with CopyModel(). Calling this function is equivalent to restarting NEST.

In particular,

• all network nodes

• all connections

• all user-defined neuron and synapse models

are deleted, and

• time

• random generators

are reset. The only exception is that dynamically loaded modules are not unloaded. This may change in a future version of NEST.

nest.lib.hl_api_simulation.Run(t)

Simulate the network for t milliseconds.

Parameters

t (float) – Time to simulate in ms

Notes

Call between Prepare and Cleanup calls, or within a with RunManager clause.

Simulate(t): t’ = t/m; Prepare(); for _ in range(m): Run(t’); Cleanup()

Prepare must be called before Run to calibrate the system, and Cleanup must be called after Run to close files, cleanup handles, and so on. After Cleanup, Prepare can and must be called before more Run calls.

Be careful about modifying the network or neurons between Prepare and Cleanup calls. In particular, do not call Create, Connect, or SetKernelStatus. Calling SetStatus to change membrane potential V_m of neurons or synaptic weights (but not delays!) will in most cases work as expected, while changing membrane or synaptic times constants will not work correctly. If in doubt, assume that changes may cause undefined behavior and check these thoroughly.

nest.lib.hl_api_simulation.RunManager()

ContextManager for Run

Calls Prepare before a series of Run calls, and calls Cleanup at end.

E.g.:

with RunManager():
for _ in range(10):
Run(100)
# extract results


Notes

Be careful about modifying the network or neurons inside the RunManager context. In particular, do not call Create, Connect, or SetKernelStatus. Calling SetStatus to change membrane potential V_m of neurons or synaptic weights (but not delays!) will in most cases work as expected, while changing membrane or synaptic times constants will not work correctly. If in doubt, assume that changes may cause undefined behavior and check these thoroughly.

nest.lib.hl_api_simulation.SetKernelStatus(params)

Set parameters for the simulation kernel.

See the documentation of Kernel attributes for a valid list of params.

Parameters

params (dict) – Dictionary of parameters to set.

nest.lib.hl_api_simulation.Simulate(t)

Simulate the network for t milliseconds.

Parameters

t (float) – Time to simulate in ms

## Functions related to parallel computing¶

Functions for parallel computing

nest.lib.hl_api_parallel_computing.GetLocalVPs()

Return iterable representing the VPs local to the MPI rank.

nest.lib.hl_api_parallel_computing.NumProcesses()

Return the overall number of MPI processes.

Returns

Number of overall MPI processes

Return type

int

nest.lib.hl_api_parallel_computing.Rank()

Return the MPI rank of the local process.

Returns

MPI rank of the local process

Return type

int

Note

DO NOT USE Rank() TO EXECUTE ANY FUNCTION IMPORTED FROM THE nest MODULE ON A SUBSET OF RANKS IN AN MPI-PARALLEL SIMULATION.

This will lead to unpredictable behavior. Symptoms may be an error message about non-synchronous global random number generators or deadlocks during simulation. In the worst case, the simulation may complete but generate nonsensical results.

nest.lib.hl_api_parallel_computing.SetAcceptableLatency(port_name, latency)

Set the acceptable latency (in ms) for a MUSIC port.

Parameters
• port_name (str) – MUSIC port to set latency for

• latency (float) – Latency in ms

nest.lib.hl_api_parallel_computing.SetMaxBuffered(port_name, size)

Set the maximum buffer size for a MUSIC port.

Parameters
• port_name (str) – MUSIC port to set buffer size for

• size (int) – Buffer size

nest.lib.hl_api_parallel_computing.SyncProcesses()

Synchronize all MPI processes.

## Functions related to NEST types¶

Classes defining the different PyNEST types

class nest.lib.hl_api_types.CollocatedSynapses(*args)

Class for collocated synapse specifications.

Wrapper around a list of specifications, used when calling Connect().

Example

nodes = nest.Create('iaf_psc_alpha', 3)
syn_spec = nest.CollocatedSynapses({'weight': 4., 'delay': 1.5},
{'synapse_model': 'stdp_synapse'},
{'synapse_model': 'stdp_synapse', 'alpha': 3.})
nest.Connect(nodes, nodes, conn_spec='one_to_one', syn_spec=syn_spec)

conns = nest.GetConnections()

print(conns.alpha)
print(len(syn_spec))

nest.lib.hl_api_types.CreateParameter(parametertype, specs)

Create a parameter.

Parameters
• parametertype (string) – Parameter type with or without distance dependency. Can be one of the following: ‘constant’, ‘linear’, ‘exponential’, ‘gaussian’, ‘gaussian2D’, ‘uniform’, ‘normal’, ‘lognormal’, ‘distance’, ‘position’

• specs (dict) – Dictionary specifying the parameters of the provided parametertype, see Parameter types.

Returns

Object representing the parameter

Return type

Parameter

Notes

• Instead of using CreateParameter you can also use the various parametrizations embedded in NEST. See for

instance uniform().

Parameter types

Some available parameter types (parametertype parameter), their function and acceptable keys for their corresponding specification dictionaries

• Constant
'constant' :
{'value' : float} # constant value

• Randomization
# random parameter with uniform distribution in [min,max)
'uniform' :
{'min' : float, # minimum value, default: 0.0
'max' : float} # maximum value, default: 1.0

# random parameter with normal distribution, optionally truncated
# to [min,max)
'normal':
{'mean' : float, # mean value, default: 0.0
'sigma': float, # standard deviation, default: 1.0
'min'  : float, # minimum value, default: -inf
'max'  : float} # maximum value, default: +inf

# random parameter with lognormal distribution,
# optionally truncated to [min,max)
'lognormal' :
{'mu'   : float, # mean value of logarithm, default: 0.0
'sigma': float, # standard deviation of log, default: 1.0
'min'  : float, # minimum value, default: -inf
'max'  : float} # maximum value, default: +inf


Masks are used when creating connections when nodes have spatial extent. A mask describes the area of the pool population that shall be searched to find nodes to connect to for any given node in the driver population. Masks are created using the CreateMask() command.

Inside(point)

Test if a point is inside a mask.

Parameters

point (tuple/list of float values) – Coordinate of point

Returns

out – True if the point is inside the mask, False otherwise

Return type

bool

class nest.lib.hl_api_types.NodeCollection(data=None)

Class for NodeCollection.

NodeCollection represents the nodes of a network. The class supports iteration, concatenation, indexing, slicing, membership, length, conversion to and from lists, test for membership, and test for equality. By using the membership functions get() and set(), you can get and set desired parameters.

A NodeCollection is created by the Create() function, or by converting a list of nodes to a NodeCollection with nest.NodeCollection(list).

If your nodes have spatial extent, use the member parameter spatial to get the spatial information.

Example

import nest

nest.ResetKernel()

# Create NodeCollection representing nodes
nc = nest.Create('iaf_psc_alpha', 10)

# Convert from list
node_ids_in = [2, 4, 6, 8]
new_nc = nest.NodeCollection(node_ids_in)

# Convert to list
nc_list =  nc.tolist()

# Concatenation
Enrns = nest.Create('aeif_cond_alpha', 600)
Inrns = nest.Create('iaf_psc_alpha', 400)
nrns = Enrns + Inrns

# Slicing and membership
print(new_nc[2])
print(new_nc[1:2])
6 in new_nc

get(*params, **kwargs)

Get parameters from nodes.

Parameters
• params (str or list, optional) –

Parameters to get from the nodes. It must be one of the following:

• A single string.

• A list of strings.

• One or more strings, followed by a string or list of strings. This is for hierarchical addressing.

• output (str, ['pandas','json'], optional) – If the returned data should be in a Pandas DataFrame or in a JSON serializable format.

Returns

• int or float – If there is a single node in the NodeCollection, and a single parameter in params.

• array_like – If there are multiple nodes in the NodeCollection, and a single parameter in params.

• dict – If there are multiple parameters in params. Or, if no parameters are specified, a dictionary containing aggregated parameter-values for all nodes is returned.

• DataFrame – Pandas Data frame if output should be in pandas format.

Raises
• TypeError – If the input params are of the wrong form.

• KeyError – If the specified parameter does not exist for the nodes.

Examples

>>>    nodes.get()
{'archiver_length': (0, 0, 0),
'beta_Ca': (0.001, 0.001, 0.001),
'C_m': (250.0, 250.0, 250.0),
...
'V_th': (-55.0, -55.0, -55.0),
'vp': (0, 0, 0)}

>>>    nodes.get('V_m')
(-70.0, -70.0, -70.0)

>>>    nodes[0].get('V_m')
-70.0

>>>    nodes.get('V_m', 'C_m')
{'V_m': (-70.0, -70.0, -70.0), 'C_m': (250.0, 250.0, 250.0)}

>>>    voltmeter.get('events', 'senders')
array([...], dtype=int64)

index(node_id)

Find the index of a node ID in the NodeCollection.

Parameters

node_id (int) – Global ID to be found.

Raises

ValueError – If the node ID is not in the NodeCollection.

set(params=None, **kwargs)

Set the parameters of nodes to params.

NB! This is almost the same implementation as SetStatus.

If kwargs is given, it has to be names and values of an attribute as keyword argument pairs. The values can be single values or list of the same size as the NodeCollection.

Parameters
• params (str or dict or list) – Dictionary of parameters (either lists or single values) or list of dictionaries of parameters of same length as the NodeCollection.

• kwargs (keyword argument pairs) – Named arguments of parameters of the elements in the NodeCollection.

Raises
• TypeError – If the input params are of the wrong form.

• KeyError – If the specified parameter does not exist for the nodes.

tolist()

Convert NodeCollection to list.

class nest.lib.hl_api_types.Parameter(datum)

Class for parameters

A parameter may be used as a probability kernel when creating connections and nodes or as synaptic parameters (such as weight and delay). Parameters are created using the CreateParameter() command.

GetValue()

Compute value of parameter.

Returns

out – The value of the parameter

Return type

value

Example

import nest

# normal distribution parameter
P = nest.CreateParameter('normal', {'mean': 0.0, 'sigma': 1.0})

# get out value
P.GetValue()

class nest.lib.hl_api_types.SynapseCollection(data)

Class for Connections.

SynapseCollection represents the connections of a network. The class supports indexing, iteration, length and equality. You can get and set connection parameters by using the membership functions get() and set(). By using the membership function sources() you get an iterator over source nodes, while targets() returns an interator over the target nodes of the connections.

A SynapseCollection is created by the GetConnections() function.

get(keys=None, output='')

Return a parameter dictionary of the connections.

If keys is a string, a list of values is returned, unless we have a single connection, in which case the single value is returned. keys may also be a list, in which case a dictionary with a list of values is returned.

Parameters
• keys (str or list, optional) – String or a list of strings naming model properties. get then returns a single value or a dictionary with lists of values belonging to the given keys.

• output (str, ['pandas','json'], optional) – If the returned data should be in a Pandas DataFrame or in a JSON serializable format.

Returns

• dict – All parameters, or, if keys is a list of strings, a dictionary with lists of corresponding parameters

• type – If keys is a string, the corresponding parameter(s) is returned

Raises
• TypeError – If input params are of the wrong form.

• KeyError – If the specified parameter does not exist for the connections.

Examples

>>>    conns.get()
{'delay': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
...
'weight': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}

>>>    conns.get('weight')
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

>>>    conns[0].get('weight')
1.0

>>>    nodes.get(['source', 'weight'])
{'source': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'weight': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}

set(params=None, **kwargs)

Set the parameters of the connections to params.

NB! This is almost the same implementation as SetStatus

If kwargs is given, it has to be names and values of an attribute as keyword argument pairs. The values can be single values or list of the same size as the SynapseCollection.

Parameters
• params (str or dict or list) – Dictionary of parameters (either lists or single values) or list of dictionaries of parameters of same length as SynapseCollection.

• kwargs (keyword argument pairs) – Named arguments of parameters of the elements in the SynapseCollection.

Raises
• TypeError – If input params are of the wrong form.

• KeyError – If the specified parameter does not exist for the connections.

sources()

Returns iterator containing the source node IDs of the SynapseCollection.

targets()

Returns iterator containing the target node IDs of the SynapseCollection.

nest.lib.hl_api_types.serializable(data)

Make data serializable for JSON.

Parameters

data (any) –

Returns

data_serialized – Data can be encoded to JSON

Return type
nest.lib.hl_api_types.to_json(data, **kwargs)

Serialize data to JSON.

Parameters
• data (any) –

• kwargs (keyword argument pairs) – Named arguments of parameters for json.dumps function.

Returns

data_json – JSON format of the data

Return type

str

## Functions related to helper info¶

These are helper functions to ease the definition of the high-level API of the PyNEST wrapper.

class nest.lib.hl_api_helper.SuppressedDeprecationWarning(no_dep_funcs)

Context manager turning off deprecation warnings for given methods.

Think thoroughly before use. This context should only be used as a way to make sure examples do not display deprecation warnings, that is, used in functions called from examples, and not as a way to make tedious deprecation warnings dissapear.

Parameters
• item (object) – Object to broadcast

• length (int) – Length to broadcast to

• allowed_types (list) – List of allowed types

• name (str, optional) – Name of item

Returns

The original item broadcasted to sequence form of length

Return type

object

Raises
nest.lib.hl_api_helper.deprecated(alt_func_name, text=None)

Decorator for deprecated functions.

Shows a warning and calls the original function.

Parameters
• alt_func_name (str, optional) – Name of the function to use instead, may be empty string

• text (str, optional) – Text to display instead of standard text

Returns

Decorator function

Return type

function

nest.lib.hl_api_helper.get_parameters(nc, param)

Get parameters from nodes.

Used by NodeCollections get() function.

Parameters
• nc (NodeCollection) – nodes to get values from

• param (string or list of strings) – string or list of string naming model properties.

Returns

• int, list – param is a string so the value(s) is returned

• dict – param is a list of string so a dictionary is returned

Get parameters from nodes, hierarchical case.

Used by NodeCollections get() function.

Parameters
• nc (NodeCollection) – nodes to get values from

• params (tuple) – first value in the tuple should be a string, second can be a string or a list of string. The first value corresponds to the path into the hierarchical structure while the second value corresponds to the name(s) of the desired properties.

Returns

• int, list – params[-1] is a string so the value(s) is returned

• dict – params[-1] is a list of string so a dictionary is returned

nest.lib.hl_api_helper.get_unistring_type()

Returns string type dependent on python version.

Returns

Depending on Python version

Return type

str or basestring

nest.lib.hl_api_helper.get_wrapped_text(text, width=80)

Formats a given multiline string to wrap at a given width, while preserving newlines (and removing excessive whitespace).

Parameters

text (str) – String to format

Returns

Wrapped string

Return type

str

nest.lib.hl_api_helper.is_coercible_to_sli_array(seq)

Checks whether a given object is coercible to a SLI array

Parameters

seq (object) – Object to check

Returns

True if object is coercible to a SLI array

Return type

bool

nest.lib.hl_api_helper.is_iterable(seq)

Return True if the given object is an iterable, False otherwise.

Parameters

seq (object) – Object to check

Returns

True if object is an iterable

Return type

bool

nest.lib.hl_api_helper.is_literal(obj)

Check whether obj is a “literal”: a unicode string or SLI literal

Parameters

obj (object) – Object to check

Returns

True if obj is a “literal”

Return type

bool

nest.lib.hl_api_helper.is_sequence_of_connections(seq)

Checks whether low-level API accepts seq as a sequence of connections.

Parameters

seq (object) – Object to check

Returns

True if object is an iterable of dictionaries or subscriptables of CONN_LEN

Return type

bool

nest.lib.hl_api_helper.is_sequence_of_node_ids(seq)

Checks whether the argument is a potentially valid sequence of node IDs (non-negative integers).

Parameters

seq (object) – Object to check

Returns

True if object is a potentially valid sequence of node IDs

Return type

bool

nest.lib.hl_api_helper.is_string(obj)

Check whether obj is a unicode string

Parameters

obj (object) – Object to check

Returns

True if obj is a unicode string

Return type

bool

Returns documentation of the given object in RST format

Parameters

obj (string) – Object to display help for

Returns

The documentation of the object or None if no help is available

Return type

string

nest.lib.hl_api_helper.model_deprecation_warning(model)

Checks whether the model is to be removed in a future version of NEST. If so, a deprecation warning is issued.

Parameters

model (str) – Name of model

nest.lib.hl_api_helper.restructure_data(result, keys)

Restructure list of status dictionaries or list of parameter values to dict with lists or single list or int.

Parameters
• result (list) – list of status dictionaries or list (of lists) of parameter values.

• keys (string or list of strings) – name(s) of properties

Return type

int, list or dict

nest.lib.hl_api_helper.show_deprecation_warning(func_name, alt_func_name=None, text=None)

Shows a deprecation warning for a function.

Parameters
• func_name (str) – Name of the deprecated function

• alt_func_name (str, optional) – Name of the function to use instead. Needed if text=None

• text (str, optional) – Text to display instead of standard text

nest.lib.hl_api_helper.show_help_with_pager(obj)

Display help text for the given object in the Python pager

If called from within a Jupyter notebook, display help in a modal window instead of in the pager.

Parameters

obj (object) – Object to display

nest.lib.hl_api_helper.uni_str

alias of str

## Functions related to randomization¶

nest.random.hl_api_random.exponential(beta=1.0)

Draws samples from an exponential distribution.

Parameters

beta (float, optional) – Scale parameter the distribution. Default value is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.random.hl_api_random.lognormal(mean=0.0, std=1.0)

Draws samples from a log-normal distribution.

Parameters
• mean (float, optional) – Mean value of the underlying normal distribution. Default value is 0.

• std (float, optional) – Standard deviation of the underlying normal distribution. Default value is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.random.hl_api_random.normal(mean=0.0, std=1.0)

Draws samples from a normal distribution.

Parameters
• mean (float, optional) – Mean of the distribution. Default value is 0.

• std (float, optional) – Standard deviation of the distribution. Default value is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.random.hl_api_random.uniform(min=0.0, max=1.0)

Draws samples from a uniform distribution.

Samples are distributed uniformly in [min, max) (includes min, but excludes max).

Parameters
• min (float, optional) – Lower boundary of the sample interval. Default value is 0.

• max (float, optional) – Upper boundary of the sample interval. Default value is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.random.hl_api_random.uniform_int(max)

Draws integer samples from a uniform distribution.

Samples are distributed uniformly in [0, max) (includes 0, but excludes max).

Parameters

max (integer) – Upper boundary of the sample interval.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

## Functions related to spatial distributions¶

nest.spatial_distributions.hl_api_spatial_distributions.exponential(x, beta=1.0)

Applies an exponential distribution on a Parameter.

Parameters
• x (Parameter) – Input Parameter.

• beta (float, optional) – Scale parameter. Default is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.spatial_distributions.hl_api_spatial_distributions.gamma(x, kappa=1.0, theta=1.0)

Applies a gamma distribution on a Parameter.

This function requires SciPy, and will raise an error if SciPy cannot be imported.

Parameters
• x (Parameter) – Input Parameter.

• kappa (float, optional) – Shape parameter. Default is 1.0.

• theta (float, optional) – Scale parameter. Default is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.spatial_distributions.hl_api_spatial_distributions.gaussian(x, mean=0.0, std=1.0)

Applies a gaussian distribution on a Parameter.

Parameters
• x (Parameter) – Input Parameter.

• mean (float, optional) – Mean of the distribution. Default is 0.0.

• std (float, optional) – Standard deviation of the distribution. Default is 1.0.

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

nest.spatial_distributions.hl_api_spatial_distributions.gaussian2D(x, y, mean_x=0.0, mean_y=0.0, std_x=1.0, std_y=1.0, rho=0.0)

Applies a bivariate gaussian distribution on two Parameters, representing values in the x and y direction.

Parameters
• x (Parameter) – Input Parameter for the x-direction.

• y (Parameter) – Input Parameter for the y-direction.

• mean_x (float, optional) – Mean of the distribution in the x-direction. Default is 0.0.

• mean_y (float, optional) – Mean of the distribution in the y-direction. Default is 0.0.

• std_x (float, optional) – Standard deviation of the distribution in the x-direction. Default is 1.0.

• std_y (float, optional) – Standard deviation of the distribution in the y-direction. Default is 1.0.

• rho (float, optional) – Correlation of x and y. Default is 0.0

Returns

Object yielding values drawn from the distribution.

Return type

Parameter

## Functions related to mathematical expressions¶

nest.math.hl_api_math.cos(parameter)

Calculate the cosine of the parameter

Parameters

parameter (Parameter) – Input Parameter.

Returns

Object representing the cosine of the parameter.

Return type

Parameter

nest.math.hl_api_math.exp(parameter)

Calculate the exponential of the parameter

Parameters

parameter (Parameter) – Input Parameter.

Returns

Object representing the exponential of the parameter.

Return type

Parameter

nest.math.hl_api_math.max(parameter, value)

Yields the largest value of the value of a parameter and a given value

Parameters
• parameter (Parameter) – Input Parameter.

• value (float) – Value to compare against.

Returns

Object yielding the largest value.

Return type

Parameter

nest.math.hl_api_math.min(parameter, value)

Yields the smallest value of the value of a parameter and a given value

Parameters
• parameter (Parameter) – Input Parameter.

• value (float) – Value to compare against.

Returns

Object yielding the smallest value.

Return type

Parameter

nest.math.hl_api_math.redraw(parameter, min, max)

Redraws the value of the parameter if it is outside of the given limits

Both min and max values are included in the limit. If the number of redraws exceeds 1000, an error is thrown.

Parameters
• parameter (Parameter) – Input Parameter.

• min (float) – Lower bound of the value.

• max (float) – Upper bound of the value.

Returns

Object redrawing the parameter until it can yield a value within the given limits.

Return type

Parameter

nest.math.hl_api_math.sin(parameter)

Calculate the sine of the parameter

Parameters

parameter (Parameter) – Input Parameter.

Returns

Object representing the sine of the parameter.

Return type

Parameter

nest.logic.hl_api_logic.conditional(condition, param_if_true, param_if_false)

Yields one value or another, based on the condition.

Parameters
• condition (Parameter) – A comparing Parameter, created with the usual comparators.

• param_if_true ([Parameter | float]) – Value or Parameter used to get a value used if the condition evaluates to true.

• param_if_false ([Parameter | float]) – Value or Parameter used to get a value used if the condition evaluates to false.

Returns

Object representing the conditional.

Return type

Parameter