ANNarchy 5.0.0
  • ANNarchy
  • Installation
  • Tutorial
  • Manual
  • Notebooks
  • Reference

  • ANNarchy
  • Core components
    • Network
    • Population
    • Projection
    • Monitor
    • PopulationView
    • Dendrite
  • Neuron and Synapse models
    • Neuron
    • Synapse
    • Parameter
    • Variable
    • Creating
    • Pruning
    • Constant
  • Neuron models
    • LeakyIntegrator
    • Izhikevich
    • IF_curr_exp
    • IF_cond_exp
    • IF_curr_alpha
    • IF_cond_alpha
    • HH_cond_exp
    • EIF_cond_alpha_isfa_ista
    • EIF_cond_exp_isfa_ista
  • Synapse models
    • Hebb
    • Oja
    • IBCM
    • STP
    • STDP
  • Inputs
    • InputArray
    • TimedArray
    • PoissonPopulation
    • TimedPoissonPopulation
    • SpikeSourceArray
    • HomogeneousCorrelatedSpikeTrains
    • CurrentInjection
    • DecodingProjection
    • ImagePopulation
    • VideoPopulation
  • Random Distributions
    • Uniform
    • DiscreteUniform
    • Normal
    • LogNormal
    • Exponential
    • Gamma
    • Binomial
  • Functions
    • add_function
    • functions
  • Callbacks
    • every
  • Utilities
    • report
    • timeit
    • sparse_random_matrix
    • sparse_delays_from_weights
    • magic_network
  • Convolution
    • Convolution
    • Pooling
    • Transpose
    • Copy
  • BOLD monitoring
    • BoldMonitor
    • BoldModel
    • balloon_RN
    • balloon_RL
    • balloon_CN
    • balloon_CL
    • balloon_maith2021
    • balloon_two_inputs
  • Tensorboard logging
    • Logger
  • ANN-to-SNN conversion
    • ANNtoSNNConverter
  • DEPRECATED Top-level API
    • setup
    • compile
    • clear
    • reset
    • set_seed
    • get_population
    • get_projection
    • populations
    • projections
    • monitors
    • simulate
    • simulate_until
    • step
    • enable_learning
    • disable_learning
    • get_time
    • set_time
    • get_current_step
    • set_current_step
    • dt
    • save
    • load
    • save_parameters
    • load_parameters
    • callbacks_enabled
    • disable_callbacks
    • enable_callbacks
    • clear_all_callbacks

On this page

  • Network
    • Parameters
    • Attributes
    • Methods
      • create
      • connect
      • monitor
      • boldmonitor
      • constant
      • compile
      • simulate
      • simulate_until
      • step
      • reset
      • enable_learning
      • disable_learning
      • clear
      • parallel_run
      • copy
      • config
      • load
      • save
      • get_population
      • get_projection
      • get_monitor
      • get_extension
      • get_constant
      • get_populations
      • get_projections
      • get_monitors
      • get_extensions
      • get_constants
      • callbacks_enabled
      • disable_callbacks
      • enable_callbacks
      • clear_all_callbacks

Network

Network(self, dt=None, seed=None)

A network creates the populations, projections and monitors, and controls the simulation.

net = ann.Network(dt=1.0, seed=42)

To create a population:

pop = net.create(100, neuron=ann.Izhikevich)

To connect two populations:

proj = net.connect(pre=pop1, post=pop2, target='exc', synapse=ann.STDP)

To monitor a population or projection:

pop = net.monitor(pop, ['spike', 'v'])

To compile the network:

net.compile()

To simulate for one second:

net.simulate(1000.)

Refer to the manual for more functionalities. dt and seed must be passed with keywords.

Parameters

Name Type Description Default
dt float step size in milliseconds. None
seed int seed for the random number generators. None

Attributes

Name Description
dt Step size in milliseconds for the integration of the ODEs.
seed Seed for the random number generator (Python and C++).
compiled Boolean indicating whether the network has been compiled.
directory Directory in which the network has been compiled.
time Current time t in milliseconds.
current_step Current simulation step.

Methods

