diff --git a/.gitignore b/.gitignore
index acf9376345..eb29f16510 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,10 +9,19 @@ reports/
pynest/pynestkernel.cxx
*.la
*.lo
+*.so
*.log
*.o
*.pyc
-*.so
+
+Makefile
+
+build/
+install/
+examples/example_logs/
+
+/extras/nest-config
+/libnestutil/config.h
/librandom/randomtest
/nest/nest
/sli/sli
@@ -45,8 +54,12 @@ doc/doctrees/
doc/html/
doc/models/
doc/pynestkernel_mock.py
+
+# created when running examples, e.g. by examples/run_examples.py
examples/microcircuit.png
examples/reference_data/
+/examples/matplotlib/fontList.json
+/examples/matplotlib/tex.cache/
# macOS
.DS_Store
diff --git a/examples/list_examples.sh b/examples/list_examples.sh
new file mode 100755
index 0000000000..a1fcc8f26c
--- /dev/null
+++ b/examples/list_examples.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+#
+# list_examples.sh
+#
+# This file is part of NEST.
+#
+# Copyright (C) 2004 The NEST Initiative
+#
+# NEST is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# NEST is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with NEST. If not, see .
+
+# set bash strict mode
+set -euo pipefail
+IFS=$' \n\t'
+
+echo ">>> Longest running examples:"
+egrep -o "real: [^,]+" example_logs/*/meta.yaml | sed -e 's/:real://' | sort -k2 -r | head -n 20 || true;
+
+echo ">>> multiple run statistics"
+for x in example_logs/*/meta.yaml; do
+ name="$(basename "$(dirname "$x")")"
+ res="$(grep "result:" "$x" | sort | uniq -c | tr "\n" "\t" | sed -e 's/failed/\x1b[1;31m\0\x1b[0m/g' -e 's/success/\x1b[1;32m\0\x1b[0m/g')"
+ warn=""
+ if grep "fail" <<<"$res" >/dev/null && grep "success" <<<"$res" >/dev/null; then
+ warn='\033[01;33m'
+ fi
+ echo -e "$res\t$warn$name\033[0m"
+done
+echo "<<< done"
diff --git a/examples/matplotlib/matplotlibrc b/examples/matplotlib/matplotlibrc
new file mode 100644
index 0000000000..c6c9449e4b
--- /dev/null
+++ b/examples/matplotlib/matplotlibrc
@@ -0,0 +1 @@
+backend : svg
diff --git a/examples/run_examples.sh b/examples/run_examples.sh
index 318d9de0dd..b00119d3b1 100755
--- a/examples/run_examples.sh
+++ b/examples/run_examples.sh
@@ -19,7 +19,7 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-NEST_CMD=`which nest`
+NEST_CMD="$(which nest)"
if [ $? != 0 ] ; then
echo "ERROR: command 'nest' not found. Please make sure PATH is set correctly"
echo " by sourcing the script nest_vars.sh from your NEST installation."
@@ -33,36 +33,48 @@ if [ $? != 0 ] ; then
exit 1
fi
-FAILURES=0
+# set bash strict mode
+set -euo pipefail
+IFS=$' \n\t'
-# Find all examples that have a line containing "autorun=true"
-# The examples can be found in subdirectory nest and in the
-# examples installation path.
-if [ -d "nest/" ] ; then
- EXAMPLES=$(grep -rl --include=\*\.sli 'autorun=true' nest/)
+declare -a EXAMPLES
+if [ "${#}" -eq 0 ]; then
+ # Find all examples that have a line containing "autorun=true"
+ # The examples can be found in subdirectory nest and in the
+ # examples installation path.
+ if [ -d "nest/" ] ; then
+ EXAMPLES="$(grep -rl --include=\*\.sli 'autorun=true' nest/)"
+ else
+ EXAMPLES="$(grep -rl --include=\*\.sli 'autorun=true' examples/)"
+ fi
+ EXAMPLES+=" $(find ../pynest/examples -name '*.py')"
else
- EXAMPLES=$(grep -rl --include=\*\.sli 'autorun=true' examples/)
+ EXAMPLES+=${@}
fi
-if test -n "$SKIP_LIST"; then
- EXAMPLES=$(echo $EXAMPLES | tr ' ' '\n' | grep -vE $SKIP)
+if [ ! -z "${SKIP_LIST+x}" ]; then
+ EXAMPLES=$(echo $EXAMPLES | tr ' ' '\n' | grep -vE $SKIP_LIST)
fi
-time_format=" TIME: real: %E, user: %U, sys: %S\n\
- MEMORY: total: %K, max rss: %M"
+# turn off plotting to the screen and waiting for input
+export MPLCONFIGDIR="$(pwd)/matplotlib/"
+
+time_format=" time: {real: %E, user: %U, system: %S}\n\
+ memory: {total: %K, max_rss: %M}"
basedir=$PWD
+FAILURES=0
START=$SECONDS
-for i in $EXAMPLES ; do
+for i in $EXAMPLES; do
- cd $(dirname $i)
+ cd "$(dirname "$i")"
- workdir=$PWD
- example=$(basename $i)
+ workdir="$PWD"
+ example="$(basename "$i")"
- ext=$(echo $example | cut -d. -f2)
+ ext="$(echo "$example" | cut -d. -f2)"
if [ $ext = sli ] ; then
runner=nest
@@ -70,35 +82,58 @@ for i in $EXAMPLES ; do
runner=python3
fi
- output_dir=$basedir/example_logs/$example
- logfile=$output_dir/output.log
- mkdir -p $output_dir
-
+ output_dir="$basedir/example_logs/$example"
+ logfile="$output_dir/output.log"
+ metafile="$output_dir/meta.yaml"
+ mkdir -p "$output_dir"
+
echo ">>> RUNNING: $workdir/$example"
echo " LOGFILE: $logfile"
-
- export NEST_DATA_PATH=$output_dir
- /usr/bin/time -f "$time_format" --quiet sh -c "$runner $example >$logfile 2>&1"
-
- if [ $? != 0 ] ; then
+ echo "- script: '$workdir/$example'" >>"$metafile"
+ echo " output_dir: '$output_dir'" >>"$metafile"
+ echo " log: '$logfile'" >>"$metafile"
+
+ export NEST_DATA_PATH="" # $output_dir"
+ touch .start_example
+ sleep 1
+ set +e
+ /usr/bin/time -f "$time_format" --quiet sh -c "'$runner' '$example' >'$logfile' 2>&1" |& tee -a "$metafile"
+ ret=$?
+ set -e
+
+ outfiles=false
+ for file in $(find . -newer .start_example); do
+ if ! $outfiles; then
+ echo " output_files:" >>"$metafile"
+ outfiles=true
+ fi
+ echo " - '$file'" >>"$metafile"
+ done
+ echo " return_code: $ret" >>"$metafile"
+ if [ $ret != 0 ] ; then
echo " FAILURE!"
+ echo " result: failed" >>"$metafile"
FAILURES=$(( $FAILURES + 1 ))
- OUTPUT=$(printf " %s\n %s\n" "$OUTPUT" "$workdir/$example")
+ OUTPUT="$(printf " %s\n %s\n" "${OUTPUT:-}" "$workdir/$example")"
else
echo " SUCCESS!"
+ echo " result: success" >>"$metafile"
fi
echo
unset NEST_DATA_PATH
- cd $basedir
+ cd "$basedir"
done
ELAPSED_TIME=$(($SECONDS - $START))
-echo ">>> RESULTS: $FAILURES failed /" $(echo $EXAMPLES | wc -w) " total"
+echo ">>> Longest running examples:"
+egrep -o "real: [^,]+" example_logs/*/meta.yaml | sed -e 's/:real://' | sort -k2 -rg | head -n 15
+
+echo ">>> RESULTS: $FAILURES failed /" $(echo "$EXAMPLES" | wc -w) " total"
echo ">>> TOTAL TIME: $(($ELAPSED_TIME/60)) min $(($ELAPSED_TIME%60)) sec."
-if [ "x$OUTPUT" != "x" ] ; then
+if [ ! -z ${OUTPUT+x} ] ; then
echo ">>> Failed examples:"
echo "$OUTPUT"
echo ""
diff --git a/pynest/examples/BrodyHopfield.py b/pynest/examples/BrodyHopfield.py
index 23a29fc450..6021cd883d 100755
--- a/pynest/examples/BrodyHopfield.py
+++ b/pynest/examples/BrodyHopfield.py
@@ -20,8 +20,9 @@
# along with NEST. If not, see .
-"""Spike synchronization through subthreshold oscillation
-------------------------------------------------------------
+"""
+Spike synchronization through subthreshold oscillation
+------------------------------------------------------
This script reproduces the spike synchronization behavior
of integrate-and-fire neurons in response to a subthreshold
@@ -33,11 +34,12 @@
matplotlib. All parameters are taken from the above paper.
References
-~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Brody CD and Hopfield JJ (2003). Simple networks for
spike-timing-based computation, with application to olfactory
processing. Neuron 37, 843-852.
+
"""
#################################################################################
diff --git a/pynest/examples/CampbellSiegert.py b/pynest/examples/CampbellSiegert.py
index 6b3a1f6a5f..e781860dbb 100755
--- a/pynest/examples/CampbellSiegert.py
+++ b/pynest/examples/CampbellSiegert.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Campbell & Siegert approximation example
-----------------------------------------------
+"""
+Campbell & Siegert approximation example
+----------------------------------------
Example script that applies Campbell's theorem and Siegert's rate
approximation to and integrate-and-fire neuron.
@@ -32,8 +33,8 @@
-References:
-~~~~~~~~~~~~
+References
+~~~~~~~~~~
.. [1] Papoulis A (1991). Probability, Random Variables, and
Stochastic Processes, McGraw-Hill
@@ -41,7 +42,7 @@
Phys Rev 81: 617-623
Authors
-~~~~~~~~
+~~~~~~~
S. Schrader, Siegert implentation by T. Tetzlaff
"""
@@ -106,8 +107,6 @@
else:
tau_syn = tau_syn_in
- t_psp = np.arange(0., 10. * (tau_m * ms + tau_syn * ms), 0.0001)
-
# We define the form of a single PSP, which allows us to match the
# maximal value to or chosen weight.
@@ -178,22 +177,18 @@ def psp(x):
# free membrane potential. In addition we choose a small resolution for
# recording the membrane to collect good statistics.
-nest.SetDefaults('iaf_psc_alpha', neurondict)
-n = nest.Create('iaf_psc_alpha', n_neurons)
-n_free = nest.Create('iaf_psc_alpha', 1, {'V_th': 1e12})
-pg = nest.Create('poisson_generator', len(rates),
- [{'rate': float(rate_i)} for rate_i in rates])
-vm = nest.Create('voltmeter', 1, {'interval': .1})
+n = nest.Create('iaf_psc_alpha', n_neurons, params=neurondict)
+n_free = nest.Create('iaf_psc_alpha', params=dict(neurondict, V_th=1e12))
+pg = nest.Create('poisson_generator', len(rates), {'rate': rates})
+vm = nest.Create('voltmeter', params={'interval': .1})
sr = nest.Create('spike_recorder')
###############################################################################
# We connect devices and neurons and start the simulation.
-for indx in range(len(pg)):
- nest.Connect(pg[indx], n,
- syn_spec={'weight': float(J[indx]), 'delay': 0.1})
- nest.Connect(pg[indx], n_free, syn_spec={'weight': J[indx]})
-
+pg_n_synspec = {'weight': np.tile(J, ((n_neurons), 1)), 'delay': 0.1}
+nest.Connect(pg, n, syn_spec=pg_n_synspec)
+nest.Connect(pg, n_free, syn_spec={'weight': [J]})
nest.Connect(vm, n_free)
nest.Connect(n, sr)
@@ -204,11 +199,8 @@ def psp(x):
# omitted so initial transients do not perturb our results. We then print the
# results from theory and simulation.
-v_free = vm.get('events', 'V_m')[500:-1]
-print('mean membrane potential (actual / calculated): {0} / {1}'
- .format(np.mean(v_free), mu * 1000))
-print('variance (actual / calculated): {0} / {1}'
- .format(np.var(v_free), sigma2 * 1e6))
-print('firing rate (actual / calculated): {0} / {1}'
- .format(nest.GetStatus(sr, 'n_events')[0] /
- (n_neurons * simtime * ms), r))
+v_free = vm.events['V_m']
+Nskip = 500
+print(f'mean membrane potential (actual / calculated): {np.mean(v_free[Nskip:])} / {mu * 1000}')
+print(f'variance (actual / calculated): {np.var(v_free[Nskip:])} / {sigma2 * 1e6}')
+print(f'firing rate (actual / calculated): {sr.n_events / (n_neurons * simtime * ms)} / {r}')
diff --git a/pynest/examples/aeif_cond_beta_multisynapse.py b/pynest/examples/aeif_cond_beta_multisynapse.py
index 0eef20defb..aa50dd21df 100644
--- a/pynest/examples/aeif_cond_beta_multisynapse.py
+++ b/pynest/examples/aeif_cond_beta_multisynapse.py
@@ -20,14 +20,14 @@
# along with NEST. If not, see .
"""
-
aeif_cond_beta_multisynapse
-+++++++++++++++++++++++++++
+---------------------------
"""
import nest
import numpy as np
+import matplotlib.pyplot as plt
neuron = nest.Create('aeif_cond_beta_multisynapse')
nest.SetStatus(neuron, {"V_peak": 0.0, "a": 4.0, "b": 80.5})
@@ -43,7 +43,7 @@
delays = [1.0, 300.0, 500.0, 700.0]
w = [1.0, 1.0, 1.0, 1.0]
for syn in range(4):
- nest.Connect(spike, neuron, syn_spec={'model': 'static_synapse',
+ nest.Connect(spike, neuron, syn_spec={'synapse_model': 'static_synapse',
'receptor_type': 1 + syn,
'weight': w[syn],
'delay': delays[syn]})
@@ -52,11 +52,8 @@
nest.Simulate(1000.0)
-dmm = nest.GetStatus(voltmeter)[0]
-Vms = dmm["events"]["V_m"]
-ts = dmm["events"]["times"]
+Vms = voltmeter.get("events", "V_m")
+ts = voltmeter.get("events", "times")
-# import pylab
-# pylab.figure(2)
-# pylab.plot(ts, Vms)
-# pylab.show()
+plt.plot(ts, Vms)
+plt.show()
diff --git a/pynest/examples/arbor_cosim_example/nest_sender.py b/pynest/examples/arbor_cosim_example/nest_sender.py
index 3cd24ae174..46ee250b70 100644
--- a/pynest/examples/arbor_cosim_example/nest_sender.py
+++ b/pynest/examples/arbor_cosim_example/nest_sender.py
@@ -4,14 +4,14 @@
from sys import argv
argv.append('--quiet')
-import sys
+import sys # noqa nopep8 (order of imports matter)
print("Getting comm")
-from mpi4py import MPI
+from mpi4py import MPI # noqa nopep8 (order of imports matter)
comm = MPI.COMM_WORLD.Split(0) # is nest
print("Getting nest")
-import nest
+import nest # noqa nopep8 (order of imports matter)
STATUS_DICT = nest.ll_api.sli_func("statusdict")
diff --git a/pynest/examples/balancedneuron.py b/pynest/examples/balancedneuron.py
index b4c9415925..59fdc4c0d3 100644
--- a/pynest/examples/balancedneuron.py
+++ b/pynest/examples/balancedneuron.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Balanced neuron example
------------------------------
+"""
+Balanced neuron example
+-----------------------
This script simulates a neuron driven by an excitatory and an
inhibitory population of neurons firing Poisson spike trains. The aim
@@ -33,7 +34,7 @@
This example is also shown in the article [1]_
References
-~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Eppler JM, Helias M, Mulller E, Diesmann M, Gewaltig MO (2009). PyNEST: A convenient interface to the NEST
simulator, Front. Neuroinform.
@@ -49,6 +50,7 @@
import nest
import nest.voltage_trace
+import matplotlib.pyplot as plt
###############################################################################
# Additionally, we set the verbosity using ``set_verbosity`` to
@@ -84,7 +86,7 @@
spikerecorder = nest.Create("spike_recorder")
###################################################################################
-# Fourth, the ``poisson_generator`` (`noise`) is configured using ``set``.
+# Fourth, the ``poisson_generator`` (`noise`) is configured.
# Note that we need not set parameters for the neuron, the spike recorder, and
# the voltmeter, since they have satisfactory defaults.
@@ -165,4 +167,4 @@ def output_rate(guess):
# time.
nest.voltage_trace.from_device(voltmeter)
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/brette_gerstner_fig_2c.py b/pynest/examples/brette_gerstner_fig_2c.py
index 10396e95f6..ae5cbfa609 100755
--- a/pynest/examples/brette_gerstner_fig_2c.py
+++ b/pynest/examples/brette_gerstner_fig_2c.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Testing the adapting exponential integrate and fire model in NEST (Brette and Gerstner Fig 2C)
-----------------------------------------------------------------------------------------------------
+"""
+Testing the adapting exponential integrate and fire model in NEST (Brette and Gerstner Fig 2C)
+----------------------------------------------------------------------------------------------
This example tests the adaptive integrate and fire model (AdEx) according to
Brette and Gerstner [1]_ reproduces Figure 2C of the paper.
@@ -29,7 +30,7 @@
converted to `pA` (pico Ampere).
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Brette R and Gerstner W (2005). Adaptive exponential integrate-and-fire model as an effective
description of neuronal activity J. Neurophysiology. https://doi.org/10.1152/jn.00686.2005
@@ -85,4 +86,4 @@
nest.voltage_trace.from_device(voltmeter)
plt.axis([0, 1000, -80, -20])
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/brette_gerstner_fig_3d.py b/pynest/examples/brette_gerstner_fig_3d.py
index ed93b2014c..a8ad6aa76e 100755
--- a/pynest/examples/brette_gerstner_fig_3d.py
+++ b/pynest/examples/brette_gerstner_fig_3d.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Testing the adapting exponential integrate and fire model in NEST (Brette and Gerstner Fig 3D)
-----------------------------------------------------------------------------------------------------
+"""
+Testing the adapting exponential integrate and fire model in NEST (Brette and Gerstner Fig 3D)
+----------------------------------------------------------------------------------------------
This example tests the adaptive integrate and fire model (AdEx) according to
Brette and Gerstner [1]_ reproduces Figure 3D of the paper.
@@ -30,10 +31,11 @@
converted to `pA` (pico Ampere).
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Brette R and Gerstner W (2005). Adaptive exponential integrate-and-fire model as an effective
description of neuronal activity J. Neurophysiology. https://doi.org/10.1152/jn.00686.2005
+
"""
import nest
@@ -82,4 +84,4 @@
nest.voltage_trace.from_device(voltmeter)
plt.axis([0, 1000, -85, 0])
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/brunel_alpha_evolution_strategies.py b/pynest/examples/brunel_alpha_evolution_strategies.py
index 5e5acd35f2..8ddf5a9e01 100644
--- a/pynest/examples/brunel_alpha_evolution_strategies.py
+++ b/pynest/examples/brunel_alpha_evolution_strategies.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Use evolution strategies to find parameters for a random balanced network (alpha synapses)
------------------------------------------------------------------------------------------------------
+"""
+Use evolution strategies to find parameters for a random balanced network (alpha synapses)
+------------------------------------------------------------------------------------------
This script uses an optimization algorithm to find the appropriate
parameter values for the external drive "eta" and the relative ratio
@@ -231,12 +232,9 @@ def ComputePSPnorm(tauMem, CMem, tauSyn):
nest.SetKernelStatus({'rng_seed': parameters['seed'],
'resolution': parameters['dt']})
- nest.SetDefaults('iaf_psc_alpha', neuron_parameters)
- nest.SetDefaults('poisson_generator', {'rate': p_rate})
-
- nodes_ex = nest.Create('iaf_psc_alpha', NE)
- nodes_in = nest.Create('iaf_psc_alpha', NI)
- noise = nest.Create('poisson_generator')
+ nodes_ex = nest.Create('iaf_psc_alpha', NE, params=neuron_parameters)
+ nodes_in = nest.Create('iaf_psc_alpha', NI, params=neuron_parameters)
+ noise = nest.Create('poisson_generator', params={'rate': p_rate})
espikes = nest.Create('spike_recorder', params={'label': 'brunel-py-ex'})
ispikes = nest.Create('spike_recorder', params={'label': 'brunel-py-in'})
@@ -250,14 +248,10 @@ def ComputePSPnorm(tauMem, CMem, tauSyn):
if parameters['N_rec'] > NE:
raise ValueError(
- 'Requested recording from {} neurons, \
- but only {} in excitatory population'.format(
- parameters['N_rec'], NE))
+ f'Requested recording from {parameters["N_rec"]} neurons, but only {NE} in excitatory population')
if parameters['N_rec'] > NI:
raise ValueError(
- 'Requested recording from {} neurons, \
- but only {} in inhibitory population'.format(
- parameters['N_rec'], NI))
+ f'Requested recording from {parameters["N_rec"]} neurons, but only {NI} in inhibitory population')
nest.Connect(nodes_ex[:parameters['N_rec']], espikes)
nest.Connect(nodes_in[:parameters['N_rec']], ispikes)
@@ -354,7 +348,7 @@ def optimize(func, mu, sigma, learning_rate_mu=None, learning_rate_sigma=None,
# min_sigma: float
# Minimal value for standard deviation of search
# distribution. If any dimension has a value smaller than this,
- # the search is stoppped.
+ # the search is stopped.
# verbosity: bool
# Whether to continuously print progress information.
#
@@ -399,11 +393,10 @@ def optimize(func, mu, sigma, learning_rate_mu=None, learning_rate_sigma=None,
# print status if enabled
if verbosity > 0:
print(
- '# Generation {:d} | fitness {:.3f} | mu {} | sigma {}'.format(
- generation, np.mean(fitness),
- ', '.join(str(np.round(mu_i, 3)) for mu_i in mu),
- ', '.join(str(np.round(sigma_i, 3)) for sigma_i in sigma)
- ))
+ f'# Generation {generation:d} | fitness {np.mean(fitness):.3f} | '
+ f'mu {", ".join(str(np.round(mu_i, 3)) for mu_i in mu)} | '
+ f'sigma {", ".join(str(np.round(sigma_i, 3)) for sigma_i in sigma)}'
+ )
# apply fitness shaping if enabled
if fitness_shaping:
@@ -462,13 +455,11 @@ def objective_function(g, eta):
# analyse the result and compute fitness
rate, cv, corr = compute_statistics(
simulation_parameters, espikes, ispikes)
- fitness = \
- - optimization_parameters['fitness_weight_rate'] * (
- rate - optimization_parameters['target_rate']) ** 2 \
- - optimization_parameters['fitness_weight_cv'] * (
- cv - optimization_parameters['target_cv']) ** 2 \
- - optimization_parameters['fitness_weight_corr'] * (
- corr - optimization_parameters['target_corr']) ** 2
+ fitness = (
+ -optimization_parameters['fitness_weight_rate'] * (rate - optimization_parameters['target_rate'])**2 -
+ optimization_parameters['fitness_weight_cv'] * (cv - optimization_parameters['target_cv'])**2 -
+ optimization_parameters['fitness_weight_corr'] * (corr - optimization_parameters['target_corr'])**2
+ )
return fitness
diff --git a/pynest/examples/brunel_alpha_nest.py b/pynest/examples/brunel_alpha_nest.py
index 9346a9e7b7..ca75d7a3a0 100755
--- a/pynest/examples/brunel_alpha_nest.py
+++ b/pynest/examples/brunel_alpha_nest.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Random balanced network (alpha synapses) connected with NEST
-------------------------------------------------------------------
+"""
+Random balanced network (alpha synapses) connected with NEST
+------------------------------------------------------------
This script simulates an excitatory and an inhibitory population on
the basis of the network used in [1]_.
@@ -35,14 +36,14 @@
network are recorded.
References
-~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Brunel N (2000). Dynamics of sparsely connected networks of excitatory and
inhibitory spiking neurons. Journal of Computational Neuroscience 8,
183-208.
See Also
-~~~~~~~~~~~~
+~~~~~~~~
:doc:`brunel_alpha_numpy`
@@ -172,25 +173,16 @@ def ComputePSPnorm(tauMem, CMem, tauSyn):
print("Building network")
-###############################################################################
-# Configuration of the model ``iaf_psc_alpha`` and ``poisson_generator`` using
-# ``SetDefaults``. This function expects the model to be the inserted as a
-# string and the parameter to be specified in a dictionary. All instances of
-# theses models created after this point will have the properties specified
-# in the dictionary by default.
-
-nest.SetDefaults("iaf_psc_alpha", neuron_params)
-nest.SetDefaults("poisson_generator", {"rate": p_rate})
-
###############################################################################
# Creation of the nodes using ``Create``. We store the returned handles in
# variables for later reference. Here the excitatory and inhibitory, as well
# as the poisson generator and two spike recorders. The spike recorders will
-# later be used to record excitatory and inhibitory spikes.
+# later be used to record excitatory and inhibitory spikes. Properties of the
+# nodes are specified via ``params``, which expects a dictionary.
-nodes_ex = nest.Create("iaf_psc_alpha", NE)
-nodes_in = nest.Create("iaf_psc_alpha", NI)
-noise = nest.Create("poisson_generator")
+nodes_ex = nest.Create("iaf_psc_alpha", NE, params=neuron_params)
+nodes_in = nest.Create("iaf_psc_alpha", NI, params=neuron_params)
+noise = nest.Create("poisson_generator", params={"rate": p_rate})
espikes = nest.Create("spike_recorder")
ispikes = nest.Create("spike_recorder")
@@ -316,14 +308,14 @@ def ComputePSPnorm(tauMem, CMem, tauSyn):
# Printing the network properties, firing rates and building times.
print("Brunel network simulation (Python)")
-print("Number of neurons : {0}".format(N_neurons))
-print("Number of synapses: {0}".format(num_synapses))
-print(" Exitatory : {0}".format(int(CE * N_neurons) + N_neurons))
-print(" Inhibitory : {0}".format(int(CI * N_neurons)))
-print("Excitatory rate : %.2f Hz" % rate_ex)
-print("Inhibitory rate : %.2f Hz" % rate_in)
-print("Building time : %.2f s" % build_time)
-print("Simulation time : %.2f s" % sim_time)
+print(f"Number of neurons : {N_neurons}")
+print(f"Number of synapses: {num_synapses}")
+print(f" Exitatory : {int(CE * N_neurons) + N_neurons}")
+print(f" Inhibitory : {int(CI * N_neurons)}")
+print(f"Excitatory rate : {rate_ex:.2f} Hz")
+print(f"Inhibitory rate : {rate_in:.2f} Hz")
+print(f"Building time : {build_time:.2f} s")
+print(f"Simulation time : {sim_time:.2f} s")
###############################################################################
# Plot a raster of the excitatory neurons and a histogram.
diff --git a/pynest/examples/brunel_delta_nest.py b/pynest/examples/brunel_delta_nest.py
index 4d72a87aa9..2c8e52f17f 100755
--- a/pynest/examples/brunel_delta_nest.py
+++ b/pynest/examples/brunel_delta_nest.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Random balanced network (delta synapses)
-----------------------------------------------
+"""
+Random balanced network (delta synapses)
+----------------------------------------
This script simulates an excitatory and an inhibitory population on
the basis of the network used in [1]_
@@ -32,7 +33,7 @@
network are recorded.
References
-~~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Brunel N (2000). Dynamics of sparsely connected networks of excitatory and
inhibitory spiking neurons. Journal of Computational Neuroscience 8,
@@ -127,25 +128,16 @@
print("Building network")
-###############################################################################
-# Configuration of the model ``iaf_psc_delta`` and ``poisson_generator`` using
-# ``SetDefaults``. This function expects the model to be the inserted as a
-# string and the parameter to be specified in a dictionary. All instances of
-# theses models created after this point will have the properties specified
-# in the dictionary by default.
-
-nest.SetDefaults("iaf_psc_delta", neuron_params)
-nest.SetDefaults("poisson_generator", {"rate": p_rate})
-
###############################################################################
# Creation of the nodes using ``Create``. We store the returned handles in
# variables for later reference. Here the excitatory and inhibitory, as well
# as the poisson generator and two spike recorders. The spike recorders will
-# later be used to record excitatory and inhibitory spikes.
+# later be used to record excitatory and inhibitory spikes. Properties of the
+# nodes are specified via ``params``, which expects a dictionary.
-nodes_ex = nest.Create("iaf_psc_delta", NE)
-nodes_in = nest.Create("iaf_psc_delta", NI)
-noise = nest.Create("poisson_generator")
+nodes_ex = nest.Create("iaf_psc_delta", NE, params=neuron_params)
+nodes_in = nest.Create("iaf_psc_delta", NI, params=neuron_params)
+noise = nest.Create("poisson_generator", params={"rate": p_rate})
espikes = nest.Create("spike_recorder")
ispikes = nest.Create("spike_recorder")
@@ -271,14 +263,14 @@
# Printing the network properties, firing rates and building times.
print("Brunel network simulation (Python)")
-print("Number of neurons : {0}".format(N_neurons))
-print("Number of synapses: {0}".format(num_synapses))
-print(" Exitatory : {0}".format(int(CE * N_neurons) + N_neurons))
-print(" Inhibitory : {0}".format(int(CI * N_neurons)))
-print("Excitatory rate : %.2f Hz" % rate_ex)
-print("Inhibitory rate : %.2f Hz" % rate_in)
-print("Building time : %.2f s" % build_time)
-print("Simulation time : %.2f s" % sim_time)
+print(f"Number of neurons : {N_neurons}")
+print(f"Number of synapses: {num_synapses}")
+print(f" Exitatory : {int(CE * N_neurons) + N_neurons}")
+print(f" Inhibitory : {int(CI * N_neurons)}")
+print(f"Excitatory rate : {rate_ex:.2f} Hz")
+print(f"Inhibitory rate : {rate_in:.2f} Hz")
+print(f"Building time : {build_time:.2f} s")
+print(f"Simulation time : {sim_time:.2f} s")
###############################################################################
# Plot a raster of the excitatory neurons and a histogram.
diff --git a/pynest/examples/brunel_exp_multisynapse_nest.py b/pynest/examples/brunel_exp_multisynapse_nest.py
index 637a695c26..885cd4ebec 100644
--- a/pynest/examples/brunel_exp_multisynapse_nest.py
+++ b/pynest/examples/brunel_exp_multisynapse_nest.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Random balanced network (exp synapses, multiple time constants)
----------------------------------------------------------------------
+"""
+Random balanced network (exp synapses, multiple time constants)
+---------------------------------------------------------------
This script simulates an excitatory and an inhibitory population on
the basis of the network used in [1]_.
@@ -39,14 +40,14 @@
network are recorded.
References
-~~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Brunel N (2000). Dynamics of sparsely connected networks of excitatory and
inhibitory spiking neurons. Journal of Computational Neuroscience 8,
183-208.
See Also
-~~~~~~~~~~
+~~~~~~~~
:doc:`brunel_alpha_nest`
@@ -143,25 +144,16 @@
print("Building network")
-##################################################################################
-# Configuration of the model ``iaf_psc_exp_multisynapse`` and
-# ``poisson_generator`` using ``SetDefaults``. This function expects the model to
-# be the inserted as a string and the parameter to be specified in a
-# dictionary. All instances of theses models created after this point will
-# have the properties specified in the dictionary by default.
-
-nest.SetDefaults("iaf_psc_exp_multisynapse", neuron_params)
-nest.SetDefaults("poisson_generator", {"rate": p_rate})
-
###############################################################################
# Creation of the nodes using ``Create``. We store the returned handles in
# variables for later reference. Here the excitatory and inhibitory, as well
# as the poisson generator and two spike recorders. The spike recorders will
-# later be used to record excitatory and inhibitory spikes.
+# later be used to record excitatory and inhibitory spikes. Properties of the
+# nodes are specified via ``params``, which expects a dictionary.
-nodes_ex = nest.Create("iaf_psc_exp_multisynapse", NE)
-nodes_in = nest.Create("iaf_psc_exp_multisynapse", NI)
-noise = nest.Create("poisson_generator")
+nodes_ex = nest.Create("iaf_psc_exp_multisynapse", NE, params=neuron_params)
+nodes_in = nest.Create("iaf_psc_exp_multisynapse", NI, params=neuron_params)
+noise = nest.Create("poisson_generator", params={"rate": p_rate})
espikes = nest.Create("spike_recorder")
ispikes = nest.Create("spike_recorder")
@@ -300,14 +292,14 @@
# Printing the network properties, firing rates and building times.
print("Brunel network simulation (Python)")
-print("Number of neurons : {0}".format(N_neurons))
-print("Number of synapses: {0}".format(num_synapses))
-print(" Exitatory : {0}".format(int(CE * N_neurons) + N_neurons))
-print(" Inhibitory : {0}".format(int(CI * N_neurons)))
-print("Excitatory rate : %.2f Hz" % rate_ex)
-print("Inhibitory rate : %.2f Hz" % rate_in)
-print("Building time : %.2f s" % build_time)
-print("Simulation time : %.2f s" % sim_time)
+print(f"Number of neurons : {N_neurons}")
+print(f"Number of synapses: {num_synapses}")
+print(f" Exitatory : {int(CE * N_neurons) + N_neurons}")
+print(f" Inhibitory : {int(CI * N_neurons)}")
+print(f"Excitatory rate : {rate_ex:.2f} Hz")
+print(f"Inhibitory rate : {rate_in:.2f} Hz")
+print(f"Building time : {build_time:.2f} s")
+print(f"Simulation time : {sim_time:.2f} s")
###############################################################################
# Plot a raster of the excitatory neurons and a histogram.
diff --git a/pynest/examples/brunel_siegert_nest.py b/pynest/examples/brunel_siegert_nest.py
index 7865525b90..2d4de4fde8 100644
--- a/pynest/examples/brunel_siegert_nest.py
+++ b/pynest/examples/brunel_siegert_nest.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Mean-field theory for random balanced network
----------------------------------------------------
+"""
+Mean-field theory for random balanced network
+---------------------------------------------
This script performs a mean-field analysis of the spiking network of
excitatory and an inhibitory population of leaky-integrate-and-fire neurons
@@ -35,7 +36,7 @@
time-averaged from the spiking simulation.
References
-~~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Hahne J, Dahmen D, Schuecker J, Frommer A, Bolten M,
Helias M and Diesmann M. (2017). Integration of continuous-time
@@ -123,18 +124,13 @@
print("Building network")
-###############################################################################
-# Configuration of the model ``siegert_neuron`` using ``SetDefaults``.
-
-nest.SetDefaults("siegert_neuron", neuron_params)
-
###############################################################################
# Creation of the nodes using ``Create``. One rate neuron represents the
# excitatory population of LIF-neurons in the SLIFN and one the inhibitory
# population assuming homogeneity of the populations.
-siegert_ex = nest.Create("siegert_neuron", 1)
-siegert_in = nest.Create("siegert_neuron", 1)
+siegert_ex = nest.Create("siegert_neuron", params=neuron_params)
+siegert_in = nest.Create("siegert_neuron", params=neuron_params)
###############################################################################
# The Poisson drive in the SLIFN is replaced by a driving rate neuron,
@@ -142,7 +138,7 @@
# neuron is controlled by setting ``mean`` to the rate of the corresponding
# poisson generator in the SLIFN.
-siegert_drive = nest.Create('siegert_neuron', 1, params={'mean': p_rate})
+siegert_drive = nest.Create('siegert_neuron', params={'mean': p_rate})
###############################################################################
# To record from the rate neurons a multimeter is created and the parameter
@@ -198,5 +194,5 @@
rates_ex = data['rate'][numpy.where(data['senders'] == siegert_ex.global_id)]
rates_in = data['rate'][numpy.where(data['senders'] == siegert_in.global_id)]
times = data['times'][numpy.where(data['senders'] == siegert_in.global_id)]
-print("Excitatory rate : %.2f Hz" % rates_ex[-1])
-print("Inhibitory rate : %.2f Hz" % rates_in[-1])
+print(f"Excitatory rate : {rates_ex[-1]:.2f} Hz")
+print(f"Inhibitory rate : {rates_in[-1]:.2f} Hz")
diff --git a/pynest/examples/clopath_synapse_small_network.py b/pynest/examples/clopath_synapse_small_network.py
index 354ebfdbf0..e21b82637d 100644
--- a/pynest/examples/clopath_synapse_small_network.py
+++ b/pynest/examples/clopath_synapse_small_network.py
@@ -21,7 +21,7 @@
"""
Clopath Rule: Bidirectional connections
------------------------------------------
+---------------------------------------
This script simulates a small network of ten excitatory and three
inhibitory ``aeif_psc_delta_clopath`` neurons. The neurons are randomly connected
@@ -34,7 +34,7 @@
bidirectional connections. The example is adapted from [1]_ (cf. fig. 5).
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Clopath C, Büsing L, Vasilaki E, Gerstner W (2010). Connectivity reflects coding:
a model of voltage-based STDP with homeostasis.
@@ -88,7 +88,7 @@
pop_input = nest.Create('parrot_neuron', 500) # helper neurons
pg = nest.Create('poisson_generator', 500)
-wr = nest.Create('weight_recorder', 1)
+wr = nest.Create('weight_recorder')
##############################################################################
# First connect Poisson generators to helper neurons
@@ -116,7 +116,7 @@
# Create exc->exc connections
nest.CopyModel('clopath_synapse', 'clopath_exc_to_exc',
- {'Wmax': 0.75, 'weight_recorder': wr[0]})
+ {'Wmax': 0.75, 'weight_recorder': wr})
syn_dict_exc_to_exc = {'synapse_model': 'clopath_exc_to_exc', 'weight': 0.25,
'delay': delay}
conn_dict_exc_to_exc = {'rule': 'all_to_all', 'allow_autapses': False}
@@ -157,7 +157,7 @@
##############################################################################
# Plot results
-fig1, axA = plt.subplots(1, sharex=False)
+fig, ax = plt.subplots(1, sharex=False)
# Plot synapse weights of the synapses within the excitatory population
# Sort weights according to sender and reshape
@@ -166,8 +166,8 @@
exc_conns_targets = np.array(exc_conns.target)
exc_conns_weights = np.array(exc_conns.weight)
idx_array = np.argsort(exc_conns_senders)
-targets = np.reshape(exc_conns_targets[idx_array], (10, 10-1))
-weights = np.reshape(exc_conns_weights[idx_array], (10, 10-1))
+targets = np.reshape(exc_conns_targets[idx_array], (10, 10 - 1))
+weights = np.reshape(exc_conns_weights[idx_array], (10, 10 - 1))
# Sort according to target
for i, (trgs, ws) in enumerate(zip(targets, weights)):
@@ -186,13 +186,13 @@
init_w_matrix = np.ones((10, 10))*0.25
init_w_matrix -= np.identity(10)*0.25
-caxA = axA.imshow(weight_matrix - init_w_matrix)
-cbarB = fig1.colorbar(caxA, ax=axA)
-axA.set_xticks([0, 2, 4, 6, 8])
-axA.set_xticklabels(['1', '3', '5', '7', '9'])
-axA.set_yticks([0, 2, 4, 6, 8])
-axA.set_xticklabels(['1', '3', '5', '7', '9'])
-axA.set_xlabel("to neuron")
-axA.set_ylabel("from neuron")
-axA.set_title("Change of syn weights before and after simulation")
+cax = ax.imshow(weight_matrix - init_w_matrix)
+cbarB = fig.colorbar(cax, ax=ax)
+ax.set_xticks([0, 2, 4, 6, 8])
+ax.set_xticklabels(['1', '3', '5', '7', '9'])
+ax.set_yticks([0, 2, 4, 6, 8])
+ax.set_xticklabels(['1', '3', '5', '7', '9'])
+ax.set_xlabel("to neuron")
+ax.set_ylabel("from neuron")
+ax.set_title("Change of syn weights before and after simulation")
plt.show()
diff --git a/pynest/examples/clopath_synapse_spike_pairing.py b/pynest/examples/clopath_synapse_spike_pairing.py
index a09ad1e4db..cc80a7f3d0 100644
--- a/pynest/examples/clopath_synapse_spike_pairing.py
+++ b/pynest/examples/clopath_synapse_spike_pairing.py
@@ -21,7 +21,7 @@
"""
Clopath Rule: Spike pairing experiment
-----------------------------------------
+--------------------------------------
This script simulates one ``aeif_psc_delta_clopath`` neuron that is connected with
a Clopath connection [1]_. The synapse receives pairs of a pre- and a postsynaptic
@@ -31,7 +31,7 @@
sequence of the spike pairs: 10Hz, 20Hz, 30Hz, 40Hz, and 50Hz.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Clopath C, Büsing L, Vasilaki E, Gerstner W (2010). Connectivity reflects coding:
a model of voltage-based STDP with homeostasis.
@@ -103,7 +103,7 @@
##############################################################################
# Loop over pairs of spike trains
-for (s_t_pre, s_t_post) in zip(spike_times_pre, spike_times_post):
+for s_t_pre, s_t_post in zip(spike_times_pre, spike_times_post):
nest.ResetKernel()
nest.SetKernelStatus({"resolution": resolution})
@@ -115,20 +115,17 @@
prrt_nrn = nest.Create("parrot_neuron", 1)
# Create and connect spike generators
- spike_gen_pre = nest.Create("spike_generator", 1, {
- "spike_times": s_t_pre})
+ spike_gen_pre = nest.Create("spike_generator", {"spike_times": s_t_pre})
nest.Connect(spike_gen_pre, prrt_nrn,
syn_spec={"delay": resolution})
- spike_gen_post = nest.Create("spike_generator", 1, {
- "spike_times": s_t_post})
+ spike_gen_post = nest.Create("spike_generator", {"spike_times": s_t_post})
- nest.Connect(spike_gen_post, nrn, syn_spec={
- "delay": resolution, "weight": 80.0})
+ nest.Connect(spike_gen_post, nrn, syn_spec={"delay": resolution, "weight": 80.0})
# Create weight recorder
- wr = nest.Create('weight_recorder', 1)
+ wr = nest.Create('weight_recorder')
# Create Clopath connection with weight recorder
nest.CopyModel("clopath_synapse", "clopath_synapse_rec",
@@ -150,14 +147,14 @@
syn_weights = 100.0*15.0*(syn_weights - init_w)/init_w + 100.0
# Plot results
-fig1, axA = plt.subplots(1, sharex=False)
-axA.plot([10., 20., 30., 40., 50.], syn_weights[5:], color='b', lw=2.5, ls='-',
- label="pre-post pairing")
-axA.plot([10., 20., 30., 40., 50.], syn_weights[:5], color='g', lw=2.5, ls='-',
- label="post-pre pairing")
-axA.set_ylabel("normalized weight change")
-axA.set_xlabel("rho (Hz)")
-axA.legend()
-axA.set_title("synaptic weight")
+fig, ax = plt.subplots(1, sharex=False)
+ax.plot([10., 20., 30., 40., 50.], syn_weights[5:], color='b', lw=2.5, ls='-',
+ label="pre-post pairing")
+ax.plot([10., 20., 30., 40., 50.], syn_weights[:5], color='g', lw=2.5, ls='-',
+ label="post-pre pairing")
+ax.set_ylabel("normalized weight change")
+ax.set_xlabel("rho (Hz)")
+ax.legend()
+ax.set_title("synaptic weight")
plt.show()
diff --git a/pynest/examples/correlospinmatrix_detector_two_neuron.py b/pynest/examples/correlospinmatrix_detector_two_neuron.py
index 33d1478b79..9fe980a7bb 100644
--- a/pynest/examples/correlospinmatrix_detector_two_neuron.py
+++ b/pynest/examples/correlospinmatrix_detector_two_neuron.py
@@ -19,18 +19,18 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Correlospinmatrix detector example
-----------------------------------------
+"""
+Correlospinmatrix detector example
+----------------------------------
This scripts simulates two connected binary neurons, similar
as in [1]_. It measures and plots the auto- and cross covariance functions
of the individual neurons and between them, repsectively.
References
-~~~~~~~~~~~~
-
-.. [1] Ginzburg and Sompolinsky (1994). Theory of correlations in stochastic neural netoworks. 50(4) p. 3175. Fig. 1.
+~~~~~~~~~~
+.. [1] Ginzburg and Sompolinsky (1994). Theory of correlations in stochastic neural networks. 50(4) p. 3175. Fig. 1.
"""
@@ -47,12 +47,11 @@
csd = nest.Create("correlospinmatrix_detector")
csd.set(N_channels=2, tau_max=tau_max, Tstart=tau_max, delta_tau=h)
-nest.SetDefaults('ginzburg_neuron', {'theta': 0.0, 'tau_m': tau_m,
- 'c_1': 0.0, 'c_2': 2. * m_x, 'c_3': 1.0})
n1 = nest.Create("ginzburg_neuron")
+n1.set(theta=0.0, tau_m=tau_m, c_1=0.0, c_2=2. * m_x, c_3=1.0)
-nest.SetDefaults("mcculloch_pitts_neuron", {'theta': 0.5, 'tau_m': tau_m})
n2 = nest.Create("mcculloch_pitts_neuron")
+n2.set(theta=0.5, tau_m=tau_m)
nest.Connect(n1, n2, syn_spec={"weight": 1.0})
@@ -61,27 +60,27 @@
nest.Simulate(T)
-c = csd.get("count_covariance")
+count_covariance = csd.count_covariance
-m = np.zeros(2, dtype=float)
+mean_activities = np.zeros(2, dtype=float)
for i in range(2):
- m[i] = c[i][i][int(tau_max / h)] * (h / T)
+ mean_activities[i] = count_covariance[i][i][int(tau_max / h)] * (h / T)
-print('mean activities =', m)
+print('mean activities =', mean_activities)
-cmat = np.zeros((2, 2, int(2 * tau_max / h) + 1), dtype=float)
+covariance_matrix = np.zeros((2, 2, int(2 * tau_max / h) + 1), dtype=float)
for i in range(2):
for j in range(2):
- cmat[i, j] = c[i][j] * (h / T) - m[i] * m[j]
+ covariance_matrix[i, j] = count_covariance[i][j] * (h / T) - mean_activities[i] * mean_activities[j]
ts = np.arange(-tau_max, tau_max + h, h)
plt.title("auto- and cross covariance functions")
-plt.plot(ts, cmat[0, 1], 'r', label=r"$c_{12}$")
-plt.plot(ts, cmat[1, 0], 'b', label=r"$c_{21}$")
-plt.plot(ts, cmat[0, 0], 'g', label=r"$c_{11}$")
-plt.plot(ts, cmat[1, 1], 'y', label=r"$c_{22}$")
+plt.plot(ts, covariance_matrix[0, 1], 'r', label=r"$c_{12}$")
+plt.plot(ts, covariance_matrix[1, 0], 'b', label=r"$c_{21}$")
+plt.plot(ts, covariance_matrix[0, 0], 'g', label=r"$c_{11}$")
+plt.plot(ts, covariance_matrix[1, 1], 'y', label=r"$c_{22}$")
plt.xlabel(r"time $t \; \mathrm{ms}$")
plt.ylabel(r"$c$")
plt.legend()
diff --git a/pynest/examples/cross_check_mip_corrdet.py b/pynest/examples/cross_check_mip_corrdet.py
index b4aaec8886..99f6b517c0 100644
--- a/pynest/examples/cross_check_mip_corrdet.py
+++ b/pynest/examples/cross_check_mip_corrdet.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Auto- and crosscorrelation functions for spike trains
------------------------------------------------------------
+"""
+Auto- and crosscorrelation functions for spike trains
+-----------------------------------------------------
A time bin of size `tbin` is centered around the time difference it
represents. If the correlation function is calculated for `tau` in
@@ -69,7 +70,8 @@ def corr_spikes_sorted(spike1, spike2, tbin, tau_max, h):
h = 0.1 # Computation step size in ms
T = 100000.0 # Total duration
delta_tau = 10.0
-tau_max = 100.0
+tau_max = 100.0 # ms correlation window
+t_bin = 10.0 # ms bin size
pc = 0.5
nu = 100.0
@@ -93,31 +95,22 @@ def corr_spikes_sorted(spike1, spike2, tbin, tau_max, h):
nest.Connect(pn1, sr)
nest.Connect(pn2, sr)
-nest.SetDefaults('static_synapse', {'weight': 1.0, 'receptor_type': 0})
-nest.Connect(pn1, cd)
-
-nest.SetDefaults('static_synapse', {'weight': 1.0, 'receptor_type': 1})
-nest.Connect(pn2, cd)
+nest.Connect(pn1, cd, syn_spec={'weight': 1.0, 'receptor_type': 0})
+nest.Connect(pn2, cd, syn_spec={'weight': 1.0, 'receptor_type': 1})
nest.Simulate(T)
-n_events = cd.get('n_events')
-n1 = n_events[0]
-n2 = n_events[1]
+n_events_1, n_events_2 = cd.n_events
-lmbd1 = (n1 / (T - tau_max)) * 1000.0
-lmbd2 = (n2 / (T - tau_max)) * 1000.0
-
-h = 0.1
-tau_max = 100.0 # ms correlation window
-t_bin = 10.0 # ms bin size
+lmbd1 = (n_events_1 / (T - tau_max)) * 1000.0
+lmbd2 = (n_events_2 / (T - tau_max)) * 1000.0
spikes = sr.get('events', 'senders')
sp1 = spikes[spikes == 4]
sp2 = spikes[spikes == 5]
-# Find crosscorrolation
+# Find crosscorrelation
cross = corr_spikes_sorted(sp1, sp2, t_bin, tau_max, h)
print("Crosscorrelation:")
diff --git a/pynest/examples/evaluate_quantal_stp_synapse.py b/pynest/examples/evaluate_quantal_stp_synapse.py
index 51e9aad699..1c26f64e63 100644
--- a/pynest/examples/evaluate_quantal_stp_synapse.py
+++ b/pynest/examples/evaluate_quantal_stp_synapse.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Example for the quantal_stp_synapse
------------------------------------------
+"""
+Example for the quantal_stp_synapse
+-----------------------------------
The ``quantal_stp_synapse`` is a stochastic version of the Tsodys-Markram model
for synaptic short term plasticity (STP).
@@ -31,7 +32,7 @@
al. [1]_ and Loebel et al. [2]_.
Each presynaptic spike will stochastically activate a fraction of the
-available release sites. This fraction is binomialy distributed and the
+available release sites. This fraction is binomially distributed and the
release probability per site is governed by the Fuhrmann et al. (2002) model.
The solution of the differential equations is taken from Maass and Markram
2002 [3]_.
@@ -40,7 +41,7 @@
obtained if all n release sites are activated.
Parameters
-~~~~~~~~~~~~~
+~~~~~~~~~~
The following parameters can be set in the status dictionary:
@@ -54,7 +55,7 @@
References
-~~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Fuhrmann G, Segev I, Markram H, and Tsodyks MV. (2002). Coding of
temporal information by activity-dependent synapses. Journal of
@@ -93,35 +94,34 @@
###############################################################################
# Then, we assign the parameter set to the synapse models
-t1_params = fac_params # for tsodyks2_synapse
-t2_params = t1_params.copy() # for quantal_stp_synapse
+tsodyks_params = dict(fac_params, synapse_model="tsodyks2_synapse") # for tsodyks2_synapse
+quantal_params = fac_params.copy() # for quantal_stp_synapse
-t1_params['x'] = t1_params['U']
-t2_params['n'] = n_syn
+tsodyks_params['x'] = tsodyks_params['U']
+quantal_params['n'] = n_syn
###############################################################################
# To make the responses comparable, we have to scale the weight by the
# number of synapses.
-t2_params['weight'] = 1. / n_syn
+quantal_params['weight'] = 1. / n_syn
###############################################################################
-# Next, we chage the defaults of the various models to our parameters.
+# Next, we change the defaults of the quantal_stdp_synapse model to our parameters,
+# because it doesn't support the setting of parameter n in syn_spec.
-nest.SetDefaults("tsodyks2_synapse", t1_params)
-nest.SetDefaults("quantal_stp_synapse", t2_params)
-nest.SetDefaults("iaf_psc_exp", {"tau_syn_ex": 3.})
+nest.SetDefaults("quantal_stp_synapse", quantal_params)
###############################################################################
# We create three different neurons.
# Neuron one is the sender, the two other neurons receive the synapses.
-neuron = nest.Create("iaf_psc_exp", 3)
+neuron = nest.Create("iaf_psc_exp", 3, params={"tau_syn_ex": 3.})
###############################################################################
# The connection from neuron 1 to neuron 2 is a deterministic synapse.
-nest.Connect(neuron[0], neuron[1], syn_spec="tsodyks2_synapse")
+nest.Connect(neuron[0], neuron[1], syn_spec=tsodyks_params)
###############################################################################
# The connection from neuron 1 to neuron 3 has a stochastic
@@ -169,8 +169,8 @@
###############################################################################
# Extract the reference trace.
-vm = numpy.array(voltmeter[1].get('events', 'V_m'))
-vm_reference = numpy.array(voltmeter[0].get('events', 'V_m'))
+vm = voltmeter[1].get('events', 'V_m')
+vm_reference = voltmeter[0].get('events', 'V_m')
vm.shape = (n_trials, 1500)
vm_reference.shape = (n_trials, 1500)
@@ -186,7 +186,7 @@
plt.show()
###############################################################################
-# Finally, print the mean-suqared error between the trial-average and the
+# Finally, print the mean-squared error between the trial-average and the
# reference trace. The value should be `< 10^-9`.
print(numpy.mean((vm_ref_mean - vm_mean) ** 2))
diff --git a/pynest/examples/evaluate_tsodyks2_synapse.py b/pynest/examples/evaluate_tsodyks2_synapse.py
index 2b78c08692..e68c879947 100644
--- a/pynest/examples/evaluate_tsodyks2_synapse.py
+++ b/pynest/examples/evaluate_tsodyks2_synapse.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Example of the tsodyks2_synapse in NEST
----------------------------------------------
+"""
+Example of the tsodyks2_synapse in NEST
+---------------------------------------
This synapse model implements synaptic short-term depression and short-term f
according to [1]_ and [2]_. It solves Eq (2) from [1]_ and modulates U according
@@ -34,7 +35,7 @@
factor that scales the synaptic weight.
Parameters
-~~~~~~~~~~~
+~~~~~~~~~~
The following parameters can be set in the status dictionary:
@@ -45,7 +46,7 @@
* tau_fac - time constant for facilitation in ms, default=0 (off)
Notes
-~~~~~~~
+~~~~~
Under identical conditions, the ``tsodyks2_synapse`` produces slightly lower
peak amplitudes than the ``tsodyks_synapse``. However, the qualitative behavior
@@ -54,7 +55,7 @@
This compares the two synapse models.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Tsodyks MV, and Markram H. (1997). The neural code between
neocortical depends on neurotransmitter release probability. PNAS,
@@ -69,6 +70,7 @@
import nest
import nest.voltage_trace
+import matplotlib.pyplot as plt
nest.ResetKernel()
@@ -87,24 +89,20 @@
###############################################################################
# Now we assign the parameter set to the synapse models.
-t1_params = fac_params # for tsodyks_synapse
-t2_params = t1_params.copy() # for tsodyks2_synapse
-
-nest.SetDefaults("tsodyks2_synapse", t1_params)
-nest.SetDefaults("tsodyks_synapse", t2_params)
-nest.SetDefaults("iaf_psc_exp", {"tau_syn_ex": 3.})
+tsodyks_params = dict(fac_params, synapse_model="tsodyks_synapse") # for tsodyks_synapse
+tsodyks2_params = dict(fac_params, synapse_model="tsodyks2_synapse") # for tsodyks2_synapse
###############################################################################
# Create three neurons.
-neuron = nest.Create("iaf_psc_exp", 3)
+neuron = nest.Create("iaf_psc_exp", 3, params={"tau_syn_ex": 3.})
###############################################################################
# Neuron one produces spikes. Neurons 2 and 3 receive the spikes via the two
# synapse models.
-nest.Connect(neuron[0], neuron[1], syn_spec="tsodyks_synapse")
-nest.Connect(neuron[0], neuron[2], syn_spec="tsodyks2_synapse")
+nest.Connect(neuron[0], neuron[1], syn_spec=tsodyks_params)
+nest.Connect(neuron[0], neuron[2], syn_spec=tsodyks2_params)
###############################################################################
# Now create two voltmeters to record the responses.
@@ -135,4 +133,4 @@
nest.voltage_trace.from_device(voltmeter[0])
nest.voltage_trace.from_device(voltmeter[1])
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/gap_junctions_inhibitory_network.py b/pynest/examples/gap_junctions_inhibitory_network.py
index 472362e5fa..2caf59c1cb 100644
--- a/pynest/examples/gap_junctions_inhibitory_network.py
+++ b/pynest/examples/gap_junctions_inhibitory_network.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Gap Junctions: Inhibitory network example
------------------------------------------------
+"""
+Gap Junctions: Inhibitory network example
+-----------------------------------------
This script simulates an inhibitory network of 500 Hodgkin-Huxley neurons.
Without the gap junctions (meaning for ``gap_weight = 0.0``) the network shows
@@ -37,7 +38,7 @@
in [1]_.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Hahne et al. (2015) A unified framework for spiking and gap-junction
interactions in distributed neuronal network simulations, Front.
@@ -142,15 +143,16 @@
nest.Simulate(simtime)
-times = sr.get('events', 'times')
-spikes = sr.get('events', 'senders')
+events = sr.events
+times = events['times']
+spikes = events['senders']
n_spikes = sr.n_events
hz_rate = (1000.0 * n_spikes / simtime) / n_neuron
plt.figure(1)
plt.plot(times, spikes, 'o')
-plt.title('Average spike rate (Hz): %.2f' % hz_rate)
+plt.title(f'Average spike rate (Hz): {hz_rate:.2f}')
plt.xlabel('time (ms)')
plt.ylabel('neuron no')
plt.show()
diff --git a/pynest/examples/gap_junctions_two_neurons.py b/pynest/examples/gap_junctions_two_neurons.py
index 3a76d4cbef..c968c58d6e 100644
--- a/pynest/examples/gap_junctions_two_neurons.py
+++ b/pynest/examples/gap_junctions_two_neurons.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Gap Junctions: Two neuron example
---------------------------------------
+"""
+Gap Junctions: Two neuron example
+---------------------------------
This script simulates two Hodgkin-Huxley neurons of type ``hh_psc_alpha_gap``
connected by a gap junction. Both neurons receive a constant current of
@@ -49,8 +50,8 @@
# Then we set the constant current input, modify the inital membrane
# potential of one of the neurons and connect the neurons to the ``voltmeter``.
-nest.SetStatus(neuron, {'I_e': 100.})
-nest.SetStatus(neuron[0], {'V_m': -10.})
+neuron.I_e = 100.
+neuron[0].V_m = -10.
nest.Connect(vm, neuron, 'all_to_all')
@@ -70,15 +71,13 @@
nest.Simulate(351.)
-senders = nest.GetStatus(vm, 'events')[0]['senders']
-times = nest.GetStatus(vm, 'events')[0]['times']
-V = nest.GetStatus(vm, 'events')[0]['V_m']
+senders = vm.events['senders']
+times = vm.events['times']
+v_m_values = vm.events['V_m']
plt.figure(1)
-plt.plot(times[numpy.where(senders == 1)],
- V[numpy.where(senders == 1)], 'r-')
-plt.plot(times[numpy.where(senders == 2)],
- V[numpy.where(senders == 2)], 'g-')
+plt.plot(times[numpy.where(senders == 1)], v_m_values[numpy.where(senders == 1)], 'r-')
+plt.plot(times[numpy.where(senders == 2)], v_m_values[numpy.where(senders == 2)], 'g-')
plt.xlabel('time (ms)')
plt.ylabel('membrane potential (mV)')
plt.show()
diff --git a/pynest/examples/gif_cond_exp_multisynapse.py b/pynest/examples/gif_cond_exp_multisynapse.py
index 67fef6b0c8..d707d51260 100644
--- a/pynest/examples/gif_cond_exp_multisynapse.py
+++ b/pynest/examples/gif_cond_exp_multisynapse.py
@@ -20,12 +20,14 @@
# along with NEST. If not, see .
"""
-
gif_cond_exp_multisynapse
-+++++++++++++++++++++++++
+-------------------------
"""
+import nest
+import numpy as np
+
neuron = nest.Create('gif_cond_exp_multisynapse',
params={'E_rev': [0.0, -85.0],
'tau_syn': [4.0, 8.0]})
@@ -36,7 +38,7 @@
delays = [1., 30.]
w = [1., 5.]
for syn in range(2):
- nest.Connect(spike, neuron, syn_spec={'model': 'static_synapse',
+ nest.Connect(spike, neuron, syn_spec={'synapse_model': 'static_synapse',
'receptor_type': 1 + syn,
'weight': w[syn],
'delay': delays[syn]})
diff --git a/pynest/examples/gif_pop_psc_exp.py b/pynest/examples/gif_pop_psc_exp.py
index 7041dfed48..56a6813e4c 100644
--- a/pynest/examples/gif_pop_psc_exp.py
+++ b/pynest/examples/gif_pop_psc_exp.py
@@ -20,8 +20,9 @@
# along with NEST. If not, see .
-"""Population rate model of generalized integrate-and-fire neurons
---------------------------------------------------------------------
+"""
+Population rate model of generalized integrate-and-fire neurons
+---------------------------------------------------------------
This script simulates a finite network of generalized integrate-and-fire
(GIF) neurons directly on the mesoscopic population level using the effective
@@ -35,7 +36,7 @@
NEST model ``gif_psc_exp``.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Schwalger T, Degert M, Gerstner W (2017). Towards a theory of cortical columns: From spiking
neurons to interacting neural populations of finite size. PLoS Comput Biol.
@@ -121,7 +122,7 @@
nest.SetKernelStatus({'resolution': dt,
'print_time': True,
'local_num_threads': 1})
-t0 = nest.GetKernelStatus('time')
+t0 = nest.GetKernelStatus('biological_time')
nest_pops = nest.Create('gif_pop_psc_exp', M)
@@ -171,8 +172,7 @@
for i in range(M):
nest_sr.append(nest.Create('spike_recorder'))
nest_sr[i].time_in_steps = True
- nest.SetDefaults('static_synapse', {'weight': 1., 'delay': dt})
- nest.Connect(nest_pops[i], nest_sr[i])
+ nest.Connect(nest_pops[i], nest_sr[i], syn_spec={'weight': 1., 'delay': dt})
###############################################################################
# All neurons in a given population will be stimulated with a step input
@@ -191,7 +191,7 @@
origin=t0,
stop=t_end)
pop_ = nest_pops[i]
- nest.Connect(nest_stepcurrent[i], pop_, syn_spec={'weight': 1.})
+ nest.Connect(nest_stepcurrent[i], pop_, syn_spec={'weight': 1., 'delay': dt})
###############################################################################
# We can now start the simulation:
@@ -246,7 +246,7 @@
nest.ResetKernel()
nest.SetKernelStatus(
{'resolution': dt, 'print_time': True, 'local_num_threads': 1})
-t0 = nest.GetKernelStatus('time')
+t0 = nest.GetKernelStatus('biological_time')
nest_pops = []
for k in range(M):
@@ -303,7 +303,7 @@
nest_mm_Vm.append(nest.Create('multimeter'))
nest_mm_Vm[i].set(record_from=['V_m'], interval=dt_rec)
if Nrecord[i] != 0:
- nest.Connect(nest_mm_Vm[i], nest_i[:Nrecord[i]])
+ nest.Connect(nest_mm_Vm[i], nest_i[:Nrecord[i]], syn_spec={'weight': 1., 'delay': dt})
###############################################################################
# As before, all neurons in a given population will be stimulated with a
@@ -324,7 +324,7 @@
stop=t_end)
# optionally a stopping time may be added by: 'stop': sim_T + t0
pop_ = nest_pops[i]
- nest.Connect(nest_stepcurrent[i], pop_, syn_spec={'weight': 1.})
+ nest.Connect(nest_stepcurrent[i], pop_, syn_spec={'weight': 1., 'delay': dt})
###############################################################################
# We can now start the microscopic simulation:
diff --git a/pynest/examples/gif_population.py b/pynest/examples/gif_population.py
index 33f90b0425..43e6f11e05 100644
--- a/pynest/examples/gif_population.py
+++ b/pynest/examples/gif_population.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Population of GIF neuron model with oscillatory behavior
--------------------------------------------------------------
+"""
+Population of GIF neuron model with oscillatory behavior
+--------------------------------------------------------
This script simulates a population of generalized integrate-and-fire (GIF)
model neurons driven by noise from a group of Poisson generators.
@@ -32,7 +33,7 @@
Population dynamics are visualized by raster plot and as average firing rate.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Schwalger T, Degert M, Gerstner W (2017). Towards a theory of cortical columns: From spiking
neurons to interacting neural populations of finite size. PLoS Comput Biol.
diff --git a/pynest/examples/hh_phaseplane.py b/pynest/examples/hh_phaseplane.py
index e17473bed2..fa0dda03f8 100644
--- a/pynest/examples/hh_phaseplane.py
+++ b/pynest/examples/hh_phaseplane.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Numerical phase-plane analysis of the Hodgkin-Huxley neuron
-----------------------------------------------------------------
+"""
+Numerical phase-plane analysis of the Hodgkin-Huxley neuron
+-----------------------------------------------------------
hh_phaseplane makes a numerical phase-plane analysis of the Hodgkin-Huxley
neuron (``hh_psc_alpha``). Dynamics is investigated in the V-n space (see remark
@@ -28,7 +29,7 @@
can be studied.
Remark
-~~~~~~~~
+~~~~~~
To make the two-dimensional analysis possible, the (four-dimensional)
Hodgkin-Huxley formalism needs to be artificially reduced to two dimensions,
@@ -67,8 +68,8 @@
# Numerically obtain equilibrium state
nest.Simulate(1000)
-m_eq = neuron[0].Act_m
-h_eq = neuron[0].Inact_h
+m_eq = neuron.Act_m
+h_eq = neuron.Inact_h
neuron.I_e = amplitude # Apply external current
@@ -87,15 +88,15 @@
# Set V_m and n
neuron.set(V_m=V, Act_n=n, Act_m=m_eq, Inact_h=h_eq)
# Find state
- V_m = neuron[0].V_m
- Act_n = neuron[0].Act_n
+ V_m = neuron.V_m
+ Act_n = neuron.Act_n
# Simulate a short while
nest.Simulate(dt)
# Find difference between new state and old state
- V_m_new = neuron[0].V_m - V
- Act_n_new = neuron[0].Act_n - n
+ V_m_new = neuron.V_m - V
+ Act_n_new = neuron.Act_n - n
# Store in vector for later analysis
V_matrix[j, i] = abs(V_m_new)
@@ -120,16 +121,16 @@
# ap will contain the trace of a single action potential as one possible
# numerical solution in the vector field
ap = np.zeros([1000, 2])
-for i in range(1, 1001):
+for i in range(1000):
# Find state
- V_m = neuron[0].V_m
- Act_n = neuron[0].Act_n
+ V_m = neuron.V_m
+ Act_n = neuron.Act_n
if i % 10 == 0:
# Write new state next to old state
print('Vm: \t', V_m)
print('Act_n:', Act_n)
- ap[i - 1] = np.array([V_m, Act_n])
+ ap[i] = np.array([V_m, Act_n])
# Simulate again
neuron.set(Act_m=m_eq, Inact_h=h_eq)
diff --git a/pynest/examples/hh_psc_alpha.py b/pynest/examples/hh_psc_alpha.py
index f4ab507c54..3d79e079fa 100644
--- a/pynest/examples/hh_psc_alpha.py
+++ b/pynest/examples/hh_psc_alpha.py
@@ -19,14 +19,15 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Example using Hodgkin-Huxley neuron
-----------------------------------------
+"""
+Example using Hodgkin-Huxley neuron
+-----------------------------------
This example produces a rate-response (FI) curve of the Hodgkin-Huxley
neuron ``hh_psc_alpha`` in response to a range of different current (DC) stimulations.
The result is plotted using matplotlib.
-Since a DC input affetcs only the neuron's channel dynamics, this routine
+Since a DC input affects only the neuron's channel dynamics, this routine
does not yet check correctness of synaptic response.
"""
@@ -59,7 +60,7 @@
event_freqs = np.zeros(n_data)
for i, amp in enumerate(range(dcfrom, dcto, dcstep)):
neuron.I_e = float(amp)
- print("Simulating with current I={} pA".format(amp))
+ print(f"Simulating with current I={amp} pA")
nest.Simulate(1000) # one second warm-up time for equilibrium state
sr.n_events = 0 # then reset spike counts
nest.Simulate(simtime) # another simulation call to record firing rate
diff --git a/pynest/examples/hpc_benchmark.py b/pynest/examples/hpc_benchmark.py
index 8c83362a67..acc63b89d1 100644
--- a/pynest/examples/hpc_benchmark.py
+++ b/pynest/examples/hpc_benchmark.py
@@ -22,7 +22,7 @@
"""
Random balanced network HPC benchmark
---------------------------------------
+-------------------------------------
This script produces a balanced random network of `scale*11250` neurons in
which the excitatory-excitatory neurons exhibit STDP with
@@ -35,7 +35,7 @@
This is the standard network investigated in [1]_, [2]_, [3]_.
A note on scaling
-~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~
This benchmark was originally developed for very large-scale simulations on
supercomputers with more than 1 million neurons in the network and
@@ -61,7 +61,7 @@
per second.
References
-~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Morrison A, Aertsen A, Diesmann M (2007). Spike-timing-dependent
plasticity in balanced random networks. Neural Comput 19(6):1437-67
@@ -125,7 +125,7 @@ def convert_synapse_weight(tau_m, tau_syn, C_m):
return 1. / v_max
###############################################################################
-# For compatiblity with earlier benchmarks, we require a rise time of
+# For compatibility with earlier benchmarks, we require a rise time of
# ``t_rise = 1.700759 ms`` and we choose ``tau_syn`` to achieve this for given
# ``tau_m``. This requires numerical inversion of the expression for ``t_rise``
# in ``convert_synapse_weight``. We computed this value once and hard-code
@@ -212,13 +212,11 @@ def build_network(logger):
'resolution': params['dt'],
'overwrite_files': True})
- nest.SetDefaults('iaf_psc_alpha', model_params)
-
nest.message(M_INFO, 'build_network', 'Creating excitatory population.')
- E_neurons = nest.Create('iaf_psc_alpha', NE)
+ E_neurons = nest.Create('iaf_psc_alpha', NE, params=model_params)
nest.message(M_INFO, 'build_network', 'Creating inhibitory population.')
- I_neurons = nest.Create('iaf_psc_alpha', NI)
+ I_neurons = nest.Create('iaf_psc_alpha', NI, params=model_params)
if brunel_params['randomize_Vm']:
nest.message(M_INFO, 'build_network',
@@ -270,7 +268,6 @@ def build_network(logger):
tic = time.time()
nest.SetDefaults('static_synapse_hpc', {'delay': brunel_params['delay']})
- nest.CopyModel('static_synapse_hpc', 'syn_std')
nest.CopyModel('static_synapse_hpc', 'syn_ex',
{'weight': JE_pA})
nest.CopyModel('static_synapse_hpc', 'syn_in',
diff --git a/pynest/examples/if_curve.py b/pynest/examples/if_curve.py
index c5045a245f..5da1f690f2 100644
--- a/pynest/examples/if_curve.py
+++ b/pynest/examples/if_curve.py
@@ -19,14 +19,15 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""IF curve example
-----------------------
+"""
+IF curve example
+----------------
This example illustrates how to measure the I-F curve of a neuron.
The program creates a small group of neurons and injects a noisy current
:math:`I(t) = I_mean + I_std*W(t)`
where :math:`W(t)` is a white noise process.
-The programm systematically drives the current through a series of values in
+The program systematically drives the current through a series of values in
the two-dimensional `(I_mean, I_std)` space and measures the firing rate of
the neurons.
@@ -69,7 +70,7 @@ class IF_curve():
n_neurons = 100 # Number of neurons
n_threads = 4 # Nubmer of threads to run the simulation
- def __init__(self, model, params=False):
+ def __init__(self, model, params=None):
self.model = model
self.params = params
self.build()
@@ -84,12 +85,9 @@ def build(self):
nest.SetKernelStatus({'local_num_threads': self.n_threads})
#######################################################################
- # We set the default parameters of the neuron model to those
- # defined above and create neurons and devices.
+ # We create neurons and devices with specified parameters.
- if self.params:
- nest.SetDefaults(self.model, self.params)
- self.neuron = nest.Create(self.model, self.n_neurons)
+ self.neuron = nest.Create(self.model, self.n_neurons, self.params)
self.noise = nest.Create('noise_generator')
self.spike_recorder = nest.Create('spike_recorder')
diff --git a/pynest/examples/intrinsic_currents_spiking.py b/pynest/examples/intrinsic_currents_spiking.py
index ccde964bbd..79cc1e6642 100644
--- a/pynest/examples/intrinsic_currents_spiking.py
+++ b/pynest/examples/intrinsic_currents_spiking.py
@@ -20,8 +20,9 @@
# along with NEST. If not, see .
#
-"""Intrinsic currents spiking
--------------------------------
+"""
+Intrinsic currents spiking
+--------------------------
This example illustrates a neuron receiving spiking input through
several different receptors (AMPA, NMDA, GABA_A, GABA_B), provoking
@@ -34,14 +35,14 @@
respectively.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Hill and Tononi (2005) Modeling sleep and wakefulness in the
thalamocortical system. J Neurophysiol 93:1671
http://dx.doi.org/10.1152/jn.00915.2004.
See Also
-~~~~~~~~~~
+~~~~~~~~
:doc:`intrinsic_currents_subthreshold`
@@ -119,7 +120,7 @@
nest.Connect(p_gens[index], nrn, syn_spec={'receptor_type': receptors[rec_name], 'weight': rec_wgt})
###############################################################################
-# We then connnect the ``multimeter``. Note that the multimeter is connected to
+# We then connect the ``multimeter``. Note that the multimeter is connected to
# the neuron, not the other way around.
nest.Connect(mm, nrn)
@@ -134,8 +135,7 @@
# a dictionary with entry ``times`` containing timestamps for all
# recorded data, plus one entry per recorded quantity.
# All data is contained in the ``events`` entry of the status dictionary
-# returned by the multimeter. Because all NEST function return arrays,
-# we need to pick out element `0` from the result of ``GetStatus``.
+# returned by the multimeter.
data = mm.events
t = data['times']
diff --git a/pynest/examples/intrinsic_currents_subthreshold.py b/pynest/examples/intrinsic_currents_subthreshold.py
index a7eeb78561..7959128a06 100644
--- a/pynest/examples/intrinsic_currents_subthreshold.py
+++ b/pynest/examples/intrinsic_currents_subthreshold.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Intrinsic currents subthreshold
-------------------------------------
+"""
+Intrinsic currents subthreshold
+-------------------------------
This example illustrates how to record from a model with multiple
intrinsic currents and visualize the results. This is illustrated
@@ -33,14 +34,14 @@
intervals become increasingly longer.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Hill and Tononi (2005) Modeling Sleep and Wakefulness in the
Thalamocortical System J Neurophysiol 93:1671
http://dx.doi.org/10.1152/jn.00915.2004.
See Also
-~~~~~~~~~~
+~~~~~~~~
:doc:`intrinsic_currents_spiking`
@@ -142,8 +143,7 @@
# data, plus one entry per recorded quantity.
#
# All data is contained in the ``events`` entry of the status dictionary
-# returned by the multimeter. Because all NEST function return arrays,
-# we need to pick out element `0` from the result of ``GetStatus``.
+# returned by the multimeter.
data = mm.events
t = data['times']
@@ -181,7 +181,9 @@
for td, th in zip(t_dep, t_hyp):
t_prev = t_dc[-1]
- t_start_dep = t_prev + dt if t_prev > 0 else t_prev + dt + delay
+ t_start_dep = t_prev + dt
+ if t_prev == 0:
+ t_start_dep += delay
t_end_dep = t_start_dep + td
t_start_hyp = t_end_dep + dt
t_end_hyp = t_start_hyp + th
diff --git a/pynest/examples/lin_rate_ipn_network.py b/pynest/examples/lin_rate_ipn_network.py
index d792553605..e3e6c2957d 100644
--- a/pynest/examples/lin_rate_ipn_network.py
+++ b/pynest/examples/lin_rate_ipn_network.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Network of linear rate neurons
------------------------------------
+"""
+Network of linear rate neurons
+------------------------------
This script simulates an excitatory and an inhibitory population
of ``lin_rate_ipn`` neurons with delayed excitatory and instantaneous
@@ -44,9 +45,9 @@
# Definition of the number of neurons
order = 50
-NE = int(4 * order) # number of excitatory neurons
-NI = int(1 * order) # number of inhibitory neurons
-N = int(NE+NI) # total number of neurons
+NE = int(4 * order) # number of excitatory neurons
+NI = int(1 * order) # number of inhibitory neurons
+N = int(NE + NI) # total number of neurons
###############################################################################
# Definition of the connections
@@ -90,16 +91,11 @@
print("Building network")
-###############################################################################
-# Configuration of the neuron model using ``SetDefaults``.
-
-nest.SetDefaults(neuron_model, neuron_params)
-
###############################################################################
# Creation of the nodes using ``Create``.
-n_e = nest.Create(neuron_model, NE)
-n_i = nest.Create(neuron_model, NI)
+n_e = nest.Create(neuron_model, NE, neuron_params)
+n_i = nest.Create(neuron_model, NI, neuron_params)
################################################################################
@@ -132,7 +128,7 @@
###############################################################################
# Connect recording device to rate units
-nest.Connect(mm, n_e+n_i)
+nest.Connect(mm, n_e + n_i)
###############################################################################
# Simulate the network
@@ -143,9 +139,18 @@
# Plot rates of one excitatory and one inhibitory neuron
data = mm.events
-rate_ex = data['rate'][numpy.where(data['senders'] == n_e[0].global_id)]
-rate_in = data['rate'][numpy.where(data['senders'] == n_i[0].global_id)]
-times = data['times'][numpy.where(data['senders'] == n_e[0].global_id)]
+senders = data['senders']
+rate = data['rate']
+times = data['times']
+
+ne_0_id = n_e[0].global_id
+ni_0_id = n_i[0].global_id
+where_sender_is_ne_0 = numpy.where(senders == ne_0_id)
+where_sender_is_ni_0 = numpy.where(senders == ni_0_id)
+
+rate_ex = rate[where_sender_is_ne_0]
+rate_in = rate[where_sender_is_ni_0]
+times = times[where_sender_is_ne_0]
plt.figure()
plt.plot(times, rate_ex, label='excitatory')
diff --git a/pynest/examples/mc_neuron.py b/pynest/examples/mc_neuron.py
index 2cb69bc28c..1249661c20 100644
--- a/pynest/examples/mc_neuron.py
+++ b/pynest/examples/mc_neuron.py
@@ -54,31 +54,30 @@
syns = nest.GetDefaults('iaf_cond_alpha_mc')['receptor_types']
-print("iaf_cond_alpha_mc receptor_types: {0}".format(syns))
+print(f"iaf_cond_alpha_mc receptor_types: {syns}")
rqs = nest.GetDefaults('iaf_cond_alpha_mc')['recordables']
-print("iaf_cond_alpha_mc recordables : {0}".format(rqs))
+print(f"iaf_cond_alpha_mc recordables : {rqs}")
###############################################################################
# The simulation parameters are assigned to variables.
-nest.SetDefaults('iaf_cond_alpha_mc',
- {'V_th': -60.0, # threshold potential
- 'V_reset': -65.0, # reset potential
- 't_ref': 10.0, # refractory period
- 'g_sp': 5.0, # somato-proximal coupling conductance
- 'soma': {'g_L': 12.0}, # somatic leak conductance
- # proximal excitatory and inhibitory synaptic time constants
- 'proximal': {'tau_syn_ex': 1.0,
- 'tau_syn_in': 5.0},
- 'distal': {'C_m': 90.0} # distal capacitance
- })
+params = {'V_th': -60.0, # threshold potential
+ 'V_reset': -65.0, # reset potential
+ 't_ref': 10.0, # refractory period
+ 'g_sp': 5.0, # somato-proximal coupling conductance
+ 'soma': {'g_L': 12.0}, # somatic leak conductance
+ # proximal excitatory and inhibitory synaptic time constants
+ 'proximal': {'tau_syn_ex': 1.0,
+ 'tau_syn_in': 5.0},
+ 'distal': {'C_m': 90.0} # distal capacitance
+ }
###############################################################################
# The nodes are created using ``Create``. We store the returned handles
# in variables for later reference.
-n = nest.Create('iaf_cond_alpha_mc')
+n = nest.Create('iaf_cond_alpha_mc', params=params)
###############################################################################
# A ``multimeter`` is created and connected to the neurons. The parameters
@@ -139,7 +138,7 @@
###############################################################################
# Now we set the intrinsic current of soma to 150 pA to make the neuron spike.
-n.set({'soma': {'I_e': 150.}})
+n.soma = {'I_e': 150.}
###############################################################################
# We simulate the network for another 300 ms and retrieve recorded data from
diff --git a/pynest/examples/multimeter_file.py b/pynest/examples/multimeter_file.py
index 16792ec6ce..6155a5f981 100644
--- a/pynest/examples/multimeter_file.py
+++ b/pynest/examples/multimeter_file.py
@@ -62,7 +62,7 @@
nest.GetDefaults("iaf_cond_alpha")["recordables"]))
###############################################################################
-# A neuron, a multimeter as recording device and two spike generators for
+# A neuron, a multimeter as recording device, and two spike generators for
# excitatory and inhibitory stimulation are instantiated. The command ``Create``
# expects a model type and, optionally, the desired number of nodes and a
# dictionary of parameters to overwrite the default values of the model.
@@ -72,7 +72,7 @@
# (`V_reset`, in mV) are specified.
# * For the ``multimeter``, the time interval for recording (`interval`, in
# ms) and the measures to record (membrane potential `V_m` in mV and
-# excitatory and inhibitoy synaptic conductances `g_ex` and`g_in` in nS)
+# excitatory and inhibitory synaptic conductances `g_ex` and`g_in` in nS)
# are set.
#
# In addition, more parameters can be modified for writing to file:
@@ -101,7 +101,7 @@
params={"spike_times": numpy.array([15.0, 25.0, 55.0])})
###############################################################################
-# Next, We connect the spike generators to the neuron with ``Connect``. Synapse
+# Next, we connect the spike generators to the neuron with ``Connect``. Synapse
# specifications can be provided in a dictionary. In this example of a
# conductance-based neuron, the synaptic weight ``weight`` is given in nS.
# Note that the values are positive for excitatory stimulation and negative
@@ -120,12 +120,12 @@
# After the simulation, the recordings are obtained from the file the
# multimeter wrote to, accessed with the `filenames` property of the
# multimeter. After three header rows, the data is formatted in columns. The
-# first column is the ID of the sender node. The second column is the ID time
+# first column is the ID of the sender node. The second column is the time
# of the recording, in ms. Subsequent rows are values of properties specified
# in the `record_from` property of the multimeter.
data = numpy.loadtxt(m.filenames[0], skiprows=3)
-sender, t, v_m, g_in, g_ex = data.T
+sender, t, v_m, g_ex, g_in = data.T
###############################################################################
# Finally, the time courses of the membrane voltage and the synaptic
diff --git a/pynest/examples/music_cont_out_proxy_example/nest_script.py b/pynest/examples/music_cont_out_proxy_example/nest_script.py
index aa430102a0..4080c2cebe 100755
--- a/pynest/examples/music_cont_out_proxy_example/nest_script.py
+++ b/pynest/examples/music_cont_out_proxy_example/nest_script.py
@@ -33,8 +33,6 @@
"""
import nest
-import music
-import numpy
proxy = nest.Create('music_cont_out_proxy', 1)
proxy.port_name = 'out'
diff --git a/pynest/examples/music_cont_out_proxy_example/receiver_script.py b/pynest/examples/music_cont_out_proxy_example/receiver_script.py
index 1fb803a2fe..ababd44c02 100755
--- a/pynest/examples/music_cont_out_proxy_example/receiver_script.py
+++ b/pynest/examples/music_cont_out_proxy_example/receiver_script.py
@@ -52,6 +52,4 @@
times = takewhile(lambda t: t < maxtime, start)
for time in times:
val = data
- sys.stdout.write(
- "t={}\treceiver {}: received {}\n".
- format(time, rank, val))
+ sys.stdout.write(f"t={time}\treceiver {rank}: received {val}\n")
diff --git a/pynest/examples/one_neuron_with_noise.py b/pynest/examples/one_neuron_with_noise.py
index 51372541f5..1d3f5d13b4 100755
--- a/pynest/examples/one_neuron_with_noise.py
+++ b/pynest/examples/one_neuron_with_noise.py
@@ -21,7 +21,7 @@
"""
One neuron with noise
-----------------------
+---------------------
This script simulates a neuron with input from the ``poisson_generator``, and
records the neuron's membrane potential.
@@ -39,6 +39,7 @@
import nest
import nest.voltage_trace
+import matplotlib.pyplot as plt
nest.set_verbosity("M_WARNING")
nest.ResetKernel()
@@ -59,7 +60,8 @@
# not need to set parameters for the neuron and the voltmeter, since they have
# satisfactory defaults.
-noise.set([{"rate": 80000.0}, {"rate": 15000.0}])
+noise[0].rate = 80000.0
+noise[1].rate = 15000.0
###############################################################################
# Fourth, the neuron is connected to the ``poisson_generator`` and to the
@@ -79,4 +81,4 @@
# time.
nest.voltage_trace.from_device(voltmeter)
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/plot_weight_matrices.py b/pynest/examples/plot_weight_matrices.py
index 02bec7874f..4257fc06a4 100644
--- a/pynest/examples/plot_weight_matrices.py
+++ b/pynest/examples/plot_weight_matrices.py
@@ -66,15 +66,11 @@ def plot_weight_matrices(E_neurons, I_neurons):
a_EE = nest.GetConnections(E_neurons, E_neurons)
- '''
- Using `get`, we can extract the value of the connection weight,
- for all the connections between these populations
- '''
+ # Using `get`, we can extract the value of the connection weight,
+ # for all the connections between these populations
c_EE = a_EE.weight
- '''
- Repeat the two previous steps for all other connection types
- '''
+ # Repeat the two previous steps for all other connection types
a_EI = nest.GetConnections(I_neurons, E_neurons)
c_EI = a_EI.weight
a_IE = nest.GetConnections(E_neurons, I_neurons)
@@ -82,18 +78,16 @@ def plot_weight_matrices(E_neurons, I_neurons):
a_II = nest.GetConnections(I_neurons, I_neurons)
c_II = a_II.weight
- '''
- We now iterate through the range of all connections of each type.
- To populate the corresponding weight matrix, we begin by identifying
- the source-node_id (by using .source) and the target-node_id.
- For each node_id, we subtract the minimum node_id within the corresponding
- population, to assure the matrix indices range from 0 to the size of
- the population.
-
- After determining the matrix indices [i, j], for each connection
- object, the corresponding weight is added to the entry W[i,j].
- The procedure is then repeated for all the different connection types.
- '''
+ # We now iterate through the range of all connections of each type.
+ # To populate the corresponding weight matrix, we begin by identifying
+ # the source-node_id (by using .source) and the target-node_id.
+ # For each node_id, we subtract the minimum node_id within the corresponding
+ # population, to assure the matrix indices range from 0 to the size of
+ # the population.
+
+ # After determining the matrix indices [i, j], for each connection
+ # object, the corresponding weight is added to the entry W[i,j].
+ # The procedure is then repeated for all the different connection types.
a_EE_src = a_EE.source
a_EE_trg = a_EE.target
a_EI_src = a_EI.source
diff --git a/pynest/examples/precise_spiking.py b/pynest/examples/precise_spiking.py
index f0f869edfb..749cf3ad96 100644
--- a/pynest/examples/precise_spiking.py
+++ b/pynest/examples/precise_spiking.py
@@ -38,7 +38,7 @@
postsynaptic currents [2]_.
References
-~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Morrison A, Straube S, Plesser HE, Diesmann M. 2007. Exact subthreshold
integration with continuous spike times in discrete-time neural network
diff --git a/pynest/examples/pulsepacket.py b/pynest/examples/pulsepacket.py
index 9c51196967..a6c0a2c854 100755
--- a/pynest/examples/pulsepacket.py
+++ b/pynest/examples/pulsepacket.py
@@ -32,7 +32,7 @@
References
-~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Diesmann M. 2002. Dissertation. Conditions for stable propagation of
synchronous spiking in cortical neural networks: Single neuron dynamics
@@ -141,7 +141,7 @@ def find_loc_pspmax(tau_s, tau_m):
mu = 0.0
x = numpy.arange(-4 * sig, 4 * sig, Convolution_resolution)
term1 = 1 / (sig * numpy.sqrt(2 * numpy.pi))
-term2 = numpy.exp(-(x - mu) ** 2 / (sig ** 2 * 2))
+term2 = numpy.exp(-(x - mu)**2 / (sig**2 * 2))
gauss = term1 * term2 * Convolution_resolution
@@ -178,7 +178,7 @@ def find_loc_pspmax(tau_s, tau_m):
# simulation outcome. Therefore we need a time vector (`t_U`) with the correct
# temporal resolution, which places the excursion of the potential at the
# correct time.
-psp_norm = numpy.pad(psp_norm, [len(psp_norm) - 1, 1])
+psp_norm = numpy.pad(psp_norm, [len(psp_norm) - 1, 1], mode='constant')
U = a * psp_amp * numpy.convolve(gauss, psp_norm)
ulen = len(U)
t_U = (convolution_resolution * numpy.linspace(-ulen / 2., ulen / 2., ulen) +
@@ -222,14 +222,12 @@ def find_loc_pspmax(tau_s, tau_m):
}
ppgs = nest.Create('pulsepacket_generator', n_neurons, ppg_pars)
vm_pars = {'interval': sampling_resolution}
-vm = nest.Create('voltmeter', 1, vm_pars)
+vm = nest.Create('voltmeter', params=vm_pars)
###############################################################################
# Now, we connect each pulse generator to one neuron via static synapses.
-# We want to keep all properties of the static synapse constant except the
-# synaptic weight. Therefore we change the weight with the help of the command
-# ``SetDefaults``.
+# We use the default static synapse, with specified weight.
# The command ``Connect`` connects all kinds of nodes/devices. Since multiple
# nodes/devices can be connected in different ways e.g., each source connects
# to all targets, each source connects to a subset of targets or each source
@@ -238,9 +236,8 @@ def find_loc_pspmax(tau_s, tau_m):
# generator (source) to one neuron (target).
# In addition we also connect the `voltmeter` to the `neurons`.
-nest.SetDefaults('static_synapse', {'weight': weight})
-nest.Connect(ppgs, neurons, 'one_to_one')
-nest.Connect(vm, neurons)
+nest.Connect(ppgs, neurons, 'one_to_one', syn_spec={'weight': weight})
+nest.Connect(vm, neurons, syn_spec={'weight': weight})
###############################################################################
diff --git a/pynest/examples/rate_neuron_dm.py b/pynest/examples/rate_neuron_dm.py
index 8eba08b98a..9944003863 100644
--- a/pynest/examples/rate_neuron_dm.py
+++ b/pynest/examples/rate_neuron_dm.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Rate neuron decision making
-------------------------------------
+"""
+Rate neuron decision making
+---------------------------
A binary decision is implemented in the form of two rate neurons
engaging in mutual inhibition.
@@ -95,7 +96,7 @@ def build_network(sigma, dt):
dt = 1e-3
sigma = [0.0, 0.1, 0.2]
dE = [0.0, 0.004, 0.008]
-T = numpy.linspace(0, 200, 200 / dt - 1)
+T = numpy.linspace(0, 200, int(200/dt) - 1)
for i in range(9):
c = i % 3
r = int(i / 3)
diff --git a/pynest/examples/recording_demo.py b/pynest/examples/recording_demo.py
index de78d8a183..8933a8f5d1 100644
--- a/pynest/examples/recording_demo.py
+++ b/pynest/examples/recording_demo.py
@@ -19,7 +19,8 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Recording examples
+"""
+Recording examples
------------------
This script demonstrates how to select different recording backends
diff --git a/pynest/examples/repeated_stimulation.py b/pynest/examples/repeated_stimulation.py
index 9d0079598c..2260515108 100644
--- a/pynest/examples/repeated_stimulation.py
+++ b/pynest/examples/repeated_stimulation.py
@@ -41,7 +41,7 @@
###############################################################################
-# First, the modules needed for simulation and analyis are imported.
+# First, the modules needed for simulation and analysis are imported.
import nest
@@ -105,7 +105,7 @@
for n in range(num_trials):
- pg.origin = nest.GetKernelStatus('time')
+ pg.origin = nest.GetKernelStatus('biological_time')
nest.Simulate(trial_duration)
diff --git a/pynest/examples/sensitivity_to_perturbation.py b/pynest/examples/sensitivity_to_perturbation.py
index 3992466bef..e9ad94e109 100644
--- a/pynest/examples/sensitivity_to_perturbation.py
+++ b/pynest/examples/sensitivity_to_perturbation.py
@@ -24,7 +24,7 @@
---------------------------
This script simulates a network in two successive trials, which are identical
-except for one extra input spike in the second realisation (a small
+except for one extra input spike in the second realization (a small
perturbation). The network consists of recurrent, randomly connected excitatory
and inhibitory neurons. Its activity is driven by an external Poisson input
provided to all neurons independently. In order to ensure that the network is
@@ -34,7 +34,7 @@
- resetting the random network generator
- resetting the internal clock
- deleting all entries in the spike recorder
-- introducing a hyperpolarisation phase between the trials
+- introducing a hyperpolarization phase between the trials
(in order to avoid that spikes remaining in the NEST memory
after the first simulation are fed into the second simulation)
@@ -113,7 +113,7 @@
fade_out = 2. * delay # fade out time (ms)
dt = 0.01 # simulation time resolution (ms)
seed_NEST = 30 # seed of random number generator in Nest
-seed_numpy = 30 # seed of random number generator in numpy
+seed_numpy = 30 # seed of random number generator in NumPy
senders = []
spiketimes = []
@@ -153,10 +153,10 @@
# Afterwards we create a ``poisson_generator`` that provides spikes (the external
# input) to the neurons until time ``T`` is reached.
# Afterwards a ``dc_generator``, which is also connected to the whole population,
- # provides a stong hyperpolarisation step for a short time period ``fade_out``.
+ # provides a strong hyperpolarization step for a short time period ``fade_out``.
#
# The ``fade_out`` period has to last at least twice as long as the simulation
- # resolution to supress the neurons from firing.
+ # resolution to suppress the neurons from firing.
ext = nest.Create("poisson_generator",
params={'rate': rate_ext, 'stop': T})
@@ -183,7 +183,7 @@
# the simulation Kernel. In addition, we ensure that there is no spike left in
# the spike recorder.
- nest.SetKernelStatus({"rng_seed": seed_NEST, 'time': 0.0})
+ nest.SetKernelStatus({"rng_seed": seed_NEST, 'biological_time': 0.0})
spikerecorder.n_events = 0
# We assign random initial membrane potentials to all neurons
diff --git a/pynest/examples/sinusoidal_gamma_generator.py b/pynest/examples/sinusoidal_gamma_generator.py
index 268ec053e4..a96b9e3422 100644
--- a/pynest/examples/sinusoidal_gamma_generator.py
+++ b/pynest/examples/sinusoidal_gamma_generator.py
@@ -65,14 +65,16 @@
# (``spike_recorder``) and connect them to the generators using ``Connect``.
-g = nest.Create('sinusoidal_gamma_generator', n=2,
- params=[{'rate': 10000.0, 'amplitude': 5000.0,
- 'frequency': 10.0, 'phase': 0.0, 'order': 2.0},
- {'rate': 10000.0, 'amplitude': 5000.0,
- 'frequency': 10.0, 'phase': 0.0, 'order': 10.0}])
+num_nodes = 2
+g = nest.Create('sinusoidal_gamma_generator', n=num_nodes,
+ params={'rate': 10000.0,
+ 'amplitude': 5000.0,
+ 'frequency': 10.0,
+ 'phase': 0.0,
+ 'order': [2.0, 10.0]}) # note the syntax for different order parameter of the two nodes
-m = nest.Create('multimeter', 2, {'interval': 0.1, 'record_from': ['rate']})
-s = nest.Create('spike_recorder', 2)
+m = nest.Create('multimeter', num_nodes, {'interval': 0.1, 'record_from': ['rate']})
+s = nest.Create('spike_recorder', num_nodes)
nest.Connect(m, g, 'one_to_one')
nest.Connect(g, s, 'one_to_one')
@@ -81,27 +83,27 @@
###############################################################################
-# After simulating, the spikes are extracted from the ``spike_recorder`` using
-# ``GetStatus`` and plots are created with panels for the PST and ISI histograms.
+# After simulating, the spikes are extracted from the ``spike_recorder`` and
+# plots are created with panels for the PST and ISI histograms.
colors = ['b', 'g']
-for j in range(2):
+for j in range(num_nodes):
ev = m[j].events
t = ev['times']
r = ev['rate']
- sp = nest.GetStatus(s[j])[0]['events']['times']
+ spike_times = s[j].events['times']
plt.subplot(221)
- h, e = np.histogram(sp, bins=np.arange(0., 201., 5.))
+ h, e = np.histogram(spike_times, bins=np.arange(0., 201., 5.))
plt.plot(t, r, color=colors[j])
plt.step(e[:-1], h * 1000 / 5., color=colors[j], where='post')
plt.title('PST histogram and firing rates')
plt.ylabel('Spikes per second')
plt.subplot(223)
- plt.hist(np.diff(sp), bins=np.arange(0., 0.505, 0.01),
+ plt.hist(np.diff(spike_times), bins=np.arange(0., 0.505, 0.01),
histtype='step', color=colors[j])
plt.title('ISI histogram')
@@ -160,7 +162,7 @@
nest.Connect(p, s)
nest.Simulate(200)
-ev = s[0].events
+ev = s.events
plt.subplot(224)
plt.plot(ev['times'], ev['senders'] - min(ev['senders']), 'o')
plt.ylim([-0.5, 19.5])
@@ -268,13 +270,10 @@ def plot_hist(spikes):
seed=123, dt=dt)
plot_hist(spikes)
exp = np.zeros(int(steps))
-exp[:int(steps / 2)] = (40. +
- 40. * np.sin(np.arange(0, t / 1000. * np.pi * 10,
- t / 1000. * np.pi * 10. /
- (steps / 2))))
-exp[int(steps / 2):] = (40. + 20. * np.sin(np.arange(0, t / 1000. * np.pi * 10,
- t / 1000. * np.pi * 10. /
- (steps / 2)) + offset))
+exp[:int(steps / 2)] = (40. + 40. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 10, t / 1000. * np.pi * 10. / (steps / 2))))
+exp[int(steps / 2):] = (40. + 20. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 10, t / 1000. * np.pi * 10. / (steps / 2)) + offset))
plt.plot(exp, 'r')
plt.title('Rate Modulation: 40 -> 20')
@@ -294,12 +293,10 @@ def plot_hist(spikes):
seed=123, dt=dt)
plot_hist(spikes)
exp = np.zeros(int(steps))
-exp[:int(steps / 2)] = (20. + 20. * np.sin(np.arange(0, t / 1000. * np.pi * 10,
- t / 1000. * np.pi * 10. /
- (steps / 2))))
-exp[int(steps / 2):] = (50. + 50. * np.sin(np.arange(0, t / 1000. * np.pi * 10,
- t / 1000. * np.pi * 10. /
- (steps / 2)) + offset))
+exp[:int(steps / 2)] = (20. + 20. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 10, t / 1000. * np.pi * 10. / (steps / 2))))
+exp[int(steps / 2):] = (50. + 50. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 10, t / 1000. * np.pi * 10. / (steps / 2)) + offset))
plt.plot(exp, 'r')
plt.title('DC Rate and Rate Modulation: 20 -> 50')
plt.ylabel('Spikes per second')
@@ -320,9 +317,8 @@ def plot_hist(spikes):
plot_hist(spikes)
exp = np.zeros(int(steps))
exp[:int(steps / 2)] = 40. * np.ones(int(steps / 2))
-exp[int(steps / 2):] = (40. + 40. * np.sin(np.arange(0, t / 1000. * np.pi * 20,
- t / 1000. * np.pi * 20. /
- (steps / 2))))
+exp[int(steps / 2):] = (40. + 40. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 20, t / 1000. * np.pi * 20. / (steps / 2))))
plt.plot(exp, 'r')
plt.title('Rate Modulation: 0 -> 40')
plt.xlabel('Time [ms]')
@@ -344,13 +340,10 @@ def plot_hist(spikes):
plot_hist(spikes)
exp = np.zeros(int(steps))
-exp[:int(steps / 2)] = (60. + 60. * np.sin(np.arange(0, t / 1000. * np.pi * 10,
- t / 1000. * np.pi * 10. /
- (steps / 2))))
-exp[int(steps / 2):] = (60. + 60. * np.sin(np.arange(0, t / 1000. * np.pi * 10,
- t / 1000. * np.pi * 10. /
- (steps / 2)) +
- offset + np.pi))
+exp[:int(steps / 2)] = (60. + 60. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 10, t / 1000. * np.pi * 10. / (steps / 2))))
+exp[int(steps / 2):] = (60. + 60. * np.sin(np.arange(
+ 0, t / 1000. * np.pi * 10, t / 1000. * np.pi * 10. / (steps / 2)) + offset + np.pi))
plt.plot(exp, 'r')
plt.title('Modulation Phase: 0 -> Pi')
plt.xlabel('Time [ms]')
diff --git a/pynest/examples/sinusoidal_poisson_generator.py b/pynest/examples/sinusoidal_poisson_generator.py
index d638252a0f..0b38326ab5 100644
--- a/pynest/examples/sinusoidal_poisson_generator.py
+++ b/pynest/examples/sinusoidal_poisson_generator.py
@@ -56,18 +56,15 @@
nest.SetKernelStatus({'resolution': 0.01})
-g = nest.Create('sinusoidal_poisson_generator', n=2,
- params=[{'rate': 10000.0,
- 'amplitude': 5000.0,
- 'frequency': 10.0,
- 'phase': 0.0},
- {'rate': 0.0,
- 'amplitude': 10000.0,
- 'frequency': 5.0,
- 'phase': 90.0}])
-
-m = nest.Create('multimeter', 2, {'interval': 0.1, 'record_from': ['rate']})
-s = nest.Create('spike_recorder', 2)
+num_nodes = 2
+g = nest.Create('sinusoidal_poisson_generator', n=num_nodes,
+ params={'rate': [10000.0, 0.0],
+ 'amplitude': [5000.0, 10000.0],
+ 'frequency': [10.0, 5.0],
+ 'phase': [0.0, 90.0]})
+
+m = nest.Create('multimeter', num_nodes, {'interval': 0.1, 'record_from': ['rate']})
+s = nest.Create('spike_recorder', num_nodes)
nest.Connect(m, g, 'one_to_one')
nest.Connect(g, s, 'one_to_one')
@@ -76,28 +73,28 @@
###############################################################################
-# After simulating, the spikes are extracted from the ``spike_recorder`` using
-# ``GetStatus`` and plots are created with panels for the PST and ISI histograms.
+# After simulating, the spikes are extracted from the ``spike_recorder`` and
+# plots are created with panels for the PST and ISI histograms.
colors = ['b', 'g']
-for j in range(2):
+for j in range(num_nodes):
ev = m[j].events
t = ev['times']
r = ev['rate']
- sp = nest.GetStatus(s[j])[0]['events']['times']
+ spike_times = s[j].events['times']
plt.subplot(221)
- h, e = np.histogram(sp, bins=np.arange(0., 201., 5.))
+ h, e = np.histogram(spike_times, bins=np.arange(0., 201., 5.))
plt.plot(t, r, color=colors[j])
plt.step(e[:-1], h * 1000 / 5., color=colors[j], where='post')
plt.title('PST histogram and firing rates')
plt.ylabel('Spikes per second')
plt.subplot(223)
- plt.hist(np.diff(sp), bins=np.arange(0., 1.005, 0.02),
+ plt.hist(np.diff(spike_times), bins=np.arange(0., 1.005, 0.02),
histtype='step', color=colors[j])
plt.title('ISI histogram')
diff --git a/pynest/examples/spatial/grid_iaf_oc.py b/pynest/examples/spatial/grid_iaf_oc.py
index accbe63a13..a7f389f213 100644
--- a/pynest/examples/spatial/grid_iaf_oc.py
+++ b/pynest/examples/spatial/grid_iaf_oc.py
@@ -47,8 +47,8 @@
plt.axes().set_xticks(np.arange(-3.0, 3.1, 1.0))
plt.axes().set_yticks(np.arange(-3.0, 3.1, 1.0))
plt.grid(True)
- plt.xlabel('4 Columns, Extent: 1.5, Center: %.1f' % ctr[0])
- plt.ylabel('2 Rows, Extent: 1.0, Center: %.1f' % ctr[1])
+ plt.xlabel(f'4 Columns, Extent: 1.5, Center: {ctr[0]:.1f}')
+ plt.ylabel(f'2 Rows, Extent: 1.0, Center: {ctr[1]:.1f}')
plt.show()
# plt.savefig('grid_iaf_oc_{}_{}.png'.format(ctr[0], ctr[1]))
diff --git a/pynest/examples/structural_plasticity.py b/pynest/examples/structural_plasticity.py
index cb5e969747..5efc1a0c21 100644
--- a/pynest/examples/structural_plasticity.py
+++ b/pynest/examples/structural_plasticity.py
@@ -21,7 +21,8 @@
"""
Structural Plasticity example
-----------------------------------
+-----------------------------
+
This example shows a simple network of two populations where structural
plasticity is used. The network has 1000 neurons, 80% excitatory and
20% inhibitory. The simulation starts without any connectivity. A set of
@@ -34,7 +35,8 @@
in the network and the average calcium concentration in the neurons is created.
References
-~~~~~~~~~~~
+~~~~~~~~~~
+
.. [1] Butz, M., and van Ooyen, A. (2013). A simple rule for dendritic spine and axonal bouton formation can
account for cortical reorganization after focal retinal lesions. PLoS Comput. Biol. 9 (10), e1003259.
@@ -243,13 +245,11 @@ def connect_external_input(self):
nest.Connect(noise, self.nodes_i, 'all_to_all',
{'weight': self.psc_ext, 'delay': 1.0})
-
-####################################################################################
-# In order to save the amount of average calcium concentration in each
-# population through time we create the function ``record_ca``. Here we use the
-# ``GetStatus`` function to retrieve the value of `Ca` for every neuron in the
-# network and then store the average.
-
+ ####################################################################################
+ # In order to save the amount of average calcium concentration in each
+ # population through time we create the function ``record_ca``. Here we use
+ # the value of `Ca` for every neuron in the network and then
+ # store the average.
def record_ca(self):
ca_e = self.nodes_e.Ca, # Calcium concentration
self.mean_ca_e.append(numpy.mean(ca_e))
@@ -257,15 +257,12 @@ def record_ca(self):
ca_i = self.nodes_i.Ca, # Calcium concentration
self.mean_ca_i.append(numpy.mean(ca_i))
-
-####################################################################################
-# In order to save the state of the connectivity in the network through time
-# we create the function ``record_connectivity``. Here we use the ``GetStatus``
-# function to retrieve the number of connected pre-synaptic elements of each
-# neuron. The total amount of excitatory connections is equal to the total
-# amount of connected excitatory pre-synaptic elements. The same applies for
-# inhibitory connections.
-
+ ####################################################################################
+ # In order to save the state of the connectivity in the network through time
+ # we create the function ``record_connectivity``. Here we retrieve the number
+ # of connected pre-synaptic elements of each neuron. The total amount of
+ # excitatory connections is equal to the total amount of connected excitatory
+ # pre-synaptic elements. The same applies for inhibitory connections.
def record_connectivity(self):
syn_elems_e = self.nodes_e.synaptic_elements
syn_elems_i = self.nodes_i.synaptic_elements
@@ -274,11 +271,9 @@ def record_connectivity(self):
self.total_connections_i.append(sum(neuron['Axon_in']['z_connected']
for neuron in syn_elems_i))
-
-####################################################################################
-# We define a function to plot the recorded values
-# at the end of the simulation.
-
+ ####################################################################################
+ # We define a function to plot the recorded values
+ # at the end of the simulation.
def plot_data(self):
fig, ax1 = plt.subplots()
ax1.axhline(self.growth_curve_e_e['eps'],
@@ -303,14 +298,12 @@ def plot_data(self):
ax2.legend(loc=4)
plt.savefig('StructuralPlasticityExample.eps', format='eps')
-
-####################################################################################
-# It is time to specify how we want to perform the simulation. In this
-# function we first enable structural plasticity in the network and then we
-# simulate in steps. On each step we record the calcium concentration and the
-# connectivity. At the end of the simulation, the plot of connections and
-# calcium concentration through time is generated.
-
+ ####################################################################################
+ # It is time to specify how we want to perform the simulation. In this
+ # function we first enable structural plasticity in the network and then we
+ # simulate in steps. On each step we record the calcium concentration and the
+ # connectivity. At the end of the simulation, the plot of connections and
+ # calcium concentration through time is generated.
def simulate(self):
if nest.NumProcesses() > 1:
sys.exit("For simplicity, this example only works " +
@@ -333,7 +326,6 @@ def simulate(self):
# connect the external input and then simulate. Please note that as we are
# simulating 200 biological seconds in this example, it will take a few minutes
# to complete.
-
if __name__ == '__main__':
example = StructralPlasticityExample()
# Prepare simulation
diff --git a/pynest/examples/synapsecollection.py b/pynest/examples/synapsecollection.py
index bfeadd5f4b..bcefb6222d 100644
--- a/pynest/examples/synapsecollection.py
+++ b/pynest/examples/synapsecollection.py
@@ -20,6 +20,9 @@
# along with NEST. If not, see .
"""
+Synapse Collection usage example
+--------------------------------
+
Example script to show some of the possibilities of the SynapseCollection class. We
connect neurons, and get the SynapseCollection with a GetConnections call. To get
a better understanding of the connections, we plot the weights between the
@@ -35,7 +38,7 @@ def makeMatrix(sources, targets, weights):
"""
Returns a matrix with the weights between the source and target node_ids.
"""
- aa = np.zeros((max(sources)+1, max(targets)+1))
+ aa = np.zeros((max(sources) + 1, max(targets) + 1))
for src, trg, wght in zip(sources, targets, weights):
aa[src, trg] += wght
@@ -49,9 +52,9 @@ def plotMatrix(srcs, tgts, weights, title, pos):
"""
plt.subplot(pos)
plt.matshow(makeMatrix(srcs, tgts, weights), fignum=False)
- plt.xlim([min(tgts)-0.5, max(tgts)+0.5])
+ plt.xlim([min(tgts) - 0.5, max(tgts) + 0.5])
plt.xlabel('target')
- plt.ylim([max(srcs)+0.5, min(srcs)-0.5])
+ plt.ylim([max(srcs) + 0.5, min(srcs) - 0.5])
plt.ylabel('source')
plt.title(title)
plt.colorbar(fraction=0.046, pad=0.04)
@@ -83,7 +86,7 @@ def plotMatrix(srcs, tgts, weights, title, pos):
Add some weights to the connections, and plot the updated weight matrix.
"""
# We can set data of the connections with a simple set() call.
-w = [{'weight': x*1.0} for x in range(1, 11)]
+w = [{'weight': x * 1.0} for x in range(1, 11)]
conns.set(w)
weights = conns.weight
@@ -165,7 +168,7 @@ def plotMatrix(srcs, tgts, weights, title, pos):
# Get SynapseCollection consisting of the fixed_total_number connections, but set
# weight before plotting
conns = nest.GetConnections(nrns[5:10], nrns[:5])
-w = [{'weight': x*1.0} for x in range(1, 6)]
+w = [{'weight': x * 1.0} for x in range(1, 6)]
conns.set(w)
g = conns.get(['source', 'target', 'weight'])
srcs = g['source']
diff --git a/pynest/examples/testiaf.py b/pynest/examples/testiaf.py
index 1ddcb6ef61..027e7ce204 100755
--- a/pynest/examples/testiaf.py
+++ b/pynest/examples/testiaf.py
@@ -19,7 +19,8 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""IAF Neuron example
+"""
+IAF neuron example
------------------
A DC current is injected into the neuron using a current generator
@@ -78,7 +79,7 @@ def build_network(dt):
# voltage trace is plotted
for dt in [0.1, 0.5, 1.0]:
- print("Running simulation with dt=%.2f" % dt)
+ print(f"Running simulation with dt={dt:.2f}")
vm, sr = build_network(dt)
nest.Simulate(1000.0)
@@ -100,8 +101,8 @@ def build_network(dt):
###########################################################################
# Using the matplotlib library the voltage trace is plotted over time
- plt.plot(times, potentials, label="dt=%.2f" % dt)
- print(" Number of spikes: {0}".format(sr.n_events))
+ plt.plot(times, potentials, label=f"dt={dt:.2f}")
+ print(f" Number of spikes: {sr.n_events}")
###########################################################################
# Finally the axis are labelled and a legend is generated
diff --git a/pynest/examples/tsodyks_depressing.py b/pynest/examples/tsodyks_depressing.py
index 9851480532..276af41d09 100644
--- a/pynest/examples/tsodyks_depressing.py
+++ b/pynest/examples/tsodyks_depressing.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Tsodyks depressing example
---------------------------------
+"""
+Tsodyks depressing example
+--------------------------
This scripts simulates two neurons. One is driven with dc-input and
connected to the other one with a depressing Tsodyks synapse. The membrane
@@ -33,13 +34,13 @@
facilitating behavior.
References
-~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Tsodyks M, Pawelzik K, Markram H (1998). Neural networks with dynamic synapses. Neural
computation, http://dx.doi.org/10.1162/089976698300017502
See Also
-~~~~~~~~~~
+~~~~~~~~
:doc:`tsodyks_facilitating`
@@ -50,6 +51,7 @@
import nest
import nest.voltage_trace
+import matplotlib.pyplot as plt
from numpy import exp
###############################################################################
@@ -145,4 +147,4 @@
nest.Simulate(Tend)
nest.voltage_trace.from_device(volts)
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/tsodyks_facilitating.py b/pynest/examples/tsodyks_facilitating.py
index 691d0213fe..7bc8ab3935 100644
--- a/pynest/examples/tsodyks_facilitating.py
+++ b/pynest/examples/tsodyks_facilitating.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Tsodyks facilitating example
---------------------------------
+"""
+Tsodyks facilitating example
+----------------------------
This scripts simulates two neurons. One is driven with dc-input and
connected to the other one with a facilitating Tsodyks synapse. The
@@ -33,13 +34,13 @@
(Eq. 2.2), enabling a facilitating behavior.
References
-~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Tsodyks M, Pawelzik K, Markram H (1998). Neural networks with dynamic synapses. Neural
computation, http://dx.doi.org/10.1162/089976698300017502
See Also
-~~~~~~~~~~
+~~~~~~~~
:doc:`tsodyks_depressing`
"""
@@ -49,6 +50,7 @@
import nest
import nest.voltage_trace
+import matplotlib.pyplot as plt
from numpy import exp
###############################################################################
@@ -144,4 +146,4 @@
nest.Simulate(Tend)
nest.voltage_trace.from_device(volts)
-nest.voltage_trace.show()
+plt.show()
diff --git a/pynest/examples/twoneurons.py b/pynest/examples/twoneurons.py
index 95a3d63884..396600f327 100644
--- a/pynest/examples/twoneurons.py
+++ b/pynest/examples/twoneurons.py
@@ -19,8 +19,9 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Two neuron example
-----------------------------
+"""
+Two neuron example
+------------------
This script simulates two connected pre- and postsynaptic neurons.
The presynaptic neuron receives a constant external current,
diff --git a/pynest/examples/urbanczik_synapse_example.py b/pynest/examples/urbanczik_synapse_example.py
index 4537ea86fd..d2588824b8 100644
--- a/pynest/examples/urbanczik_synapse_example.py
+++ b/pynest/examples/urbanczik_synapse_example.py
@@ -19,59 +19,62 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-'''
+"""
Weight adaptation according to the Urbanczik-Senn plasticity
-------------------
+------------------------------------------------------------
This script demonstrates the learning in a compartmental neuron where the
dendritic synapses adapt their weight according to the plasticity rule by
-Urbanczik and Senn [1]. In this simple setup, a spike pattern of 200 poisson
+Urbanczik and Senn [1]_. In this simple setup, a spike pattern of 200 poisson
spike trains is repeatedly presented to a neuron that is composed of one
somatic and one dendritic compartment. At the same time, the somatic
conductances are activated to produce a time-varying matching potential.
After the learning, this signal is then reproreproduced by the membrane
-potential of the neuron. This script produces Fig. 1B in [1] but uses standard
+potential of the neuron. This script produces Fig. 1B in [1]_ but uses standard
units instead of the unitless quantities used in the paper.
-[1] R. Urbanczik, W. Senn (2014): Learning by the Dendritic Prediction of
- Somatic Spiking. Neuron, 81, 521-528.
-'''
+References
+~~~~~~~~~~
+
+.. [1] R. Urbanczik, W. Senn (2014): Learning by the Dendritic Prediction of
+ Somatic Spiking. Neuron, 81, 521-528.
+"""
import numpy as np
from matplotlib import pyplot as plt
import nest
def g_inh(amplitude, t_start, t_end):
- '''
+ """
returns weights for the spike generator that drives the inhibitory
somatic conductance.
- '''
+ """
return lambda t: np.piecewise(t, [(t >= t_start) & (t < t_end)],
[amplitude, 0.0])
def g_exc(amplitude, freq, offset, t_start, t_end):
- '''
+ """
returns weights for the spike generator that drives the excitatory
somatic conductance.
- '''
+ """
return lambda t: np.piecewise(t, [(t >= t_start) & (t < t_end)],
[lambda t: amplitude*np.sin(freq*t) + offset, 0.0])
def matching_potential(g_E, g_I, nrn_params):
- '''
+ """
returns the matching potential as a function of the somatic conductances.
- '''
+ """
E_E = nrn_params['soma']['E_ex']
E_I = nrn_params['soma']['E_in']
return (g_E*E_E + g_I*E_I) / (g_E + g_I)
def V_w_star(V_w, nrn_params):
- '''
+ """
returns the dendritic prediction of the somatic membrane potential.
- '''
+ """
g_D = nrn_params['g_sp']
g_L = nrn_params['soma']['g_L']
E_L = nrn_params['soma']['E_L']
@@ -79,9 +82,9 @@ def V_w_star(V_w, nrn_params):
def phi(U, nrn_params):
- '''
+ """
rate function of the soma
- '''
+ """
phi_max = nrn_params['phi_max']
k = nrn_params['rate_slope']
beta = nrn_params['beta']
@@ -90,19 +93,16 @@ def phi(U, nrn_params):
def h(U, nrn_params):
- '''
+ """
derivative of the rate function phi
- '''
- phi_max = nrn_params['phi_max']
+ """
k = nrn_params['rate_slope']
beta = nrn_params['beta']
theta = nrn_params['theta']
return 15.0*beta / (1.0 + np.exp(-beta*(theta - U)) / k)
-'''
-simulation params
-'''
+# simulation params
n_pattern_rep = 100 # number of repetitions of the spike pattern
pattern_duration = 200.0
t_start = 2.0*pattern_duration
@@ -112,9 +112,7 @@ def h(U, nrn_params):
resolution = 0.1
nest.SetKernelStatus({'resolution': resolution})
-'''
-neuron parameters
-'''
+# neuron parameters
nrn_model = 'pp_cond_exp_mc_urbanczik'
nrn_params = {
't_ref': 3.0, # refractory period
@@ -144,9 +142,7 @@ def h(U, nrn_params):
'theta': -55.0,
}
-'''
-synapse params
-'''
+# synapse params
syns = nest.GetDefaults(nrn_model)['receptor_types']
init_w = 0.3*nrn_params['dendritic']['C_m']
syn_params = {
@@ -159,7 +155,7 @@ def h(U, nrn_params):
'delay': resolution,
}
-'''
+"""
# in case you want to use the unitless quantities as in [1]:
# neuron params:
@@ -206,11 +202,9 @@ def h(U, nrn_params):
'Wmax': 3.0*nrn_params['dendritic']['g_L'],
'delay': resolution,
}
-'''
+"""
-'''
-somatic input
-'''
+# somatic input
ampl_exc = 0.016*nrn_params['dendritic']['C_m']
offset = 0.018*nrn_params['dendritic']['C_m']
ampl_inh = 0.06*nrn_params['dendritic']['C_m']
@@ -218,12 +212,10 @@ def h(U, nrn_params):
soma_exc_inp = g_exc(ampl_exc, 2.0*np.pi*freq, offset, t_start, t_end)
soma_inh_inp = g_inh(ampl_inh, t_start, t_end)
-'''
-dendritic input
-create spike pattern by recording the spikes of a simulation of n_pg
-poisson generators. The recorded spike times are then given to spike
-generators.
-'''
+# dendritic input
+# create spike pattern by recording the spikes of a simulation of n_pg
+# poisson generators. The recorded spike times are then given to spike
+# generators.
n_pg = 200 # number of poisson generators
p_rate = 10.0 # rate in Hz
@@ -237,19 +229,15 @@ def h(U, nrn_params):
nest.Connect(prrt_nrns_pg, sr, {'rule': 'one_to_one'})
nest.Simulate(pattern_duration)
-t_srs = []
-for i, ssr in enumerate(nest.GetStatus(sr)):
- t_sr = ssr['events']['times']
- t_srs.append(t_sr)
+t_srs = [ssr.get('events', 'times') for ssr in sr]
nest.ResetKernel()
nest.SetKernelStatus({'resolution': resolution})
-'''
+"""
neuron and devices
-'''
-nest.SetDefaults(nrn_model, nrn_params)
-nrn = nest.Create(nrn_model)
+"""
+nrn = nest.Create(nrn_model, params=nrn_params)
# poisson generators are connected to parrot neurons which are
# connected to the mc neuron
@@ -278,9 +266,8 @@ def h(U, nrn_params):
# for recording the spiking of the soma
sr_soma = nest.Create('spike_recorder')
-'''
-create connections
-'''
+
+# create connections
nest.Connect(sg_prox, prrt_nrns, {'rule': 'one_to_one'})
nest.CopyModel('urbanczik_synapse', 'urbanczik_synapse_wr',
{'weight_recorder': wr[0]})
@@ -292,9 +279,7 @@ def h(U, nrn_params):
syn_spec={'receptor_type': syns['soma_inh'], 'weight': 10.0*resolution, 'delay': resolution})
nest.Connect(nrn, sr_soma)
-'''
-simulation divided into intervals of the pattern duration
-'''
+# simulation divided into intervals of the pattern duration
for i in np.arange(n_rep_total):
# Set the spike times of the pattern for each spike generator
for (sg, t_sp) in zip(sg_prox, t_srs):
@@ -303,35 +288,33 @@ def h(U, nrn_params):
nest.Simulate(pattern_duration)
-'''
-read out devices
-'''
+
+# read out devices
+
# multimeter
-rec = nest.GetStatus(mm)[0]['events']
-t = rec['times']
-V_s = rec['V_m.s']
-V_d = rec['V_m.p']
+mm_events = mm.events
+t = mm_events['times']
+V_s = mm_events['V_m.s']
+V_d = mm_events['V_m.p']
V_d_star = V_w_star(V_d, nrn_params)
-g_in = rec['g_in.s']
-g_ex = rec['g_ex.s']
-I_ex = rec['I_ex.p']
-I_in = rec['I_in.p']
+g_in = mm_events['g_in.s']
+g_ex = mm_events['g_ex.s']
+I_ex = mm_events['I_ex.p']
+I_in = mm_events['I_in.p']
U_M = matching_potential(g_ex, g_in, nrn_params)
# weight recorder
-data = nest.GetStatus(wr)
-senders = data[0]['events']['senders']
-targets = data[0]['events']['targets']
-weights = data[0]['events']['weights']
-times = data[0]['events']['times']
+wr_events = wr.events
+senders = wr_events['senders']
+targets = wr_events['targets']
+weights = wr_events['weights']
+times = wr_events['times']
# spike recorder
-data = nest.GetStatus(sr_soma)[0]['events']
-spike_times_soma = data['times']
+spike_times_soma = sr_soma.get('events', 'times')
+
-'''
-plot results
-'''
+# plot results
fs = 22
lw = 2.5
fig1, (axA, axB, axC, axD) = plt.subplots(4, 1, sharex=True)
diff --git a/pynest/examples/vinit_example.py b/pynest/examples/vinit_example.py
index 675bbc1e96..aaf2d8a0eb 100755
--- a/pynest/examples/vinit_example.py
+++ b/pynest/examples/vinit_example.py
@@ -19,14 +19,15 @@
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see .
-"""Initial membrane voltage
-----------------------------
+"""
+Initial membrane voltage
+------------------------
Plot several runs of the ``iaf_cond_exp_sfa_rr`` neuron without input for various
initial values of the membrane potential.
References
-~~~~~~~~~~~~
+~~~~~~~~~~
.. [1] Dayan, P. and Abbott, L.F. (2001) Theoretical neuroscience,
MIT Press, page 166
@@ -60,19 +61,17 @@
# Then, a simulation with a duration of 75 ms is started with ``Simulate``.
#
# When the simulation has finished, the recorded times and membrane voltages
-# are read from the voltmeter via ``GetStatus`` where they can be accessed
-# through the key ``events`` of the status dictionary.
+# are read from the voltmeter via ``get``.
#
# Finally, the time course of the membrane voltages is plotted for each of
-# the different inital values.
+# the different initial values.
for vinit in numpy.arange(-100, -50, 10, float):
nest.ResetKernel()
cbn = nest.Create("iaf_cond_exp_sfa_rr")
-
- nest.SetStatus(cbn, "V_m", vinit)
+ cbn.V_m = vinit
voltmeter = nest.Create("voltmeter")
nest.Connect(voltmeter, cbn)
diff --git a/pynest/nest/tests/test_spatial/test_basics.py b/pynest/nest/tests/test_spatial/test_basics.py
index 3d40bca7ad..8065d86664 100644
--- a/pynest/nest/tests/test_spatial/test_basics.py
+++ b/pynest/nest/tests/test_spatial/test_basics.py
@@ -40,7 +40,7 @@ def test_create_layer(self):
shape = [5, 4]
nest.ResetKernel()
layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=shape))
- self.assertEqual(len(layer), shape[0] * shape[1])
+ self.assertEqual(len(layer), shape[0]*shape[1])
def test_create_layer_with_param(self):
"""Creating a layer with parameters."""
@@ -292,10 +292,10 @@ def test_GetCenterElement(self):
self.assertEqual(n, layer[4:5])
# new layer
- l2 = nest.Create('iaf_psc_alpha',
- positions=nest.spatial.grid(shape=[3, 3], extent=(2., 2.)))
- n = nest.FindCenterElement(l2)
- self.assertEqual(n, l2[4:5])
+ layer2 = nest.Create('iaf_psc_alpha',
+ positions=nest.spatial.grid(shape=[3, 3], extent=(2., 2.)))
+ n = nest.FindCenterElement(layer2)
+ self.assertEqual(n, layer2[4:5])
def test_GetTargetNodes(self):
"""Interface check for finding targets."""
diff --git a/pynest/nest/tests/test_spatial/test_plotting.py b/pynest/nest/tests/test_spatial/test_plotting.py
index 8fdbee0da5..96319b3b3c 100644
--- a/pynest/nest/tests/test_spatial/test_plotting.py
+++ b/pynest/nest/tests/test_spatial/test_plotting.py
@@ -33,7 +33,7 @@
tmp_fig = plt.figure() # make sure we can open a window; DISPLAY may not be set
plt.close(tmp_fig)
PLOTTING_POSSIBLE = True
-except:
+except ImportError:
PLOTTING_POSSIBLE = False
@@ -43,14 +43,14 @@ class PlottingTestCase(unittest.TestCase):
def test_PlotLayer(self):
"""Test plotting layer."""
nest.ResetKernel()
- l = nest.Create('iaf_psc_alpha',
- positions=nest.spatial.grid(shape=[3, 3],
- extent=[2., 2.],
- edge_wrap=True))
- nest.PlotLayer(l)
+ layer = nest.Create('iaf_psc_alpha',
+ positions=nest.spatial.grid(shape=[3, 3],
+ extent=[2., 2.],
+ edge_wrap=True))
+ nest.PlotLayer(layer)
plotted_datapoints = plt.gca().collections[-1].get_offsets().data
- reference_datapoints = nest.GetPosition(l)
+ reference_datapoints = nest.GetPosition(layer)
self.assertTrue(np.allclose(plotted_datapoints, reference_datapoints))
def test_PlotTargets(self):
@@ -61,26 +61,26 @@ def test_PlotTargets(self):
'mask': mask}
sdict = {'synapse_model': 'stdp_synapse'}
nest.ResetKernel()
- l = nest.Create('iaf_psc_alpha',
- positions=nest.spatial.grid(shape=[3, 3],
- extent=[2., 2.],
- edge_wrap=True))
+ layer = nest.Create('iaf_psc_alpha',
+ positions=nest.spatial.grid(shape=[3, 3],
+ extent=[2., 2.],
+ edge_wrap=True))
- # connect l -> l
- nest.Connect(l, l, cdict, sdict)
+ # connect layer -> layer
+ nest.Connect(layer, layer, cdict, sdict)
- ctr = nest.FindCenterElement(l)
- fig = nest.PlotTargets(ctr, l)
+ ctr = nest.FindCenterElement(layer)
+ fig = nest.PlotTargets(ctr, layer)
fig.gca().set_title('Plain call')
plotted_datapoints = plt.gca().collections[0].get_offsets().data
eps = 0.01
- pos = np.array(nest.GetPosition(l))
+ pos = np.array(nest.GetPosition(layer))
pos_xmask = pos[np.where(pos[:, 0] > -eps)]
reference_datapoints = pos_xmask[np.where(pos_xmask[:, 1] < eps)][::-1]
self.assertTrue(np.array_equal(np.sort(plotted_datapoints, axis=0), np.sort(reference_datapoints, axis=0)))
- fig = nest.PlotTargets(ctr, l, mask=mask)
+ fig = nest.PlotTargets(ctr, layer, mask=mask)
ax = fig.gca()
ax.set_title('Call with mask')
self.assertGreaterEqual(len(ax.patches), 1)
@@ -94,8 +94,8 @@ def test_plot_probability_kernel(self):
def probability_calculation(distance):
return 1 - 1.5*distance
- l = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([10, 10], edge_wrap=False))
- source = l[25]
+ layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([10, 10], edge_wrap=False))
+ source = layer[25]
source_pos = np.array(nest.GetPosition(source))
source_x, source_y = source_pos
@@ -124,10 +124,10 @@ def test_plot_probability_kernel_with_mask(self):
plot_shape = [10, 10]
plot_edges = [-0.5, 0.5, -0.5, 0.5]
- l = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([10, 10], edge_wrap=False))
+ layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid([10, 10], edge_wrap=False))
parameter = 1 - 1.5*nest.spatial.distance
- source = l[25]
+ source = layer[25]
masks = [{'circular': {'radius': 0.4}},
{'doughnut': {'inner_radius': 0.2, 'outer_radius': 0.45}},
{'rectangular': {'lower_left': [-.3, -.3], 'upper_right': [0.3, 0.3]}},
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000000..bd7db15c79
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,4 @@
+[pycodestyle]
+max-line-length = 120
+statistics = True
+; show-pep8 = True