├── .github └── workflows │ └── python_actions.yml ├── .gitignore ├── .pylintrc ├── .ratexcludes ├── CITATION.cff ├── LICENSE ├── LICENSE_POLICY.md ├── README.md ├── balanced_random ├── __init__.py ├── balanced_random.py └── split │ └── balanced_random_split.py ├── examples ├── __init__.py ├── current_injection_example.py ├── external_devices_examples │ ├── __init__.py │ ├── live_examples │ │ ├── __init__.py │ │ ├── balanced_random_live_rate.py │ │ ├── spike_io.colour_map │ │ ├── spike_io.py │ │ ├── spike_io_interactive_demo_with_c_vis.py │ │ ├── synfire_if_curr_exp_live.py │ │ └── synfire_live.colour_map │ ├── motor_example.py │ ├── pushbot_ethernet_example.py │ ├── pushbot_light_follower.py │ ├── pushbot_spinnaker_link_example.py │ └── retina_example.py ├── extra_models_examples │ ├── IF_cond_exp_stoc.py │ ├── IF_curr_delta.py │ ├── IF_curr_exp_ca2_adaptive.py │ ├── IF_curr_exp_sEMD.py │ ├── LGN_Izhikevich.py │ ├── __init__.py │ ├── stdp_associative_memory.py │ ├── stdp_example_izk_cond.py │ ├── stdp_triplet.py │ ├── synfire_if_curr_dual_exp.py │ └── vogel_2011 │ │ ├── .gitignore │ │ ├── __init__.py │ │ ├── spynnaker.cfg │ │ ├── vogels_2011.py │ │ ├── vogels_2011_live.col │ │ └── vogels_2011_live.py ├── hbp_neuroguidebook_example.py ├── if_curr_alpha.py ├── if_curr_delta.py ├── partitioner_examples │ ├── __init__.py │ └── splitter_usage.py ├── pynnBrunnel.py ├── simple_STDP.py ├── spike_time_compare.py ├── split_examples │ ├── pynnBrunnelSplit.py │ ├── stdp_neuromodulated_example_split.py │ ├── structural_plasticity_with_stdp_neuromodulated.py │ └── va_benchmark_split.py ├── stdp_curve.py ├── stdp_curve_cond.py ├── stdp_example.py ├── stdp_example_cond.py ├── stdp_example_get_plastic_params.py ├── stdp_example_izk.py ├── stdp_neuromodulated_example.py ├── stdp_neuromodulation_test.py ├── stdp_pairing.py ├── structural_plasticity_with_stdp_2d.py ├── structural_plasticity_with_stdp_neuromodulated_separate_pops.py ├── structural_plasticity_without_stdp_2d.py ├── synfire_if_cond_exp.py ├── synfire_if_curr_exp.py ├── synfire_if_curr_exp_get_weights.py ├── synfire_if_curr_exp_large_array.py ├── synfire_if_curr_exp_random.py ├── synfire_izk_curr_exp.py ├── va_benchmark.py └── wta_example.py ├── integration_tests ├── README.md ├── __init__.py ├── script_builder.py └── test_scripts.py ├── learning ├── __init__.py ├── random_dist.py ├── simple.py ├── split │ ├── stdp_split.py │ ├── struct_pl_split.py │ └── struct_pl_stdp_split.py ├── stdp.py ├── struct_pl.py └── struct_pl_stdp.py ├── pendulum ├── pendulum ├── pendulum_follow_c_vis.py ├── pendulum_follow_python_vis.py ├── spike_filter.py └── spynnaker.cfg ├── spiNNaker_start ├── .gitignore └── spinnaker_start.py ├── sudoku ├── __init__.py ├── libgcc_s_dw2-1.dll ├── libsqlite3-0.dll ├── pthreadGC2.dll ├── set_numbers.py ├── spynnaker.cfg ├── sudoku.exe ├── sudoku.png ├── sudoku_linux ├── sudoku_main.py ├── sudoku_osx └── utils.py ├── synfire ├── __init__.py ├── synfire.py └── synfire_collab.py └── unittests └── test_cfg_checker.py /.github/workflows/python_actions.yml: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # This workflow will install Python dependencies, run lint and rat with a variety of Python versions 16 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 17 | 18 | name: Python Actions 19 | on: [push] 20 | 21 | jobs: 22 | call: 23 | uses: SpiNNakerManchester/SupportScripts/.github/workflows/python_checks.yml@main 24 | with: 25 | dependencies: > 26 | SpiNNUtils SpiNNMachine SpiNNMan PACMAN spalloc 27 | SpiNNFrontEndCommon sPyNNaker 28 | install-module: false 29 | pip-installs: pytest 30 | ubuntu-packages: graphviz 31 | test-directories: unittests 32 | coverage-package: 33 | flake8-packages: examples balanced_random learning sudoku synfire 34 | pylint-packages: examples balanced_random learning sudoku synfire 35 | # invalid-name because scripts have values pylint considers constants 36 | # wrong-spelling-in-docstring due to param names ect 37 | pylint-disable: R, wrong-spelling-in-docstring, invalid-name 38 | # Examples are not typed to keep them easier to read 39 | mypy-packages: 40 | run-sphinx: false 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .settings/ 3 | .pydevproject 4 | *.pyc 5 | .idea/ 6 | __pycache__ 7 | .pytest_cache 8 | *application_generated_data_files/ 9 | *reports/ 10 | .cache/ 11 | .mypy_cache/ 12 | -------------------------------------------------------------------------------- /.ratexcludes: -------------------------------------------------------------------------------- 1 | **/*.colour_map 2 | **/*.col 3 | **/SpiNNUtils/** 4 | **/SpiNNMachine/** 5 | **/SpiNNMan/** 6 | **/PACMAN/** 7 | **/spalloc/** 8 | **/SpiNNFrontEndCommon/** 9 | **/sPyNNaker/** 10 | **/sPyNNaker8/** 11 | **/.pylintrc 12 | **/*.dll 13 | **/*.exe 14 | **/*.png 15 | **/*linux 16 | **/*osx 17 | **/*.exe 18 | **/.pylintrc -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | cff-version: 1.2.0 16 | message: If you use this software, please cite it as below. 17 | preferred-citation: 18 | type: article 19 | doi: 10.3389/fnins.2018.00816 20 | issn: 1662-453X 21 | url: https://www.frontiersin.org/articles/10.3389/fnins.2018.00816 22 | title: "sPyNNaker: A Software Package for Running PyNN Simulations on SpiNNaker" 23 | journal: Frontiers in Neuroscience 24 | volume: 12 25 | year: 2018 26 | month: 11 27 | abstract: This work presents sPyNNaker 4.0.0, the latest version of the software package for simulating PyNN-defined spiking neural networks (SNNs) on the SpiNNaker neuromorphic platform. Operations underpinning realtime SNN execution are presented, including an event-based operating system facilitating efficient time-driven neuron state updates and pipelined event-driven spike processing. Preprocessing, realtime execution, and neuron/synapse model implementations are discussed, all in the context of a simple example SNN. Simulation results are demonstrated, together with performance profiling providing insights into how software interacts with the underlying hardware to achieve realtime execution. System performance is shown to be within a factor of 2 of the original design target of 10,000 synaptic events per millisecond, however SNN topology is shown to influence performance considerably. A cost model is therefore developed characterizing the effect of network connectivity and SNN partitioning. This model enables users to estimate SNN simulation performance, allows the SpiNNaker team to make predictions on the impact of performance improvements, and helps demonstrate the continued potential of the SpiNNaker neuromorphic hardware. 28 | authors: 29 | - given-names: Oliver 30 | family-names: Rhodes 31 | affiliation: University Of Manchester 32 | orcid: https://orcid.org/0000-0003-1728-2828 33 | website: https://research.manchester.ac.uk/en/persons/oliver.rhodes 34 | - given-names: Petrut 35 | family-names: Bogdan 36 | affiliation: University Of Manchester 37 | orcid: https://orcid.org/0000-0001-5535-7865 38 | - given-names: Christian Y. 39 | family-names: Brenninkmeijer 40 | affiliation: University Of Manchester 41 | email: christian.brenninkmeijer@manchester.ac.uk 42 | orcid: https://orcid.org/0000-0002-2937-7819 43 | website: https://www.researchgate.net/profile/Christian_Brenninkmeijer 44 | - given-names: Simon 45 | family-names: Davidson 46 | affiliation: University Of Manchester 47 | orcid: https://orcid.org/0000-0001-5385-442X 48 | website: https://research.manchester.ac.uk/en/persons/simon.davidson 49 | - given-names: Donal 50 | family-names: Fellows 51 | affiliation: University Of Manchester 52 | orcid: https://orcid.org/0000-0002-9091-5938 53 | website: https://www.researchgate.net/profile/Donal-Fellows 54 | - given-names: Andrew 55 | family-names: Gait 56 | affiliation: University Of Manchester 57 | orcid: https://orcid.org/0000-0001-9349-1096 58 | website: https://personalpages.manchester.ac.uk/staff/andrew.gait/ 59 | - given-names: David R. 60 | family-names: Lester 61 | affiliation: University Of Manchester 62 | orcid: https://orcid.org/0000-0002-7267-291X 63 | - given-names: Mantas 64 | family-names: Mikaitis 65 | affiliation: University Of Manchester 66 | orcid: https://orcid.org/0000-0001-8706-1436 67 | website: https://research.manchester.ac.uk/en/persons/mantas.mikaitis 68 | - given-names: Luis A. 69 | family-names: Plana 70 | affiliation: University Of Manchester 71 | orcid: https://orcid.org/0000-0002-6113-3929 72 | website: https://research.manchester.ac.uk/en/persons/luis.plana 73 | - given-names: Andrew G. D. 74 | family-names: Rowley 75 | affiliation: University Of Manchester 76 | email: Andrew.Rowley@manchester.ac.uk 77 | orcid: https://orcid.org/0000-0002-2646-8520 78 | website: https://www.researchgate.net/profile/Andrew_Rowley2 79 | - given-names: Alan B. 80 | family-names: Stokes 81 | affiliation: University Of Manchester 82 | orcid: https://orcid.org/0000-0002-6110-1484 83 | - given-names: Steve B. 84 | family-names: Furber 85 | affiliation: University Of Manchester 86 | orcid: https://orcid.org/0000-0002-6524-3367 87 | website: https://research.manchester.ac.uk/en/persons/steve.furber 88 | 89 | title: This repository holds miscellaneous examples of using sPyNNaker for PyNN 90 | authors: 91 | - name: SpiNNaker Software Team 92 | alias: For a list of contributors see https://github.com/SpiNNakerManchester/PyNNExamples/graphs/contributors or for a combined list see https://spinnakermanchester.github.io/latest/LicenseAgreement.html#contributors 93 | address: University of Manchester, Oxford Road 94 | city: Manchester 95 | country: GB 96 | email: spinnakerusers@googlegroups.com 97 | post-code: M13 9PL 98 | website: https://apt.cs.manchester.ac.uk/projects/SpiNNaker/ 99 | url: https://spinnakermanchester.github.io/ 100 | contact: 101 | - address: University of Manchester, Oxford Road 102 | city: Manchester 103 | country: GB 104 | email: spinnakerusers@googlegroups.com 105 | name: SpiNNaker Software Team 106 | post-code: M13 9PL 107 | license: Apache-2.0 108 | repository: https://github.com/SpiNNakerManchester/PyNNExamples 109 | -------------------------------------------------------------------------------- /LICENSE_POLICY.md: -------------------------------------------------------------------------------- 1 | # License Agreement 2 | 3 | Up to date information for the whole [SpiNNakerManchester Projects](https://github.com/SpiNNakerManchester) can be found [here](https://spinnakermanchester.github.io/latest/LicenseAgreement.html) 4 | 5 | As shown there the software is currently being released under the Apache License 2.0 listed [here](https://www.apache.org/licenses/LICENSE-2.0) 6 | 7 | 8 | # Paper Authorship 9 | 10 | See: [here](https://spinnakermanchester.github.io/latest/LicenseAgreement.html#paper-authorship) 11 | 12 | # Modifications 13 | 14 | See: [here](https://spinnakermanchester.github.io/latest/LicenseAgreement.html#modifications) 15 | 16 | # Contributors 17 | 18 | For up to date information on Contributors see the graphs/contributors pages on each project. 19 | 20 | For example [https://github.com/SpiNNakerManchester/PyNNExamples/graphs/contributors](https://github.com/SpiNNakerManchester/PyNN8Examples/graphs/contributors) 21 | 22 | [Combined list](https://spinnakermanchester.github.io/latest/LicenseAgreement.html#contributors) 23 | 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/SpiNNakerManchester/PyNNExamples.svg?branch=master)](https://travis-ci.org/SpiNNakerManchester/PyNNExamples) 2 | 3 | Examples for PyNN 4 | ================= 5 | 6 | This repository holds miscellaneous examples of using sPyNNaker for PyNN 7 | 8 | See Also 9 | -------- 10 | * [SpiNNaker online documentation](http://spinnakermanchester.github.io/) 11 | * [sPyNNakerGithub](/SpiNNakerManchester/sPyNNaker) for the implementation 12 | * [Combined python documentation](http://spinnakermanchester.readthedocs.io) 13 | * [PyNN documentation](http://neuralensemble.org/docs/PyNN) 14 | -------------------------------------------------------------------------------- /balanced_random/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /balanced_random/balanced_random.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as pylab 16 | import numpy 17 | from pyNN.random import RandomDistribution 18 | from pyNN.utility.plotting import Figure, Panel 19 | import pyNN.spiNNaker as p 20 | 21 | p.setup(timestep=0.1) 22 | p.set_number_of_neurons_per_core(p.IF_curr_exp, 64) 23 | p.set_number_of_neurons_per_core(p.SpikeSourcePoisson, 64) 24 | n_neurons = 500 25 | n_exc = int(round(n_neurons * 0.8)) 26 | n_inh = int(round(n_neurons * 0.2)) 27 | weight_exc = 0.1 28 | weight_inh = -5.0 * weight_exc 29 | weight_input = 0.001 30 | 31 | pop_input = p.Population(100, p.SpikeSourcePoisson(rate=0.0), 32 | additional_parameters={ 33 | "max_rate": 50.0, 34 | "seed": 0}, 35 | label="Input") 36 | 37 | pop_exc = p.Population(n_exc, p.IF_curr_exp, label="Excitatory", seed=1) 38 | pop_inh = p.Population(n_inh, p.IF_curr_exp, label="Inhibitory", seed=2) 39 | stim_exc = p.Population( 40 | n_exc, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Exc", 41 | additional_parameters={"seed": 3}) 42 | stim_inh = p.Population( 43 | n_inh, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Inh", 44 | additional_parameters={"seed": 4}) 45 | 46 | delays_exc = RandomDistribution( 47 | "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=1.6) 48 | weights_exc = RandomDistribution( 49 | "normal_clipped", mu=weight_exc, sigma=0.1, low=0, high=numpy.inf) 50 | conn_exc = p.FixedProbabilityConnector(0.1) 51 | synapse_exc = p.StaticSynapse(weight=weights_exc, delay=delays_exc) 52 | delays_inh = RandomDistribution( 53 | "normal_clipped", mu=0.75, sigma=0.375, low=1.0, high=1.6) 54 | weights_inh = RandomDistribution( 55 | "normal_clipped", mu=weight_inh, sigma=0.1, low=-numpy.inf, high=0) 56 | conn_inh = p.FixedProbabilityConnector(0.1) 57 | synapse_inh = p.StaticSynapse(weight=weights_inh, delay=delays_inh) 58 | p.Projection( 59 | pop_exc, pop_exc, conn_exc, synapse_exc, receptor_type="excitatory") 60 | p.Projection( 61 | pop_exc, pop_inh, conn_exc, synapse_exc, receptor_type="excitatory") 62 | p.Projection( 63 | pop_inh, pop_inh, conn_inh, synapse_inh, receptor_type="inhibitory") 64 | p.Projection( 65 | pop_inh, pop_exc, conn_inh, synapse_inh, receptor_type="inhibitory") 66 | 67 | conn_stim = p.OneToOneConnector() 68 | synapse_stim = p.StaticSynapse(weight=weight_exc, delay=1.0) 69 | p.Projection( 70 | stim_exc, pop_exc, conn_stim, synapse_stim, receptor_type="excitatory") 71 | p.Projection( 72 | stim_inh, pop_inh, conn_stim, synapse_stim, receptor_type="excitatory") 73 | 74 | delays_input = RandomDistribution( 75 | "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=1.6) 76 | weights_input = RandomDistribution( 77 | "normal_clipped", mu=weight_input, sigma=0.01, low=0, high=numpy.inf) 78 | p.Projection(pop_input, pop_exc, p.AllToAllConnector(), p.StaticSynapse( 79 | weight=weights_input, delay=delays_input)) 80 | 81 | pop_exc.initialize( 82 | v=RandomDistribution("uniform", low=-65.0, high=-55.0)) 83 | pop_inh.initialize( 84 | v=RandomDistribution("uniform", low=-65.0, high=-55.0)) 85 | 86 | pop_exc.record("spikes") 87 | 88 | p.run(1000) 89 | 90 | pop_input.set(rate=50.0) 91 | p.run(1000) 92 | 93 | pop_input.set(rate=10.0) 94 | p.run(1000) 95 | 96 | pop_input.set(rate=20.0) 97 | p.run(1000) 98 | 99 | data = pop_exc.get_data("spikes") 100 | end_time = p.get_current_time() 101 | 102 | p.end() 103 | 104 | Figure( 105 | # raster plot of the presynaptic neuron spike times 106 | Panel(data.segments[0].spiketrains, 107 | yticks=True, markersize=2.0, xlim=(0, end_time)), 108 | title="Balanced Random Network", 109 | annotations=f"Simulated with {p.name()}" 110 | ) 111 | pylab.show() 112 | -------------------------------------------------------------------------------- /balanced_random/split/balanced_random_split.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import pylab 16 | import numpy 17 | from pyNN.random import RandomDistribution 18 | from pyNN.utility.plotting import Figure, Panel 19 | import pyNN.spiNNaker as p 20 | 21 | p.setup(timestep=0.1) 22 | p.set_number_of_neurons_per_core(p.IF_curr_exp, 64) 23 | p.set_number_of_neurons_per_core(p.SpikeSourcePoisson, 64) 24 | n_neurons = 500 25 | n_exc = int(round(n_neurons * 0.8)) 26 | n_inh = int(round(n_neurons * 0.2)) 27 | weight_exc = 0.1 28 | weight_inh = -5.0 * weight_exc 29 | weight_input = 0.001 30 | 31 | pop_input = p.Population( 32 | 100, p.SpikeSourcePoisson(rate=0.0), label="Input", seed=0, max_rate=50.0) 33 | 34 | pop_exc = p.Population(n_exc, p.IF_curr_exp, label="Excitatory", seed=1) 35 | pop_inh = p.Population(n_inh, p.IF_curr_exp, label="Inhibitory", seed=2) 36 | stim_exc = p.Population( 37 | n_exc, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Exc", seed=3) 38 | stim_inh = p.Population( 39 | n_inh, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Inh", seed=4) 40 | 41 | delays_exc = RandomDistribution( 42 | "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=1.6) 43 | weights_exc = RandomDistribution( 44 | "normal_clipped", mu=weight_exc, sigma=0.1, low=0, high=numpy.inf) 45 | conn_exc = p.FixedProbabilityConnector(0.1) 46 | synapse_exc = p.StaticSynapse(weight=weights_exc, delay=delays_exc) 47 | delays_inh = RandomDistribution( 48 | "normal_clipped", mu=0.75, sigma=0.375, low=1.0, high=1.6) 49 | weights_inh = RandomDistribution( 50 | "normal_clipped", mu=weight_inh, sigma=0.1, low=-numpy.inf, high=0) 51 | conn_inh = p.FixedProbabilityConnector(0.1) 52 | synapse_inh = p.StaticSynapse(weight=weights_inh, delay=delays_inh) 53 | p.Projection( 54 | pop_exc, pop_exc, conn_exc, synapse_exc, receptor_type="excitatory", 55 | label="exc_exc") 56 | p.Projection( 57 | pop_exc, pop_inh, conn_exc, synapse_exc, receptor_type="excitatory", 58 | label="exc_inh") 59 | p.Projection( 60 | pop_inh, pop_inh, conn_inh, synapse_inh, receptor_type="inhibitory", 61 | label="inh_inh") 62 | p.Projection( 63 | pop_inh, pop_exc, conn_inh, synapse_inh, receptor_type="inhibitory", 64 | label="inh_exc") 65 | 66 | conn_stim = p.OneToOneConnector() 67 | synapse_stim = p.StaticSynapse(weight=weight_exc, delay=1.0) 68 | p.Projection( 69 | stim_exc, pop_exc, conn_stim, synapse_stim, receptor_type="excitatory", 70 | label="stim_exc_exc") 71 | p.Projection( 72 | stim_inh, pop_inh, conn_stim, synapse_stim, receptor_type="excitatory", 73 | label="stim_inh_inh") 74 | 75 | delays_input = RandomDistribution( 76 | "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=1.6) 77 | weights_input = RandomDistribution( 78 | "normal_clipped", mu=weight_input, sigma=0.01, low=0, high=numpy.inf) 79 | p.Projection(pop_input, pop_exc, p.AllToAllConnector(), p.StaticSynapse( 80 | weight=weights_input, delay=delays_input), 81 | label="input_exc") 82 | 83 | pop_exc.initialize( 84 | v=RandomDistribution("uniform", low=-65.0, high=-55.0)) 85 | pop_inh.initialize( 86 | v=RandomDistribution("uniform", low=-65.0, high=-55.0)) 87 | 88 | pop_exc.record("spikes") 89 | 90 | p.run(1000) 91 | 92 | pop_input.set(rate=50.0) 93 | p.run(1000) 94 | 95 | pop_input.set(rate=10.0) 96 | p.run(1000) 97 | 98 | pop_input.set(rate=20.0) 99 | p.run(1000) 100 | 101 | data = pop_exc.get_data("spikes") 102 | end_time = p.get_current_time() 103 | 104 | p.end() 105 | 106 | Figure( 107 | # raster plot of the presynaptic neuron spike times 108 | Panel(data.segments[0].spiketrains, 109 | yticks=True, markersize=2.0, xlim=(0, end_time)), 110 | title="Balanced Random Network", 111 | annotations=f"Simulated with {p.name()}" 112 | ) 113 | pylab.show() 114 | -------------------------------------------------------------------------------- /examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /examples/current_injection_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Injecting time-varying current into a cell. 17 | 18 | There are four "standard" current sources in PyNN: 19 | 20 | - DCSource 21 | - ACSource 22 | - StepCurrentSource 23 | - NoisyCurrentSource 24 | 25 | Any other current waveforms could be implemented using StepCurrentSource. 26 | 27 | Script from 28 | https://neuralensemble.org/docs/PyNN/examples/current_injection.html 29 | 30 | """ 31 | 32 | import pyNN.spiNNaker as sim 33 | from pyNN.utility.plotting import Figure, Panel 34 | import matplotlib.pyplot as plt 35 | from quantities import mV 36 | 37 | sim.setup(timestep=1.0) 38 | 39 | # === Create four cells and inject current into each one ===================== 40 | cells = sim.Population(4, sim.IF_curr_exp( 41 | v_thresh=-55.0, tau_refrac=5.0, tau_m=10.0)) 42 | 43 | current_sources = [sim.DCSource(amplitude=0.5, start=50.0, stop=400.0), 44 | sim.StepCurrentSource(times=[50.0, 210.0, 250.0, 410.0], 45 | amplitudes=[0.4, 0.6, -0.2, 0.2]), 46 | sim.ACSource(start=50.0, stop=450.0, amplitude=0.2, 47 | offset=0.1, frequency=10.0, phase=180.0), 48 | sim.NoisyCurrentSource(mean=0.5, stdev=0.2, start=50.0, 49 | stop=450.0, dt=1.0)] 50 | 51 | for cell, current_source in zip(cells, current_sources): 52 | cell.inject(current_source) 53 | 54 | cells.record('v') 55 | 56 | # === Run the simulation ===================================================== 57 | sim.run(500.0) 58 | 59 | 60 | # === Save the results, optionally plot a figure ============================= 61 | vm = cells.get_data().segments[0].filter(name="v")[0] 62 | sim.end() 63 | 64 | Figure( 65 | Panel(vm, y_offset=-10 * mV, xticks=True, yticks=True, 66 | xlabel="Time (ms)", ylabel="Membrane potential (mV)", 67 | ylim=(-96, -59)), 68 | title="Current injection example", 69 | annotations=f"Simulated with {sim.name()}" 70 | ) 71 | 72 | plt.show() 73 | -------------------------------------------------------------------------------- /examples/external_devices_examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /examples/external_devices_examples/live_examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /examples/external_devices_examples/live_examples/balanced_random_live_rate.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import time 16 | import numpy 17 | import pylab 18 | import pyNN.spiNNaker as p 19 | from pyNN.random import RandomDistribution 20 | from pyNN.utility.plotting import Figure, Panel 21 | 22 | # We need a time scale factor here as we are interacting live, so too fast 23 | # otherwise! 24 | p.setup(timestep=0.1, time_scale_factor=10.0) 25 | p.set_number_of_neurons_per_core(p.SpikeSourcePoisson, 50) 26 | n_neurons = 500 27 | n_exc = int(round(n_neurons * 0.8)) 28 | n_inh = int(round(n_neurons * 0.2)) 29 | weight_exc = 0.1 30 | weight_inh = -5.0 * weight_exc 31 | weight_input = 0.001 32 | 33 | pop_input = p.Population(100, p.SpikeSourcePoisson(rate=0), label="Input") 34 | 35 | pop_exc = p.Population(n_exc, p.IF_curr_exp, label="Excitatory", 36 | additional_parameters={"spikes_per_second": 100}) 37 | pop_inh = p.Population(n_inh, p.IF_curr_exp, label="Inhibitory", 38 | additional_parameters={"spikes_per_second": 100}) 39 | stim_exc = p.Population( 40 | n_exc, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Exc") 41 | stim_inh = p.Population( 42 | n_inh, p.SpikeSourcePoisson(rate=1000.0), label="Stim_Inh") 43 | 44 | rng = p.NumpyRNG() 45 | delays_exc = RandomDistribution( 46 | "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=14.4, rng=rng) 47 | weights_exc = RandomDistribution( 48 | "normal_clipped", mu=weight_exc, sigma=0.1, low=0, high=numpy.inf, rng=rng) 49 | conn_exc = p.FixedProbabilityConnector(0.1, rng=rng) 50 | synapse_exc = p.StaticSynapse(weight=weights_exc, delay=delays_exc) 51 | delays_inh = RandomDistribution( 52 | "normal_clipped", mu=0.75, sigma=0.375, low=1.0, high=14.4, rng=rng) 53 | weights_inh = RandomDistribution( 54 | "normal_clipped", mu=weight_inh, sigma=0.1, low=-numpy.inf, high=0, 55 | rng=rng) 56 | conn_inh = p.FixedProbabilityConnector(0.1, rng=rng) 57 | synapse_inh = p.StaticSynapse(weight=weights_inh, delay=delays_inh) 58 | p.Projection( 59 | pop_exc, pop_exc, conn_exc, synapse_exc, receptor_type="excitatory") 60 | p.Projection( 61 | pop_exc, pop_inh, conn_exc, synapse_exc, receptor_type="excitatory") 62 | p.Projection( 63 | pop_inh, pop_inh, conn_inh, synapse_inh, receptor_type="inhibitory") 64 | p.Projection( 65 | pop_inh, pop_exc, conn_inh, synapse_inh, receptor_type="inhibitory") 66 | 67 | conn_stim = p.OneToOneConnector() 68 | synapse_stim = p.StaticSynapse(weight=weight_exc, delay=1.0) 69 | p.Projection( 70 | stim_exc, pop_exc, conn_stim, synapse_stim, receptor_type="excitatory") 71 | p.Projection( 72 | stim_inh, pop_inh, conn_stim, synapse_stim, receptor_type="excitatory") 73 | 74 | delays_input = RandomDistribution( 75 | "normal_clipped", mu=1.5, sigma=0.75, low=1.0, high=14.4, rng=rng) 76 | weights_input = RandomDistribution( 77 | "normal_clipped", mu=weight_input, sigma=0.01, low=0, high=numpy.inf, 78 | rng=rng) 79 | p.Projection(pop_input, pop_exc, p.AllToAllConnector(), p.StaticSynapse( 80 | weight=weights_input, delay=delays_input)) 81 | 82 | pop_exc.initialize( 83 | v=RandomDistribution("uniform", low=-65.0, high=-55.0, rng=rng)) 84 | pop_inh.initialize( 85 | v=RandomDistribution("uniform", low=-65.0, high=-55.0, rng=rng)) 86 | 87 | pop_exc.record("spikes") 88 | 89 | poisson_control = p.external_devices.SpynnakerPoissonControlConnection( 90 | poisson_labels=[pop_input.label], local_port=None) 91 | 92 | p.external_devices.add_poisson_live_rate_control( 93 | pop_input, database_notify_port_num=poisson_control.local_port) 94 | 95 | 96 | def start_callback(label, connection): 97 | """ 98 | Changes the connection rate very 10 seconds 99 | 100 | :param str label: 101 | :param SpynnakerPoissonControlConnection connection: 102 | """ 103 | for rate in [50, 10, 20]: 104 | time.sleep(10.0) 105 | connection.set_rates(label, [(i, rate) for i in range(100)]) 106 | 107 | 108 | print(pop_input.label) 109 | poisson_control.add_start_resume_callback(pop_input.label, start_callback) 110 | 111 | p.run(5000) 112 | 113 | data = pop_exc.get_data("spikes") 114 | end_time = p.get_current_time() 115 | 116 | p.end() 117 | 118 | Figure( 119 | # raster plot of the presynaptic neuron spike times 120 | Panel(data.segments[0].spiketrains, 121 | yticks=True, markersize=2.0, xlim=(0, end_time)), 122 | title="Balanced Random Network", 123 | annotations=f"Simulated with {p.name()}" 124 | ) 125 | pylab.show() 126 | -------------------------------------------------------------------------------- /examples/external_devices_examples/live_examples/spike_io.colour_map: -------------------------------------------------------------------------------- 1 | pop_forward 255 0 0 2 | pop_backward 0 0 255 3 | -------------------------------------------------------------------------------- /examples/external_devices_examples/live_examples/synfire_if_curr_exp_live.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Standard PyNN imports 16 | import pyNN.spiNNaker as p 17 | 18 | # pynn plotting stuff 19 | from pyNN.utility.plotting import Figure, Panel 20 | import matplotlib.pyplot as plt 21 | 22 | # Define a synfire chain as usual 23 | p.setup(timestep=1.0, min_delay=1.0) 24 | nNeurons = 200 # number of neurons in each population 25 | p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) 26 | 27 | cell_params_lif = {'cm': 0.25, 28 | 'i_offset': 0.0, 29 | 'tau_m': 20.0, 30 | 'tau_refrac': 2.0, 31 | 'tau_syn_E': 5.0, 32 | 'tau_syn_I': 5.0, 33 | 'v_reset': -70.0, 34 | 'v_rest': -65.0, 35 | 'v_thresh': -50.0 36 | } 37 | 38 | populations = list() 39 | projections = list() 40 | 41 | weight_to_spike = 2.0 42 | delay = 17 43 | 44 | loopConnections = list() 45 | for i in range(0, nNeurons): 46 | singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay) 47 | loopConnections.append(singleConnection) 48 | 49 | injectionConnection = [(0, 0, weight_to_spike, 1)] 50 | spikeArray = {'spike_times': [[0]]} 51 | populations.append(p.Population( 52 | nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1')) 53 | populations.append( 54 | p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) 55 | 56 | projections.append(p.Projection(populations[0], populations[0], 57 | p.FromListConnector(loopConnections))) 58 | projections.append(p.Projection(populations[1], populations[0], 59 | p.FromListConnector(injectionConnection))) 60 | 61 | populations[0].record('spikes') 62 | 63 | # Activate live output for the population 64 | p.external_devices.activate_live_output_for( 65 | populations[0], database_notify_host="localhost", 66 | database_notify_port_num=19999) 67 | 68 | # Start the simulation 69 | p.run(5000) 70 | 71 | spikes = populations[0].get_data("spikes") 72 | 73 | Figure( 74 | # raster plot of the presynaptic neuron spike times 75 | Panel(spikes.segments[0].spiketrains, 76 | yticks=True, markersize=0.2, xlim=(0, 5000)), 77 | title="Simple synfire chain example with injected spikes", 78 | annotations=f"Simulated with {p.name()}" 79 | ) 80 | plt.show() 81 | 82 | p.end() 83 | -------------------------------------------------------------------------------- /examples/external_devices_examples/live_examples/synfire_live.colour_map: -------------------------------------------------------------------------------- 1 | pop_1 255 0 0 2 | -------------------------------------------------------------------------------- /examples/external_devices_examples/motor_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | motor example that just feeds data to the motor pop which starts the motor 17 | going forward 18 | """ 19 | 20 | import pyNN.spiNNaker as p 21 | 22 | # set up the tools 23 | p.setup(timestep=1.0, min_delay=1.0) 24 | 25 | # set up the virtual chip coordinates for the motor 26 | connected_chip_coords = {'x': 0, 'y': 0} 27 | link = 4 28 | 29 | populations = list() 30 | projections = list() 31 | 32 | 33 | input_population = p.Population(6, p.SpikeSourcePoisson(rate=10)) 34 | control_population = p.Population(6, p.IF_curr_exp()) 35 | motor_device = p.Population( 36 | 6, p.external_devices.MunichMotorDevice(spinnaker_link_id=0)) 37 | 38 | p.Projection( 39 | input_population, control_population, p.OneToOneConnector(), 40 | synapse_type=p.StaticSynapse(weight=5.0)) 41 | 42 | p.external_devices.activate_live_output_to(control_population, motor_device) 43 | 44 | p.run(1000) 45 | p.end() 46 | -------------------------------------------------------------------------------- /examples/external_devices_examples/pushbot_ethernet_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import pyNN.spiNNaker as p 16 | 17 | p.setup(1.0) 18 | 19 | # Set up the PushBot devices 20 | pushbot_protocol = p.external_devices.MunichIoSpiNNakerLinkProtocol( 21 | mode=p.external_devices.protocols.MUNICH_MODES.PUSH_BOT, uart_id=0) 22 | motor_0 = p.external_devices.PushBotEthernetMotorDevice( 23 | p.external_devices.PushBotMotor.MOTOR_0_PERMANENT, pushbot_protocol) 24 | motor_1 = p.external_devices.PushBotEthernetMotorDevice( 25 | p.external_devices.PushBotMotor.MOTOR_1_PERMANENT, pushbot_protocol) 26 | speaker = p.external_devices.PushBotEthernetSpeakerDevice( 27 | p.external_devices.PushBotSpeaker.SPEAKER_TONE, pushbot_protocol) 28 | laser = p.external_devices.PushBotEthernetLaserDevice( 29 | p.external_devices.PushBotLaser.LASER_ACTIVE_TIME, pushbot_protocol, 30 | start_total_period=1000) 31 | led_front = p.external_devices.PushBotEthernetLEDDevice( 32 | p.external_devices.PushBotLED.LED_FRONT_ACTIVE_TIME, pushbot_protocol, 33 | start_total_period=1000) 34 | led_back = p.external_devices.PushBotEthernetLEDDevice( 35 | p.external_devices.PushBotLED.LED_BACK_ACTIVE_TIME, pushbot_protocol, 36 | start_total_period=1000) 37 | 38 | weights = { 39 | motor_0: 10.0, 40 | motor_1: 10.0, 41 | speaker: 100.0, 42 | laser: 100.0, 43 | led_front: 100.0, 44 | led_back: 100.0, 45 | } 46 | 47 | devices = [motor_0, motor_1, speaker, laser, led_front, led_back] 48 | 49 | # Set up the PushBot control 50 | pushbot = p.external_devices.EthernetControlPopulation( 51 | len(devices), p.external_devices.PushBotLifEthernet( 52 | protocol=pushbot_protocol, 53 | devices=devices, 54 | pushbot_ip_address="10.10.10.1", 55 | pushbot_port=3000, 56 | # "pushbot_ip_address": "127.0.0.1", 57 | tau_syn_E=500.0), 58 | label="PushBot" 59 | ) 60 | 61 | # Send in some spikes 62 | stimulation = p.Population( 63 | len(devices), p.SpikeSourceArray( 64 | spike_times=[[i * 1000] for i in range(len(devices))]), 65 | label="input" 66 | ) 67 | 68 | connections = [ 69 | (i, i, weights[device], 1) for i, device in enumerate(devices) 70 | ] 71 | p.Projection(stimulation, pushbot, p.FromListConnector(connections)) 72 | 73 | retina_resolution = \ 74 | p.external_devices.PushBotRetinaResolution.DOWNSAMPLE_64_X_64 75 | pushbot_retina = p.external_devices.EthernetSensorPopulation( 76 | p.external_devices.PushBotEthernetRetinaDevice( 77 | protocol=pushbot_protocol, 78 | resolution=retina_resolution, 79 | pushbot_ip_address="10.10.10.1", 80 | pushbot_port=3000, 81 | retina_injector_label="Retina" 82 | )) 83 | 84 | retina_viewer = p.external_devices.PushBotRetinaViewer( 85 | retina_resolution, pushbot_retina.label) 86 | p.external_devices.activate_live_output_for( 87 | pushbot_retina, database_notify_port_num=retina_viewer.port) 88 | 89 | retina_viewer.run(len(devices) * 1000) 90 | -------------------------------------------------------------------------------- /examples/external_devices_examples/pushbot_light_follower.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | ########################################### 16 | # Import libraries 17 | ############################################ 18 | import numpy 19 | import pyNN.spiNNaker as p 20 | 21 | 22 | ########################################### 23 | # Connection and simulation specifications 24 | ########################################### 25 | 26 | # The UART port on IO Board the pushbot connected to 27 | UART_ID = 0 28 | 29 | # SpiNNaker link ID (IO Board connected to) 30 | spinnaker_link = 0 31 | 32 | # Retina resolution 33 | retina_resolution = \ 34 | p.external_devices.PushBotRetinaResolution.NATIVE_128_X_128 35 | 36 | # Number of machine vertices. We divide the retina into eight and then also 37 | # into polarity. 38 | n_machine_vertices = retina_resolution.value.pixels * 16 39 | 40 | # Name to call the retina 41 | retina_label = "Retina" 42 | 43 | retina_viewer = p.external_devices.PushBotRetinaViewer( 44 | retina_resolution, retina_label) 45 | 46 | # Simulate with 1 ms time step 47 | p.setup(1.0) 48 | p.set_number_of_neurons_per_core(p.IF_curr_exp, 1) 49 | 50 | 51 | ########################################### 52 | # Create external devices 53 | ########################################### 54 | # Create the pushbot protocols to pass to the devices of Pushbot 55 | # (i.e. motors, laser, etc) 56 | pushbot_protocol = p.external_devices.MunichIoSpiNNakerLinkProtocol( 57 | mode=p.external_devices.protocols.MUNICH_MODES.PUSH_BOT, 58 | uart_id=UART_ID) 59 | 60 | # Create motor devices on SpiNNaker 61 | motor_0 = p.external_devices.PushBotSpiNNakerLinkMotorDevice( 62 | p.external_devices.PushBotMotor.MOTOR_0_PERMANENT, pushbot_protocol, 63 | spinnaker_link) 64 | 65 | motor_1 = p.external_devices.PushBotSpiNNakerLinkMotorDevice( 66 | p.external_devices.PushBotMotor.MOTOR_1_PERMANENT, pushbot_protocol, 67 | spinnaker_link) 68 | 69 | # Create retina device on SpiNNaker 70 | retina_device = p.external_devices.PushBotSpiNNakerLinkRetinaDevice( 71 | spinnaker_link_id=spinnaker_link, 72 | protocol=pushbot_protocol, 73 | resolution=retina_resolution, 74 | n_machine_vertices=n_machine_vertices) 75 | 76 | # Motor devices for connection 77 | devices = [motor_0, motor_1] 78 | 79 | ########################################### 80 | # Create populations 81 | ########################################### 82 | 83 | # Retina population ( number of neurons:n_pixel*n_pixel*2 ) 84 | pushbot_retina = p.Population( 85 | retina_resolution.value.n_neurons, retina_device, label=retina_label) 86 | p.external_devices.activate_live_output_for( 87 | pushbot_retina, database_notify_port_num=retina_viewer.port) 88 | 89 | # A conceptual neuron population to drive motor neurons 90 | # (0: left, 1:right) 91 | driver_pop = p.Population(2, p.IF_curr_exp(), label='driver') 92 | 93 | ########################################### 94 | # Connections lists 95 | ########################################### 96 | 97 | # Connection from exc_pop to driver_pop 98 | # Number of columns to separate for left, right and forward 99 | n_conn = 3 * (retina_resolution.value.pixels / 8) 100 | 101 | # The events coming from the specified columns of exc_pop population 102 | # will be connected to the relevant neuron in driver_pop 103 | # Starting column of the left-side column group 104 | start_of_left = 0 105 | 106 | # Last column of the left-side column group 107 | end_of_left = n_conn 108 | 109 | # Starting column of the right-side column group 110 | start_of_right = retina_resolution.value.pixels - n_conn 111 | 112 | # Last column of the right-side column group 113 | end_of_right = retina_resolution.value.pixels 114 | 115 | # Connection weights for this connection list 116 | w_conn = 0.2 117 | 118 | # Connection delays for this connection list 119 | d_conn = 1 120 | 121 | # Array containing id of each neuron 122 | arr = numpy.arange(retina_resolution.value.n_neurons / 2) 123 | 124 | # Determines which neuron IDs are on the left group 125 | id_to_left = (arr % retina_resolution.value.pixels) < end_of_left 126 | 127 | # Determines which neuron IDs are on the right group 128 | id_to_right = (arr % retina_resolution.value.pixels) >= start_of_right 129 | 130 | # Extracts the neuron IDs to be connected to the left neuron of driver_pop 131 | id_to_left = numpy.extract(id_to_left, arr) 132 | print("left =", id_to_left) 133 | 134 | # Extracts the neuron IDs to be connected to the right neuron of driver_pop 135 | id_to_right = numpy.extract(id_to_right, arr) 136 | print("right =", id_to_right) 137 | 138 | # Connection list: (source neuron, target neuron, weight, delay) 139 | # Creates connection list to connect left neuron 140 | conn_list_left = [(i, 0, w_conn, d_conn) for i in id_to_left] 141 | 142 | # Creates connection list to connect right neuron 143 | conn_list_right = [(i, 1, w_conn, d_conn) for i in id_to_right] 144 | 145 | # Winner-takes-all connections from driver_pop to motor neurons 146 | w_motor = 1 147 | conn_motor_exc = [(0, 1, w_motor, 1), (1, 0, w_motor, 1)] 148 | conn_motor_inh = [(0, 0, w_motor, 1), (1, 1, w_motor, 1)] 149 | 150 | 151 | ########################################### 152 | # Projections 153 | ########################################### 154 | 155 | # w_inh=90.#70 156 | 157 | # Pushbot motor neuron population 158 | # Each member of population is a LIF neuron without a threshold 159 | pushbot = p.Population( 160 | len(devices), p.external_devices.PushBotLifSpinnakerLink( 161 | protocol=pushbot_protocol, 162 | devices=devices, 163 | tau_syn_E=5.0, tau_syn_I=5.0), 164 | label="PushBot" 165 | ) 166 | 167 | p.Projection( 168 | pushbot_retina, driver_pop, 169 | p.FromListConnector(conn_list_left + conn_list_right)) 170 | p.Projection( 171 | driver_pop, pushbot, p.FromListConnector(conn_motor_exc), 172 | receptor_type='excitatory') 173 | p.Projection( 174 | driver_pop, pushbot, p.FromListConnector(conn_motor_inh), 175 | receptor_type='inhibitory') 176 | 177 | 178 | ########################################### 179 | # Simulation 180 | ########################################### 181 | 182 | # Record spikes and membrane potentials 183 | # driver_pop.record(['spikes','v']) 184 | 185 | retina_viewer.run_until_closed() 186 | -------------------------------------------------------------------------------- /examples/external_devices_examples/pushbot_spinnaker_link_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import pyNN.spiNNaker as p 15 | 16 | p.setup(1.0) 17 | 18 | # Set up the PushBot devices 19 | pushbot_protocol = p.external_devices.MunichIoSpiNNakerLinkProtocol( 20 | mode=p.external_devices.protocols.MUNICH_MODES.PUSH_BOT, uart_id=0) 21 | spinnaker_link = 0 22 | motor_0 = p.external_devices.PushBotSpiNNakerLinkMotorDevice( 23 | p.external_devices.PushBotMotor.MOTOR_0_PERMANENT, pushbot_protocol, 24 | spinnaker_link) 25 | motor_1 = p.external_devices.PushBotSpiNNakerLinkMotorDevice( 26 | p.external_devices.PushBotMotor.MOTOR_1_PERMANENT, pushbot_protocol, 27 | spinnaker_link) 28 | speaker = p.external_devices.PushBotSpiNNakerLinkSpeakerDevice( 29 | p.external_devices.PushBotSpeaker.SPEAKER_TONE, pushbot_protocol, 30 | spinnaker_link) 31 | laser = p.external_devices.PushBotSpiNNakerLinkLaserDevice( 32 | p.external_devices.PushBotLaser.LASER_ACTIVE_TIME, pushbot_protocol, 33 | spinnaker_link, start_total_period=1000) 34 | led_front = p.external_devices.PushBotSpiNNakerLinkLEDDevice( 35 | p.external_devices.PushBotLED.LED_FRONT_ACTIVE_TIME, pushbot_protocol, 36 | spinnaker_link, start_total_period=1000) 37 | led_back = p.external_devices.PushBotSpiNNakerLinkLEDDevice( 38 | p.external_devices.PushBotLED.LED_BACK_ACTIVE_TIME, pushbot_protocol, 39 | spinnaker_link, start_total_period=1000) 40 | 41 | weights = { 42 | motor_0: 10.0, 43 | motor_1: 10.0, 44 | speaker: 100.0, 45 | laser: 100.0, 46 | led_front: 100.0, 47 | led_back: 100.0, 48 | } 49 | 50 | devices = [motor_0, motor_1, speaker, laser, led_front, led_back] 51 | 52 | # Set up the PushBot control 53 | pushbot = p.Population( 54 | len(devices), p.external_devices.PushBotLifSpinnakerLink( 55 | protocol=pushbot_protocol, 56 | devices=devices, 57 | tau_syn_E=500.0), 58 | label="PushBot" 59 | ) 60 | 61 | # Send in some spikes 62 | stimulation = p.Population( 63 | len(devices), p.SpikeSourceArray( 64 | spike_times=[[i * 1000] for i in range(len(devices))]), 65 | label="input" 66 | ) 67 | 68 | connections = [ 69 | (i, i, weights[device], 1) for i, device in enumerate(devices) 70 | ] 71 | p.Projection(stimulation, pushbot, p.FromListConnector(connections)) 72 | 73 | retina_resolution = \ 74 | p.external_devices.PushBotRetinaResolution.DOWNSAMPLE_64_X_64 75 | pushbot_retina = p.Population( 76 | retina_resolution.value.n_neurons, 77 | p.external_devices.PushBotSpiNNakerLinkRetinaDevice( 78 | spinnaker_link_id=spinnaker_link, 79 | protocol=pushbot_protocol, 80 | resolution=retina_resolution), 81 | label="Retina") 82 | 83 | retina_viewer = p.external_devices.PushBotRetinaViewer( 84 | retina_resolution, pushbot_retina.label) 85 | p.external_devices.activate_live_output_for( 86 | pushbot_retina, database_notify_port_num=retina_viewer.port) 87 | 88 | retina_viewer.run(len(devices) * 1000) 89 | -------------------------------------------------------------------------------- /examples/external_devices_examples/retina_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | retina example that just feeds data from a retina to live output via an 17 | intermediate population 18 | """ 19 | import pyNN.spiNNaker as p 20 | 21 | connected_chip_details = { 22 | "spinnaker_link_id": 0, 23 | } 24 | 25 | 26 | def get_updated_params(params): 27 | """ 28 | Adds extra values to the params 29 | 30 | :param dict params: 31 | """ 32 | params.update(connected_chip_details) 33 | return params 34 | 35 | 36 | # Setup 37 | p.setup(timestep=1.0) 38 | 39 | # FPGA Retina - Down Polarity 40 | retina_pop = p.Population( 41 | None, p.external_devices.ExternalFPGARetinaDevice, get_updated_params({ 42 | 'retina_key': 0x5, 43 | 'mode': p.external_devices.ExternalFPGARetinaDevice.MODE_128, 44 | 'polarity': ( 45 | p.external_devices.ExternalFPGARetinaDevice.DOWN_POLARITY)}), 46 | label='External retina') 47 | 48 | population = p.Population(256, p.IF_curr_exp(), label='pop_1') 49 | p.Projection( 50 | retina_pop, population, p.FixedProbabilityConnector(0.1), 51 | synapse_type=p.StaticSynapse(weight=0.1)) 52 | 53 | # q.activate_live_output_for(population) 54 | p.run(1000) 55 | p.end() 56 | -------------------------------------------------------------------------------- /examples/extra_models_examples/IF_cond_exp_stoc.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | A single IF neuron with exponential, current-based synapses, fed by two 17 | spike sources. 18 | 19 | Run as: 20 | 21 | $ python IF_curr_exp.py 22 | 23 | where is 'neuron', 'nest', etc 24 | 25 | Andrew Davison, UNIC, CNRS 26 | September 2006 27 | 28 | $Id$ 29 | """ 30 | 31 | import pylab 32 | import pyNN.spiNNaker as sim 33 | from pyNN.utility.plotting import Figure, Panel 34 | import matplotlib.pyplot as plt 35 | 36 | sim.setup(timestep=1.0, min_delay=1.0) 37 | 38 | stoc_cell = sim.Population(1, sim.extra_models.IFCondExpStoc(**{ 39 | 'i_offset': 0.1, 40 | 'tau_refrac': 3.0, 41 | 'v_thresh': -51.0, 42 | 'v_reset': -70.0, 43 | 'tau_syn_E': 5.0, 44 | 'tau_syn_I': 5.0})) 45 | 46 | exp_cell = sim.Population(1, sim.IF_cond_exp(**{ 47 | 'i_offset': 0.1, 48 | 'tau_refrac': 3.0, 49 | 'v_thresh': -51.0, 50 | 'v_reset': -70.0, 51 | 'tau_syn_E': 5.0, 52 | 'tau_syn_I': 5.0})) 53 | 54 | 55 | spike_sourceE = sim.Population(1, sim.SpikeSourceArray(**{ 56 | 'spike_times': [float(i) for i in range(5, 105, 10)]})) 57 | spike_sourceI = sim.Population(1, sim.SpikeSourceArray(**{ 58 | 'spike_times': [float(i) for i in range(155, 255, 10)]})) 59 | 60 | sim.Projection(spike_sourceE, exp_cell, 61 | sim.OneToOneConnector(), 62 | synapse_type=sim.StaticSynapse(weight=0.15, delay=2.0), 63 | receptor_type='excitatory') 64 | sim.Projection(spike_sourceI, exp_cell, 65 | sim.OneToOneConnector(), 66 | synapse_type=sim.StaticSynapse(weight=-0.15, delay=4.0), 67 | receptor_type='inhibitory') 68 | sim.Projection(spike_sourceE, stoc_cell, 69 | sim.OneToOneConnector(), 70 | synapse_type=sim.StaticSynapse(weight=0.15, delay=2.0), 71 | receptor_type='excitatory') 72 | sim.Projection(spike_sourceI, stoc_cell, 73 | sim.OneToOneConnector(), 74 | synapse_type=sim.StaticSynapse(weight=-0.15, delay=4.0), 75 | receptor_type='inhibitory') 76 | 77 | stoc_cell.record('all') 78 | exp_cell.record('all') 79 | 80 | runtime = 200.0 81 | 82 | sim.run(runtime) 83 | 84 | stoc_data = stoc_cell.get_data() 85 | exp_data = exp_cell.get_data() 86 | 87 | # Plot 88 | Figure( 89 | # raster plot of the presynaptic neuron spike times 90 | Panel(stoc_data.segments[0].spiketrains, 91 | yticks=True, markersize=0.2, xlim=(0, runtime)), 92 | Panel(exp_data.segments[0].spiketrains, 93 | yticks=True, markersize=0.2, xlim=(0, runtime)), 94 | # membrane potential of the postsynaptic neuron 95 | Panel(stoc_data.segments[0].filter(name='v')[0], 96 | ylabel="Membrane potential (mV)", 97 | data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), 98 | Panel(stoc_data.segments[0].filter(name='gsyn_exc')[0], 99 | ylabel="gsyn excitatory (mV)", 100 | data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), 101 | Panel(stoc_data.segments[0].filter(name='gsyn_inh')[0], 102 | ylabel="gsyn inhibitory (mV)", 103 | data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), 104 | # membrane potential of the postsynaptic neuron 105 | Panel(exp_data.segments[0].filter(name='v')[0], 106 | ylabel="Membrane potential (mV)", 107 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 108 | Panel(exp_data.segments[0].filter(name='gsyn_exc')[0], 109 | ylabel="gsyn excitatory (mV)", 110 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 111 | Panel(exp_data.segments[0].filter(name='gsyn_inh')[0], 112 | ylabel="gsyn inhibitory (mV)", 113 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 114 | title="IF_cond_exp_stoc example", 115 | annotations=f"Simulated with {sim.name()}" 116 | ) 117 | plt.show() 118 | 119 | sim.end() 120 | pylab.show() 121 | -------------------------------------------------------------------------------- /examples/extra_models_examples/IF_curr_delta.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | A single LIF neuron with two exponential, current-based synapses, 17 | and two delta, current-based synapses, fed by two spike sources. 18 | """ 19 | 20 | import pyNN.spiNNaker as sim 21 | from pyNN.utility.plotting import Figure, Panel 22 | import matplotlib.pyplot as plt 23 | 24 | sim.setup(timestep=0.1, min_delay=0.1) 25 | 26 | delta_cell = sim.Population(1, sim.extra_models.IFCurDelta(**{ 27 | 'i_offset': 0.1, 28 | 'tau_refrac': 3.0, 29 | 'v_thresh': -51.0, 30 | 'v_reset': -70.0})) 31 | 32 | exp_cell = sim.Population(1, sim.IF_curr_exp(**{ 33 | 'i_offset': 0.1, 34 | 'tau_refrac': 3.0, 35 | 'v_thresh': -51.0, 36 | 'v_reset': -70.0, 37 | 'tau_syn_E': 5.0, 38 | 'tau_syn_I': 5.0})) 39 | 40 | 41 | spike_sourceE = sim.Population(1, sim.SpikeSourceArray(**{ 42 | 'spike_times': [float(i) for i in range(5, 105, 10)]})) 43 | spike_sourceI = sim.Population(1, sim.SpikeSourceArray(**{ 44 | 'spike_times': [float(i) for i in range(155, 255, 10)]})) 45 | 46 | sim.Projection(spike_sourceE, exp_cell, 47 | sim.OneToOneConnector(), 48 | synapse_type=sim.StaticSynapse(weight=1.5, delay=2.0), 49 | receptor_type='excitatory') 50 | sim.Projection(spike_sourceI, exp_cell, 51 | sim.OneToOneConnector(), 52 | synapse_type=sim.StaticSynapse(weight=-1.5, delay=4.0), 53 | receptor_type='inhibitory') 54 | sim.Projection(spike_sourceE, delta_cell, 55 | sim.OneToOneConnector(), 56 | synapse_type=sim.StaticSynapse(weight=1.5, delay=2.0), 57 | receptor_type='excitatory') 58 | sim.Projection(spike_sourceI, delta_cell, 59 | sim.OneToOneConnector(), 60 | synapse_type=sim.StaticSynapse(weight=-1.5, delay=4.0), 61 | receptor_type='inhibitory') 62 | 63 | delta_cell.record('all') 64 | exp_cell.record('all') 65 | 66 | runtime = 200.0 67 | 68 | sim.run(runtime) 69 | 70 | stoc_data = delta_cell.get_data() 71 | exp_data = exp_cell.get_data() 72 | 73 | # Plot 74 | Figure( 75 | # raster plot of the presynaptic neuron spike times 76 | Panel(stoc_data.segments[0].spiketrains, 77 | yticks=True, markersize=0.2, xlim=(0, runtime)), 78 | Panel(exp_data.segments[0].spiketrains, 79 | yticks=True, markersize=0.2, xlim=(0, runtime)), 80 | # membrane potential of the postsynaptic neuron 81 | Panel(stoc_data.segments[0].filter(name='v')[0], 82 | ylabel="Membrane potential (mV)", 83 | data_labels=[delta_cell.label], yticks=True, xlim=(0, runtime)), 84 | Panel(stoc_data.segments[0].filter(name='gsyn_exc')[0], 85 | ylabel="gsyn excitatory (mV)", 86 | data_labels=[delta_cell.label], yticks=True, xlim=(0, runtime)), 87 | Panel(stoc_data.segments[0].filter(name='gsyn_inh')[0], 88 | ylabel="gsyn inhibitory (mV)", 89 | data_labels=[delta_cell.label], yticks=True, xlim=(0, runtime)), 90 | # membrane potential of the postsynaptic neuron 91 | Panel(exp_data.segments[0].filter(name='v')[0], 92 | ylabel="Membrane potential (mV)", 93 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 94 | Panel(exp_data.segments[0].filter(name='gsyn_exc')[0], 95 | ylabel="gsyn excitatory (mV)", 96 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 97 | Panel(exp_data.segments[0].filter(name='gsyn_inh')[0], 98 | ylabel="gsyn inhibitory (mV)", 99 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 100 | title="IF_curr_delta example", 101 | annotations=f"Simulated with {sim.name()}" 102 | ) 103 | plt.show() 104 | 105 | sim.end() 106 | -------------------------------------------------------------------------------- /examples/extra_models_examples/IF_curr_exp_ca2_adaptive.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # ----------------------------------------------------------------------------- 16 | # Example of integrate-and-fire neuron with spike-frequency adaption 17 | # Model and example taken from Liu, Y. H., & Wang, X. J. (2001). 18 | # Spike-frequency adaptation of a generalized leaky integrate-and-fire model 19 | # neuron. 20 | # Journal of Computational Neuroscience, 10(1), 25-45. 21 | # doi:10.1023/A:1008916026143 22 | # ----------------------------------------------------------------------------- 23 | import math 24 | import numpy 25 | import matplotlib.pyplot as pylab 26 | import pyNN.spiNNaker as sim 27 | 28 | # Timestep (ms) 29 | # **NOTE** the 2.5Khz input frequency is not going to work particularly well 30 | # at 1ms 31 | dt = 0.1 32 | 33 | # Number of neurons - used to gather enough ISIs to get a smooth estimate 34 | N = 300 35 | 36 | # Time (ms) to simulate for 37 | T = 250 38 | 39 | # Setup simulator 40 | sim.setup(timestep=dt, min_delay=1.0) 41 | 42 | # Create population of neurons 43 | cell = sim.Population(N, sim.extra_models.IFCurrExpCa2Adaptive(**{ 44 | "tau_m": 20.0, "cm": 0.5, 45 | "v_rest": -70.0, 46 | "v_reset": -60.0, 47 | "v_thresh": -54.0, 48 | "i_alpha": 0.1, 49 | "tau_ca2": 50.0})) 50 | 51 | # Create poisson spike source 52 | spike_source = sim.Population(N, sim.SpikeSourcePoisson(rate=2500.0)) 53 | 54 | sim.Projection(spike_source, cell, 55 | sim.OneToOneConnector(), 56 | sim.StaticSynapse(weight=0.1, delay=0.1), 57 | receptor_type="excitatory") 58 | 59 | cell.record('spikes') 60 | # cell.record_gsyn() 61 | 62 | sim.run(T) 63 | 64 | spike_times = cell.spinnaker_get_data('spikes') 65 | # ca2 = cell.get_gsyn(compatible_output=True) 66 | 67 | # Split into list of spike times for each neuron 68 | neuron_spikes = [spike_times[spike_times[:, 0] == n, 1] for n in range(N)] 69 | 70 | # Calculate interspike intervals 71 | # and pair these with bin index of last spike time in pair 72 | # **NOTE** using first spike time in pair leads to a dip at the 73 | # end as the end of long pairs goes off the end of the simulation 74 | binned_isis = numpy.hstack([ 75 | numpy.vstack( 76 | (t[1:] - t[:-1], 77 | numpy.digitize(t[1:], numpy.arange(T)) - 1)) 78 | for t in neuron_spikes]) 79 | 80 | # Split interspike intervals into separate array for each time bin 81 | time_binned_isis = [binned_isis[0, binned_isis[1] == t] for t in range(T)] 82 | 83 | # Create a dictionary of non-empty time bins to mean interspike interval 84 | mean_isis = {t: numpy.average(i) 85 | for (t, i) in enumerate(time_binned_isis) if len(i) > 0} 86 | 87 | # Calculate the coefficient of variance for each time bin 88 | isi_cv = {t: math.sqrt( 89 | numpy.sum(numpy.power(time_binned_isis[t] - mean_isi, 2)) / 90 | float(len(time_binned_isis[t]))) / mean_isi 91 | for (t, mean_isi) in mean_isis.items()} 92 | 93 | # Take average CA2 level across all neurons 94 | # average_ca2 = numpy.average(numpy.reshape(ca2[:,2], (N, int(T / dt))), 95 | # axis=0) 96 | 97 | # Plot 98 | fig, axes = pylab.subplots(2, sharex=True) 99 | 100 | axes[0].scatter(mean_isis.keys(), 101 | [1000.0 / i for i in mean_isis.values()], s=2) 102 | axes[0].set_ylabel("Firing rate/Hz") 103 | 104 | # axes[1].scatter(numpy.arange(0.0, T, dt), average_ca2, s=2) 105 | # axes[1].set_ylabel("CA2/mA") 106 | # axes[1].set_ylim((0.0, numpy.amax(average_ca2) * 1.25)) 107 | 108 | axes[1].scatter(isi_cv.keys(), isi_cv.values(), s=2) 109 | axes[1].set_ylabel("Coefficient of ISI variance") 110 | 111 | axes[1].set_xlim((0.0, T)) 112 | axes[1].set_xlabel("Time/ms") 113 | 114 | sim.end() 115 | pylab.show() 116 | -------------------------------------------------------------------------------- /examples/extra_models_examples/IF_curr_exp_sEMD.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | """ 17 | Spiking ELementary Motion Detector (sEMD) example 18 | See https://www.cit-ec.de/en/nbs/spiking-insect-vision for more details 19 | """ 20 | 21 | # imports 22 | import pyNN.spiNNaker as p 23 | import matplotlib.pyplot as plt 24 | from pyNN.utility.plotting import Figure, Panel 25 | 26 | # variables 27 | weights = 1 28 | spike_time_facilitation = 4 29 | spike_time_trigger = 20 30 | 31 | # set up simulation 32 | simulation_timestep = 1 # ms 33 | simulation_runtime = 100 # ms 34 | p.setup(timestep=simulation_timestep) 35 | 36 | # neuron parameters 37 | cell_params_semd = {'cm': 0.25, 38 | 'i_offset': 0, # offset current 39 | 'tau_m': 10, # membrane potential time constant 40 | 'tau_refrac': 1, # refractory period time constant 41 | 'tau_syn_E': 20, # excitatory current time constant 42 | 'tau_syn_I': 20, # inhibitory current time constant 43 | 'v_reset': -85, # reset potential 44 | 'v_rest': -60, # resting potential 45 | 'v_thresh': -50, # spiking threshold 46 | 'scaling_factor': 100.0 # scaling factor for 2nd response 47 | } 48 | 49 | # neuron populations 50 | # (population size, neuron type, cell parameters, label) 51 | sEMD = p.Population(1, p.extra_models.IF_curr_exp_sEMD, 52 | cell_params_semd, label="sEMD") 53 | input_facilitation = p.Population(1, p.SpikeSourceArray, 54 | {'spike_times': [[spike_time_facilitation]]}, 55 | label="input_facilitation") 56 | input_trigger = p.Population(1, p.SpikeSourceArray, 57 | {'spike_times': [[spike_time_trigger]]}, 58 | label="input_trigger") 59 | 60 | sEMD.initialize(v=-60.0) 61 | 62 | # projections 63 | p.Projection(input_facilitation, sEMD, p.OneToOneConnector(), 64 | p.StaticSynapse(weight=weights, delay=1), 65 | receptor_type='excitatory') 66 | p.Projection(input_trigger, sEMD, p.OneToOneConnector(), 67 | p.StaticSynapse(weight=weights, delay=1), 68 | receptor_type='excitatory2') 69 | 70 | # records 71 | sEMD.record(['spikes', 'v', 'gsyn_exc', 'gsyn_inh']) 72 | 73 | # run simulation 74 | p.run(simulation_runtime) 75 | 76 | # receive data from neurons 77 | spikes = sEMD.get_data(['spikes']) 78 | v = sEMD.get_data(['v']) 79 | current_exc = sEMD.get_data(['gsyn_exc']) 80 | current_inh = sEMD.get_data(['gsyn_inh']) 81 | 82 | # plots 83 | Figure( 84 | # raster plot of the neuron spike times 85 | Panel(spikes.segments[0].spiketrains, 86 | yticks=True, markersize=4, xlim=(0, simulation_runtime)), 87 | # membrane potential 88 | Panel(v.segments[0].filter(name='v')[0], 89 | ylabel="Membrane potential (mV)", 90 | data_labels=[sEMD.label], yticks=True, xlim=(0, simulation_runtime)), 91 | # excitatory current 92 | Panel(current_exc.segments[0].filter(name='gsyn_exc')[0], 93 | ylabel="gsyn excitatory (mV)", 94 | data_labels=[sEMD.label], yticks=True, xlim=(0, simulation_runtime)), 95 | # inhibitory current 96 | Panel(current_inh.segments[0].filter(name='gsyn_inh')[0], 97 | xlabel="Time (ms)", xticks=True, 98 | ylabel="gsyn inhibitory (mV)", 99 | data_labels=[sEMD.label], yticks=True, xlim=(0, simulation_runtime)), 100 | title="SEMD example", 101 | annotations=f"Simulated with {p.name()}" 102 | ) 103 | plt.show() 104 | 105 | # end 106 | p.end() 107 | -------------------------------------------------------------------------------- /examples/extra_models_examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /examples/extra_models_examples/stdp_triplet.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as pylab 16 | 17 | import pyNN.spiNNaker as sim 18 | 19 | # pylint: disable=wrong-spelling-in-comment 20 | # ------------------------------------------------------------------- 21 | # This example uses the sPyNNaker implementation of the triplet rule 22 | # Developed by Pfister and Gerstner(2006) to reproduce the pairing 23 | # Experiment first performed by Sjostrom (2001) 24 | # ------------------------------------------------------------------- 25 | 26 | # ------------------------------------------------------------------- 27 | # Common parameters 28 | # ------------------------------------------------------------------- 29 | start_time = 100 30 | time_between_pairs = 1000 31 | num_pairs = 60 32 | 33 | start_w = 0.5 34 | frequencies = [0.1, 10, 20, 40, 50] 35 | delta_t = [-10, 10] 36 | 37 | 38 | def generate_fixed_frequency_test_data( 39 | frequency, first_spike_time, num_spikes): 40 | """ 41 | Generates a list of spike times based on the frequency 42 | 43 | :param int frequency: 44 | :param int first_spike_time: 45 | :param int num_spikes: 46 | :rtype: list(int) 47 | """ 48 | # Calculate interspike delays in ms 49 | interspike_delay = int(1000.0 / float(frequency)) 50 | 51 | # Generate spikes 52 | return [first_spike_time + (s * interspike_delay) 53 | for s in range(num_spikes)] 54 | 55 | 56 | # ------------------------------------------------------------------- 57 | # Experiment loop 58 | # ------------------------------------------------------------------- 59 | # Population parameters 60 | model = sim.IF_curr_exp 61 | cell_params = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 10.0, 'tau_refrac': 2.0, 62 | 'tau_syn_E': 2.5, 'tau_syn_I': 2.5, 'v_reset': -70.0, 63 | 'v_rest': -65.0, 'v_thresh': -55.4} 64 | 65 | # SpiNNaker setup 66 | sim.setup(timestep=1.0, min_delay=1.0) 67 | 68 | # Sweep times and frequencies 69 | projections = [] 70 | sim_time = 0 71 | for t in delta_t: 72 | projections.append([]) 73 | for f in frequencies: 74 | # Neuron populations 75 | pre_pop = sim.Population(1, model(**cell_params)) 76 | post_pop = sim.Population(1, model(**cell_params)) 77 | 78 | # Stimulating populations 79 | pre_times = generate_fixed_frequency_test_data( 80 | f, start_time - 1, num_pairs + 1) 81 | post_times = generate_fixed_frequency_test_data( 82 | f, start_time + t, num_pairs) 83 | pre_stim = sim.Population(1, sim.SpikeSourceArray( 84 | spike_times=[pre_times])) 85 | post_stim = sim.Population( 86 | 1, sim.SpikeSourceArray(spike_times=[post_times])) 87 | 88 | # Update simulation time 89 | # You can not nest max or a int and a list 90 | # pylint: disable=nested-min-max 91 | sim_time = max(sim_time, max(max(pre_times), max(post_times)) + 100) 92 | 93 | # Connections between spike sources and neuron populations 94 | ee_connector = sim.OneToOneConnector() 95 | sim.Projection( 96 | pre_stim, pre_pop, ee_connector, receptor_type='excitatory', 97 | synapse_type=sim.StaticSynapse(weight=2)) 98 | sim.Projection( 99 | post_stim, post_pop, ee_connector, receptor_type='excitatory', 100 | synapse_type=sim.StaticSynapse(weight=2)) 101 | 102 | # **HACK** 103 | param_scale = 0.5 104 | 105 | # Plastic Connection between pre_pop and post_pop 106 | # Sjostrom visual cortex min-triplet params 107 | stdp_model = sim.STDPMechanism( 108 | timing_dependence=sim.extra_models.PfisterSpikeTriplet( 109 | tau_plus=16.8, tau_minus=33.7, tau_x=101, tau_y=114, 110 | A_plus=param_scale * 0.0, A_minus=param_scale * 7.1e-3), 111 | weight_dependence=sim.extra_models.WeightDependenceAdditiveTriplet( 112 | w_min=0.0, w_max=1.0, A3_plus=param_scale * 6.5e-3, 113 | A3_minus=param_scale * 0.0), 114 | weight=start_w, delay=1) 115 | 116 | projections[-1].append( 117 | sim.Projection( 118 | pre_pop, post_pop, sim.OneToOneConnector(), 119 | synapse_type=stdp_model)) 120 | 121 | print(f"Simulating for {(sim_time / 1000)}s") 122 | 123 | # Run simulation 124 | sim.run(sim_time) 125 | 126 | # Read weights from each parameter value being tested 127 | weights = [] 128 | for projection_delta_t in projections: 129 | weights.append([p.get('weight', 'list', with_address=False)[0] 130 | for p in projection_delta_t]) 131 | 132 | # End simulation on SpiNNaker 133 | sim.end() 134 | 135 | # ------------------------------------------------------------------- 136 | # Plotting 137 | # ------------------------------------------------------------------- 138 | # Sjostrom et al. (2001) experimental data 139 | data_w = [ 140 | [-0.29, -0.41, -0.34, 0.56, 0.75], 141 | [-0.04, 0.14, 0.29, 0.53, 0.56] 142 | ] 143 | data_e = [ 144 | [0.08, 0.11, 0.1, 0.32, 0.19], 145 | [0.05, 0.1, 0.14, 0.11, 0.26] 146 | ] 147 | 148 | # Plot Frequency response 149 | figure, axis = pylab.subplots() 150 | axis.set_xlabel("Frequency/Hz") 151 | axis.set_ylabel(r"$(\frac{\Delta w_{ij}}{w_{ij}})$", rotation="horizontal", 152 | size="xx-large") 153 | 154 | line_styles = ["--", "-"] 155 | for m_w, d_w, d_e, l, t in zip(weights, data_w, data_e, line_styles, delta_t): 156 | # Calculate deltas from end weights 157 | delta_w = [(w - start_w) / start_w for w in m_w] 158 | 159 | # Plot experimental data and error bars 160 | axis.errorbar( 161 | frequencies, d_w, yerr=d_e, color="black", linestyle=l, 162 | label=r"Experimental data, delta $(\Delta{t}=%dms)$" % t) 163 | 164 | # Plot model data 165 | axis.plot(frequencies, delta_w, color="blue", linestyle=l, 166 | label=r"Triplet rule, delta $(\Delta{t}=%dms)$" % t) 167 | 168 | axis.legend(loc="upper right", bbox_to_anchor=(1.0, 1.0)) 169 | 170 | pylab.show() 171 | -------------------------------------------------------------------------------- /examples/extra_models_examples/synfire_if_curr_dual_exp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import pyNN.spiNNaker as p 19 | from pyNN.utility.plotting import Figure, Panel 20 | import matplotlib.pyplot as plt 21 | 22 | runtime = 5000 23 | p.setup(timestep=1.0, min_delay=1.0) 24 | nNeurons = 200 # number of neurons in each population 25 | p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) 26 | 27 | cell_params_lif = {'cm': 0.25, 28 | 'i_offset': 0.0, 29 | 'tau_m': 20.0, 30 | 'tau_refrac': 2.0, 31 | 'tau_syn_E': 5.0, 32 | 'tau_syn_I': 5.0, 33 | 'v_reset': -70.0, 34 | 'v_rest': -65.0, 35 | 'v_thresh': -50.0 36 | } 37 | 38 | populations = list() 39 | projections = list() 40 | 41 | weight_to_spike = 2.0 42 | delay = 17 43 | 44 | loopConnections = list() 45 | for i in range(0, nNeurons): 46 | singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) 47 | loopConnections.append(singleConnection) 48 | 49 | injectionConnection = [(0, 0)] 50 | spikeArray = {'spike_times': [[0]]} 51 | populations.append( 52 | p.Population(nNeurons, p.extra_models.IF_curr_dual_exp(**cell_params_lif), 53 | label='pop_1')) 54 | populations.append( 55 | p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) 56 | 57 | projections.append(p.Projection( 58 | populations[0], populations[0], p.FromListConnector(loopConnections), 59 | p.StaticSynapse(weight=weight_to_spike, delay=delay))) 60 | projections.append(p.Projection( 61 | populations[1], populations[0], p.FromListConnector(injectionConnection), 62 | p.StaticSynapse(weight=weight_to_spike, delay=1))) 63 | 64 | populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) 65 | 66 | p.run(runtime) 67 | 68 | # get data (could be done as one, but can be done bit by bit as well) 69 | data = populations[0].get_data(['v', 'gsyn_exc', 'spikes', 'gsyn_inh']) 70 | 71 | figure_filename = "results.png" 72 | Figure( 73 | # raster plot of the presynaptic neuron spike times 74 | Panel(data.segments[0].spiketrains, 75 | yticks=True, markersize=0.2, xlim=(0, runtime)), 76 | # membrane potential of the postsynaptic neuron 77 | Panel(data.segments[0].filter(name='v')[0], 78 | ylabel="Membrane potential (mV)", 79 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 80 | Panel(data.segments[0].filter(name='gsyn_exc')[0], 81 | ylabel="gsyn excitatory (mV)", 82 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 83 | Panel(data.segments[0].filter(name='gsyn_inh')[0], 84 | ylabel="gsyn inhibitory (mV)", 85 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 86 | title="Synfire chain example with dual exponential synapse", 87 | annotations=f"Simulated with {p.name()}" 88 | ) 89 | plt.show() 90 | print(figure_filename) 91 | 92 | p.end() 93 | -------------------------------------------------------------------------------- /examples/extra_models_examples/vogel_2011/.gitignore: -------------------------------------------------------------------------------- 1 | /staticExcitSpikes0 2 | /staticInhibSpikes0 3 | -------------------------------------------------------------------------------- /examples/extra_models_examples/vogel_2011/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /examples/extra_models_examples/vogel_2011/spynnaker.cfg: -------------------------------------------------------------------------------- 1 | [Simulation] 2 | incoming_spike_buffer_size = 2048 3 | -------------------------------------------------------------------------------- /examples/extra_models_examples/vogel_2011/vogels_2011_live.col: -------------------------------------------------------------------------------- 1 | Excitatory 255 0 0 2 | Inhibitory 0 0 255 -------------------------------------------------------------------------------- /examples/extra_models_examples/vogel_2011/vogels_2011_live.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import pyNN.spiNNaker as sim 16 | 17 | # pylint: disable=wrong-spelling-in-comment 18 | # ------------------------------------------------------------------- 19 | # This example uses the sPyNNaker implementation of the inhibitory 20 | # Plasticity rule developed by Vogels, Sprekeler, Zenke et al (2011) 21 | # To reproduce the experiment from their paper 22 | # ------------------------------------------------------------------- 23 | # Population parameters 24 | model = sim.IF_curr_exp 25 | cell_params = { 26 | 'cm': 0.2, # nF 27 | 'i_offset': 0.2, 28 | 'tau_m': 20.0, 29 | 'tau_refrac': 5.0, 30 | 'tau_syn_E': 5.0, 31 | 'tau_syn_I': 10.0, 32 | 'v_reset': -60.0, 33 | 'v_rest': -60.0, 34 | 'v_thresh': -50.0} 35 | 36 | 37 | # How large should the population of excitatory neurons be? 38 | # (Number of inhibitory neurons is proportional to this) 39 | NUM_EXCITATORY = 2000 40 | 41 | # SpiNNaker setup 42 | sim.setup(timestep=1.0, min_delay=1.0, time_scale_factor=10) 43 | 44 | # Reduce number of neurons to simulate on each core 45 | sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100) 46 | 47 | # Create excitatory and inhibitory populations of neurons 48 | ex_pop = sim.Population(NUM_EXCITATORY, model(**cell_params), 49 | label="Excitatory", additional_parameters={"seed": 2}) 50 | in_pop = sim.Population(NUM_EXCITATORY / 4, model(**cell_params), 51 | label="Inhibitory", additional_parameters={"seed": 9}) 52 | 53 | # Record excitatory spikes 54 | ex_pop.record('spikes') 55 | 56 | # Make excitatory->inhibitory projections 57 | sim.Projection(ex_pop, in_pop, sim.FixedProbabilityConnector(0.02), 58 | receptor_type='excitatory', 59 | synapse_type=sim.StaticSynapse(weight=0.029)) 60 | sim.Projection(ex_pop, ex_pop, sim.FixedProbabilityConnector(0.02), 61 | receptor_type='excitatory', 62 | synapse_type=sim.StaticSynapse(weight=0.029)) 63 | 64 | # Make inhibitory->inhibitory projections 65 | sim.Projection(in_pop, in_pop, sim.FixedProbabilityConnector(0.02), 66 | receptor_type='inhibitory', 67 | synapse_type=sim.StaticSynapse(weight=-0.29)) 68 | 69 | # Build inhibitory plasticity model 70 | stdp_model = sim.STDPMechanism( 71 | timing_dependence=sim.extra_models.Vogels2011Rule(alpha=0.12, tau=20.0, 72 | A_plus=0.05), 73 | weight_dependence=sim.AdditiveWeightDependence(w_min=0.0, w_max=1.0)) 74 | 75 | # Make inhibitory->excitatory projections 76 | sim.Projection(in_pop, ex_pop, sim.FixedProbabilityConnector(0.02), 77 | receptor_type='inhibitory', 78 | synapse_type=stdp_model) 79 | 80 | # Activate live output for excitatory spikes 81 | sim.external_devices.activate_live_output_for(ex_pop) 82 | sim.external_devices.activate_live_output_for(in_pop) 83 | 84 | # Run simulation 85 | sim.run(5000) 86 | 87 | # End simulation on SpiNNaker 88 | sim.end() 89 | -------------------------------------------------------------------------------- /examples/hbp_neuroguidebook_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | A population of integrate-and-firing neurons with different input firing rates 17 | (example used in the HBP Neuromorphic Computing Guidebook) 18 | """ 19 | 20 | import numpy as np 21 | import matplotlib.pyplot as plt 22 | import pyNN.spiNNaker as sim 23 | 24 | sim.setup(timestep=1.0, min_delay=1.0) 25 | 26 | # create cells 27 | cell_params = { 28 | 'cm': 0.25, 'tau_m': 10.0, 'tau_refrac': 2.0, 29 | 'tau_syn_E': 2.5, 'tau_syn_I': 2.5, 30 | 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -55.0} 31 | 32 | neurons = sim.Population(100, sim.IF_cond_exp(**cell_params)) 33 | inputs = sim.Population(100, sim.SpikeSourcePoisson(rate=0.0)) 34 | 35 | # set input firing rates as a linear function of cell index 36 | input_firing_rates = np.linspace(0.0, 1000.0, num=inputs.size) 37 | inputs.set(rate=input_firing_rates) 38 | 39 | # create one-to-one connections 40 | wiring = sim.OneToOneConnector() 41 | static_synapse = sim.StaticSynapse(weight=0.1, delay=2.0) 42 | connections = sim.Projection(inputs, neurons, wiring, static_synapse) 43 | 44 | # configure recording 45 | neurons.record('spikes') 46 | 47 | # run simulation 48 | sim_duration = 10.0 # seconds 49 | sim.run(sim_duration*1000.0) 50 | 51 | # retrieve recorded data 52 | spike_counts = neurons.get_spike_counts() 53 | print(spike_counts) 54 | output_firing_rates = np.array( 55 | [value for (key, value) in sorted(spike_counts.items())])/sim_duration 56 | 57 | sim.end() 58 | 59 | # plot graph 60 | plt.plot(input_firing_rates, output_firing_rates) 61 | plt.xlabel("Input firing rate (spikes/second)") 62 | plt.ylabel("Output firing rate (spikes/second)") 63 | plt.savefig("simple_example.png") 64 | plt.show() 65 | -------------------------------------------------------------------------------- /examples/if_curr_alpha.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import pyNN.spiNNaker as p 15 | import pyNN.utility.plotting as plot 16 | import matplotlib.pyplot as plt 17 | 18 | p.setup(0.1) 19 | runtime = 50 20 | populations = [] 21 | title = "PyNN0.8 alpha synapse testing" 22 | 23 | pop_src1 = p.Population(1, p.SpikeSourceArray, 24 | {'spike_times': [[5, 15, 20, 30]]}, label="src1") 25 | 26 | populations.append(p.Population(1, p.IF_curr_alpha, {}, label="test")) 27 | 28 | populations[0].set(tau_syn_E=2) 29 | populations[0].set(tau_syn_I=4) 30 | 31 | # define the projections 32 | exc_proj = p.Projection(pop_src1, populations[0], 33 | p.OneToOneConnector(), 34 | p.StaticSynapse(weight=1, delay=1), 35 | receptor_type="excitatory") 36 | inh_proj = p.Projection(pop_src1, populations[0], 37 | p.OneToOneConnector(), 38 | p.StaticSynapse(weight=1, delay=10), 39 | receptor_type="inhibitory") 40 | 41 | populations[0].record("all") 42 | p.run(runtime) 43 | 44 | v = populations[0].get_data("v") 45 | gsyn_exc = populations[0].get_data("gsyn_exc") 46 | gsyn_inh = populations[0].get_data("gsyn_inh") 47 | spikes = populations[0].get_data("spikes") 48 | 49 | plot.Figure( 50 | plot.Panel(v.segments[0].filter(name='v')[0], 51 | ylabel="Membrane potential (mV)", 52 | data_labels=[populations[0].label], 53 | yticks=True, xlim=(0, runtime)), 54 | plot.Panel(gsyn_exc.segments[0].filter(name='gsyn_exc')[0], 55 | ylabel="gsyn excitatory (mV)", 56 | data_labels=[populations[0].label], 57 | yticks=True, xlim=(0, runtime)), 58 | plot.Panel(gsyn_inh.segments[0].filter(name='gsyn_inh')[0], 59 | ylabel="gsyn inhibitory (mV)", 60 | data_labels=[populations[0].label], 61 | yticks=True, xlim=(0, runtime)), 62 | title=title, 63 | annotations=f"Simulated with {p.name()}" 64 | ) 65 | plt.show() 66 | p.end() 67 | -------------------------------------------------------------------------------- /examples/if_curr_delta.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | A single LIF neuron with two exponential, current-based synapses, 17 | and two delta, current-based synapses, fed by two spike sources. 18 | """ 19 | 20 | import pyNN.spiNNaker as sim 21 | from pyNN.utility.plotting import Figure, Panel 22 | import matplotlib.pyplot as plt 23 | 24 | sim.setup(timestep=1.0, min_delay=1.0) 25 | 26 | delta_cell = sim.Population(1, sim.IF_curr_delta(**{ 27 | 'i_offset': 0.1, 28 | 'tau_refrac': 3.0, 29 | 'v_thresh': -51.0, 30 | 'v_reset': -70.0})) 31 | 32 | exp_cell = sim.Population(1, sim.IF_curr_exp(**{ 33 | 'i_offset': 0.1, 34 | 'tau_refrac': 3.0, 35 | 'v_thresh': -51.0, 36 | 'v_reset': -70.0, 37 | 'tau_syn_E': 5.0, 38 | 'tau_syn_I': 5.0})) 39 | 40 | 41 | spike_sourceE = sim.Population(1, sim.SpikeSourceArray(**{ 42 | 'spike_times': [float(i) for i in range(5, 105, 10)]})) 43 | spike_sourceI = sim.Population(1, sim.SpikeSourceArray(**{ 44 | 'spike_times': [float(i) for i in range(155, 255, 10)]})) 45 | 46 | sim.Projection(spike_sourceE, exp_cell, 47 | sim.OneToOneConnector(), 48 | synapse_type=sim.StaticSynapse(weight=1.5, delay=2.0), 49 | receptor_type='excitatory') 50 | sim.Projection(spike_sourceI, exp_cell, 51 | sim.OneToOneConnector(), 52 | synapse_type=sim.StaticSynapse(weight=-1.5, delay=4.0), 53 | receptor_type='inhibitory') 54 | sim.Projection(spike_sourceE, delta_cell, 55 | sim.OneToOneConnector(), 56 | synapse_type=sim.StaticSynapse(weight=1.5, delay=2.0), 57 | receptor_type='excitatory') 58 | sim.Projection(spike_sourceI, delta_cell, 59 | sim.OneToOneConnector(), 60 | synapse_type=sim.StaticSynapse(weight=-1.5, delay=4.0), 61 | receptor_type='inhibitory') 62 | 63 | delta_cell.record('all') 64 | exp_cell.record('all') 65 | 66 | runtime = 200.0 67 | 68 | sim.run(runtime) 69 | 70 | stoc_data = delta_cell.get_data() 71 | exp_data = exp_cell.get_data() 72 | 73 | # Plot 74 | Figure( 75 | # raster plot of the presynaptic neuron spike times 76 | Panel(stoc_data.segments[0].spiketrains, 77 | yticks=True, markersize=0.2, xlim=(0, runtime)), 78 | Panel(exp_data.segments[0].spiketrains, 79 | yticks=True, markersize=0.2, xlim=(0, runtime)), 80 | # membrane potential of the postsynaptic neuron 81 | Panel(stoc_data.segments[0].filter(name='v')[0], 82 | ylabel="Membrane potential (mV)", 83 | data_labels=[delta_cell.label], yticks=True, xlim=(0, runtime)), 84 | Panel(stoc_data.segments[0].filter(name='gsyn_exc')[0], 85 | ylabel="gsyn excitatory (mV)", 86 | data_labels=[delta_cell.label], yticks=True, xlim=(0, runtime)), 87 | Panel(stoc_data.segments[0].filter(name='gsyn_inh')[0], 88 | ylabel="gsyn inhibitory (mV)", 89 | data_labels=[delta_cell.label], yticks=True, xlim=(0, runtime)), 90 | # membrane potential of the postsynaptic neuron 91 | Panel(exp_data.segments[0].filter(name='v')[0], 92 | ylabel="Membrane potential (mV)", 93 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 94 | Panel(exp_data.segments[0].filter(name='gsyn_exc')[0], 95 | ylabel="gsyn excitatory (mV)", 96 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 97 | Panel(exp_data.segments[0].filter(name='gsyn_inh')[0], 98 | ylabel="gsyn inhibitory (mV)", 99 | data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), 100 | title="IF_curr_delta example", 101 | annotations=f"Simulated with {sim.name()}" 102 | ) 103 | plt.show() 104 | 105 | sim.end() 106 | -------------------------------------------------------------------------------- /examples/partitioner_examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /examples/partitioner_examples/splitter_usage.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import pyNN.spiNNaker as p 15 | from pyNN.utility.plotting import Figure, Panel 16 | import matplotlib.pyplot as plt 17 | from pacman.model.partitioner_splitters import ( 18 | SplitterOneToOneLegacy as OneToOneSplitter, 19 | SplitterFixedLegacy) 20 | from spynnaker.pyNN.extra_algorithms.splitter_components import ( 21 | SplitterPopulationVertexFixed) 22 | 23 | runtime = 1000 24 | n_neurons = 100 # number of neurons in each population 25 | weight_to_spike = 2.0 # weight to spike 26 | delay = 17 # delay (above delay extension point) 27 | 28 | p.setup(timestep=1.0, min_delay=1.0) 29 | p.set_number_of_neurons_per_core(p.IF_curr_exp, int(n_neurons / 2)) 30 | 31 | neuron = p.Population( 32 | n_neurons, p.IF_curr_exp(), label='pop_1', 33 | additional_parameters={ 34 | "splitter_object": SplitterPopulationVertexFixed()}) 35 | neuron.record("all") 36 | neuron2 = p.Population( 37 | int(n_neurons / 2), p.IF_curr_exp(), label='pop_1', 38 | additional_parameters={ 39 | "splitter_object": SplitterPopulationVertexFixed()}) 40 | neuron3 = p.Population( 41 | n_neurons * 2, p.IF_curr_exp(), label='pop_1', 42 | additional_parameters={ 43 | "splitter_object": SplitterPopulationVertexFixed()}) 44 | neuron4 = p.Population( 45 | int(n_neurons / 3), p.IF_curr_exp(), label='pop_1', 46 | additional_parameters={ 47 | "splitter_object": SplitterPopulationVertexFixed()}) 48 | input1 = p.Population( 49 | n_neurons, p.SpikeSourcePoisson(), label='inputSpikes_1', 50 | additional_parameters={ 51 | "splitter_object": SplitterFixedLegacy()}) 52 | input2 = p.Population( 53 | n_neurons, p.SpikeSourcePoisson(), label='inputSpikes_2', 54 | additional_parameters={ 55 | "splitter_object": OneToOneSplitter()}) 56 | 57 | for pop in [neuron, neuron2, neuron3, neuron4]: 58 | for pop2 in [neuron, neuron2, neuron3, neuron4]: 59 | p.Projection( 60 | pop, pop2, p.FixedProbabilityConnector(p_connect=0.1), 61 | p.StaticSynapse(weight=weight_to_spike, delay=delay)) 62 | p.Projection( 63 | input1, neuron, p.OneToOneConnector(), 64 | p.StaticSynapse(weight=weight_to_spike, delay=delay)) 65 | p.Projection( 66 | input2, neuron, p.OneToOneConnector(), 67 | p.StaticSynapse(weight=weight_to_spike, delay=delay)) 68 | 69 | p.run(runtime) 70 | 71 | # get data (could be done as one, but can be done bit by bit as well) 72 | v = neuron.get_data('v') 73 | gsyn_exc = neuron.get_data('gsyn_exc') 74 | gsyn_inh = neuron.get_data('gsyn_inh') 75 | spikes = neuron.get_data('spikes') 76 | p.end() 77 | 78 | Figure( 79 | # raster plot of the presynaptic neuron spike times 80 | Panel(spikes.segments[0].spiketrains, 81 | yticks=True, markersize=0.2, xlim=(0, runtime)), 82 | # membrane potential of the postsynaptic neuron 83 | Panel(v.segments[0].filter(name='v')[0], 84 | ylabel="Membrane potential (mV)", 85 | data_labels=[neuron.label], yticks=True, xlim=(0, runtime)), 86 | Panel(gsyn_exc.segments[0].filter(name='gsyn_exc')[0], 87 | ylabel="gsyn excitatory (mV)", 88 | data_labels=[neuron.label], yticks=True, xlim=(0, runtime)), 89 | Panel(gsyn_inh.segments[0].filter(name='gsyn_inh')[0], 90 | xlabel="Time (ms)", xticks=True, 91 | ylabel="gsyn inhibitory (mV)", 92 | data_labels=[neuron.label], yticks=True, xlim=(0, runtime)), 93 | title="Simple synfire chain example", 94 | annotations=f"Simulated with {p.name()}" 95 | ) 96 | plt.show() 97 | -------------------------------------------------------------------------------- /examples/simple_STDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2020 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | A simple example of using STDP. 17 | 18 | A single post-synaptic neuron fires at a constant rate. We connect several 19 | pre-synaptic neurons to it, each of which fires spikes with a fixed time 20 | lag or time advance with respect to the post-synaptic neuron. 21 | The weights of these connections are small, so they will not 22 | significantly affect the firing times of the post-synaptic neuron. 23 | We plot the amount of potentiation or depression of each synapse as a 24 | function of the time difference. 25 | 26 | Adapted from https://neuralensemble.org/docs/PyNN/examples/simple_STDP.html 27 | to run on SpiNNaker, but with alpha-synapses rather than conductance neurons; 28 | the weights involved are too low to be resolved using fixed-point arithmetic, 29 | so some alteration of parameters is necessary to get a similar effect. 30 | """ 31 | 32 | import numpy 33 | import pyNN.spiNNaker as sim 34 | # from quantities import ms 35 | from pyNN.utility.plotting import Figure, Panel, DataTable 36 | import matplotlib.pyplot as plt 37 | 38 | # === Parameters ============================================================ 39 | 40 | firing_period = 100.0 # (ms) interval between spikes 41 | cell_parameters = { 42 | "tau_m": 10.0, # (ms) 43 | "v_thresh": -50.0, # (mV) 44 | "v_reset": -60.0, # (mV) 45 | "v_rest": -60.0, # (mV) 46 | "cm": 1.0, # (nF) 47 | "tau_refrac": firing_period / 2, # (ms) long period to prevent bursting 48 | } 49 | n = 60 # number of synapses / number of presynaptic neurons 50 | delta_t = 1.0 # (ms) time between firing of neighbouring neurons 51 | t_stop = 10 * firing_period + n * delta_t 52 | delay = 3.0 # (ms) synaptic time delay 53 | 54 | # === Set up the simulator ================================================== 55 | 56 | sim.setup(timestep=0.1, min_delay=delay) 57 | 58 | # === Build the network ===================================================== 59 | 60 | 61 | def build_spike_sequences(_period, _duration, _n, _delta_t): 62 | """ 63 | Return a spike time generator for `n` neurons (spike sources), where 64 | all neurons fire with the same period, but neighbouring neurons have a 65 | relative firing time difference of `delta_t`. 66 | """ 67 | def spike_time_gen(i): 68 | """Spike time generator. `i` should be an array of indices.""" 69 | return [numpy.arange( 70 | _period + j * _delta_t, _duration, _period) for j in (i - _n // 2)] 71 | return spike_time_gen 72 | 73 | 74 | spike_sequence_generator = build_spike_sequences( 75 | firing_period, t_stop, n, delta_t) 76 | 77 | spike_sequence = spike_sequence_generator(numpy.arange(n)) 78 | 79 | # presynaptic population 80 | p1 = sim.Population(n, sim.SpikeSourceArray(spike_times=spike_sequence), 81 | label="presynaptic") 82 | # single postsynaptic neuron 83 | p2 = sim.Population(1, sim.IF_curr_alpha(**cell_parameters), 84 | initial_values={"v": cell_parameters["v_reset"]}, 85 | label="postsynaptic") 86 | # drive to the postsynaptic neuron, ensuring it fires at exact multiples of 87 | # the firing period 88 | p3 = sim.Population( 89 | 1, sim.SpikeSourceArray(spike_times=numpy.arange( 90 | firing_period - delay, t_stop, firing_period)), 91 | label="driver") 92 | 93 | # we set the initial weights to be small, to avoid perturbing the firing 94 | # times of the postsynaptic neurons 95 | stdp_model = sim.STDPMechanism( 96 | timing_dependence=sim.SpikePairRule( 97 | tau_plus=20.0, tau_minus=20.0, A_plus=0.05, A_minus=0.06), 98 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=1.0), 99 | weight=0.5, delay=delay) 100 | connections = sim.Projection(p1, p2, sim.AllToAllConnector(), stdp_model) 101 | 102 | # the connection weight from the driver neuron is very strong, to ensure the 103 | # postsynaptic neuron fires at the correct times 104 | driver_connection = sim.Projection(p3, p2, sim.OneToOneConnector(), 105 | sim.StaticSynapse(weight=10.0, delay=delay)) 106 | 107 | # === Instrument the network ================================================= 108 | 109 | p1.record('spikes') 110 | p2.record(['spikes', 'v']) 111 | 112 | # === Run the simulation ===================================================== 113 | 114 | sim.run(t_stop) 115 | 116 | # === Save the results, optionally plot a figure ============================= 117 | 118 | presynaptic_spikes = p1.get_data('spikes').segments[0] 119 | postsynaptic_spikes = p2.get_data('spikes').segments[0] 120 | postsynaptic_v = p2.get_data('v').segments[0] 121 | print(f"Post-synaptic spike times: {postsynaptic_spikes.spiketrains[0]}") 122 | 123 | weights = connections.get(["weight"], "list") 124 | final_weights = numpy.array([w[-1] for w in weights]) 125 | deltas = delta_t * numpy.arange(n // 2, -n // 2, -1) 126 | print(f"Final weights: {final_weights}") 127 | plasticity_data = DataTable(deltas, final_weights) 128 | 129 | Figure( 130 | # pylint: disable=wrong-spelling-in-comment 131 | # raster plot of the presynaptic neuron spike times 132 | Panel(presynaptic_spikes.spiketrains, 133 | yticks=True, markersize=0.2, xlim=(0, t_stop)), 134 | # membrane potential of the postsynaptic neuron 135 | Panel(postsynaptic_v.filter(name='v')[0], 136 | ylabel="Membrane potential (mV)", 137 | data_labels=[p2.label], xticks=True, yticks=True, xlim=(0, t_stop)), 138 | # evolution of the synaptic weights with time 139 | # Panel(weights, xticks=True, yticks=True, xlabel="Time (ms)", 140 | # legend=False, xlim=(0, t_stop)), 141 | # scatterplot of the final weight of each synapse against the relative 142 | # timing of pre- and postsynaptic spikes for that synapse 143 | Panel(plasticity_data, 144 | xticks=True, yticks=True, xlim=(-n / 2 * delta_t, n / 2 * delta_t), 145 | ylim=(0.9 * final_weights.min(), 1.1 * final_weights.max()), 146 | xlabel="t_post - t_pre (ms)", ylabel="Final weight (nA)"), 147 | title="Simple STDP example", 148 | annotations=f"Simulated with {sim.name()}" 149 | ) 150 | 151 | # figure_filename = "simple_STDP.png" 152 | # plt.savefig(figure_filename) 153 | plt.show() 154 | 155 | # === Clean up and quit ======================================================= 156 | 157 | sim.end() 158 | -------------------------------------------------------------------------------- /examples/spike_time_compare.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # A simple script that compares the spikes from two inputs to determine if 16 | # one spiked just before or after the other. 17 | 18 | import pyNN.spiNNaker as sim 19 | import pyNN.utility.plotting as plot 20 | import matplotlib.pyplot as plt 21 | 22 | sim.setup(timestep=1.0) 23 | 24 | # A population that will only spike if it receives exactly two spikes at 25 | # exactly the same time. 26 | # NOTE: Weird parameters tweaked to get the desired result 27 | # this set of parameters require very high weight so are NOT ideal 28 | pop_1 = sim.Population(11, sim.IF_curr_exp( 29 | tau_syn_E=1, tau_refrac=0, tau_m=1), label="pop_1") 30 | 31 | # Two population that spike at slightly different times 32 | input_1 = sim.Population( 33 | 1, sim.SpikeSourceArray(spike_times=[1, 21, 42, 61, 84]), label="input") 34 | input_2 = sim.Population( 35 | 1, sim.SpikeSourceArray(spike_times=[1, 22, 41, 57, 81]), label="input") 36 | 37 | # One projection which sends the spikes to different neurons 38 | # with a range of delays 39 | input_proj = sim.Projection( 40 | input_1, pop_1, sim.FromListConnector( 41 | [(0, i, 20, i + 1) for i in range(pop_1.size)]), 42 | synapse_type=sim.StaticSynapse()) 43 | # One projection that always sends to all neurons with the average delay 44 | input_proj = sim.Projection(input_2, pop_1, sim.AllToAllConnector(), 45 | synapse_type=sim.StaticSynapse(weight=20, delay=6)) 46 | 47 | # Request to record data 48 | pop_1.record(["spikes", "v"]) 49 | 50 | # run 51 | simtime = 100 52 | sim.run(simtime) 53 | 54 | # get the Data out in PyNN's Neo format 55 | neo = pop_1.get_data(variables=["spikes", "v"]) 56 | spikes = neo.segments[0].spiketrains 57 | print(spikes) 58 | v = neo.segments[0].filter(name='v')[0] 59 | print(v) 60 | 61 | # End the simulation 62 | sim.end() 63 | 64 | # Plot 65 | plot.Figure( 66 | # plot voltage for first ([0]) neuron 67 | plot.Panel(v, ylabel="Membrane potential (mV)", 68 | data_labels=[pop_1.label], yticks=True, xlim=(0, simtime)), 69 | # plot spikes (or in this case spike) 70 | plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)), 71 | title="Simple Example", 72 | annotations=f"Simulated with {sim.name()}" 73 | ) 74 | plt.show() 75 | -------------------------------------------------------------------------------- /examples/split_examples/stdp_neuromodulated_example_split.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Simple test for neuromodulated-STDP 17 | We take 10 populations of 5 stimuli neurons and connect to each 18 | 10 post-synaptic populations of 5 neurons. The spiking of stimuli causes some 19 | spikes in post-synaptic neurons initially. 20 | We then inject reward signals from dopaminergic neurons 21 | periodically to reinforce synapses that are active. This 22 | is followed by increased weights of some synapses and thus 23 | increased response to the stimuli. 24 | We then proceed to inject punishment signals from dopaminergic 25 | neurons which causes an inverse effect to reduce response of 26 | post-synaptic neurons to the same stimuli. 27 | """ 28 | 29 | import pyNN.spiNNaker as sim 30 | import pylab 31 | 32 | timestep = 1.0 33 | stim_rate = 50 34 | duration = 12000 35 | plastic_weights = 1.5 36 | n_neurons = 5 37 | n_pops = 10 38 | 39 | # Times of rewards and punishments 40 | rewards = [x for x in range(2000, 2010)] + \ 41 | [x for x in range(3000, 3020)] + \ 42 | [x for x in range(4000, 4100)] 43 | punishments = [x for x in range(6000, 6010)] + \ 44 | [x for x in range(7000, 7020)] + \ 45 | [x for x in range(8000, 8100)] 46 | 47 | cell_params = {'cm': 0.25, 48 | 'i_offset': 0.0, 49 | 'tau_m': 20.0, 50 | 'tau_refrac': 2.0, 51 | 'tau_syn_E': 1.0, 52 | 'tau_syn_I': 1.0, 53 | 'v_reset': -70.0, 54 | 'v_rest': -65.0, 55 | 'v_thresh': -50.0 56 | } 57 | 58 | sim.setup(timestep=timestep) 59 | sim.set_number_of_synapse_cores(sim.IF_curr_exp, 1) 60 | 61 | # Create a population of dopaminergic neurons for reward and punishment 62 | reward_pop = sim.Population(n_neurons, sim.SpikeSourceArray, 63 | {'spike_times': rewards}, label='reward') 64 | punishment_pop = sim.Population(n_neurons, sim.SpikeSourceArray, 65 | {'spike_times': punishments}, 66 | label='punishment') 67 | 68 | pre_pops = [] 69 | stimulation = [] 70 | post_pops = [] 71 | reward_projections = [] 72 | punishment_projections = [] 73 | plastic_projections = [] 74 | stim_projections = [] 75 | 76 | # Create synapse dynamics with neuromodulated STDP. 77 | synapse_dynamics = sim.STDPMechanism( 78 | timing_dependence=sim.SpikePairRule( 79 | tau_plus=2, tau_minus=1, 80 | A_plus=1, A_minus=1), 81 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=20), 82 | weight=plastic_weights) 83 | 84 | for i in range(n_pops): 85 | stimulation.append(sim.Population( 86 | n_neurons, sim.SpikeSourcePoisson(rate=stim_rate, duration=duration), 87 | label="pre")) 88 | post_pops.append(sim.Population( 89 | n_neurons, sim.IF_curr_exp, cell_params, label='post')) 90 | plastic_projections.append( 91 | sim.Projection(stimulation[i], post_pops[i], 92 | sim.OneToOneConnector(), 93 | synapse_type=synapse_dynamics, 94 | receptor_type='excitatory', 95 | label='Pre-post projection')) 96 | post_pops[i].record('spikes') 97 | reward_projections.append(sim.Projection( 98 | reward_pop, post_pops[i], sim.OneToOneConnector(), 99 | synapse_type=sim.extra_models.Neuromodulation( 100 | weight=0.05, tau_c=100.0, tau_d=5.0, w_max=20.0), 101 | receptor_type='reward', label='reward synapses')) 102 | punishment_projections.append(sim.Projection( 103 | punishment_pop, post_pops[i], sim.OneToOneConnector(), 104 | synapse_type=sim.extra_models.Neuromodulation( 105 | weight=0.05, tau_c=100.0, tau_d=5.0, w_max=20.0), 106 | receptor_type='punishment', label='punishment synapses')) 107 | 108 | sim.run(duration) 109 | 110 | # Graphical diagnostics 111 | 112 | 113 | def plot_spikes(spikes, title, n_neurons): 114 | if spikes is not None: 115 | pylab.figure(figsize=(15, 5)) 116 | pylab.xlim((0, duration)) 117 | pylab.ylim((0, (10 * n_neurons) + 1)) 118 | pylab.plot([i[1] for i in spikes], [i[0] for i in spikes], ".") 119 | pylab.xlabel('Time/ms') 120 | pylab.ylabel('spikes') 121 | pylab.title(title) 122 | else: 123 | print("No spikes received") 124 | 125 | 126 | post_spikes = [] 127 | weights = [] 128 | 129 | for i in range(n_pops): 130 | weights.append(plastic_projections[i].get('weight', 'list')) 131 | spikes = post_pops[i].get_data('spikes').segments[0].spiketrains 132 | for j in range(n_neurons): 133 | for x in spikes[j]: 134 | post_spikes.append([(i*n_neurons)+j+1, x]) 135 | 136 | plot_spikes(post_spikes, "post-synaptic neuron activity", n_neurons) 137 | pylab.plot(rewards, [0.5 for x in rewards], 'g^') 138 | pylab.plot(punishments, [0.5 for x in punishments], 'r^') 139 | pylab.show() 140 | 141 | print("Weights(Initial %s)" % plastic_weights) 142 | for x in weights: 143 | print(x) 144 | 145 | sim.end() 146 | -------------------------------------------------------------------------------- /examples/split_examples/structural_plasticity_with_stdp_neuromodulated.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Simple test for neuromodulated-STDP with structural plasticity 17 | We take 10 populations of 49 stimuli neurons and connect to each 18 | 10 post-synaptic populations of 49 neurons. The spiking of stimuli causes some 19 | spikes in post-synaptic neurons initially. 20 | We then inject reward signals from dopaminergic neurons 21 | periodically to reinforce synapses that are active. This 22 | is followed by increased weights of some synapses and thus 23 | increased response to the stimuli. 24 | We then proceed to inject punishment signals from dopaminergic 25 | neurons which causes an inverse effect to reduce response of 26 | post-synaptic neurons to the same stimuli. 27 | At the same time we implement a straightforward creation/elimination structural 28 | method (similar to that used in the other structural plasticity examples). 29 | 30 | This uses the split neuron-synapse modelling as otherwise the neuromodulated 31 | STDP, structural plasticity and neuron instructions would not fit on one core 32 | """ 33 | 34 | import pyNN.spiNNaker as sim 35 | import pylab 36 | import numpy as np 37 | 38 | timestep = 1.0 39 | stim_rate = 50 40 | duration = 12000 41 | plastic_weights = 0.5 42 | n_neurons = 7**2 43 | n_pops = 10 44 | 45 | # Times of rewards and punishments 46 | rewards = [x for x in range(2000, 2010)] + \ 47 | [x for x in range(3000, 3020)] + \ 48 | [x for x in range(4000, 4100)] 49 | punishments = [x for x in range(6000, 6010)] + \ 50 | [x for x in range(7000, 7020)] + \ 51 | [x for x in range(8000, 8100)] 52 | 53 | cell_params = {'cm': 0.25, 54 | 'i_offset': 0.0, 55 | 'tau_m': 20.0, 56 | 'tau_refrac': 2.0, 57 | 'tau_syn_E': 1.0, 58 | 'tau_syn_I': 1.0, 59 | 'v_reset': -70.0, 60 | 'v_rest': -65.0, 61 | 'v_thresh': -50.0 62 | } 63 | 64 | sim.setup(timestep=timestep) 65 | 66 | # Create a population of dopaminergic neurons for reward and punishment 67 | reward_pop = sim.Population(n_neurons, sim.SpikeSourceArray, 68 | {'spike_times': rewards}, label='reward') 69 | punishment_pop = sim.Population(n_neurons, sim.SpikeSourceArray, 70 | {'spike_times': punishments}, 71 | label='punishment') 72 | 73 | pre_pops = [] 74 | stimulation = [] 75 | post_pops = [] 76 | reward_projections = [] 77 | punishment_projections = [] 78 | plastic_projections = [] 79 | stim_projections = [] 80 | 81 | 82 | # Create synapse dynamics with neuromodulated STDP and structural plasticity 83 | # Structurally plastic connection between pre_pop and post_pop 84 | partner_selection_last_neuron = sim.RandomSelection() 85 | formation_distance = sim.DistanceDependentFormation( 86 | grid=[np.sqrt(n_neurons), np.sqrt(n_neurons)], # spatial neurons 87 | sigma_form_forward=0.5 # spread of feed-forward connections 88 | ) 89 | elimination_weight = sim.RandomByWeightElimination( 90 | prob_elim_potentiated=0.2, # no eliminations for potentiated synapses 91 | prob_elim_depressed=0.2, # no elimination for depressed synapses 92 | threshold=plastic_weights # Use same weight as initial weight for static 93 | ) 94 | 95 | synapse_dynamics = sim.StructuralMechanismSTDP( 96 | # Partner selection, formation and elimination rules from above 97 | partner_selection_last_neuron, formation_distance, elimination_weight, 98 | # Use this weight when creating a new synapse 99 | initial_weight=plastic_weights, 100 | # Use this weight for synapses at start of simulation 101 | weight=plastic_weights, 102 | # Use this delay when creating a new synapse 103 | initial_delay=10, 104 | # Use this delay for synapses at the start of simulation 105 | delay=10, 106 | # Maximum allowed fan-in per target-layer neuron 107 | s_max=64, 108 | # Frequency of rewiring in Hz 109 | f_rew=10 ** 4, 110 | # timing and weight as required for neuromodulation 111 | timing_dependence=sim.SpikePairRule( 112 | tau_plus=2, tau_minus=1, 113 | A_plus=1, A_minus=1), 114 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=5.0)) 115 | 116 | for i in range(n_pops): 117 | stimulation.append(sim.Population( 118 | n_neurons, sim.SpikeSourcePoisson(rate=stim_rate, duration=duration), 119 | label="pre")) 120 | post_pops.append(sim.Population( 121 | n_neurons, sim.IF_curr_exp, cell_params, label='post')) 122 | plastic_projections.append( 123 | sim.Projection(stimulation[i], post_pops[i], 124 | sim.FixedProbabilityConnector(0.), # no initial conns 125 | synapse_type=synapse_dynamics, 126 | receptor_type='excitatory', 127 | label='Pre-post projection')) 128 | post_pops[i].record('spikes') 129 | reward_projections.append(sim.Projection( 130 | reward_pop, post_pops[i], sim.OneToOneConnector(), 131 | synapse_type=sim.extra_models.Neuromodulation( 132 | weight=0.05, tau_c=100.0, tau_d=5.0, w_max=5.0), 133 | receptor_type='reward', label='reward synapses')) 134 | punishment_projections.append(sim.Projection( 135 | punishment_pop, post_pops[i], sim.OneToOneConnector(), 136 | synapse_type=sim.extra_models.Neuromodulation( 137 | weight=0.05, tau_c=100.0, tau_d=5.0, w_max=5.0), 138 | receptor_type='punishment', label='punishment synapses')) 139 | 140 | sim.run(duration) 141 | 142 | # Graphical diagnostics 143 | 144 | 145 | def plot_spikes(spikes, title, n_pops, n_neurons): 146 | if spikes is not None: 147 | pylab.figure(figsize=(15, 5)) 148 | pylab.xlim((0, duration)) 149 | pylab.ylim((0, (n_pops * n_neurons) + 1)) 150 | pylab.plot([i[1] for i in spikes], [i[0] for i in spikes], ".") 151 | pylab.xlabel('Time/ms') 152 | pylab.ylabel('spikes') 153 | pylab.title(title) 154 | else: 155 | print("No spikes received") 156 | 157 | 158 | post_spikes = [] 159 | weights = [] 160 | 161 | for i in range(n_pops): 162 | weights.append(plastic_projections[i].get('weight', 'list')) 163 | spikes = post_pops[i].get_data('spikes').segments[0].spiketrains 164 | for j in range(n_neurons): 165 | for x in spikes[j]: 166 | post_spikes.append([(i*n_neurons)+j+1, x]) 167 | 168 | plot_spikes(post_spikes, "post-synaptic neuron activity", n_pops, n_neurons) 169 | pylab.plot(rewards, [0.5 for x in rewards], 'g^') 170 | pylab.plot(punishments, [0.5 for x in punishments], 'r^') 171 | pylab.show() 172 | 173 | print("Weights(Initial %s)" % plastic_weights) 174 | for x in weights: 175 | print(x) 176 | 177 | sim.end() 178 | -------------------------------------------------------------------------------- /examples/stdp_curve.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as pylab 16 | import pyNN.spiNNaker as sim 17 | 18 | # ------------------------------------------------------------------ 19 | # This example uses the sPyNNaker implementation of pair-based STDP 20 | # To reproduce the eponymous STDP curve first 21 | # Plotted by Bi and Poo (1998) 22 | # ------------------------------------------------------------------ 23 | 24 | # ------------------------------------------------------------------ 25 | # Common parameters 26 | # ------------------------------------------------------------------ 27 | time_between_pairs = 1000 28 | num_pairs = 60 29 | start_w = 0.5 30 | delta_t = [-100, -60, -40, -30, -20, -10, -1, 1, 10, 20, 30, 40, 60, 100] 31 | start_time = 200 32 | mad = True 33 | 34 | # Population parameters 35 | model = sim.IF_curr_exp 36 | cell_params = {'cm': 0.25, # nF 37 | 'i_offset': 0.0, 38 | 'tau_m': 10.0, 39 | 'tau_refrac': 2.0, 40 | 'tau_syn_E': 2.5, 41 | 'tau_syn_I': 2.5, 42 | 'v_reset': -70.0, 43 | 'v_rest': -65.0, 44 | 'v_thresh': -55.4 45 | } 46 | 47 | # SpiNNaker setup 48 | sim.setup(timestep=1.0, min_delay=1.0) 49 | 50 | # ------------------------------------------------------------------- 51 | # Experiment loop 52 | # ------------------------------------------------------------------- 53 | projections = [] 54 | sim_time = 0 55 | for t in delta_t: 56 | # Calculate phase of input spike trains 57 | # If M.A.D., take into account dendritic delay 58 | if mad: 59 | # Pre after post 60 | if t > 0: 61 | post_phase = 0 62 | pre_phase = t + 1 63 | # Post after pre 64 | else: 65 | post_phase = -t 66 | pre_phase = 1 67 | # Otherwise, take into account axonal delay 68 | else: 69 | # Pre after post 70 | if t > 0: 71 | post_phase = 1 72 | pre_phase = t 73 | # Post after pre 74 | else: 75 | post_phase = 1 - t 76 | pre_phase = 0 77 | 78 | sim_time = max(sim_time, (num_pairs * time_between_pairs) + abs(t)) 79 | 80 | # Neuron populations 81 | pre_pop = sim.Population(1, model(**cell_params)) 82 | post_pop = sim.Population(1, model, cell_params) 83 | 84 | # Stimulating populations 85 | pre_times = [i for i in range(pre_phase, sim_time, time_between_pairs)] 86 | post_times = [i for i in range(post_phase, sim_time, time_between_pairs)] 87 | pre_stim = sim.Population( 88 | 1, sim.SpikeSourceArray(spike_times=[pre_times])) 89 | post_stim = sim.Population( 90 | 1, sim.SpikeSourceArray(spike_times=[post_times])) 91 | 92 | weight = 2 93 | 94 | # Connections between spike sources and neuron populations 95 | ee_connector = sim.OneToOneConnector() 96 | sim.Projection( 97 | pre_stim, pre_pop, ee_connector, receptor_type='excitatory', 98 | synapse_type=sim.StaticSynapse(weight=weight)) 99 | sim.Projection( 100 | post_stim, post_pop, ee_connector, receptor_type='excitatory', 101 | synapse_type=sim.StaticSynapse(weight=weight)) 102 | 103 | # Plastic Connection between pre_pop and post_pop 104 | stdp_model = sim.STDPMechanism( 105 | timing_dependence=sim.SpikePairRule( 106 | tau_plus=16.7, tau_minus=33.7, A_plus=0.005, A_minus=0.005), 107 | weight_dependence=sim.AdditiveWeightDependence( 108 | w_min=0.0, w_max=1), weight=start_w) 109 | 110 | projections.append(sim.Projection( 111 | pre_pop, post_pop, sim.OneToOneConnector(), 112 | synapse_type=stdp_model)) 113 | 114 | print("Simulating for {sim_time / 1000}s") 115 | 116 | # Run simulation 117 | sim.run(sim_time) 118 | 119 | # Get weight from each projection 120 | end_w = [p.get('weight', 'list', with_address=False)[0] for p in projections] 121 | 122 | # End simulation on SpiNNaker 123 | sim.end() 124 | 125 | # ------------------------------------------------------------------- 126 | # Plot curve 127 | # ------------------------------------------------------------------- 128 | # Calculate deltas from end weights 129 | delta_w = [(w - start_w) / start_w for w in end_w] 130 | 131 | # Plot STDP curve 132 | figure, axis = pylab.subplots() 133 | axis.set_xlabel(r"$(t_{j} - t_{i}/ms)$") 134 | axis.set_ylabel(r"$(\frac{\Delta w_{ij}}{w_{ij}})$", 135 | rotation="horizontal", size="xx-large") 136 | axis.plot(delta_t, delta_w) 137 | axis.axhline(color="grey", linestyle="--") 138 | axis.axvline(color="grey", linestyle="--") 139 | 140 | pylab.show() 141 | -------------------------------------------------------------------------------- /examples/stdp_curve_cond.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as pylab 16 | import pyNN.spiNNaker as sim 17 | 18 | # ------------------------------------------------------------------ 19 | # This example uses the sPyNNaker implementation of pair-based STDP 20 | # To reproduce the eponymous STDP curve first 21 | # Plotted by Bi and Poo (1998) 22 | # ------------------------------------------------------------------ 23 | 24 | # ------------------------------------------------------------------ 25 | # Common parameters 26 | # ------------------------------------------------------------------ 27 | time_between_pairs = 1000 28 | num_pairs = 60 29 | start_w = 0.005 30 | delta_t = [-100, -60, -40, -30, -20, -10, -1, 1, 10, 20, 30, 40, 60, 100] 31 | start_time = 200 32 | mad = True 33 | 34 | # Population parameters 35 | model = sim.IF_cond_exp 36 | cell_params = {'cm': 0.25, # nF 37 | 'i_offset': 0.0, 38 | 'tau_m': 10.0, 39 | 'tau_refrac': 2.0, 40 | 'tau_syn_E': 2.5, 41 | 'tau_syn_I': 2.5, 42 | 'v_reset': -70.0, 43 | 'v_rest': -65.0, 44 | 'v_thresh': -55.4 45 | } 46 | 47 | # SpiNNaker setup 48 | sim.setup(timestep=1.0, min_delay=1.0) 49 | 50 | # ------------------------------------------------------------------- 51 | # Experiment loop 52 | # ------------------------------------------------------------------- 53 | projections = [] 54 | sim_time = 0 55 | for t in delta_t: 56 | # Calculate phase of input spike trains 57 | # If M.A.D., take into account dendritic delay 58 | if mad: 59 | # Pre after post 60 | if t > 0: 61 | post_phase = 0 62 | pre_phase = t + 1 63 | # Post after pre 64 | else: 65 | post_phase = -t 66 | pre_phase = 1 67 | # Otherwise, take into account axonal delay 68 | else: 69 | # Pre after post 70 | if t > 0: 71 | post_phase = 1 72 | pre_phase = t 73 | # Post after pre 74 | else: 75 | post_phase = 1 - t 76 | pre_phase = 0 77 | 78 | sim_time = max(sim_time, (num_pairs * time_between_pairs) + abs(t)) 79 | 80 | # Neuron populations 81 | pre_pop = sim.Population(1, model(**cell_params)) 82 | post_pop = sim.Population(1, model, cell_params) 83 | 84 | # Stimulating populations 85 | pre_times = [i for i in range(pre_phase, sim_time, time_between_pairs)] 86 | post_times = [i for i in range(post_phase, sim_time, time_between_pairs)] 87 | pre_stim = sim.Population( 88 | 1, sim.SpikeSourceArray(spike_times=[pre_times])) 89 | post_stim = sim.Population( 90 | 1, sim.SpikeSourceArray(spike_times=[post_times])) 91 | 92 | weight = 0.035 93 | 94 | # Connections between spike sources and neuron populations 95 | ee_connector = sim.OneToOneConnector() 96 | sim.Projection( 97 | pre_stim, pre_pop, ee_connector, receptor_type='excitatory', 98 | synapse_type=sim.StaticSynapse(weight=weight)) 99 | sim.Projection( 100 | post_stim, post_pop, ee_connector, receptor_type='excitatory', 101 | synapse_type=sim.StaticSynapse(weight=weight)) 102 | 103 | # Plastic Connection between pre_pop and post_pop 104 | stdp_model = sim.STDPMechanism( 105 | timing_dependence=sim.SpikePairRule( 106 | tau_plus=16.7, tau_minus=33.7, 107 | A_plus=0.0000875, A_minus=0.0000875), 108 | weight_dependence=sim.AdditiveWeightDependence( 109 | w_min=0.0, w_max=0.0175), weight=start_w) 110 | 111 | projections.append(sim.Projection( 112 | pre_pop, post_pop, sim.OneToOneConnector(), 113 | synapse_type=stdp_model)) 114 | 115 | print(f"Simulating for {sim_time / 1000}s") 116 | 117 | # Run simulation 118 | sim.run(sim_time) 119 | 120 | # Get weight from each projection 121 | end_w = [p.get('weight', 'list', with_address=False)[0] for p in projections] 122 | 123 | # End simulation on SpiNNaker 124 | sim.end() 125 | 126 | # ------------------------------------------------------------------- 127 | # Plot curve 128 | # ------------------------------------------------------------------- 129 | # Calculate deltas from end weights 130 | delta_w = [(w - start_w) / start_w for w in end_w] 131 | 132 | # Plot STDP curve 133 | figure, axis = pylab.subplots() 134 | axis.set_xlabel(r"$(t_{j} - t_{i}/ms)$") 135 | axis.set_ylabel(r"$(\frac{\Delta w_{ij}}{w_{ij}})$", 136 | rotation="horizontal", size="xx-large") 137 | axis.plot(delta_t, delta_w) 138 | axis.axhline(color="grey", linestyle="--") 139 | axis.axvline(color="grey", linestyle="--") 140 | 141 | pylab.show() 142 | -------------------------------------------------------------------------------- /examples/stdp_example_get_plastic_params.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Simple test for STDP : 17 | 18 | Reproduces a classical plasticity experiment of plasticity induction by 19 | pre/post synaptic pairing specifically : 20 | 21 | * At the beginning of the simulation, "n_stim_test" external stimulations of 22 | the "pre_pop" (presynaptic) population do not trigger activity in the 23 | "post_pop" (postsynaptic) population. 24 | 25 | * Then the presynaptic and postsynaptic populations are stimulated together 26 | "n_stim_pairing" times by an external source so that the "post_pop" 27 | population spikes 10ms after the "pre_pop" population. 28 | 29 | * Ater that period, only the "pre_pop" population is externally stimulated 30 | "n_stim_test" times, but now it should trigger activity in the "post_pop" 31 | population (due to STDP learning) 32 | 33 | Run as : 34 | 35 | $ ./stdp_example 36 | 37 | This example requires that the NeuroTools package is installed 38 | (https://neuralensemble.org/trac/NeuroTools) 39 | 40 | Authors : Catherine Wacongne < catherine.waco@gmail.com > 41 | Xavier Lagorce < Xavier.Lagorce@crans.org > 42 | 43 | April 2013 44 | """ 45 | import pyNN.spiNNaker as sim 46 | 47 | # SpiNNaker setup 48 | sim.setup(timestep=1.0, min_delay=1.0) 49 | 50 | # +-------------------------------------------------------------------+ 51 | # | General Parameters | 52 | # +-------------------------------------------------------------------+ 53 | 54 | # Population parameters 55 | model = sim.IF_curr_exp 56 | 57 | cell_params = { 58 | 'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0, 59 | 'tau_refrac': 2.0, 'tau_syn_E': 5.0, 'tau_syn_I': 5.0, 60 | 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -50.0} 61 | 62 | 63 | # Other simulation parameters 64 | e_rate = 80 65 | in_rate = 300 66 | 67 | n_stim_test = 5 68 | n_stim_pairing = 20 69 | dur_stim = 20 70 | 71 | pop_size = 40 72 | 73 | ISI = 90. 74 | start_test_pre_pairing = 200. 75 | start_pairing = 1500. 76 | start_test_post_pairing = 700. 77 | 78 | simtime = (start_pairing + start_test_post_pairing 79 | + ISI * (n_stim_pairing + n_stim_test) + 550.) 80 | 81 | # Initialisations of the different types of populations 82 | IAddPre = [] 83 | IAddPost = [] 84 | 85 | # +-------------------------------------------------------------------+ 86 | # | Creation of neuron populations | 87 | # +-------------------------------------------------------------------+ 88 | 89 | # Neuron populations 90 | pre_pop = sim.Population(pop_size, model(**cell_params)) 91 | post_pop = sim.Population(pop_size, model(**cell_params)) 92 | 93 | # Test of the effect of activity of the pre_pop population on the post_pop 94 | # population prior to the "pairing" protocol : only pre_pop is stimulated 95 | for i in range(n_stim_test): 96 | IAddPre.append(sim.Population( 97 | pop_size, sim.SpikeSourcePoisson( 98 | rate=in_rate, start=start_test_pre_pairing + ISI * i, 99 | duration=dur_stim))) 100 | 101 | # Pairing protocol : pre_pop and post_pop are stimulated with a 10 ms 102 | # difference 103 | for i in range(n_stim_pairing): 104 | IAddPre.append(sim.Population( 105 | pop_size, sim.SpikeSourcePoisson( 106 | rate=in_rate, start=start_pairing + ISI * i, duration=dur_stim))) 107 | IAddPost.append(sim.Population( 108 | pop_size, sim.SpikeSourcePoisson( 109 | rate=in_rate, start=start_pairing + ISI * i + 10., 110 | duration=dur_stim))) 111 | 112 | # Test post pairing : only pre_pop is stimulated (and should trigger activity 113 | # in Post) 114 | for i in range(n_stim_test): 115 | IAddPre.append(sim.Population( 116 | pop_size, sim.SpikeSourcePoisson( 117 | rate=in_rate, start=( 118 | start_pairing + ISI * n_stim_pairing + 119 | start_test_post_pairing + ISI * i), 120 | duration=dur_stim))) 121 | 122 | # Noise inputs 123 | INoisePre = sim.Population( 124 | pop_size, sim.SpikeSourcePoisson( 125 | rate=e_rate, start=0, duration=simtime), label="expoisson") 126 | INoisePost = sim.Population( 127 | pop_size, sim.SpikeSourcePoisson( 128 | rate=e_rate, start=0, duration=simtime), label="expoisson") 129 | 130 | # +-------------------------------------------------------------------+ 131 | # | Creation of connections | 132 | # +-------------------------------------------------------------------+ 133 | 134 | # Connection parameters 135 | JEE = 3. 136 | 137 | # Connection type between noise poisson generator and excitatory populations 138 | ee_connector = sim.OneToOneConnector() 139 | 140 | # Noise projections 141 | sim.Projection( 142 | INoisePre, pre_pop, ee_connector, receptor_type='excitatory', 143 | synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) 144 | sim.Projection( 145 | INoisePost, post_pop, ee_connector, receptor_type='excitatory', 146 | synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) 147 | 148 | # Additional Inputs projections 149 | for iAddPre in IAddPre: 150 | sim.Projection( 151 | iAddPre, pre_pop, ee_connector, receptor_type='excitatory', 152 | synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) 153 | for iAddPost in IAddPost: 154 | sim.Projection( 155 | iAddPost, post_pop, ee_connector, receptor_type='excitatory', 156 | synapse_type=sim.StaticSynapse(weight=JEE * 0.05)) 157 | 158 | # Plastic Connections between pre_pop and post_pop 159 | stdp_model = sim.STDPMechanism( 160 | timing_dependence=sim.SpikePairRule( 161 | tau_plus=20., tau_minus=20.0, A_plus=0.02, A_minus=0.02), 162 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.01)) 163 | 164 | plastic_projection = sim.Projection( 165 | pre_pop, post_pop, sim.FixedProbabilityConnector(p_connect=0.5), 166 | synapse_type=stdp_model) 167 | 168 | # +-------------------------------------------------------------------+ 169 | # | Simulation and results | 170 | # +-------------------------------------------------------------------+ 171 | 172 | # Run simulation 173 | sim.run(simtime) 174 | 175 | print(f"Weights:{plastic_projection.get('weight', 'list')}") 176 | print(f"plastic1:{plastic_projection.get('tau_plus', 'list')}") 177 | print(f"plastic2andweights:" 178 | f"{plastic_projection.get(['weight', 'tau_plus'], 'list')}") 179 | 180 | # End simulation on SpiNNaker 181 | sim.end() 182 | -------------------------------------------------------------------------------- /examples/stdp_neuromodulated_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Simple test for neuromodulated-STDP 17 | We take 10 populations of 5 stimuli neurons and connect to each 18 | 10 post-synaptic populations of 5 neurons. The spiking of stimuli causes some 19 | spikes in post-synaptic neurons initially. 20 | We then inject reward signals from dopaminergic neurons 21 | periodically to reinforce synapses that are active. This 22 | is followed by increased weights of some synapses and thus 23 | increased response to the stimuli. 24 | We then proceed to inject punishment signals from dopaminergic 25 | neurons which causes an inverse effect to reduce response of 26 | post-synaptic neurons to the same stimuli. 27 | """ 28 | 29 | import pyNN.spiNNaker as sim 30 | import pylab 31 | 32 | timestep = 1.0 33 | stim_rate = 50 34 | duration = 12000 35 | plastic_weights = 1.5 36 | n_neurons = 5 37 | n_pops = 10 38 | 39 | # Times of rewards and punishments 40 | rewards = [x for x in range(2000, 2010)] + \ 41 | [x for x in range(3000, 3020)] + \ 42 | [x for x in range(4000, 4100)] 43 | punishments = [x for x in range(6000, 6010)] + \ 44 | [x for x in range(7000, 7020)] + \ 45 | [x for x in range(8000, 8100)] 46 | 47 | cell_params = {'cm': 0.25, 48 | 'i_offset': 0.0, 49 | 'tau_m': 20.0, 50 | 'tau_refrac': 2.0, 51 | 'tau_syn_E': 1.0, 52 | 'tau_syn_I': 1.0, 53 | 'v_reset': -70.0, 54 | 'v_rest': -65.0, 55 | 'v_thresh': -50.0 56 | } 57 | 58 | sim.setup(timestep=timestep) 59 | 60 | # Create a population of dopaminergic neurons for reward and punishment 61 | reward_pop = sim.Population(n_neurons, sim.SpikeSourceArray, 62 | {'spike_times': rewards}, label='reward') 63 | punishment_pop = sim.Population(n_neurons, sim.SpikeSourceArray, 64 | {'spike_times': punishments}, 65 | label='punishment') 66 | 67 | pre_pops = [] 68 | stimulation = [] 69 | post_pops = [] 70 | reward_projections = [] 71 | punishment_projections = [] 72 | plastic_projections = [] 73 | stim_projections = [] 74 | 75 | # Create synapse dynamics with neuromodulated STDP. 76 | synapse_dynamics = sim.STDPMechanism( 77 | timing_dependence=sim.SpikePairRule( 78 | tau_plus=2, tau_minus=1, 79 | A_plus=1, A_minus=1), 80 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=20), 81 | weight=plastic_weights) 82 | 83 | for i in range(n_pops): 84 | stimulation.append(sim.Population(n_neurons, sim.SpikeSourcePoisson, 85 | {'rate': stim_rate, 'duration': duration}, label="pre")) 86 | post_pops.append(sim.Population( 87 | n_neurons, sim.IF_curr_exp, cell_params, label='post')) 88 | plastic_projections.append( 89 | sim.Projection(stimulation[i], post_pops[i], 90 | sim.OneToOneConnector(), 91 | synapse_type=synapse_dynamics, 92 | receptor_type='excitatory', 93 | label='Pre-post projection')) 94 | post_pops[i].record('spikes') 95 | reward_projections.append(sim.Projection( 96 | reward_pop, post_pops[i], sim.OneToOneConnector(), 97 | synapse_type=sim.extra_models.Neuromodulation( 98 | weight=0.05, tau_c=100.0, tau_d=5.0, w_max=20.0), 99 | receptor_type='reward', label='reward synapses')) 100 | punishment_projections.append(sim.Projection( 101 | punishment_pop, post_pops[i], sim.OneToOneConnector(), 102 | synapse_type=sim.extra_models.Neuromodulation( 103 | weight=0.05, tau_c=100.0, tau_d=5.0, w_max=20.0), 104 | receptor_type='punishment', label='punishment synapses')) 105 | 106 | sim.run(duration) 107 | 108 | # Graphical diagnostics 109 | 110 | 111 | def plot_spikes(_spikes, _title, _n_neurons): 112 | """ 113 | Plots the spikes if there are any. 114 | 115 | :param list([int, quantity]) _spikes: 116 | :param str _title: 117 | :param int _n_neurons: 118 | """ 119 | if _spikes is not None: 120 | pylab.figure(figsize=(15, 5)) 121 | pylab.xlim((0, duration)) 122 | pylab.ylim((0, (10 * _n_neurons) + 1)) 123 | pylab.plot([i[1] for i in _spikes], [i[0] for i in _spikes], ".") 124 | pylab.xlabel('Time/ms') 125 | pylab.ylabel('spikes') 126 | pylab.title(_title) 127 | else: 128 | print("No spikes received") 129 | 130 | 131 | post_spikes = [] 132 | weights = [] 133 | 134 | for i in range(n_pops): 135 | weights.append(plastic_projections[i].get('weight', 'list')) 136 | spikes = post_pops[i].get_data('spikes').segments[0].spiketrains 137 | for j in range(n_neurons): 138 | for x in spikes[j]: 139 | post_spikes.append([(i*n_neurons)+j+1, x]) 140 | 141 | plot_spikes(post_spikes, "post-synaptic neuron activity", n_neurons) 142 | pylab.plot(rewards, [0.5 for x in rewards], 'g^') 143 | pylab.plot(punishments, [0.5 for x in punishments], 'r^') 144 | pylab.show() 145 | 146 | print("Weights(Initial {plastic_weights})") 147 | for x in weights: 148 | print(x) 149 | 150 | sim.end() 151 | -------------------------------------------------------------------------------- /examples/stdp_neuromodulation_test.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Simple test for neuromodulated STDP. 17 | Two pre-synaptic spikes are added, at times 1500 and 2400ms. 18 | Post-synaptic neuron is stimulated at 1502 and fires at time 1503ms. 19 | Dendritic delay is 1ms so post-synaptic time is at 1504ms when processed in 20 | STDP. Dopamine neuron spikes at 1600+1ms (Also added dendritic delay). 21 | Calculating weight change in this scenario, according to equations in the 22 | Izhikevich 2007 paper*, gives us the weight change of 10.0552710... 23 | *https://www.ncbi.nlm.nih.gov/pubmed/17220510 24 | Simulation from SpiNNaker gives us the weight change of 10.0654296875. 25 | Some inaccuracy occurs due to precision loss in s5.11 fixed point format 26 | used in STDP traces and exp LUTs. Also, due to long timing constants, exp 27 | LUTs are discretized further by TAU_C_SHIFT and TAU_D_SHIFT to be able to 28 | fit them into memory, adding another level of inaccuracy. Finally, some more 29 | accuracy may be lost due to weight scaling. 30 | """ 31 | 32 | import pyNN.spiNNaker as sim 33 | 34 | timestep = 1.0 35 | duration = 3000 36 | 37 | # Main parameters from Izhikevich 2007 STDP paper 38 | t_pre = [1500, 2400] # Pre-synaptic neuron times 39 | t_post = [1502] # Post-synaptic neuron stimuli time 40 | t_dopamine = [1600] # Dopaminergic neuron spike times 41 | tau_c = 1000 # Eligibility trace decay time constant. 42 | tau_d = 200 # Dopamine trace decay time constant. 43 | DA_concentration = 0.1 # Dopamine trace step increase size 44 | 45 | # Initial weight 46 | rewarded_syn_weight = 0.0 47 | 48 | cell_params = { 49 | 'cm': 0.3, 50 | 'i_offset': 0.0, 51 | 'tau_m': 10.0, 52 | 'tau_refrac': 4.0, 53 | 'tau_syn_E': 1.0, 54 | 'tau_syn_I': 1.0, 55 | 'v_reset': -70.0, 56 | 'v_rest': -65.0, 57 | 'v_thresh': -55.4} 58 | 59 | sim.setup(timestep=timestep) 60 | 61 | pre_pop = sim.Population(1, sim.SpikeSourceArray, { 62 | 'spike_times': t_pre}) 63 | 64 | # Create a population of dopaminergic neurons for reward 65 | reward_pop = sim.Population(1, sim.SpikeSourceArray, { 66 | 'spike_times': t_dopamine}, label='reward') 67 | 68 | # Stimulus for post synaptic population 69 | post_stim = sim.Population(1, sim.SpikeSourceArray, { 70 | 'spike_times': t_post}) 71 | 72 | # Create post synaptic population which will be modulated by DA concentration. 73 | post_pop = sim.Population( 74 | 1, sim.IF_curr_exp, cell_params, 75 | label='post1') 76 | 77 | # Stimulate post-synaptic neuron 78 | sim.Projection( 79 | post_stim, post_pop, 80 | sim.AllToAllConnector(), 81 | synapse_type=sim.StaticSynapse(weight=6), 82 | receptor_type='excitatory') 83 | 84 | # Create STDP dynamics 85 | synapse_dynamics = sim.STDPMechanism( 86 | timing_dependence=sim.SpikePairRule( 87 | tau_plus=10, tau_minus=12, 88 | A_plus=1, A_minus=1), 89 | weight_dependence=sim.AdditiveWeightDependence( 90 | w_min=0, w_max=20), 91 | weight=0.0) 92 | 93 | # Create a plastic connection between pre and post neurons 94 | plastic_projection = sim.Projection( 95 | pre_pop, post_pop, 96 | sim.AllToAllConnector(), 97 | synapse_type=synapse_dynamics, 98 | receptor_type='excitatory', label='Pre-post projection') 99 | 100 | # Create dopaminergic connection 101 | reward_projection = sim.Projection( 102 | reward_pop, post_pop, 103 | sim.AllToAllConnector(), 104 | synapse_type=sim.extra_models.Neuromodulation( 105 | tau_c=1000, tau_d=200, weight=DA_concentration, w_max=20.0), 106 | receptor_type='reward', label='reward synapses') 107 | 108 | sim.run(duration) 109 | 110 | # End simulation on SpiNNaker 111 | print("Final weight: " + repr(plastic_projection.get('weight', 'list'))) 112 | 113 | sim.end() 114 | -------------------------------------------------------------------------------- /examples/stdp_pairing.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import pyNN.spiNNaker as sim 16 | 17 | # SpiNNaker setup 18 | sim.setup(timestep=1.0, min_delay=1.0) 19 | 20 | # +-------------------------------------------------------------------+ 21 | # | General Parameters | 22 | # +-------------------------------------------------------------------+ 23 | 24 | # Population parameters 25 | model = sim.IF_curr_exp 26 | cell_params = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 10.0, 27 | 'tau_refrac': 2.0, 'tau_syn_E': 2.5, 'tau_syn_I': 2.5, 28 | 'v_reset': -70.0, 'v_rest': -65.0, 'v_thresh': -55.4} 29 | 30 | delta_t = 10 31 | time_between_pairs = 150 32 | num_pre_pairs = 10 33 | num_pairs = 100 34 | num_post_pairs = 10 35 | pop_size = 1 36 | 37 | pairing_start_time = (num_pre_pairs * time_between_pairs) + delta_t 38 | pairing_end_time = pairing_start_time + (num_pairs * time_between_pairs) 39 | sim_time = pairing_end_time + (num_post_pairs * time_between_pairs) 40 | 41 | # +-------------------------------------------------------------------+ 42 | # | Creation of neuron populations | 43 | # +-------------------------------------------------------------------+ 44 | # Neuron populations 45 | pre_pop = sim.Population(pop_size, model, cell_params) 46 | post_pop = sim.Population(pop_size, model, cell_params) 47 | 48 | # Stimulating populations 49 | pre_stim = sim.Population(pop_size, sim.SpikeSourceArray, 50 | {'spike_times': 51 | [[i for i in range(0, sim_time, 52 | time_between_pairs)], ]}) 53 | post_stim = sim.Population(pop_size, sim.SpikeSourceArray, 54 | {'spike_times': 55 | [[i for i in range(pairing_start_time, 56 | pairing_end_time, 57 | time_between_pairs)], ]}) 58 | 59 | # +-------------------------------------------------------------------+ 60 | # | Creation of connections | 61 | # +-------------------------------------------------------------------+ 62 | # Connection type between noise poisson generator and 63 | # excitatory populations 64 | ee_connector = sim.OneToOneConnector() 65 | synapse_type = sim.StaticSynapse(weight=2) 66 | 67 | sim.Projection(pre_stim, pre_pop, ee_connector, synapse_type=synapse_type, 68 | receptor_type='excitatory') 69 | sim.Projection(post_stim, post_pop, ee_connector, 70 | synapse_type=synapse_type, receptor_type='excitatory') 71 | 72 | # Plastic Connections between pre_pop and post_pop 73 | stdp_model = sim.STDPMechanism( 74 | timing_dependence=sim.SpikePairRule(tau_plus=20.0, tau_minus=50.0, 75 | A_plus=0.02, A_minus=0.02), 76 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=1)) 77 | 78 | sim.Projection(pre_pop, post_pop, sim.OneToOneConnector(), 79 | synapse_type=stdp_model) 80 | 81 | # Record spikes 82 | pre_pop.record("spikes") 83 | post_pop.record("spikes") 84 | 85 | # Run simulation 86 | sim.run(sim_time) 87 | 88 | pre_neo = pre_pop.get_data("spikes") 89 | post_neo = post_pop.get_data("spikes") 90 | 91 | # End simulation on SpiNNaker 92 | sim.end() 93 | -------------------------------------------------------------------------------- /examples/synfire_if_cond_exp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import pyNN.spiNNaker as p 19 | from pyNN.utility.plotting import Figure, Panel 20 | import matplotlib.pyplot as plt 21 | 22 | runtime = 5000 23 | p.setup(timestep=1.0, min_delay=1.0) 24 | nNeurons = 200 # number of neurons in each population 25 | p.set_number_of_neurons_per_core(p.IF_cond_exp, nNeurons / 2) 26 | 27 | cell_params_lif = {'cm': 0.25, 28 | 'i_offset': 0.0, 29 | 'tau_m': 20.0, 30 | 'tau_refrac': 2.0, 31 | 'tau_syn_E': 5.0, 32 | 'tau_syn_I': 5.0, 33 | 'v_reset': -70.0, 34 | 'v_rest': -65.0, 35 | 'v_thresh': -50.0, 36 | 'e_rev_E': 0., 37 | 'e_rev_I': -80. 38 | } 39 | 40 | weight_to_spike = 0.035 41 | delay = 17 42 | 43 | loopConnections = list() 44 | for i in range(0, nNeurons): 45 | singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) 46 | loopConnections.append(singleConnection) 47 | 48 | injectionConnection = [(0, 0)] 49 | spikeArray = {'spike_times': [[0]]} 50 | main_pop = p.Population( 51 | nNeurons, p.IF_cond_exp(**cell_params_lif), label='pop_1') 52 | input_pop = p.Population( 53 | 1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1') 54 | 55 | p.Projection( 56 | main_pop, main_pop, p.FromListConnector(loopConnections), 57 | p.StaticSynapse(weight=weight_to_spike, delay=delay)) 58 | p.Projection( 59 | input_pop, main_pop, p.FromListConnector(injectionConnection), 60 | p.StaticSynapse(weight=weight_to_spike, delay=1)) 61 | 62 | main_pop.record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) 63 | 64 | p.run(runtime) 65 | 66 | # get data (could be done as one, but can be done bit by bit as well) 67 | v = main_pop.get_data('v') 68 | gsyn_exc = main_pop.get_data('gsyn_exc') 69 | gsyn_inh = main_pop.get_data('gsyn_inh') 70 | spikes = main_pop.get_data('spikes') 71 | 72 | figure_filename = "results.png" 73 | Figure( 74 | # raster plot of the presynaptic neuron spike times 75 | Panel(spikes.segments[0].spiketrains, 76 | yticks=True, markersize=0.2, xlim=(0, runtime)), 77 | # membrane potential of the postsynaptic neuron 78 | Panel(v.segments[0].filter(name='v')[0], 79 | ylabel="Membrane potential (mV)", 80 | data_labels=[main_pop.label], yticks=True, xlim=(0, runtime)), 81 | Panel(gsyn_exc.segments[0].filter(name='gsyn_exc')[0], 82 | ylabel="gsyn excitatory (mV)", 83 | data_labels=[main_pop.label], yticks=True, xlim=(0, runtime)), 84 | Panel(gsyn_inh.segments[0].filter(name='gsyn_inh')[0], 85 | ylabel="gsyn inhibitory (mV)", 86 | data_labels=[main_pop.label], yticks=True, xlim=(0, runtime)), 87 | title="Simple synfire chain example", 88 | annotations=f"Simulated with {p.name()}" 89 | ) 90 | plt.show() 91 | print(figure_filename) 92 | 93 | p.end() 94 | -------------------------------------------------------------------------------- /examples/synfire_if_curr_exp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import pyNN.spiNNaker as p 19 | from pyNN.utility.plotting import Figure, Panel 20 | import matplotlib.pyplot as plt 21 | 22 | runtime = 5000 23 | p.setup(timestep=1.0, min_delay=1.0) 24 | nNeurons = 200 # number of neurons in each population 25 | p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) 26 | 27 | cell_params_lif = {'cm': 0.25, 28 | 'i_offset': 0.0, 29 | 'tau_m': 20.0, 30 | 'tau_refrac': 2.0, 31 | 'tau_syn_E': 5.0, 32 | 'tau_syn_I': 5.0, 33 | 'v_reset': -70.0, 34 | 'v_rest': -65.0, 35 | 'v_thresh': -50.0 36 | } 37 | 38 | populations = list() 39 | projections = list() 40 | 41 | weight_to_spike = 2.0 42 | delay = 17 43 | 44 | loopConnections = list() 45 | for i in range(0, nNeurons): 46 | singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) 47 | loopConnections.append(singleConnection) 48 | 49 | injectionConnection = [(0, 0)] 50 | spikeArray = {'spike_times': [[0]]} 51 | populations.append( 52 | p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1')) 53 | populations.append( 54 | p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) 55 | 56 | projections.append(p.Projection( 57 | populations[0], populations[0], p.FromListConnector(loopConnections), 58 | p.StaticSynapse(weight=weight_to_spike, delay=delay))) 59 | projections.append(p.Projection( 60 | populations[1], populations[0], p.FromListConnector(injectionConnection), 61 | p.StaticSynapse(weight=weight_to_spike, delay=1))) 62 | 63 | populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) 64 | 65 | p.run(runtime) 66 | 67 | # get data (could be done as one, but can be done bit by bit as well) 68 | v = populations[0].get_data('v') 69 | gsyn_exc = populations[0].get_data('gsyn_exc') 70 | gsyn_inh = populations[0].get_data('gsyn_inh') 71 | spikes = populations[0].get_data('spikes') 72 | 73 | Figure( 74 | # raster plot of the presynaptic neuron spike times 75 | Panel(spikes.segments[0].spiketrains, 76 | yticks=True, markersize=0.2, xlim=(0, runtime)), 77 | # membrane potential of the postsynaptic neuron 78 | Panel(v.segments[0].filter(name='v')[0], 79 | ylabel="Membrane potential (mV)", 80 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 81 | Panel(gsyn_exc.segments[0].filter(name='gsyn_exc')[0], 82 | ylabel="gsyn excitatory (mV)", 83 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 84 | Panel(gsyn_inh.segments[0].filter(name='gsyn_inh')[0], 85 | xlabel="Time (ms)", xticks=True, 86 | ylabel="gsyn inhibitory (mV)", 87 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 88 | title="Simple synfire chain example", 89 | annotations=f"Simulated with {p.name()}".format() 90 | ) 91 | plt.show() 92 | 93 | p.end() 94 | -------------------------------------------------------------------------------- /examples/synfire_if_curr_exp_get_weights.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import pyNN.spiNNaker as p 19 | 20 | runtime = 5000 21 | p.setup(timestep=1.0, min_delay=1.0) 22 | nNeurons = 200 # number of neurons in each population 23 | p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) 24 | 25 | cell_params_lif = {'cm': 0.25, 26 | 'i_offset': 0.0, 27 | 'tau_m': 20.0, 28 | 'tau_refrac': 2.0, 29 | 'tau_syn_E': 5.0, 30 | 'tau_syn_I': 5.0, 31 | 'v_reset': -70.0, 32 | 'v_rest': -65.0, 33 | 'v_thresh': -50.0 34 | } 35 | 36 | populations = list() 37 | projections = list() 38 | 39 | weight_to_spike = 2.0 40 | delay = 17 41 | 42 | loopConnections = list() 43 | for i in range(0, nNeurons): 44 | singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) 45 | loopConnections.append(singleConnection) 46 | 47 | injectionConnection = [(0, 0)] 48 | spikeArray = {'spike_times': [[0]]} 49 | populations.append( 50 | p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1')) 51 | populations.append( 52 | p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) 53 | 54 | projections.append(p.Projection( 55 | populations[0], populations[0], p.FromListConnector(loopConnections), 56 | p.StaticSynapse(weight=weight_to_spike, delay=delay))) 57 | projections.append(p.Projection( 58 | populations[1], populations[0], p.FromListConnector(injectionConnection), 59 | p.StaticSynapse(weight=weight_to_spike, delay=1))) 60 | 61 | p.run(runtime) 62 | 63 | print(projections[0].get(['weight', 'delay'], 'list')) 64 | 65 | 66 | p.end() 67 | -------------------------------------------------------------------------------- /examples/synfire_if_curr_exp_large_array.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import pyNN.spiNNaker as p 19 | from pyNN.utility.plotting import Figure, Panel 20 | import matplotlib.pyplot as plt 21 | 22 | run_time = 6000 23 | p.setup(timestep=1.0, min_delay=1.00) 24 | nNeurons = 10 # number of neurons in each population 25 | 26 | cell_params_lif = {'cm': 0.25, 27 | 'i_offset': 0.0, 28 | 'tau_m': 20.0, 29 | 'tau_refrac': 2.0, 30 | 'tau_syn_E': 1.0, 31 | 'tau_syn_I': 1.0, 32 | 'v_reset': -70.0, 33 | 'v_rest': -65.0, 34 | 'v_thresh': -50.0 35 | } 36 | 37 | weight_to_spike = 10.0 38 | delay = 2 39 | second_spike_start = delay * nNeurons 40 | space_between_inputs = delay * nNeurons * 2 41 | 42 | connections = list() 43 | reverseConnections = list() 44 | for i in range(0, nNeurons - 1): 45 | connections.append((i, (i + 1) % nNeurons, weight_to_spike, delay)) 46 | reverseConnections.append(((i + 1) % nNeurons, i, weight_to_spike, delay)) 47 | 48 | injectionConnection_1 = [(0, 0, weight_to_spike, 1)] 49 | injectionConnection_2 = [(1, nNeurons - 1, weight_to_spike, 1)] 50 | input_1 = list(range(0, run_time, space_between_inputs)) 51 | input_2 = list(range(second_spike_start, run_time, space_between_inputs)) 52 | spikeArray = {'spike_times': [input_1, input_2]} 53 | 54 | main_pop = p.Population( 55 | nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1') 56 | second_main_pop = p.Population( 57 | nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_2') 58 | input_pop = p.Population( 59 | 2, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1') 60 | 61 | p.Projection( 62 | main_pop, main_pop, p.FromListConnector(connections), 63 | p.StaticSynapse(weight=weight_to_spike, delay=delay)) 64 | p.Projection( 65 | second_main_pop, second_main_pop, p.FromListConnector(reverseConnections), 66 | p.StaticSynapse(weight=weight_to_spike, delay=delay)) 67 | 68 | p.Projection( 69 | input_pop, main_pop, p.FromListConnector(injectionConnection_1), 70 | p.StaticSynapse(weight=weight_to_spike, delay=1)) 71 | 72 | p.Projection( 73 | input_pop, second_main_pop, p.FromListConnector(injectionConnection_2), 74 | p.StaticSynapse(weight=weight_to_spike, delay=1)) 75 | 76 | main_pop.record("spikes") 77 | second_main_pop.record("spikes") 78 | 79 | p.run(run_time) 80 | 81 | # get data (could be done as one, but can be done bit by bit as well) 82 | spikes1 = main_pop.get_data('spikes') 83 | spikes2 = second_main_pop.get_data("spikes") 84 | 85 | Figure( 86 | # raster plot of the pre_synaptic neuron spike times 87 | Panel(spikes1.segments[0].spiketrains, 88 | ylabel="spikes from first pop", 89 | yticks=True, markersize=0.2, xlim=(0, run_time)), 90 | # membrane potential of the post_synaptic neuron 91 | Panel(spikes2.segments[0].spiketrains, 92 | ylabel="spikes from second pop", 93 | yticks=True, markersize=0.2, xlim=(0, run_time)), 94 | title="large data Simple synfire chain example", 95 | annotations=f"Simulated with {p.name()}" 96 | ) 97 | plt.show() 98 | 99 | p.end() 100 | -------------------------------------------------------------------------------- /examples/synfire_if_curr_exp_random.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import matplotlib.pyplot as plt 19 | from pyNN.random import RandomDistribution 20 | import pyNN.spiNNaker as p 21 | from pyNN.utility.plotting import Figure, Panel 22 | 23 | 24 | p.setup(timestep=1.0, min_delay=1.0) 25 | nNeurons = 200 # number of neurons in each population 26 | max_delay = 50 27 | run_time = max_delay * nNeurons 28 | p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) 29 | 30 | cell_params_lif = {'cm': 0.25, 31 | 'i_offset': 0.0, 32 | 'tau_m': 20.0, 33 | 'tau_refrac': 2.0, 34 | 'tau_syn_E': 5.0, 35 | 'tau_syn_I': 5.0, 36 | 'v_reset': -70.0, 37 | 'v_rest': -65.0, 38 | 'v_thresh': -50.0 39 | } 40 | 41 | weight_to_spike = 2.0 42 | delay = RandomDistribution("uniform", low=1, high=max_delay) 43 | 44 | loopConnections = list() 45 | for i in range(0, nNeurons): 46 | delay_value = delay.next() 47 | singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay_value) 48 | loopConnections.append(singleConnection) 49 | 50 | injectionConnection = [(0, 0, weight_to_spike, 1)] 51 | spikeArray = {'spike_times': [[0]]} 52 | main_pop = p.Population( 53 | nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1') 54 | input_pop = p.Population( 55 | 1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1') 56 | 57 | p.Projection(main_pop, main_pop, p.FromListConnector(loopConnections)) 58 | p.Projection(input_pop, main_pop, p.FromListConnector(injectionConnection)) 59 | 60 | main_pop.record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) 61 | 62 | print(f"Running for {run_time} ms") 63 | p.run(run_time) 64 | # get data (could be done as one, but can be done bit by bit as well) 65 | data = main_pop.get_data(['v', 'gsyn_exc', 'spikes', 'gsyn_inh']) 66 | 67 | Figure( 68 | # raster plot of the presynaptic neuron spike times 69 | Panel(data.segments[0].spiketrains, 70 | yticks=True, markersize=0.2, xlim=(0, run_time)), 71 | # membrane potential of the postsynaptic neuron 72 | Panel(data.segments[0].filter(name='v')[0], 73 | ylabel="Membrane potential (mV)", 74 | data_labels=[main_pop.label], yticks=True, xlim=(0, run_time)), 75 | Panel(data.segments[0].filter(name='gsyn_exc')[0], 76 | ylabel="gsyn excitatory (mV)", 77 | data_labels=[main_pop.label], yticks=True, xlim=(0, run_time)), 78 | Panel(data.segments[0].filter(name='gsyn_inh')[0], 79 | ylabel="gsyn inhibitory (mV)", 80 | data_labels=[main_pop.label], yticks=True, xlim=(0, run_time)), 81 | title="Simple synfire chain example", 82 | annotations=f"Simulated with {p.name()}" 83 | ) 84 | plt.show() 85 | 86 | p.end() 87 | -------------------------------------------------------------------------------- /examples/synfire_izk_curr_exp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfirechain-like example 17 | """ 18 | import pyNN.spiNNaker as p 19 | from pyNN.utility.plotting import Figure, Panel 20 | import matplotlib.pyplot as plt 21 | 22 | runtime = 500 23 | p.setup(timestep=1.0, min_delay=1.0) 24 | nNeurons = 200 # number of neurons in each population 25 | p.set_number_of_neurons_per_core(p.Izhikevich, nNeurons / 2) 26 | 27 | cell_params_izk = {'a': 0.02, 28 | 'b': 0.2, 29 | 'c': -65, 30 | 'd': 8, 31 | 'v': -75, 32 | 'u': 0, 33 | 'tau_syn_E': 2, 34 | 'tau_syn_I': 2, 35 | 'i_offset': 0 36 | } 37 | 38 | populations = list() 39 | projections = list() 40 | 41 | weight_to_spike = 30 42 | delay = 1 43 | 44 | loopConnections = list() 45 | for i in range(0, nNeurons): 46 | singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) 47 | loopConnections.append(singleConnection) 48 | 49 | injectionConnection = [(0, 0)] 50 | spikeArray = {'spike_times': [[50]]} 51 | populations.append( 52 | p.Population(nNeurons, p.Izhikevich(**cell_params_izk), label='pop_1')) 53 | populations.append( 54 | p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) 55 | 56 | projections.append(p.Projection( 57 | populations[0], populations[0], p.FromListConnector(loopConnections), 58 | p.StaticSynapse(weight=weight_to_spike, delay=delay))) 59 | projections.append(p.Projection( 60 | populations[1], populations[0], p.FromListConnector(injectionConnection), 61 | p.StaticSynapse(weight=weight_to_spike, delay=1))) 62 | 63 | populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) 64 | 65 | p.run(runtime) 66 | 67 | # get data (could be done as one, but can be done bit by bit as well) 68 | data = populations[0].get_data(['v', 'gsyn_exc', 'spikes', 'gsyn_inh']) 69 | 70 | Figure( 71 | # raster plot of the presynaptic neuron spike times 72 | Panel(data.segments[0].spiketrains, 73 | yticks=True, markersize=0.2, xlim=(0, runtime)), 74 | # membrane potential of the postsynaptic neuron 75 | Panel(data.segments[0].filter(name='v')[0], 76 | ylabel="Membrane potential (mV)", 77 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 78 | Panel(data.segments[0].filter(name='gsyn_exc')[0], 79 | ylabel="gsyn excitatory (mV)", 80 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 81 | Panel(data.segments[0].filter(name='gsyn_inh')[0], 82 | ylabel="gsyn inhibitory (mV)", 83 | data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), 84 | title="Simple synfire chain example", 85 | annotations=f"Simulated with {p.name()}" 86 | ) 87 | plt.show() 88 | 89 | p.end() 90 | -------------------------------------------------------------------------------- /examples/wta_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Demonstration of the winner-takes-all connector in use. There are two 16 | # populations both receiving input from the same Poisson source. One 17 | # population has a self-connection with a winner-takes-all connector, which 18 | # will attempt to ensure that only one neuron in the population spikes at a 19 | # time. As neuron 2 has a higher rate of input than the others, it will be 20 | # the "winner" more often than the others. 21 | 22 | # Note that SpiNNaker does not send "instantaneous" spikes, so there can be 23 | # times where two neurons spike in the same time step. 24 | 25 | # The output graph shows the difference in the outputs of the two populations. 26 | 27 | import pyNN.spiNNaker as sim 28 | import matplotlib.pyplot as plt 29 | import numpy 30 | 31 | sim.setup(1.0) 32 | 33 | pop = sim.Population(10, sim.IF_curr_exp(), label="pop") 34 | wta = sim.Population(10, sim.IF_curr_exp(), label="wta") 35 | stim = sim.Population( 36 | 10, sim.SpikeSourcePoisson( 37 | rate=[10, 10, 20, 10, 10, 10, 10, 10, 10, 10]), 38 | label="stim") 39 | pop.record("spikes") 40 | wta.record("spikes") 41 | 42 | sim.Projection( 43 | stim, pop, sim.OneToOneConnector(), sim.StaticSynapse(weight=5.0)) 44 | sim.Projection( 45 | stim, wta, sim.OneToOneConnector(), sim.StaticSynapse(weight=5.0)) 46 | sim.Projection( 47 | wta, wta, sim.extra_models.AllButMeConnector(), 48 | sim.StaticSynapse(weight=10.0), receptor_type="inhibitory") 49 | 50 | sim.run(10000) 51 | 52 | pop_spikes = pop.get_data("spikes").segments[0].spiketrains 53 | wta_spikes = wta.get_data("spikes").segments[0].spiketrains 54 | 55 | sim.end() 56 | 57 | # Plot the spikes 58 | for spiketrain in pop_spikes: 59 | y = numpy.ones_like(spiketrain) * spiketrain.annotations["source_index"] 60 | line, = plt.plot(spiketrain, y.magnitude * 2, "r|", 61 | label="Without AllButMe") 62 | for spiketrain in wta_spikes: 63 | y = numpy.ones_like(spiketrain) * spiketrain.annotations["source_index"] 64 | line_2, = plt.plot(spiketrain, (y.magnitude * 2) + 1, "b|", 65 | label="With AllButMe") 66 | plt.xlabel("Time (ms)") 67 | plt.title("Simple example") 68 | plt.legend(handles=[line, line_2], loc=9) 69 | plt.ylim(-2, 24) 70 | plt.yticks([], []) 71 | plt.show() 72 | -------------------------------------------------------------------------------- /integration_tests/README.md: -------------------------------------------------------------------------------- 1 | These tests depend on https://github.com/SpiNNakerManchester/TestBase 2 | 3 | This is not added automatically by setup.py 4 | 5 | Running integration_tests/script_builder.py will recreate test_scipts.py adding any new files added to existing directories. 6 | 7 | -------------------------------------------------------------------------------- /integration_tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /integration_tests/script_builder.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from spinnaker_testbase import RootScriptBuilder 16 | 17 | 18 | class ScriptBuilder(RootScriptBuilder): 19 | """ 20 | This file will recreate the test_scripts.py file 21 | 22 | To skip the too_long scripts run this script with a parameter 23 | """ 24 | 25 | def build_scripts(self): 26 | # These scripts raise a SkipTest with the reasons given 27 | exceptions = {} 28 | exceptions["pushbot_ethernet_example.py"] = "Needs a physical pushbot" 29 | exceptions["pushbot_light_follower.py"] = "Runs forever" 30 | 31 | # For branches these raise a SkipTest quoting the time given 32 | # For cron and manual runs these just and a warning 33 | too_long = {} 34 | too_long["stdp_triplet.py"] = "10 minutes" 35 | 36 | self.create_test_scripts( 37 | ["examples","balanced_random", "learning", "synfire"], 38 | too_long, exceptions) 39 | 40 | 41 | if __name__ == '__main__': 42 | builder = ScriptBuilder() 43 | builder.build_scripts() 44 | -------------------------------------------------------------------------------- /learning/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /learning/random_dist.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | from pyNN.random import RandomDistribution 17 | import pyNN.utility.plotting as plot 18 | import pyNN.spiNNaker as sim 19 | 20 | n_neurons = 1000 21 | n_exc = int(round(n_neurons * 0.8)) 22 | n_inh = int(round(n_neurons * 0.2)) 23 | simtime = 1000 24 | 25 | sim.setup(timestep=0.1) 26 | 27 | pop_exc = sim.Population(n_exc, sim.IF_curr_exp(), label="Excitatory") 28 | pop_inh = sim.Population(n_inh, sim.IF_curr_exp(), label="Inhibitory") 29 | stim_exc = sim.Population(n_exc, sim.SpikeSourcePoisson(rate=10.0), 30 | label="Stim_Exc") 31 | stim_inh = sim.Population(n_inh, sim.SpikeSourcePoisson(rate=10.0), 32 | label="Stim_Inh") 33 | 34 | synapse_exc = sim.StaticSynapse(weight=0.2, delay=2.0) 35 | synapse_inh = sim.StaticSynapse(weight=-1.0, delay=2.0) 36 | sim.Projection(pop_exc, pop_exc, sim.FixedProbabilityConnector(0.1), 37 | synapse_type=synapse_exc, receptor_type="excitatory") 38 | sim.Projection(pop_exc, pop_inh, sim.FixedProbabilityConnector(0.1), 39 | synapse_type=synapse_exc, receptor_type="excitatory") 40 | sim.Projection(pop_inh, pop_inh, sim.FixedProbabilityConnector(0.1), 41 | synapse_type=synapse_inh, receptor_type="inhibitory") 42 | sim.Projection(pop_inh, pop_exc, sim.FixedProbabilityConnector(0.1), 43 | synapse_type=synapse_inh, receptor_type="inhibitory") 44 | 45 | delays = RandomDistribution("uniform", parameters_pos=[1.0, 1.6]) 46 | conn_stim = sim.OneToOneConnector() 47 | synapse_stim = sim.StaticSynapse(weight=2.0, delay=delays) 48 | 49 | sim.Projection(stim_exc, pop_exc, conn_stim, synapse_type=synapse_stim, 50 | receptor_type="excitatory") 51 | sim.Projection(stim_inh, pop_inh, conn_stim, synapse_type=synapse_stim, 52 | receptor_type="excitatory") 53 | 54 | pop_exc.initialize( 55 | v=RandomDistribution("uniform", parameters_pos=[-65.0, -55.0])) 56 | pop_inh.initialize( 57 | v=RandomDistribution("uniform", parameters_pos=[-65.0, -55.0])) 58 | pop_exc.record("spikes") 59 | sim.run(simtime) 60 | 61 | neo = pop_exc.get_data(variables=["spikes"]) 62 | spikes = neo.segments[0].spiketrains 63 | 64 | sim.end() 65 | 66 | plot.Figure( 67 | # plot spikes 68 | plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)), 69 | title="Balanced Random Network Example", 70 | annotations=f"Simulated with {sim.name()}" 71 | ) 72 | plt.show() 73 | -------------------------------------------------------------------------------- /learning/simple.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | import pyNN.spiNNaker as sim 17 | import pyNN.utility.plotting as plot 18 | 19 | sim.setup(timestep=1.0, n_boards_required=1) 20 | machine = sim.get_machine() 21 | sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100) 22 | 23 | pop_1 = sim.Population(1, sim.IF_curr_exp(), label="pop_1") 24 | input_pop = sim.Population( 25 | 1, sim.SpikeSourceArray(spike_times=[0]), label="input") 26 | input_proj = sim.Projection(input_pop, pop_1, sim.OneToOneConnector(), 27 | synapse_type=sim.StaticSynapse(weight=5, delay=1)) 28 | pop_1.record(["spikes", "v"]) 29 | simtime = 10 30 | sim.run(simtime) 31 | 32 | neo = pop_1.get_data(variables=["spikes", "v"]) 33 | spikes = neo.segments[0].spiketrains 34 | print(spikes) 35 | v = neo.segments[0].filter(name='v')[0] 36 | print(v) 37 | sim.end() 38 | 39 | plot.Figure( 40 | # plot voltage for first ([0]) neuron 41 | plot.Panel(v, ylabel="Membrane potential (mV)", 42 | data_labels=[pop_1.label], yticks=True, xlim=(0, simtime)), 43 | # plot spikes (or in this case spike) 44 | plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)), 45 | title="Simple Example", 46 | annotations=f"Simulated with {sim.name()}" 47 | ) 48 | plt.show() 49 | -------------------------------------------------------------------------------- /learning/split/stdp_split.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import pyNN.utility.plotting as plot 16 | import matplotlib.pyplot as plt 17 | import pyNN.spiNNaker as sim 18 | 19 | n_neurons = 192 20 | simtime = 5000 21 | 22 | sim.setup(timestep=1.0) 23 | sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 64) 24 | sim.set_number_of_synapse_cores(sim.IF_curr_exp, 1) 25 | sim.set_allow_delay_extensions(sim.IF_curr_exp, False) 26 | 27 | pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Pre") 28 | post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Post") 29 | pre_noise = sim.Population( 30 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Pre") 31 | post_noise = sim.Population( 32 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Post") 33 | 34 | pre_pop.record("spikes") 35 | post_pop.record("spikes") 36 | 37 | training = sim.Population( 38 | n_neurons, 39 | sim.SpikeSourcePoisson(rate=10.0, start=1500.0, duration=1500.0), 40 | label="Training") 41 | 42 | sim.Projection(pre_noise, pre_pop, sim.OneToOneConnector(), 43 | synapse_type=sim.StaticSynapse(weight=2.0)) 44 | sim.Projection(post_noise, post_pop, sim.OneToOneConnector(), 45 | synapse_type=sim.StaticSynapse(weight=2.0)) 46 | 47 | sim.Projection(training, pre_pop, sim.OneToOneConnector(), 48 | synapse_type=sim.StaticSynapse(weight=5.0, delay=1.0)) 49 | sim.Projection(training, post_pop, sim.OneToOneConnector(), 50 | synapse_type=sim.StaticSynapse(weight=5.0, delay=10.0)) 51 | 52 | timing_rule = sim.SpikePairRule(tau_plus=20.0, tau_minus=20.0, 53 | A_plus=0.5, A_minus=0.5) 54 | weight_rule = sim.AdditiveWeightDependence(w_max=5.0, w_min=0.0) 55 | 56 | stdp_model = sim.STDPMechanism(timing_dependence=timing_rule, 57 | weight_dependence=weight_rule, 58 | weight=0.0, delay=5.0) 59 | 60 | stdp_projection = sim.Projection(pre_pop, post_pop, sim.OneToOneConnector(), 61 | # sim.StaticSynapse(0, 5.0)) 62 | synapse_type=stdp_model) 63 | 64 | sim.run(simtime) 65 | 66 | pre_neo = pre_pop.get_data(variables=["spikes"]) 67 | pre_spikes = pre_neo.segments[0].spiketrains 68 | 69 | post_neo = post_pop.get_data(variables=["spikes"]) 70 | post_spikes = post_neo.segments[0].spiketrains 71 | 72 | print(stdp_projection.get('weight', format="list")) 73 | 74 | sim.end() 75 | 76 | line_properties = [{'color': 'red', 'markersize': 5}, 77 | {'color': 'blue', 'markersize': 2}] 78 | 79 | plot.Figure( 80 | # plot spikes 81 | plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), 82 | line_properties=line_properties), 83 | title="STDP Network Example", 84 | annotations=f"Simulated with {sim.name()}" 85 | ) 86 | plt.show() 87 | -------------------------------------------------------------------------------- /learning/split/struct_pl_split.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | import numpy 17 | import pyNN.utility.plotting as plot 18 | import pyNN.spiNNaker as sim 19 | 20 | n_neurons = 64 21 | simtime = 5000 22 | 23 | sim.setup(timestep=1.0) 24 | sim.set_number_of_synapse_cores(sim.IF_curr_exp, 1) 25 | sim.set_allow_delay_extensions(sim.IF_curr_exp, False) 26 | 27 | pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Pre") 28 | post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Post") 29 | pre_noise = sim.Population( 30 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Pre") 31 | post_noise = sim.Population( 32 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Post") 33 | 34 | pre_pop.record("spikes") 35 | post_pop.record("spikes") 36 | 37 | training = sim.Population( 38 | n_neurons, 39 | sim.SpikeSourcePoisson(rate=10.0, start=1500.0, duration=1500.0), 40 | label="Training") 41 | 42 | sim.Projection(pre_noise, pre_pop, sim.OneToOneConnector(), 43 | synapse_type=sim.StaticSynapse(weight=2.0)) 44 | sim.Projection(post_noise, post_pop, sim.OneToOneConnector(), 45 | synapse_type=sim.StaticSynapse(weight=2.0)) 46 | 47 | sim.Projection(training, pre_pop, sim.OneToOneConnector(), 48 | synapse_type=sim.StaticSynapse(weight=5.0, delay=1.0)) 49 | sim.Projection(training, post_pop, sim.OneToOneConnector(), 50 | synapse_type=sim.StaticSynapse(weight=5.0, delay=10.0)) 51 | 52 | # Structurally plastic connection between pre_pop and post_pop 53 | partner_selection_last_neuron = sim.RandomSelection() 54 | formation_distance = sim.DistanceDependentFormation( 55 | grid=[numpy.sqrt(n_neurons), numpy.sqrt(n_neurons)], 56 | sigma_form_forward=.5 # spread of feed-forward connections 57 | ) 58 | elimination_weight = sim.RandomByWeightElimination( 59 | threshold=.2 # Use same weight as initial weight for static connections 60 | ) 61 | structure_model_without_stdp = sim.StructuralMechanismStatic( 62 | # Partner selection, formation and elimination rules from above 63 | partner_selection_last_neuron, formation_distance, elimination_weight, 64 | # Use this weight when creating a new synapse 65 | initial_weight=5, 66 | # Use this weight for synapses at start of simulation 67 | weight=5, 68 | # Use this delay when creating a new synapse 69 | initial_delay=5, 70 | # Use this weight for synapses at the start of simulation 71 | delay=5, 72 | # Maximum allowed fan-in per target-layer neuron 73 | s_max=32, 74 | # Frequency of rewiring in Hz 75 | f_rew=10 ** 4 76 | ) 77 | 78 | plastic_projection = sim.Projection( 79 | pre_pop, post_pop, 80 | sim.FixedProbabilityConnector(0.), # No initial connections 81 | synapse_type=structure_model_without_stdp, 82 | label="structurally_plastic_projection" 83 | ) 84 | 85 | sim.run(simtime) 86 | 87 | pre_neo = pre_pop.get_data(variables=["spikes"]) 88 | pre_spikes = pre_neo.segments[0].spiketrains 89 | 90 | post_neo = post_pop.get_data(variables=["spikes"]) 91 | post_spikes = post_neo.segments[0].spiketrains 92 | 93 | print(plastic_projection.get('weight', format="list")) 94 | 95 | sim.end() 96 | 97 | line_properties = [{'color': 'red', 'markersize': 5}, 98 | {'color': 'blue', 'markersize': 2}] 99 | 100 | plot.Figure( 101 | # plot spikes 102 | plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), 103 | line_properties=line_properties), 104 | title="STDP Network Example", 105 | annotations=f"Simulated with {sim.name()}" 106 | ) 107 | plt.show() 108 | -------------------------------------------------------------------------------- /learning/split/struct_pl_stdp_split.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | import numpy 17 | import pyNN.spiNNaker as sim 18 | import pyNN.utility.plotting as plot 19 | 20 | n_neurons = 192 21 | simtime = 5000 22 | 23 | sim.setup(timestep=1.0) 24 | sim.set_number_of_synapse_cores(sim.IF_curr_exp, 1) 25 | sim.set_allow_delay_extensions(sim.IF_curr_exp, False) 26 | 27 | sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 64) 28 | pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Pre") 29 | post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Post") 30 | pre_noise = sim.Population( 31 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Pre") 32 | post_noise = sim.Population( 33 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Post") 34 | 35 | pre_pop.record("spikes") 36 | post_pop.record("spikes") 37 | 38 | training = sim.Population( 39 | n_neurons, 40 | sim.SpikeSourcePoisson(rate=10.0, start=1500.0, duration=1500.0), 41 | label="Training") 42 | 43 | sim.Projection(pre_noise, pre_pop, sim.OneToOneConnector(), 44 | synapse_type=sim.StaticSynapse(weight=2.0)) 45 | sim.Projection(post_noise, post_pop, sim.OneToOneConnector(), 46 | synapse_type=sim.StaticSynapse(weight=2.0)) 47 | 48 | sim.Projection(training, pre_pop, sim.OneToOneConnector(), 49 | synapse_type=sim.StaticSynapse(weight=5.0, delay=1.0)) 50 | sim.Projection(training, post_pop, sim.OneToOneConnector(), 51 | synapse_type=sim.StaticSynapse(weight=5.0, delay=10.0)) 52 | 53 | timing_rule = sim.SpikePairRule(tau_plus=20.0, tau_minus=20.0, 54 | A_plus=0.5, A_minus=0.5) 55 | weight_rule = sim.AdditiveWeightDependence(w_max=5.0, w_min=0.0) 56 | 57 | partner_selection_last_neuron = sim.RandomSelection() 58 | formation_distance = sim.DistanceDependentFormation( 59 | grid=[numpy.sqrt(n_neurons), numpy.sqrt(n_neurons)], 60 | sigma_form_forward=.5 # spread of feed-forward connections 61 | ) 62 | elimination_weight = sim.RandomByWeightElimination( 63 | prob_elim_potentiated=0, # no eliminations for potentiated synapses 64 | prob_elim_depressed=0, # no elimination for depressed synapses 65 | threshold=0.5 # Use same weight as initial weight for static connections 66 | ) 67 | structure_model_with_stdp = sim.StructuralMechanismSTDP( 68 | # Partner selection, formation and elimination rules from above 69 | partner_selection_last_neuron, formation_distance, elimination_weight, 70 | # Use this weight when creating a new synapse 71 | initial_weight=0, 72 | # Use this weight for synapses at start of simulation 73 | weight=0, 74 | # Use this delay when creating a new synapse 75 | initial_delay=5, 76 | # Use this weight for synapses at the start of simulation 77 | delay=5, 78 | # Maximum allowed fan-in per target-layer neuron 79 | s_max=64, 80 | # Frequency of rewiring in Hz 81 | f_rew=10 ** 4, 82 | # STDP rules 83 | timing_dependence=sim.SpikePairRule( 84 | tau_plus=20., tau_minus=20.0, A_plus=0.5, A_minus=0.5), 85 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=5.) 86 | ) 87 | 88 | plastic_projection = sim.Projection( 89 | pre_pop, post_pop, 90 | sim.FixedProbabilityConnector(0.), # No initial connections 91 | synapse_type=structure_model_with_stdp, 92 | label="structurally_plastic_projection" 93 | ) 94 | 95 | sim.run(simtime) 96 | 97 | pre_neo = pre_pop.get_data(variables=["spikes"]) 98 | pre_spikes = pre_neo.segments[0].spiketrains 99 | 100 | post_neo = post_pop.get_data(variables=["spikes"]) 101 | post_spikes = post_neo.segments[0].spiketrains 102 | 103 | print(plastic_projection.get('weight', format="list")) 104 | 105 | sim.end() 106 | 107 | line_properties = [{'color': 'red', 'markersize': 5}, 108 | {'color': 'blue', 'markersize': 2}] 109 | 110 | plot.Figure( 111 | # plot spikes 112 | plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), 113 | line_properties=line_properties), 114 | title="STDP Network Example", 115 | annotations=f"Simulated with {sim.name()}" 116 | ) 117 | plt.show() 118 | -------------------------------------------------------------------------------- /learning/stdp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | import pyNN.spiNNaker as sim 17 | import pyNN.utility.plotting as plot 18 | 19 | n_neurons = 100 20 | simtime = 5000 21 | 22 | sim.setup(timestep=1.0) 23 | 24 | pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Pre") 25 | post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Post") 26 | pre_noise = sim.Population( 27 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Pre") 28 | post_noise = sim.Population( 29 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Post") 30 | 31 | pre_pop.record("spikes") 32 | post_pop.record("spikes") 33 | 34 | training = sim.Population( 35 | n_neurons, 36 | sim.SpikeSourcePoisson(rate=10.0, start=1500.0, duration=1500.0), 37 | label="Training") 38 | 39 | sim.Projection(pre_noise, pre_pop, sim.OneToOneConnector(), 40 | synapse_type=sim.StaticSynapse(weight=2.0)) 41 | sim.Projection(post_noise, post_pop, sim.OneToOneConnector(), 42 | synapse_type=sim.StaticSynapse(weight=2.0)) 43 | 44 | sim.Projection(training, pre_pop, sim.OneToOneConnector(), 45 | synapse_type=sim.StaticSynapse(weight=5.0, delay=1.0)) 46 | sim.Projection(training, post_pop, sim.OneToOneConnector(), 47 | synapse_type=sim.StaticSynapse(weight=5.0, delay=10.0)) 48 | 49 | timing_rule = sim.SpikePairRule(tau_plus=20.0, tau_minus=20.0, 50 | A_plus=0.5, A_minus=0.5) 51 | weight_rule = sim.AdditiveWeightDependence(w_max=5.0, w_min=0.0) 52 | 53 | stdp_model = sim.STDPMechanism(timing_dependence=timing_rule, 54 | weight_dependence=weight_rule, 55 | weight=0.0, delay=5.0) 56 | 57 | stdp_projection = sim.Projection(pre_pop, post_pop, sim.OneToOneConnector(), 58 | synapse_type=stdp_model) 59 | 60 | sim.run(simtime) 61 | 62 | pre_neo = pre_pop.get_data(variables=["spikes"]) 63 | pre_spikes = pre_neo.segments[0].spiketrains 64 | 65 | post_neo = post_pop.get_data(variables=["spikes"]) 66 | post_spikes = post_neo.segments[0].spiketrains 67 | 68 | print(stdp_projection.get('weight', format="list")) 69 | 70 | sim.end() 71 | 72 | line_properties = [{'color': 'red', 'markersize': 5}, 73 | {'color': 'blue', 'markersize': 2}] 74 | 75 | plot.Figure( 76 | # plot spikes 77 | plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), 78 | line_properties=line_properties), 79 | title="STDP Network Example", 80 | annotations=f"Simulated with {sim.name()}" 81 | ) 82 | plt.show() 83 | -------------------------------------------------------------------------------- /learning/struct_pl.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | import numpy 17 | import pyNN.spiNNaker as sim 18 | import pyNN.utility.plotting as plot 19 | 20 | n_neurons = 100 21 | simtime = 5000 22 | 23 | sim.setup(timestep=1.0) 24 | 25 | pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Pre") 26 | post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Post") 27 | pre_noise = sim.Population( 28 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Pre") 29 | post_noise = sim.Population( 30 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Post") 31 | 32 | pre_pop.record("spikes") 33 | post_pop.record("spikes") 34 | 35 | training = sim.Population( 36 | n_neurons, 37 | sim.SpikeSourcePoisson(rate=10.0, start=1500.0, duration=1500.0), 38 | label="Training") 39 | 40 | sim.Projection(pre_noise, pre_pop, sim.OneToOneConnector(), 41 | synapse_type=sim.StaticSynapse(weight=2.0)) 42 | sim.Projection(post_noise, post_pop, sim.OneToOneConnector(), 43 | synapse_type=sim.StaticSynapse(weight=2.0)) 44 | 45 | sim.Projection(training, pre_pop, sim.OneToOneConnector(), 46 | synapse_type=sim.StaticSynapse(weight=5.0, delay=1.0)) 47 | sim.Projection(training, post_pop, sim.OneToOneConnector(), 48 | synapse_type=sim.StaticSynapse(weight=5.0, delay=10.0)) 49 | 50 | timing_rule = sim.SpikePairRule(tau_plus=20.0, tau_minus=20.0, 51 | A_plus=0.5, A_minus=0.5) 52 | weight_rule = sim.AdditiveWeightDependence(w_max=5.0, w_min=0.0) 53 | 54 | # Structurally plastic connection between pre_pop and post_pop 55 | partner_selection_last_neuron = sim.RandomSelection() 56 | formation_distance = sim.DistanceDependentFormation( 57 | grid=[numpy.sqrt(n_neurons), numpy.sqrt(n_neurons)], 58 | sigma_form_forward=.5 # spread of feed-forward connections 59 | ) 60 | elimination_weight = sim.RandomByWeightElimination( 61 | threshold=.2 # Use same weight as initial weight for static connections 62 | ) 63 | structure_model_without_stdp = sim.StructuralMechanismStatic( 64 | # Partner selection, formation and elimination rules from above 65 | partner_selection_last_neuron, formation_distance, elimination_weight, 66 | # Use this weight when creating a new synapse 67 | initial_weight=5, 68 | # Use this weight for synapses at start of simulation 69 | weight=5, 70 | # Use this delay when creating a new synapse 71 | initial_delay=5, 72 | # Use this weight for synapses at the start of simulation 73 | delay=5, 74 | # Maximum allowed fan-in per target-layer neuron 75 | s_max=32, 76 | # Frequency of rewiring in Hz 77 | f_rew=10 ** 4 78 | ) 79 | 80 | plastic_projection = sim.Projection( 81 | pre_pop, post_pop, 82 | sim.FixedProbabilityConnector(0.), # No initial connections 83 | synapse_type=structure_model_without_stdp, 84 | label="structurally_plastic_projection" 85 | ) 86 | 87 | sim.run(simtime) 88 | 89 | pre_neo = pre_pop.get_data(variables=["spikes"]) 90 | pre_spikes = pre_neo.segments[0].spiketrains 91 | 92 | post_neo = post_pop.get_data(variables=["spikes"]) 93 | post_spikes = post_neo.segments[0].spiketrains 94 | 95 | print(plastic_projection.get('weight', format="list")) 96 | 97 | sim.end() 98 | 99 | line_properties = [{'color': 'red', 'markersize': 5}, 100 | {'color': 'blue', 'markersize': 2}] 101 | 102 | plot.Figure( 103 | # plot spikes 104 | plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), 105 | line_properties=line_properties), 106 | title="STDP Network Example", 107 | annotations=f"Simulated with {sim.name()}" 108 | ) 109 | plt.show() 110 | -------------------------------------------------------------------------------- /learning/struct_pl_stdp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import matplotlib.pyplot as plt 16 | import numpy 17 | import pyNN.spiNNaker as sim 18 | import pyNN.utility.plotting as plot 19 | 20 | n_neurons = 100 21 | simtime = 5000 22 | 23 | sim.setup(timestep=1.0) 24 | 25 | pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Pre") 26 | post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="Post") 27 | pre_noise = sim.Population( 28 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Pre") 29 | post_noise = sim.Population( 30 | n_neurons, sim.SpikeSourcePoisson(rate=10.0), label="Noise_Post") 31 | 32 | pre_pop.record("spikes") 33 | post_pop.record("spikes") 34 | 35 | training = sim.Population( 36 | n_neurons, 37 | sim.SpikeSourcePoisson(rate=10.0, start=1500.0, duration=1500.0), 38 | label="Training") 39 | 40 | sim.Projection(pre_noise, pre_pop, sim.OneToOneConnector(), 41 | synapse_type=sim.StaticSynapse(weight=2.0)) 42 | sim.Projection(post_noise, post_pop, sim.OneToOneConnector(), 43 | synapse_type=sim.StaticSynapse(weight=2.0)) 44 | 45 | sim.Projection(training, pre_pop, sim.OneToOneConnector(), 46 | synapse_type=sim.StaticSynapse(weight=5.0, delay=1.0)) 47 | sim.Projection(training, post_pop, sim.OneToOneConnector(), 48 | synapse_type=sim.StaticSynapse(weight=5.0, delay=10.0)) 49 | 50 | timing_rule = sim.SpikePairRule(tau_plus=20.0, tau_minus=20.0, 51 | A_plus=0.5, A_minus=0.5) 52 | weight_rule = sim.AdditiveWeightDependence(w_max=5.0, w_min=0.0) 53 | 54 | partner_selection_last_neuron = sim.RandomSelection() 55 | formation_distance = sim.DistanceDependentFormation( 56 | grid=[numpy.sqrt(n_neurons), numpy.sqrt(n_neurons)], 57 | sigma_form_forward=.5 # spread of feed-forward connections 58 | ) 59 | elimination_weight = sim.RandomByWeightElimination( 60 | prob_elim_potentiated=0, # no eliminations for potentiated synapses 61 | prob_elim_depressed=0, # no elimination for depressed synapses 62 | threshold=0.5 # Use same weight as initial weight for static connections 63 | ) 64 | structure_model_with_stdp = sim.StructuralMechanismSTDP( 65 | # Partner selection, formation and elimination rules from above 66 | partner_selection_last_neuron, formation_distance, elimination_weight, 67 | # Use this weight when creating a new synapse 68 | initial_weight=0, 69 | # Use this weight for synapses at start of simulation 70 | weight=0, 71 | # Use this delay when creating a new synapse 72 | initial_delay=5, 73 | # Use this weight for synapses at the start of simulation 74 | delay=5, 75 | # Maximum allowed fan-in per target-layer neuron 76 | s_max=64, 77 | # Frequency of rewiring in Hz 78 | f_rew=10 ** 4, 79 | # STDP rules 80 | timing_dependence=sim.SpikePairRule( 81 | tau_plus=20., tau_minus=20.0, A_plus=0.5, A_minus=0.5), 82 | weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=5.) 83 | ) 84 | 85 | plastic_projection = sim.Projection( 86 | pre_pop, post_pop, 87 | sim.FixedProbabilityConnector(0.), # No initial connections 88 | synapse_type=structure_model_with_stdp, 89 | label="structurally_plastic_projection" 90 | ) 91 | 92 | sim.run(simtime) 93 | 94 | pre_neo = pre_pop.get_data(variables=["spikes"]) 95 | pre_spikes = pre_neo.segments[0].spiketrains 96 | 97 | post_neo = post_pop.get_data(variables=["spikes"]) 98 | post_spikes = post_neo.segments[0].spiketrains 99 | 100 | print(plastic_projection.get('weight', format="list")) 101 | 102 | sim.end() 103 | 104 | line_properties = [{'color': 'red', 'markersize': 5}, 105 | {'color': 'blue', 'markersize': 2}] 106 | 107 | plot.Figure( 108 | # plot spikes 109 | plot.Panel(pre_spikes, post_spikes, yticks=True, xlim=(0, simtime), 110 | line_properties=line_properties), 111 | title="STDP Network Example", 112 | annotations=f"Simulated with {sim.name()}" 113 | ) 114 | plt.show() 115 | -------------------------------------------------------------------------------- /pendulum/pendulum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/pendulum/pendulum -------------------------------------------------------------------------------- /pendulum/spynnaker.cfg: -------------------------------------------------------------------------------- 1 | [Simulation] 2 | drop_late_spikes = False 3 | -------------------------------------------------------------------------------- /spiNNaker_start/.gitignore: -------------------------------------------------------------------------------- 1 | /record/ 2 | -------------------------------------------------------------------------------- /sudoku/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /sudoku/libgcc_s_dw2-1.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/libgcc_s_dw2-1.dll -------------------------------------------------------------------------------- /sudoku/libsqlite3-0.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/libsqlite3-0.dll -------------------------------------------------------------------------------- /sudoku/pthreadGC2.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/pthreadGC2.dll -------------------------------------------------------------------------------- /sudoku/spynnaker.cfg: -------------------------------------------------------------------------------- 1 | [Database] 2 | wait_on_confirmation_timeout = None 3 | -------------------------------------------------------------------------------- /sudoku/sudoku.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/sudoku.exe -------------------------------------------------------------------------------- /sudoku/sudoku.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/sudoku.png -------------------------------------------------------------------------------- /sudoku/sudoku_linux: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/sudoku_linux -------------------------------------------------------------------------------- /sudoku/sudoku_osx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpiNNakerManchester/PyNNExamples/f53050293f28002ef894b1f190dfcb0e6ff2a5ff/sudoku/sudoku_osx -------------------------------------------------------------------------------- /sudoku/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2018 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | puzzles = list() 16 | puzzles.append( 17 | # Diabolical problem: 18 | [[0, 0, 1, 0, 0, 8, 0, 7, 3], 19 | [0, 0, 5, 6, 0, 0, 0, 0, 1], 20 | [7, 0, 0, 0, 0, 1, 0, 0, 0], 21 | 22 | [0, 9, 0, 8, 1, 0, 0, 0, 0], 23 | [5, 3, 0, 0, 0, 0, 0, 4, 6], 24 | [0, 0, 0, 0, 6, 5, 0, 3, 0], 25 | 26 | [0, 0, 0, 1, 0, 0, 0, 0, 4], 27 | [8, 0, 0, 0, 0, 9, 3, 0, 0], 28 | [9, 4, 0, 5, 0, 0, 7, 0, 0]]) 29 | puzzles.append( 30 | [[2, 0, 0, 0, 0, 6, 0, 3, 0], 31 | [4, 8, 0, 0, 1, 9, 0, 0, 0], 32 | [0, 0, 7, 0, 2, 0, 9, 0, 0], 33 | 34 | [0, 0, 0, 3, 0, 0, 0, 9, 0], 35 | [7, 0, 8, 0, 0, 0, 1, 0, 5], 36 | [0, 4, 0, 0, 0, 7, 0, 0, 0], 37 | 38 | [0, 0, 4, 0, 9, 0, 6, 0, 0], 39 | [0, 0, 0, 6, 4, 0, 0, 1, 9], 40 | [0, 5, 0, 1, 0, 0, 0, 0, 8]]) 41 | puzzles.append( 42 | [[0, 0, 3, 2, 0, 0, 0, 7, 0], 43 | [0, 0, 5, 0, 0, 0, 3, 0, 0], 44 | [0, 0, 8, 9, 7, 0, 0, 5, 0], 45 | 46 | [0, 0, 0, 8, 9, 0, 0, 0, 0], 47 | [0, 5, 0, 0, 0, 0, 0, 2, 0], 48 | [0, 0, 0, 0, 6, 1, 0, 0, 0], 49 | 50 | [0, 1, 0, 0, 2, 5, 6, 0, 0], 51 | [0, 0, 4, 0, 0, 0, 8, 0, 0], 52 | [0, 9, 0, 0, 0, 7, 5, 0, 0]]) 53 | puzzles.append( 54 | [[0, 1, 0, 0, 0, 0, 0, 0, 2], 55 | [8, 7, 0, 0, 0, 0, 5, 0, 4], 56 | [5, 0, 2, 0, 0, 0, 0, 9, 0], 57 | 58 | [0, 5, 0, 4, 0, 9, 0, 0, 1], 59 | [0, 0, 0, 7, 3, 2, 0, 0, 0], 60 | [9, 0, 0, 5, 0, 1, 0, 4, 0], 61 | 62 | [0, 2, 0, 0, 0, 0, 4, 0, 8], 63 | [4, 0, 6, 0, 0, 0, 0, 1, 3], 64 | [1, 0, 0, 0, 0, 0, 0, 2, 0]]) 65 | puzzles.append( 66 | [[8, 9, 0, 2, 0, 0, 0, 7, 0], 67 | [0, 0, 0, 0, 8, 0, 0, 0, 0], 68 | [0, 4, 1, 0, 3, 0, 5, 0, 0], 69 | 70 | [2, 5, 8, 0, 0, 0, 0, 0, 6], 71 | [0, 0, 0, 0, 0, 0, 0, 0, 0], 72 | [6, 0, 0, 0, 0, 0, 1, 4, 7], 73 | 74 | [0, 0, 7, 0, 1, 0, 4, 3, 0], 75 | [0, 0, 0, 0, 2, 0, 0, 0, 0], 76 | [0, 2, 0, 0, 0, 7, 0, 5, 1]]) 77 | puzzles.append( 78 | # "World's hardest sudoku": 79 | # http://www.telegraph.co.uk/news/science/science-news/9359579/\ 80 | # Worlds-hardest-sudoku-can-you-crack-it.html 81 | [[8, 0, 0, 0, 0, 0, 0, 0, 0], 82 | [0, 0, 3, 6, 0, 0, 0, 0, 0], 83 | [0, 7, 0, 0, 9, 0, 2, 0, 0], 84 | 85 | [0, 5, 0, 0, 0, 7, 0, 0, 0], 86 | [0, 0, 0, 0, 4, 5, 7, 0, 0], 87 | [0, 0, 0, 1, 0, 0, 0, 3, 0], 88 | 89 | [0, 0, 1, 0, 0, 0, 0, 6, 8], 90 | [0, 0, 8, 5, 0, 0, 0, 1, 0], 91 | [0, 9, 0, 0, 0, 0, 4, 0, 0]]) 92 | puzzles.append( 93 | [[1, 0, 0, 4, 0, 0, 0, 0, 0], 94 | [7, 0, 0, 5, 0, 0, 6, 0, 3], 95 | [0, 0, 0, 0, 3, 0, 4, 2, 0], 96 | 97 | [0, 0, 9, 0, 0, 0, 0, 3, 5], 98 | [0, 0, 0, 3, 0, 5, 0, 0, 0], 99 | [6, 3, 0, 0, 0, 0, 1, 0, 0], 100 | 101 | [0, 2, 6, 0, 5, 0, 0, 0, 0], 102 | [9, 0, 4, 0, 0, 6, 0, 0, 7], 103 | [0, 0, 0, 0, 0, 8, 0, 0, 2]]) 104 | 105 | 106 | def get_rates(values, n_total, n_cell, n_N, default_rate, max_rate): 107 | """ 108 | Calculates the list of rates for a given number of cells. 109 | 110 | :param list(list(int)) values: 111 | :param int n_total: 112 | :param int n_cell: 113 | :param int n_N: 114 | :param float default_rate: 115 | :param float max_rate: 116 | :rtype: list(float) 117 | """ 118 | rates = [default_rate] * n_total 119 | for x in range(9): 120 | for y in range(9): 121 | if values[8 - y][x] != 0: 122 | base = ((y * 9) + x) * n_cell 123 | for j in range(n_N * (values[8 - y][x] - 1), 124 | n_N * values[8 - y][x]): 125 | rates[j + base] = max_rate 126 | return rates 127 | -------------------------------------------------------------------------------- /synfire/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /synfire/synfire.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfire chain example 17 | """ 18 | import matplotlib.pyplot as plt 19 | import pyNN.spiNNaker as sim 20 | from spynnaker.pyNN.utilities import neo_convertor 21 | 22 | # number of neurons in each population 23 | n_neurons = 100 24 | n_populations = 10 25 | weights = 0.5 26 | delays = 17.0 27 | simtime = 1000 28 | 29 | sim.setup(timestep=1.0, min_delay=1.0) 30 | 31 | spikeArray = {'spike_times': [[0]]} 32 | stimulus = sim.Population(1, sim.SpikeSourceArray, spikeArray, 33 | label='stimulus') 34 | 35 | chain_pops = [ 36 | sim.Population(n_neurons, sim.IF_curr_exp, {}, label=f'chain_{i}') 37 | for i in range(n_populations) 38 | ] 39 | for pop in chain_pops: 40 | pop.record("spikes") 41 | 42 | connector = sim.FixedNumberPreConnector(10) 43 | for i in range(n_populations): 44 | sim.Projection(chain_pops[i], chain_pops[(i + 1) % n_populations], 45 | connector, 46 | synapse_type=sim.StaticSynapse(weight=weights, 47 | delay=delays)) 48 | 49 | sim.Projection(stimulus, chain_pops[0], sim.AllToAllConnector(), 50 | synapse_type=sim.StaticSynapse(weight=5.0)) 51 | 52 | sim.run(simtime) 53 | # None PyNN method which is faster 54 | # spikes = [pop.spinnaker_get_data("spikes") for pop in chain_pops] 55 | 56 | # Pynn method and support method 57 | neos = [pop.get_data("spikes") for pop in chain_pops] 58 | spikes = map(neo_convertor.convert_spikes, neos) 59 | 60 | sim.end() 61 | 62 | 63 | try: 64 | plt.figure() 65 | plt.xlabel('Time (ms)') 66 | plt.ylabel('Neuron') 67 | plt.title('Spikes Sent By Chain') 68 | offset = 0 69 | for pop_spikes in spikes: 70 | plt.plot( 71 | [i[1] for i in pop_spikes], 72 | [i[0] + offset for i in pop_spikes], "." 73 | ) 74 | offset += n_neurons 75 | plt.show() 76 | except Exception as ex: 77 | print(spikes) 78 | raise ex 79 | 80 | # pylint: disable=wrong-spelling-in-comment 81 | # Way to plot the spikes without neo converter but without the colours 82 | # try: 83 | # import matplotlib.pyplot as plt 84 | # import pyNN.utility.plotting as plotting 85 | # spike_trains = [neo.segments[0].spiketrains for neo in neos] 86 | # offset = 0 87 | # for spike_train_list in spike_trains: 88 | # for spike_train in spike_train_list: 89 | # spike_train.annotations["source_index"] += offset 90 | # offset += n_neurons 91 | # spike_trains = [ 92 | # spike_train for spike_train_list in spike_trains 93 | # for spike_train in spike_train_list] 94 | # panel = plotting.Panel( 95 | # spike_trains, 96 | # yticks=True, markersize=2, xlim=(0, simtime), 97 | # line_properties=[ 98 | # {"color": colour} 99 | # for i, colour in enumerate(colours)]) 100 | # plotting.Figure( 101 | # panel, title="Synfire Example", 102 | # annotations="Simulated with {}".format(sim.name())) 103 | # plt.show() 104 | # except Exception as ex: 105 | # print(ex) 106 | # for neo in neos: 107 | # print(neo.segments[0].spiketrains) 108 | # print("====") 109 | -------------------------------------------------------------------------------- /synfire/synfire_collab.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Synfire chain example 17 | """ 18 | import matplotlib.pyplot as plt 19 | import pyNN.spiNNaker as sim 20 | from spynnaker.pyNN.utilities import neo_convertor 21 | 22 | # number of neurons in each population 23 | n_neurons = 100 24 | n_populations = 10 25 | weights = 0.5 26 | delays = 17.0 27 | simtime = 1000 28 | 29 | sim.setup(timestep=1.0, min_delay=1.0) 30 | 31 | spikeArray = {'spike_times': [[0]]} 32 | stimulus = sim.Population(1, sim.SpikeSourceArray, spikeArray, 33 | label='stimulus') 34 | 35 | chain_pops = [ 36 | sim.Population(n_neurons, sim.IF_curr_exp, {}, label='chain_{i}') 37 | for i in range(n_populations) 38 | ] 39 | for pop in chain_pops: 40 | pop.record("spikes") 41 | 42 | connector = sim.FixedNumberPreConnector(10) 43 | for i in range(n_populations): 44 | sim.Projection(chain_pops[i], chain_pops[(i + 1) % n_populations], 45 | connector, 46 | synapse_type=sim.StaticSynapse(weight=weights, 47 | delay=delays)) 48 | 49 | sim.Projection(stimulus, chain_pops[0], sim.AllToAllConnector(), 50 | synapse_type=sim.StaticSynapse(weight=5.0)) 51 | 52 | sim.run(simtime) 53 | # None PyNN method which is faster 54 | # spikes = [pop.spinnaker_get_data("spikes") for pop in chain_pops] 55 | 56 | # Pynn method and support method 57 | neos = [pop.get_data("spikes") for pop in chain_pops] 58 | spikes = map(neo_convertor.convert_spikes, neos) 59 | 60 | sim.end() 61 | 62 | 63 | try: 64 | plt.figure() 65 | plt.xlabel('Time (ms)') 66 | plt.ylabel('Neuron') 67 | plt.title('Spikes Sent By Chain') 68 | offset = 0 69 | for pop_spikes in spikes: 70 | plt.plot( 71 | [i[1] for i in pop_spikes], 72 | [i[0] + offset for i in pop_spikes], "." 73 | ) 74 | offset += n_neurons 75 | plt.show() 76 | except Exception as ex: 77 | print(spikes) 78 | raise ex 79 | -------------------------------------------------------------------------------- /unittests/test_cfg_checker.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The University of Manchester 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | import unittest 17 | from spinn_utilities.configs.config_checker import ConfigChecker 18 | from spynnaker.pyNN.config_setup import unittest_setup 19 | 20 | 21 | class TestCfgChecker(unittest.TestCase): 22 | 23 | def setUp(self): 24 | unittest_setup() 25 | 26 | def test_config_checks(self): 27 | unittests = os.path.dirname(__file__) 28 | parent = os.path.dirname(unittests) 29 | examples = os.path.join(parent, "examples") 30 | integration_tests = os.path.join(parent, "integration_tests") 31 | checker = ConfigChecker([examples, integration_tests, unittests]) 32 | checker.check(local_defaults=False) 33 | --------------------------------------------------------------------------------