Name Description
create Adds a population of neurons to the network.
connect Connects two populations by creating a projection.
monitor Creates a Monitor on variables of the specified object.
boldmonitor Monitors the BOLD signal of several populations using a computational model.
constant Adds a constant to the network.
compile Compiles the network.
simulate Runs the network for the given duration in milliseconds.
simulate_until Runs the network for the maximal duration in milliseconds until a stop_condition is met.
step Performs a single simulation step (duration = dt).
reset Reinitialises the network to its state before the call to compile().
enable_learning Enables learning for all projections.
disable_learning Disables learning for all projections.
clear Empties the network to prevent a memory leak until the garbage collector wakes up.
parallel_run Runs the provided method for multiple copies of the network.
copy Returns a new instance of the Network class, using the provided arguments to the constructor.
config Configuration of the network.
load Loads parameters and variables from a file created with Network.save().
save Saves the parameters and variables of the networkin a file.
get_population Returns the population with the given name.
get_projection Returns the projection with the given name.
get_monitor Returns the monitor with the given name.
get_extension Returns the extension with the given name.
get_constant Returns the constant with the given name.
get_populations Returns a list of all declared populations in this network.
get_projections Returns a list of all declared projections for the current network.
get_monitors Returns a list of declared monitors.
get_extensions Returns a list of declared extensions (e.g. BOLD monitors).
get_constants Returns a list of declared constants.
callbacks_enabled Returns True if callbacks are enabled for the network.
disable_callbacks Disables all callbacks for the network.
enable_callbacks Enables all declared callbacks for the network.
clear_all_callbacks Clears the list of declared callbacks for the network.

create

create(
    geometry,
    neuron=None,
    stop_condition=None,
    name=None,
    population=None,
    storage_order='post_to_pre',
)

Adds a population of neurons to the network.

net = ann.Network()
pop = net.create(geometry=100, neuron=ann.Izhikevich, name="Excitatory population")

Specific populations (e.g. PoissonPopulation()) can also be passed to the population argument, or simply as the first argument:

pop = net.create(population=ann.PoissonPopulation(100, rates=20.))
# or
pop = net.create(ann.PoissonPopulation(100, rates=20.))

Parameters

Name Type Description Default
geometry tuple | int population geometry as tuple. If an integer is given, it is the size of the population. required
neuron Neuron Neuron instance. It can be user-defined or a built-in model. None
name str unique name of the population (optional). None
stop_condition str a single condition on a neural variable which can stop the simulation whenever it is true. None
population Population instance of a SpecificPopulation. None

connect

connect(
    pre,
    post=None,
    target='',
    synapse=None,
    name=None,
    projection=None,
    disable_omp=True,
)

Connects two populations by creating a projection.

net.connect(pre=pop1, post=pop2, target="exc", synapse=STDP)

If the synapse argument is omitted, defaults synapses without plastivity will be used (psp = "w * pre.r" for rate-coded projections, pre_spike="g_target += w" for spiking ones.).

Specific projections can be passed to the projection argument, or as the first unnamed argument.

