diff --git a/examples/extra_models_examples/IF_cond_exp_stoc.py b/examples/extra_models_examples/IF_cond_exp_stoc.py index b4798a8..4bee132 100644 --- a/examples/extra_models_examples/IF_cond_exp_stoc.py +++ b/examples/extra_models_examples/IF_cond_exp_stoc.py @@ -33,88 +33,107 @@ from pyNN.utility.plotting import Figure, Panel import matplotlib.pyplot as plt -sim.setup(timestep=1.0, min_delay=1.0) - -stoc_cell = sim.Population(1, sim.extra_models.IFCondExpStoc(**{ - 'i_offset': 0.1, - 'tau_refrac': 3.0, - 'v_thresh': -51.0, - 'v_reset': -70.0, - 'tau_syn_E': 5.0, - 'tau_syn_I': 5.0})) - -exp_cell = sim.Population(1, sim.IF_cond_exp(**{ - 'i_offset': 0.1, - 'tau_refrac': 3.0, - 'v_thresh': -51.0, - 'v_reset': -70.0, - 'tau_syn_E': 5.0, - 'tau_syn_I': 5.0})) - - -spike_sourceE = sim.Population(1, sim.SpikeSourceArray(**{ - 'spike_times': [float(i) for i in range(5, 105, 10)]})) -spike_sourceI = sim.Population(1, sim.SpikeSourceArray(**{ - 'spike_times': [float(i) for i in range(155, 255, 10)]})) - -sim.Projection(spike_sourceE, exp_cell, - sim.OneToOneConnector(), - synapse_type=sim.StaticSynapse(weight=0.15, delay=2.0), - receptor_type='excitatory') -sim.Projection(spike_sourceI, exp_cell, - sim.OneToOneConnector(), - synapse_type=sim.StaticSynapse(weight=-0.15, delay=4.0), - receptor_type='inhibitory') -sim.Projection(spike_sourceE, stoc_cell, - sim.OneToOneConnector(), - synapse_type=sim.StaticSynapse(weight=0.15, delay=2.0), - receptor_type='excitatory') -sim.Projection(spike_sourceI, stoc_cell, - sim.OneToOneConnector(), - synapse_type=sim.StaticSynapse(weight=-0.15, delay=4.0), - receptor_type='inhibitory') - -stoc_cell.record('all') -exp_cell.record('all') - -runtime = 200.0 - -sim.run(runtime) - -stoc_data = stoc_cell.get_data() -exp_data = exp_cell.get_data() - -# Plot -Figure( - # raster plot of the presynaptic neuron spike times - Panel(stoc_data.segments[0].spiketrains, - yticks=True, markersize=0.2, xlim=(0, runtime)), - Panel(exp_data.segments[0].spiketrains, - yticks=True, markersize=0.2, xlim=(0, runtime)), - # membrane potential of the postsynaptic neuron - Panel(stoc_data.segments[0].filter(name='v')[0], - ylabel="Membrane potential (mV)", - data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), - Panel(stoc_data.segments[0].filter(name='gsyn_exc')[0], - ylabel="gsyn excitatory (mV)", - data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), - Panel(stoc_data.segments[0].filter(name='gsyn_inh')[0], - ylabel="gsyn inhibitory (mV)", - data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), - # membrane potential of the postsynaptic neuron - Panel(exp_data.segments[0].filter(name='v')[0], - ylabel="Membrane potential (mV)", - data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), - Panel(exp_data.segments[0].filter(name='gsyn_exc')[0], - ylabel="gsyn excitatory (mV)", - data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), - Panel(exp_data.segments[0].filter(name='gsyn_inh')[0], - ylabel="gsyn inhibitory (mV)", - data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), - title="IF_cond_exp_stoc example", - annotations=f"Simulated with {sim.name()}" -) -plt.show() - -sim.end() -pylab.show() + +def run_script(*, split: bool = False) -> None: + """ + Runs the example script + + :param split: If True will split the Populations that receive data + into synapse and neuron cores. + This requires more cores but allows more spikes to be received. + """ + sim.setup(timestep=1.0, min_delay=1.0) + + if split: + sim.extra_models.IFCondExpStoc.set_model_n_synapse_cores(1) + sim.IF_cond_exp.set_model_n_synapse_cores(1) + + stoc_cell = sim.Population(1, sim.extra_models.IFCondExpStoc(**{ + 'i_offset': 0.1, + 'tau_refrac': 3.0, + 'v_thresh': -51.0, + 'v_reset': -70.0, + 'tau_syn_E': 5.0, + 'tau_syn_I': 5.0})) + + exp_cell = sim.Population(1, sim.IF_cond_exp(**{ + 'i_offset': 0.1, + 'tau_refrac': 3.0, + 'v_thresh': -51.0, + 'v_reset': -70.0, + 'tau_syn_E': 5.0, + 'tau_syn_I': 5.0})) + + spike_sourceE = sim.Population(1, sim.SpikeSourceArray(**{ + 'spike_times': [float(i) for i in range(5, 105, 10)]})) + spike_sourceI = sim.Population(1, sim.SpikeSourceArray(**{ + 'spike_times': [float(i) for i in range(155, 255, 10)]})) + + sim.Projection(spike_sourceE, exp_cell, + sim.OneToOneConnector(), + synapse_type=sim.StaticSynapse(weight=0.15, delay=2.0), + receptor_type='excitatory') + sim.Projection(spike_sourceI, exp_cell, + sim.OneToOneConnector(), + synapse_type=sim.StaticSynapse(weight=-0.15, delay=4.0), + receptor_type='inhibitory') + sim.Projection(spike_sourceE, stoc_cell, + sim.OneToOneConnector(), + synapse_type=sim.StaticSynapse(weight=0.15, delay=2.0), + receptor_type='excitatory') + sim.Projection(spike_sourceI, stoc_cell, + sim.OneToOneConnector(), + synapse_type=sim.StaticSynapse(weight=-0.15, delay=4.0), + receptor_type='inhibitory') + + stoc_cell.record('all') + exp_cell.record('all') + + runtime = 200.0 + + sim.run(runtime) + + stoc_data = stoc_cell.get_data() + exp_data = exp_cell.get_data() + + # Plot + Figure( + # raster plot of the presynaptic neuron spike times + Panel(stoc_data.segments[0].spiketrains, + yticks=True, markersize=0.2, xlim=(0, runtime)), + Panel(exp_data.segments[0].spiketrains, + yticks=True, markersize=0.2, xlim=(0, runtime)), + # membrane potential of the postsynaptic neuron + Panel(stoc_data.segments[0].filter(name='v')[0], + ylabel="Membrane potential (mV)", + data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), + Panel(stoc_data.segments[0].filter(name='gsyn_exc')[0], + ylabel="gsyn excitatory (mV)", + data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), + Panel(stoc_data.segments[0].filter(name='gsyn_inh')[0], + ylabel="gsyn inhibitory (mV)", + data_labels=[stoc_cell.label], yticks=True, xlim=(0, runtime)), + # membrane potential of the postsynaptic neuron + Panel(exp_data.segments[0].filter(name='v')[0], + ylabel="Membrane potential (mV)", + data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), + Panel(exp_data.segments[0].filter(name='gsyn_exc')[0], + ylabel="gsyn excitatory (mV)", + data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), + Panel(exp_data.segments[0].filter(name='gsyn_inh')[0], + ylabel="gsyn inhibitory (mV)", + data_labels=[exp_cell.label], yticks=True, xlim=(0, runtime)), + title="IF_cond_exp_stoc example", + annotations=f"Simulated with {sim.name()}" + ) + plt.show() + + sim.end() + pylab.show() + +# combined binaries [IF_cond_exp_stoc.aplx, IF_cond_exp.aplx] +# split binaries [IF_cond_exp_stoc_neuron.aplx, IF_cond_exp_neuron.aplx] + + +if __name__ == "__main__": + run_script() diff --git a/examples/extra_models_examples/IF_curr_exp_ca2_adaptive.py b/examples/extra_models_examples/IF_curr_exp_ca2_adaptive.py index ebf299a..4352871 100644 --- a/examples/extra_models_examples/IF_curr_exp_ca2_adaptive.py +++ b/examples/extra_models_examples/IF_curr_exp_ca2_adaptive.py @@ -25,91 +25,111 @@ import matplotlib.pyplot as pylab import pyNN.spiNNaker as sim -# Timestep (ms) -# **NOTE** the 2.5Khz input frequency is not going to work particularly well -# at 1ms -dt = 0.1 - -# Number of neurons - used to gather enough ISIs to get a smooth estimate -N = 300 - -# Time (ms) to simulate for -T = 250 - -# Setup simulator -sim.setup(timestep=dt, min_delay=1.0) - -# Create population of neurons -cell = sim.Population(N, sim.extra_models.IFCurrExpCa2Adaptive(**{ - "tau_m": 20.0, "cm": 0.5, - "v_rest": -70.0, - "v_reset": -60.0, - "v_thresh": -54.0, - "i_alpha": 0.1, - "tau_ca2": 50.0})) - -# Create poisson spike source -spike_source = sim.Population(N, sim.SpikeSourcePoisson(rate=2500.0)) - -sim.Projection(spike_source, cell, - sim.OneToOneConnector(), - sim.StaticSynapse(weight=0.1, delay=0.1), - receptor_type="excitatory") - -cell.record('spikes') -# cell.record_gsyn() - -sim.run(T) - -spike_times = cell.spinnaker_get_data('spikes') -# ca2 = cell.get_gsyn(compatible_output=True) - -# Split into list of spike times for each neuron -neuron_spikes = [spike_times[spike_times[:, 0] == n, 1] for n in range(N)] - -# Calculate interspike intervals -# and pair these with bin index of last spike time in pair -# **NOTE** using first spike time in pair leads to a dip at the -# end as the end of long pairs goes off the end of the simulation -binned_isis = numpy.hstack([ - numpy.vstack( - (t[1:] - t[:-1], - numpy.digitize(t[1:], numpy.arange(T)) - 1)) - for t in neuron_spikes]) - -# Split interspike intervals into separate array for each time bin -time_binned_isis = [binned_isis[0, binned_isis[1] == t] for t in range(T)] - -# Create a dictionary of non-empty time bins to mean interspike interval -mean_isis = {t: numpy.average(i) - for (t, i) in enumerate(time_binned_isis) if len(i) > 0} - -# Calculate the coefficient of variance for each time bin -isi_cv = {t: math.sqrt( - numpy.sum(numpy.power(time_binned_isis[t] - mean_isi, 2)) / - float(len(time_binned_isis[t]))) / mean_isi - for (t, mean_isi) in mean_isis.items()} - -# Take average CA2 level across all neurons -# average_ca2 = numpy.average(numpy.reshape(ca2[:,2], (N, int(T / dt))), -# axis=0) - -# Plot -fig, axes = pylab.subplots(2, sharex=True) - -axes[0].scatter(mean_isis.keys(), - [1000.0 / i for i in mean_isis.values()], s=2) -axes[0].set_ylabel("Firing rate/Hz") - -# axes[1].scatter(numpy.arange(0.0, T, dt), average_ca2, s=2) -# axes[1].set_ylabel("CA2/mA") -# axes[1].set_ylim((0.0, numpy.amax(average_ca2) * 1.25)) - -axes[1].scatter(isi_cv.keys(), isi_cv.values(), s=2) -axes[1].set_ylabel("Coefficient of ISI variance") - -axes[1].set_xlim((0.0, T)) -axes[1].set_xlabel("Time/ms") - -sim.end() -pylab.show() + +def run_script(*, split: bool = False) -> None: + """ + Runs the example script + + :param split: If True will split the Populations that receive data + into synapse and neuron cores. + This requires more cores but allows more spikes to be received. + """ + # Timestep (ms) + # **NOTE** + # the 2.5Khz input frequency is not going to work particularly well at 1ms + dt = 0.1 + + # Number of neurons - used to gather enough ISIs to get a smooth estimate + N = 300 + + # Time (ms) to simulate for + T = 250 + + # Setup simulator + sim.setup(timestep=dt, min_delay=1.0) + + if split: + sim.extra_models.IFCurrExpCa2Adaptive.set_model_n_synapse_cores(1) + + # Create population of neurons + cell = sim.Population(N, sim.extra_models.IFCurrExpCa2Adaptive(**{ + "tau_m": 20.0, "cm": 0.5, + "v_rest": -70.0, + "v_reset": -60.0, + "v_thresh": -54.0, + "i_alpha": 0.1, + "tau_ca2": 50.0})) + + # Create poisson spike source + spike_source = sim.Population(N, sim.SpikeSourcePoisson(rate=2500.0)) + + sim.Projection(spike_source, cell, + sim.OneToOneConnector(), + sim.StaticSynapse(weight=0.1, delay=0.1), + receptor_type="excitatory") + + cell.record('spikes') + # cell.record_gsyn() + + sim.run(T) + + spike_times = cell.spinnaker_get_data('spikes') + # ca2 = cell.get_gsyn(compatible_output=True) + + # Split into list of spike times for each neuron + neuron_spikes = [spike_times[spike_times[:, 0] == n, 1] for n in range(N)] + + # Calculate interspike intervals + # and pair these with bin index of last spike time in pair + # **NOTE** using first spike time in pair leads to a dip at the + # end as the end of long pairs goes off the end of the simulation + binned_isis = numpy.hstack([ + numpy.vstack( + (t[1:] - t[:-1], + numpy.digitize(t[1:], numpy.arange(T)) - 1)) + for t in neuron_spikes]) + + # Split interspike intervals into separate array for each time bin + time_binned_isis = [binned_isis[0, binned_isis[1] == t] for t in range(T)] + + # Create a dictionary of non-empty time bins to mean interspike interval + mean_isis = {t: numpy.average(i) + for (t, i) in enumerate(time_binned_isis) if len(i) > 0} + + # Calculate the coefficient of variance for each time bin + isi_cv = {t: math.sqrt( + numpy.sum(numpy.power(time_binned_isis[t] - mean_isi, 2)) / + float(len(time_binned_isis[t]))) / mean_isi + for (t, mean_isi) in mean_isis.items()} + + # Take average CA2 level across all neurons + # average_ca2 = numpy.average(numpy.reshape(ca2[:,2], (N, int(T / dt))), + # axis=0) + + # Plot + _, axes = pylab.subplots(2, sharex=True) + + axes[0].scatter(mean_isis.keys(), + [1000.0 / i for i in mean_isis.values()], s=2) + axes[0].set_ylabel("Firing rate/Hz") + + # axes[1].scatter(numpy.arange(0.0, T, dt), average_ca2, s=2) + # axes[1].set_ylabel("CA2/mA") + # axes[1].set_ylim((0.0, numpy.amax(average_ca2) * 1.25)) + + axes[1].scatter(isi_cv.keys(), isi_cv.values(), s=2) + axes[1].set_ylabel("Coefficient of ISI variance") + + axes[1].set_xlim((0.0, T)) + axes[1].set_xlabel("Time/ms") + + sim.end() + pylab.show() + + +# combined binaries [IF_curr_exp_ca2_adaptive.aplx] +# split binaries [IF_curr_exp_ca2_adaptive_neuron.aplx] + + +if __name__ == "__main__": + run_script() diff --git a/examples/extra_models_examples/IF_curr_exp_sEMD.py b/examples/extra_models_examples/IF_curr_exp_sEMD.py index ef9eb1d..136b91b 100644 --- a/examples/extra_models_examples/IF_curr_exp_sEMD.py +++ b/examples/extra_models_examples/IF_curr_exp_sEMD.py @@ -23,84 +23,108 @@ import matplotlib.pyplot as plt from pyNN.utility.plotting import Figure, Panel -# variables -weights = 1 -spike_time_facilitation = 4 -spike_time_trigger = 20 - -# set up simulation -simulation_timestep = 1 # ms -simulation_runtime = 100 # ms -p.setup(timestep=simulation_timestep) - -# neuron parameters -cell_params_semd = {'cm': 0.25, - 'i_offset': 0, # offset current - 'tau_m': 10, # membrane potential time constant - 'tau_refrac': 1, # refractory period time constant - 'tau_syn_E': 20, # excitatory current time constant - 'tau_syn_I': 20, # inhibitory current time constant - 'v_reset': -85, # reset potential - 'v_rest': -60, # resting potential - 'v_thresh': -50, # spiking threshold - 'scaling_factor': 100.0 # scaling factor for 2nd response - } - -# neuron populations -# (population size, neuron type, cell parameters, label) -sEMD = p.Population(1, p.extra_models.IF_curr_exp_sEMD, - cell_params_semd, label="sEMD") -input_facilitation = p.Population(1, p.SpikeSourceArray, - {'spike_times': [[spike_time_facilitation]]}, - label="input_facilitation") -input_trigger = p.Population(1, p.SpikeSourceArray, - {'spike_times': [[spike_time_trigger]]}, - label="input_trigger") - -sEMD.initialize(v=-60.0) - -# projections -p.Projection(input_facilitation, sEMD, p.OneToOneConnector(), - p.StaticSynapse(weight=weights, delay=1), - receptor_type='excitatory') -p.Projection(input_trigger, sEMD, p.OneToOneConnector(), - p.StaticSynapse(weight=weights, delay=1), - receptor_type='excitatory2') - -# records -sEMD.record(['spikes', 'v', 'gsyn_exc', 'gsyn_inh']) - -# run simulation -p.run(simulation_runtime) - -# receive data from neurons -spikes = sEMD.get_data(['spikes']) -v = sEMD.get_data(['v']) -current_exc = sEMD.get_data(['gsyn_exc']) -current_inh = sEMD.get_data(['gsyn_inh']) - -# plots -Figure( - # raster plot of the neuron spike times - Panel(spikes.segments[0].spiketrains, - yticks=True, markersize=4, xlim=(0, simulation_runtime)), - # membrane potential - Panel(v.segments[0].filter(name='v')[0], - ylabel="Membrane potential (mV)", - data_labels=[sEMD.label], yticks=True, xlim=(0, simulation_runtime)), - # excitatory current - Panel(current_exc.segments[0].filter(name='gsyn_exc')[0], - ylabel="gsyn excitatory (mV)", - data_labels=[sEMD.label], yticks=True, xlim=(0, simulation_runtime)), - # inhibitory current - Panel(current_inh.segments[0].filter(name='gsyn_inh')[0], - xlabel="Time (ms)", xticks=True, - ylabel="gsyn inhibitory (mV)", - data_labels=[sEMD.label], yticks=True, xlim=(0, simulation_runtime)), - title="SEMD example", - annotations=f"Simulated with {p.name()}" -) -plt.show() - -# end -p.end() + +def run_script(*, split: bool = False) -> None: + """ + Runs the example script + + :param split: If True will split the Populations that receive data + into synapse and neuron cores. + This requires more cores but allows more spikes to be received. + """ + # variables + weights = 1 + spike_time_facilitation = 4 + spike_time_trigger = 20 + + # set up simulation + simulation_timestep = 1 # ms + simulation_runtime = 100 # ms + p.setup(timestep=simulation_timestep) + + if split: + p.extra_models.IF_curr_exp_sEMD.set_model_n_synapse_cores(1) + + # neuron parameters + cell_params_semd = { + 'cm': 0.25, + 'i_offset': 0, # offset current + 'tau_m': 10, # membrane potential time constant + 'tau_refrac': 1, # refractory period time constant + 'tau_syn_E': 20, # excitatory current time constant + 'tau_syn_I': 20, # inhibitory current time constant + 'v_reset': -85, # reset potential + 'v_rest': -60, # resting potential + 'v_thresh': -50, # spiking threshold + 'scaling_factor': 100.0 # scaling factor for 2nd response + } + + # neuron populations + # (population size, neuron type, cell parameters, label) + sEMD = p.Population(1, p.extra_models.IF_curr_exp_sEMD, + cell_params_semd, label="sEMD") + input_facilitation = p.Population( + 1, p.SpikeSourceArray, {'spike_times': [[spike_time_facilitation]]}, + label="input_facilitation") + input_trigger = p.Population( + 1, p.SpikeSourceArray, {'spike_times': [[spike_time_trigger]]}, + label="input_trigger") + + sEMD.initialize(v=-60.0) + + # projections + p.Projection(input_facilitation, sEMD, p.OneToOneConnector(), + p.StaticSynapse(weight=weights, delay=1), + receptor_type='excitatory') + p.Projection(input_trigger, sEMD, p.OneToOneConnector(), + p.StaticSynapse(weight=weights, delay=1), + receptor_type='excitatory2') + + # records + sEMD.record(['spikes', 'v', 'gsyn_exc', 'gsyn_inh']) + + # run simulation + p.run(simulation_runtime) + + # receive data from neurons + spikes = sEMD.get_data(['spikes']) + v = sEMD.get_data(['v']) + current_exc = sEMD.get_data(['gsyn_exc']) + current_inh = sEMD.get_data(['gsyn_inh']) + + # plots + Figure( + # raster plot of the neuron spike times + Panel(spikes.segments[0].spiketrains, + yticks=True, markersize=4, xlim=(0, simulation_runtime)), + # membrane potential + Panel(v.segments[0].filter(name='v')[0], + ylabel="Membrane potential (mV)", + data_labels=[sEMD.label], + yticks=True, xlim=(0, simulation_runtime)), + # excitatory current + Panel(current_exc.segments[0].filter(name='gsyn_exc')[0], + ylabel="gsyn excitatory (mV)", + data_labels=[sEMD.label], + yticks=True, xlim=(0, simulation_runtime)), + # inhibitory current + Panel(current_inh.segments[0].filter(name='gsyn_inh')[0], + xlabel="Time (ms)", xticks=True, + ylabel="gsyn inhibitory (mV)", + data_labels=[sEMD.label], + yticks=True, xlim=(0, simulation_runtime)), + title="SEMD example", + annotations=f"Simulated with {p.name()}" + ) + plt.show() + + # end + p.end() + + +# combined binaries [IF_curr_exp_sEMD.aplx] +# split binaries [IF_curr_exp_sEMD_neuron.aplx] + + +if __name__ == "__main__": + run_script() diff --git a/examples/extra_models_examples/stdp_mad_recurrent_pre_stochastic_multiplicative.py b/examples/extra_models_examples/stdp_mad_recurrent_pre_stochastic_multiplicative.py new file mode 100644 index 0000000..a200766 --- /dev/null +++ b/examples/extra_models_examples/stdp_mad_recurrent_pre_stochastic_multiplicative.py @@ -0,0 +1,134 @@ +# Copyright (c) 2026 The University of Manchester +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +stdp_mad_recurrent_pre_stochastic_multiplicative +""" +import matplotlib.pyplot as plt +import pyNN.spiNNaker as p +from pyNN.utility.plotting import Figure, Panel +# pylint: disable=wrong-spelling-in-comment + +p.setup(timestep=1.0, min_delay=1.0) +p.set_number_of_neurons_per_core(p.IF_curr_exp, 100) + +nSourceNeurons = 1 # number of input (excitatory) neurons +nExcitNeurons = 1 # number of excitatory neurons in the recurrent memory +nInhibNeurons = 10 # number of inhibitory neurons in the recurrent memory +nTeachNeurons = 1 +runTime = 3200 + +cell_params_lif = { + 'cm': 0.25, # nF was 0.25 + 'i_offset': 0.0, + 'tau_m': 10.0, + 'tau_refrac': 2.0, + 'tau_syn_E': 0.5, + 'tau_syn_I': 0.5, + 'v_reset': -70.0, + 'v_rest': -70.0, + 'v_thresh': -50.0} + +populations = list() +projections = list() + +stimulus = 0 +inhib = 1 +excit = 2 +teacher = 3 + +weight_to_force_firing = 15.0 +baseline_excit_weight = 2.0 + +spikes0 = list() +teachingSpikes = list() +for i in range(runTime//40): + spikes0.append(i*40) +for i in range(runTime//80): + teachingSpikes.append(i*40+5+120) + +arrayEntries = [] +for i in range(nSourceNeurons): + newEntry = [] + for spike in spikes0: + newEntry.append(spike + i*40.0/100.0) + arrayEntries.append(newEntry) +spikeArray = {'spike_times': arrayEntries} + +teachlist = list() +for i in range(nSourceNeurons): + teachlist.append(teachingSpikes) +teachingSpikeArray = {'spike_times': teachlist} +populations.append(p.Population(nSourceNeurons, + p.SpikeSourceArray(**spikeArray), + label='excit_pop_ss_array')) # 0 +populations.append(p.Population(nInhibNeurons, + p.IF_curr_exp(**cell_params_lif), + label='inhib_pop')) # 1 +populations.append(p.Population(nExcitNeurons, + p.IF_curr_exp(**cell_params_lif), + label='excit_pop')) # 2 +populations.append(p.Population(nTeachNeurons, + p.SpikeSourceArray(**teachingSpikeArray), + label='teaching_ss_array')) # 3 + +stdp_model = p.STDPMechanism( + timing_dependence=p.extra_models.RecurrentRule( + accumulator_depression=-6, accumulator_potentiation=3, + mean_pre_window=10.0, mean_post_window=10.0, dual_fsm=False, + A_plus=0.2, A_minus=0.2), + weight_dependence=p.MultiplicativeWeightDependence(w_min=0.0, w_max=16.0), + weight=baseline_excit_weight, delay=1) + +projections.append( + p.Projection(populations[stimulus], populations[excit], + p.AllToAllConnector(), synapse_type=stdp_model)) + +projections.append( + p.Projection(populations[teacher], populations[excit], + p.OneToOneConnector(), receptor_type='excitatory', + synapse_type=p.StaticSynapse( + weight=weight_to_force_firing, delay=1))) + +populations[inhib].record(['v', 'spikes']) +populations[excit].record(['v', 'spikes']) + +p.run(runTime) + +final_weights = projections[0].get('weight', 'list', with_address=False) +print(f"Final weights: {final_weights}") + +v = populations[excit].get_data('v') +spikes = populations[excit].get_data('spikes') +vInhib = populations[inhib].get_data('v') +spikesInhib = populations[inhib].get_data('spikes') + +Figure( + # plot of the neuron spike times + Panel(spikes.segments[0].spiketrains, + yticks=True, markersize=0.2, xlim=(0, runTime)), + # membrane potential of the neurons + Panel(v.segments[0].filter(name='v')[0], + ylabel="Membrane potential (mV)", + data_labels=[populations[excit].label], yticks=True, + xlim=(0, runTime), xticks=True), + title="Simple associative memory: spikes and membrane potential", + annotations=f"Simulated with {p.name()}" +) +plt.show() + +p.end() + +# combined binaries [ +# IF_curr_exp_stdp_mad_recurrent_pre_stochastic_multiplicative.aplx] diff --git a/examples/extra_models_examples/synfire_if_curr_dual_exp.py b/examples/extra_models_examples/synfire_if_curr_dual_exp.py index 1af151c..927f341 100644 --- a/examples/extra_models_examples/synfire_if_curr_dual_exp.py +++ b/examples/extra_models_examples/synfire_if_curr_dual_exp.py @@ -19,74 +19,101 @@ from pyNN.utility.plotting import Figure, Panel import matplotlib.pyplot as plt -runtime = 5000 -p.setup(timestep=1.0, min_delay=1.0) -nNeurons = 200 # number of neurons in each population -p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) - -cell_params_lif = {'cm': 0.25, - 'i_offset': 0.0, - 'tau_m': 20.0, - 'tau_refrac': 2.0, - 'tau_syn_E': 5.0, - 'tau_syn_I': 5.0, - 'v_reset': -70.0, - 'v_rest': -65.0, - 'v_thresh': -50.0 - } - -populations = list() -projections = list() - -weight_to_spike = 2.0 -delay = 17 - -loopConnections = list() -for i in range(0, nNeurons): - singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) - loopConnections.append(singleConnection) - -injectionConnection = [(0, 0)] -spikeArray = {'spike_times': [[0]]} -populations.append( - p.Population(nNeurons, p.extra_models.IF_curr_dual_exp(**cell_params_lif), - label='pop_1')) -populations.append( - p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')) - -projections.append(p.Projection( - populations[0], populations[0], p.FromListConnector(loopConnections), - p.StaticSynapse(weight=weight_to_spike, delay=delay))) -projections.append(p.Projection( - populations[1], populations[0], p.FromListConnector(injectionConnection), - p.StaticSynapse(weight=weight_to_spike, delay=1))) - -populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) - -p.run(runtime) - -# get data (could be done as one, but can be done bit by bit as well) -data = populations[0].get_data(['v', 'gsyn_exc', 'spikes', 'gsyn_inh']) - -figure_filename = "results.png" -Figure( - # raster plot of the presynaptic neuron spike times - Panel(data.segments[0].spiketrains, - yticks=True, markersize=0.2, xlim=(0, runtime)), - # membrane potential of the postsynaptic neuron - Panel(data.segments[0].filter(name='v')[0], - ylabel="Membrane potential (mV)", - data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), - Panel(data.segments[0].filter(name='gsyn_exc')[0], - ylabel="gsyn excitatory (mV)", - data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), - Panel(data.segments[0].filter(name='gsyn_inh')[0], - ylabel="gsyn inhibitory (mV)", - data_labels=[populations[0].label], yticks=True, xlim=(0, runtime)), - title="Synfire chain example with dual exponential synapse", - annotations=f"Simulated with {p.name()}" -) -plt.show() -print(figure_filename) - -p.end() + +def run_script(*, split: bool = False) -> None: + """ + Runs the example script + + :param split: If True will split the Populations that receive data + into synapse and neuron cores. + This requires more cores but allows more spikes to be received. + """ + runtime = 5000 + p.setup(timestep=1.0, min_delay=1.0) + + if split: + p.extra_models.IF_curr_dual_exp.set_model_n_synapse_cores(1) + + nNeurons = 200 # number of neurons in each population + p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2) + + cell_params_lif = {'cm': 0.25, + 'i_offset': 0.0, + 'tau_m': 20.0, + 'tau_refrac': 2.0, + 'tau_syn_E': 5.0, + 'tau_syn_I': 5.0, + 'v_reset': -70.0, + 'v_rest': -65.0, + 'v_thresh': -50.0 + } + + populations = list() + projections = list() + + weight_to_spike = 2.0 + delay = 17 + + loopConnections = list() + for i in range(0, nNeurons): + singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay)) + loopConnections.append(singleConnection) + + injectionConnection = [(0, 0)] + spikeArray = {'spike_times': [[0]]} + populations.append( + p.Population( + nNeurons, p.extra_models.IF_curr_dual_exp(**cell_params_lif), + label='pop_1')) + populations.append( + p.Population(1, p.SpikeSourceArray(**spikeArray), + label='inputSpikes_1')) + + projections.append(p.Projection( + populations[0], populations[0], p.FromListConnector(loopConnections), + p.StaticSynapse(weight=weight_to_spike, delay=delay))) + projections.append(p.Projection( + populations[1], populations[0], + p.FromListConnector(injectionConnection), + p.StaticSynapse(weight=weight_to_spike, delay=1))) + + populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes']) + + p.run(runtime) + + # get data (could be done as one, but can be done bit by bit as well) + data = populations[0].get_data(['v', 'gsyn_exc', 'spikes', 'gsyn_inh']) + + figure_filename = "results.png" + Figure( + # raster plot of the presynaptic neuron spike times + Panel(data.segments[0].spiketrains, + yticks=True, markersize=0.2, xlim=(0, runtime)), + # membrane potential of the postsynaptic neuron + Panel(data.segments[0].filter(name='v')[0], + ylabel="Membrane potential (mV)", + data_labels=[populations[0].label], + yticks=True, xlim=(0, runtime)), + Panel(data.segments[0].filter(name='gsyn_exc')[0], + ylabel="gsyn excitatory (mV)", + data_labels=[populations[0].label], + yticks=True, xlim=(0, runtime)), + Panel(data.segments[0].filter(name='gsyn_inh')[0], + ylabel="gsyn inhibitory (mV)", + data_labels=[populations[0].label], + yticks=True, xlim=(0, runtime)), + title="Synfire chain example with dual exponential synapse", + annotations=f"Simulated with {p.name()}" + ) + plt.show() + print(figure_filename) + + p.end() + + +# combined binaries [IF_curr_exp_dual.aplx] +# split binaries [IF_curr_exp_dual_neuron.aplx] + + +if __name__ == "__main__": + run_script() diff --git a/examples/extra_models_examples/vogels_2011_live.py b/examples/extra_models_examples/vogels_2011_live.py index 38df246..9ff72a3 100644 --- a/examples/extra_models_examples/vogels_2011_live.py +++ b/examples/extra_models_examples/vogels_2011_live.py @@ -38,51 +38,73 @@ # (Number of inhibitory neurons is proportional to this) NUM_EXCITATORY = 2000 -# SpiNNaker setup -sim.setup(timestep=1.0, min_delay=1.0, time_scale_factor=10) - -# Reduce number of neurons to simulate on each core -sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100) - -# Create excitatory and inhibitory populations of neurons -ex_pop = sim.Population(NUM_EXCITATORY, model(**cell_params), - label="Excitatory", additional_parameters={"seed": 2}) -in_pop = sim.Population(NUM_EXCITATORY / 4, model(**cell_params), - label="Inhibitory", additional_parameters={"seed": 9}) - -# Record excitatory spikes -ex_pop.record('spikes') - -# Make excitatory->inhibitory projections -sim.Projection(ex_pop, in_pop, sim.FixedProbabilityConnector(0.02), - receptor_type='excitatory', - synapse_type=sim.StaticSynapse(weight=0.029)) -sim.Projection(ex_pop, ex_pop, sim.FixedProbabilityConnector(0.02), - receptor_type='excitatory', - synapse_type=sim.StaticSynapse(weight=0.029)) - -# Make inhibitory->inhibitory projections -sim.Projection(in_pop, in_pop, sim.FixedProbabilityConnector(0.02), - receptor_type='inhibitory', - synapse_type=sim.StaticSynapse(weight=-0.29)) - -# Build inhibitory plasticity model -stdp_model = sim.STDPMechanism( - timing_dependence=sim.extra_models.Vogels2011Rule(alpha=0.12, tau=20.0, - A_plus=0.05), - weight_dependence=sim.AdditiveWeightDependence(w_min=0.0, w_max=1.0)) - -# Make inhibitory->excitatory projections -sim.Projection(in_pop, ex_pop, sim.FixedProbabilityConnector(0.02), - receptor_type='inhibitory', - synapse_type=stdp_model) - -# Activate live output for excitatory spikes -sim.external_devices.activate_live_output_for(ex_pop) -sim.external_devices.activate_live_output_for(in_pop) - -# Run simulation -sim.run(5000) - -# End simulation on SpiNNaker -sim.end() + +def run_script(*, split: bool = False) -> None: + """ + Runs the example script + + :param split: If True will split the Populations that receive data + into synapse and neuron cores. + This requires more cores but allows more spikes to be received. + """ + # SpiNNaker setup + sim.setup(timestep=1.0, min_delay=1.0, time_scale_factor=10) + + if split: + model.set_model_n_synapse_cores(1) + + # Reduce number of neurons to simulate on each core + sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100) + + # Create excitatory and inhibitory populations of neurons + ex_pop = sim.Population( + NUM_EXCITATORY, model(**cell_params), + label="Excitatory", additional_parameters={"seed": 2}) + in_pop = sim.Population( + NUM_EXCITATORY / 4, model(**cell_params), + label="Inhibitory", additional_parameters={"seed": 9}) + + # Record excitatory spikes + ex_pop.record('spikes') + + # Make excitatory->inhibitory projections + sim.Projection(ex_pop, in_pop, sim.FixedProbabilityConnector(0.02), + receptor_type='excitatory', + synapse_type=sim.StaticSynapse(weight=0.029)) + sim.Projection(ex_pop, ex_pop, sim.FixedProbabilityConnector(0.02), + receptor_type='excitatory', + synapse_type=sim.StaticSynapse(weight=0.029)) + + # Make inhibitory->inhibitory projections + sim.Projection(in_pop, in_pop, sim.FixedProbabilityConnector(0.02), + receptor_type='inhibitory', + synapse_type=sim.StaticSynapse(weight=-0.29)) + + # Build inhibitory plasticity model + stdp_model = sim.STDPMechanism( + timing_dependence=sim.extra_models.Vogels2011Rule( + alpha=0.12, tau=20.0, A_plus=0.05), + weight_dependence=sim.AdditiveWeightDependence(w_min=0.0, w_max=1.0)) + + # Make inhibitory->excitatory projections + sim.Projection(in_pop, ex_pop, sim.FixedProbabilityConnector(0.02), + receptor_type='inhibitory', + synapse_type=stdp_model) + + # Activate live output for excitatory spikes + sim.external_devices.activate_live_output_for(ex_pop) + sim.external_devices.activate_live_output_for(in_pop) + + # Run simulation + sim.run(5000) + + # End simulation on SpiNNaker + sim.end() + + +# combined binaries [IF_curr_exp_stdp_mad_vogels_2011_additive] +# split binaries [synapses_stdp_mad_vogels_2011_additive] + + +if __name__ == "__main__": + run_script() diff --git a/integration_tests/test_scripts.py b/integration_tests/test_scripts.py index f6a5696..3ab9da9 100644 --- a/integration_tests/test_scripts.py +++ b/integration_tests/test_scripts.py @@ -81,8 +81,8 @@ def test_examples_external_devices_examples_live_examples_spike_io(self): def test_examples_external_devices_examples_live_examples_synfire_if_curr_exp_live(self): self.check_script("examples/external_devices_examples/live_examples/synfire_if_curr_exp_live.py") - def test_examples_external_devices_examples_live_examples_spike_io_interactive_demo_with_c_vis(self): - self.check_script("examples/external_devices_examples/live_examples/spike_io_interactive_demo_with_c_vis.py") + # Not testing file due to: Unhandled main + # examples/external_devices_examples/live_examples/spike_io_interactive_demo_with_c_vis.py def test_examples_external_devices_examples_live_examples_balanced_random_live_rate(self): self.check_script("examples/external_devices_examples/live_examples/balanced_random_live_rate.py") @@ -150,23 +150,48 @@ def test_examples_stdp_example_get_plastic_params(self): def test_examples_extra_models_examples_LGN_Izhikevich(self): self.check_script("examples/extra_models_examples/LGN_Izhikevich.py") - def test_examples_extra_models_examples_vogel_2011_vogels_2011_live(self): - self.check_script("examples/extra_models_examples/vogel_2011/vogels_2011_live.py") + def test_examples_extra_models_examples_vogel_2011_vogels_2011_live_combined(self): + from examples.extra_models_examples.vogel_2011.vogels_2011_live import run_script + run_script(split=False) + self.check_binaries_used(["IF_curr_exp_stdp_mad_vogels_2011_additive"]) - def test_examples_extra_models_examples_vogel_2011_vogels_2011(self): - self.check_script("examples/extra_models_examples/vogel_2011/vogels_2011.py") + def test_examples_extra_models_examples_vogel_2011_vogels_2011_live_split(self): + from examples.extra_models_examples.vogel_2011.vogels_2011_live import run_script + run_script(split=True) + self.check_binaries_used(["synapses_stdp_mad_vogels_2011_additive"]) + + # Not testing file due to: Unhandled main + # examples/extra_models_examples/vogel_2011/vogels_2011.py def test_examples_extra_models_examples_stdp_associative_memory(self): self.check_script("examples/extra_models_examples/stdp_associative_memory.py") + def test_examples_extra_models_examples_stdp_mad_recurrent_pre_stochastic_multiplicative(self): + self.check_script("examples/extra_models_examples/stdp_mad_recurrent_pre_stochastic_multiplicative.py") + self.check_binaries_used(["IF_curr_exp_stdp_mad_recurrent_pre_stochastic_multiplicative.aplx"]) + def test_examples_extra_models_examples_stdp_triplet(self): self.check_script("examples/extra_models_examples/stdp_triplet.py") - def test_examples_extra_models_examples_synfire_if_curr_dual_exp(self): - self.check_script("examples/extra_models_examples/synfire_if_curr_dual_exp.py") + def test_examples_extra_models_examples_synfire_if_curr_dual_exp_combined(self): + from examples.extra_models_examples.synfire_if_curr_dual_exp import run_script + run_script(split=False) + self.check_binaries_used(["IF_curr_exp_dual.aplx"]) + + def test_examples_extra_models_examples_synfire_if_curr_dual_exp_split(self): + from examples.extra_models_examples.synfire_if_curr_dual_exp import run_script + run_script(split=True) + self.check_binaries_used(["IF_curr_exp_dual_neuron.aplx"]) - def test_examples_extra_models_examples_IF_curr_exp_sEMD(self): - self.check_script("examples/extra_models_examples/IF_curr_exp_sEMD.py") + def test_examples_extra_models_examples_IF_curr_exp_sEMD_combined(self): + from examples.extra_models_examples.IF_curr_exp_sEMD import run_script + run_script(split=False) + self.check_binaries_used(["IF_curr_exp_sEMD.aplx"]) + + def test_examples_extra_models_examples_IF_curr_exp_sEMD_split(self): + from examples.extra_models_examples.IF_curr_exp_sEMD import run_script + run_script(split=True) + self.check_binaries_used(["IF_curr_exp_sEMD_neuron.aplx"]) def test_examples_extra_models_examples_IF_curr_delta(self): self.check_script("examples/extra_models_examples/IF_curr_delta.py") @@ -174,11 +199,25 @@ def test_examples_extra_models_examples_IF_curr_delta(self): def test_examples_extra_models_examples_stdp_example_izk_cond(self): self.check_script("examples/extra_models_examples/stdp_example_izk_cond.py") - def test_examples_extra_models_examples_IF_curr_exp_ca2_adaptive(self): - self.check_script("examples/extra_models_examples/IF_curr_exp_ca2_adaptive.py") - - def test_examples_extra_models_examples_IF_cond_exp_stoc(self): - self.check_script("examples/extra_models_examples/IF_cond_exp_stoc.py") + def test_examples_extra_models_examples_IF_curr_exp_ca2_adaptive_combined(self): + from examples.extra_models_examples.IF_curr_exp_ca2_adaptive import run_script + run_script(split=False) + self.check_binaries_used(["IF_curr_exp_ca2_adaptive.aplx"]) + + def test_examples_extra_models_examples_IF_curr_exp_ca2_adaptive_split(self): + from examples.extra_models_examples.IF_curr_exp_ca2_adaptive import run_script + run_script(split=True) + self.check_binaries_used(["IF_curr_exp_ca2_adaptive_neuron.aplx"]) + + def test_examples_extra_models_examples_IF_cond_exp_stoc_combined(self): + from examples.extra_models_examples.IF_cond_exp_stoc import run_script + run_script(split=False) + self.check_binaries_used(["IF_cond_exp_stoc.aplx", "IF_cond_exp.aplx"]) + + def test_examples_extra_models_examples_IF_cond_exp_stoc_split(self): + from examples.extra_models_examples.IF_cond_exp_stoc import run_script + run_script(split=True) + self.check_binaries_used(["IF_cond_exp_stoc_neuron.aplx", "IF_cond_exp_neuron.aplx"]) def test_examples_wta_example(self): self.check_script("examples/wta_example.py")