net.connect(projection=ann.DecodingProjection(pre, post, 'exc))

Parameters

Name Type Description Default
pre str | Population pre-synaptic population. required
post str | Population post-synaptic population. None
target str type of the connection. ''
synapse Synapse Synapse class or instance. None
name str (optional) name of the Projection. None
projection Projection specific projection. None

monitor

monitor(
    obj,
    variables=[],
    period=None,
    period_offset=None,
    start=True,
    name=None,
)

Creates a Monitor on variables of the specified object.

The object can be an instance of either Population, PopulationView, Dendrite or Projection.

The variables must be declared by the neuron or synapse type. For spiking neurons, 'spike' can be also recorded.

m = net.monitor(pop, ['v', 'spike'])
m = net.monitor(proj.dendrite(0), 'w')

By default, the monitors start recording right after Network.compile(), but you can hold them with start=False. Starting the recordings necessitates then to call the start()mehtod. Pausing/resuming the recordings is cheived through the pause() and resume().

m.start() # Start recording
net.simulate(T)
m.pause() # Pause recording
net.simulate(T)
m.resume() # Resume recording
net.simulate(T)

data = m.get() # Get the data

Parameters

Name Type Description Default
obj Population | PopulationView | Projection object to monitor. Must be a Population, PopulationView, Dendrite or Projection object. required
variables list single variable name or list of variable names to record (default: []). []
period float None
period_offset float None
start bool True
name str None

boldmonitor

boldmonitor(
    populations=None,
    bold_model=None,
    mapping={'I_CBF': 'r'},
    scale_factor=None,
    normalize_input=None,
    recorded_variables=None,
    start=False,
)

Monitors the BOLD signal of several populations using a computational model.

The BOLD monitor transforms one or two input population variables (such as the mean firing rate) into a recordable BOLD signal according to a computational model (for example a variation of the Balloon model).

Several models are available or can be created with a bold.BoldModel instance. These models must be explicitly imported:

import ANNarchy.extensions.bold as bold

m_bold = net.boldmonitor(
    # Recorded populations
    populations = [pop1, pop2], 
    # BOLD model to use (default is balloon_RN)
    bold_model = bold.balloon_RN(), 
    # Mapping from pop.r to I_CBF
    mapping = {'I_CBF': 'r'}, 
    # Time window to compute the baseline.
    normalize_input = 2000,  
    # Variables to be recorded
    recorded_variables = ["I_CBF", "BOLD"]  
)

# Unlike regular monitors, BOLD monitors must be explicitly started
m_bold.start()
net.simulate(5000) 
bold_data = m_bold.get("BOLD")

Parameters

Name Type Description Default
populations list list of recorded populations. None
bold_model bold.BoldModel computational model for BOLD signal defined as a BoldModel object. Default is bold.balloon_RN. None
mapping dict mapping dictionary between the inputs of the BOLD model (I_CBF for single inputs, I_CBF and I_CMRO2 for double inputs in the provided examples) and the variables of the input populations. By default, {'I_CBF': 'r'} maps the firing rate r of the input population(s) to the variable I_CBF of the BOLD model. {'I_CBF': 'r'}
scale_factor list[float] list of float values to allow a weighting of signals between populations. By default, the input signal is weighted by the ratio of the population size to all populations within the recorded region. None
normalize_input list[int] list of integer values which represent a optional baseline per population. The input signals will require an additional normalization using a baseline value. A value different from 0 represents the time period for determing this baseline in milliseconds (biological time). None
recorded_variables list[str] which variables of the BOLD model should be recorded? (by default, the output variable of the BOLD model is added, e.g. [“BOLD”] for the provided examples). None
start bool whether to start recording directly. False

constant

constant(name, value)

Adds a constant to the network.

c = net.constant('c', 2.0)

# `c` can be used in a neuron/synapse definition
neuron = ann.Neuron(equations="r = c * sum(exc)")

# Change the value of the constant in the network.
c.set(10.0) 

Parameters

Name Type Description Default
name name of the constant. required
value initial value of the constant. required

compile

compile(
    directory='annarchy',
    clean=False,
    compiler='default',
    compiler_flags='default',
    add_sources='',
    extra_libs='',
    cuda_config={'device': 0},
    annarchy_json='',
    silent=False,
    debug_build=False,
    profile_enabled=False,
)

Compiles the network.

Parameters

Name Type Description Default
directory str name of the subdirectory where the code will be generated and compiled. Default: “./annarchy/”. 'annarchy'
clean bool boolean to specifying if the library should be recompiled entirely or only the changes since last compilation (default: False). False
compiler str C++ compiler to use. Default: g++ on GNU/Linux, clang++ on OS X. Valid compilers are [g++, clang++]. 'default'
compiler_flags list[str] platform-specific flags to pass to the compiler. Default: “-march=native -O2”. Warning: -O3 often generates slower code and can cause linking problems, so it is not recommended. 'default'
cuda_config dict dictionary defining the CUDA configuration for each population and projection. {'device': 0}
annarchy_json str compiler flags etc are stored in a .json file normally placed in the home directory. With this flag one can directly assign a file location. ''
silent bool defines if the “Compiling… OK” should be printed. False

simulate

simulate(duration, measure_time=False)

Runs the network for the given duration in milliseconds.

The number of simulation steps is computed relative to the discretization step dt declared in the constructor (default: 1 ms):

net.simulate(1000.0)

Parameters

Name Type Description Default
duration float the duration in milliseconds. required
measure_time bool defines whether the simulation time should be printed. False

simulate_until

simulate_until(max_duration, population, operator='and', measure_time=False)

Runs the network for the maximal duration in milliseconds until a stop_condition is met.

Whenever the stop_condition defined in population becomes true, the simulation is stopped.

The method returns the actual duration of the simulation in milliseconds.

One can specify several populations. If the stop condition is true for any of the populations, the simulation will stop (‘or’ function).

Example:

pop1 = net.create( ..., stop_condition = "r > 1.0 : any")

net.compile()

net.simulate_until(max_duration=1000.0. population=pop1)

Parameters

Name Type Description Default
max_duration float the maximum duration of the simulation in milliseconds. required
population Population the (list of) population whose stop_condition should be checked to stop the simulation. required
operator str operator to be used (‘and’ or ‘or’) when multiple populations are provided (default: ‘and’). 'and'
measure_time bool defines whether the simulation time should be printed (default=False). False

step

step()

Performs a single simulation step (duration = dt).

reset

reset(populations=True, projections=False, monitors=True, synapses=False)

Reinitialises the network to its state before the call to compile().

Parameters

Name Type Description Default
populations bool if True (default), the neural parameters and variables will be reset to their initial value. True
projections bool if True, the synaptic parameters and variables (except the connections) will be reset (default=False). False
synapses bool if True, the synaptic weights will be erased and recreated (default=False). False

enable_learning

enable_learning(projections=None, period=None, offset=None)

Enables learning for all projections.

Parameters

Name Type Description Default
projections list the projections whose learning should be enabled. By default, all the existing projections are disabled. None

disable_learning

disable_learning(projections=None)

Disables learning for all projections.

Parameters

Name Type Description Default
projections list the projections whose learning should be disabled. By default, all the existing projections are disabled. None

clear

clear()

Empties the network to prevent a memory leak until the garbage collector wakes up.

parallel_run

parallel_run(
    method,
    number,
    max_processes=-1,
    seeds=None,
    measure_time=False,
    **kwargs,
)

Runs the provided method for multiple copies of the network.

Important: The network must have defined as a subclass of Network, not a Network instance where create() and connect() where sequentially called.

See the manual for more explanations:

class PulseNetwork(ann.Network):
    def __init__(self):
        self.create(...)

# Simulation method
def simulation(net, duration=1000.):
    net.simulate(duration)
    t, n = net.m.raster_plot()
    return t, n

# Create a network
net = PulseNetwork()
net.compile()

# Parallel simulation
results = net.parallel_run(method=simulation, number=4)

Parameters

Name Type Description Default
method method invoked for each copy of the network. required
number int number of simulations. required
max_processes int maximum number of concurrent processes. Defaults to the number of cores. -1
seeds int | str | list[int] list of seeds for each network. If None, the seeds will be be randomly set. If 'same', it will be the same as the current network. If 'sequential', the seeds will be incremented for each network (42, 43, 44, etc). None
measure_time bool if the total duration of the simulation should be reported at the end. False

copy

copy(*args, **kwargs)

Returns a new instance of the Network class, using the provided arguments to the constructor.

Beware, Network.compile() is not called, only the instantiation of the data structures. Nothing in the constructor should induce a recompilation.

config

config(*args, **kwargs)

Configuration of the network.

This method is equivalent to calling setup() at the global level, but only influences the current network. The initial configuration of the network copies the values set in setup() at the time of the creation of the network.

It can be called multiple times until compile() is called, new values of keys erasing older ones.

The only functional difference with setup() is the seed, which should be passed to the constructor of Network, otherwise any random number generation in the constructor might be unseeded. dt can also be passed to the constructor, but setting it in config() is also fine.

It takes various optional arguments. The most useful ones are:

  • dt: simulation step size in milliseconds (default: 1.0).
  • paradigm: parallel framework for code generation. Accepted values: “openmp” or “cuda” (default: “openmp”).
  • method: default method to numerize the ODEs. Default is the explicit forward Euler method (‘explicit’).
  • precision: default floating precision for variables in ANNarchy. Accepted values: “float” or “double” (default: “double”)
  • structural_plasticity: allows synapses to be dynamically added/removed during the simulation (default: False).
  • seed: the seed (integer) to be used in the random number generators (default = None is equivalent to time(NULL)).
  • num_threads: number of treads used by openMP (overrides the environment variable OMP_NUM_THREADS when set, default = None).

Flags related to the optimization of the simulation kernels are:

  • sparse_matrix_format: the default matrix format for projections in ANNarchy (by default: List-In-List for CPUs and Compressed Sparse Row). Note that this affects only the C++ data structures.
  • sparse_matrix_storage_order: encodes whether the row in a connectivity matrix encodes pre-synaptic neurons (post_to_pre, default) or post-synaptic neurons (pre_to_post). Note that affects only the C++ data structures.
  • only_int_idx_type: if set to True (default) only signed integers are used to store pre-/post-synaptic ranks which was default until 4.7. If set to False, the index type used in a single projection is selected based on the size of the corresponding populations.
  • visible_cores: allows a fine-grained control which cores are useable for the created threads (default = [] for no limitation). It can be used to limit created openMP threads to a physical socket.

The following parameters are mainly for debugging and profiling, and should be ignored by most users:

  • verbose: shows details about compilation process on console (by default False). Additional some information of the network construction will be shown.
  • suppress_warnings: if True, warnings (e. g. from the mathematical parser) are suppressed.
  • show_time: if True, initialization times are shown. Attention: verbose should be set to True additionally.
  • disable_shared_library_time_offset: by default False. If set to True, the shared library generated by ANNarchy will not be extended by time offset.

load

load(filename, populations=True, projections=True, pickle_encoding=None)

Loads parameters and variables from a file created with Network.save().

Parameters

Name Type Description Default
filename str filename, may contain relative or absolute path. required
populations bool if True, population data will be saved. True
projections bool if True, projection data will be saved. True
pickle_encoding str optional parameter provided to the pickle.load() method. If set to None the default is used. None

save

save(filename, populations=True, projections=True)

Saves the parameters and variables of the networkin a file.

  • If the extension is ‘.npz’, the data will be saved and compressed using np.savez_compressed (recommended).
  • If the extension is ‘.mat’, the data will be saved as a Matlab 7.2 file. Scipy must be installed.
  • If the extension ends with ‘.gz’, the data will be pickled into a binary file and compressed using gzip.
  • Otherwise, the data will be pickled into a simple binary text file using cPickle.

Warning: The ‘.mat’ data will not be loadable by ANNarchy, it is only for external analysis purpose.

Example:

net.save('results/init.npz')

net.save('results/init.data')

net.save('results/init.txt.gz')

net.save('1000_trials.mat')

Parameters

Name Type Description Default
filename str filename, may contain relative or absolute path. required
populations bool if True, population data will be saved. True
projections bool if True, projection data will be saved. True

get_population

get_population(name)

Returns the population with the given name.

Parameters

Name Type Description Default
name str name of the population required

get_projection

get_projection(name)

Returns the projection with the given name.

Parameters

Name Type Description Default
name str name of the projection required

get_monitor

get_monitor(name)

Returns the monitor with the given name.

Parameters

Name Type Description Default
name str name of the monitor required

get_extension

get_extension(name)

Returns the extension with the given name.

Parameters

Name Type Description Default
name str name of the extension required

get_constant

get_constant(name)

Returns the constant with the given name.

Parameters

Name Type Description Default
name str name of the constant required

get_populations

get_populations()

Returns a list of all declared populations in this network.

get_projections

get_projections()

Returns a list of all declared projections for the current network.

get_monitors

get_monitors()

Returns a list of declared monitors.

get_extensions

get_extensions()

Returns a list of declared extensions (e.g. BOLD monitors).

get_constants

get_constants()

Returns a list of declared constants.

callbacks_enabled

callbacks_enabled()

Returns True if callbacks are enabled for the network.

disable_callbacks

disable_callbacks()

Disables all callbacks for the network.

enable_callbacks

enable_callbacks()

Enables all declared callbacks for the network.

clear_all_callbacks

clear_all_callbacks()

Clears the list of declared callbacks for the network.

Cannot be undone!

ANNarchy
Population
 

Copyright Julien Vitay, Helge Ülo Dinkelbach, Fred Hamker