Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TEST add-nest-example-scripts #802

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions examples/balanced_neuron_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from scipy.optimize import bisect
import matplotlib.pyplot as plt
import pyNN.nest as sim
from pyNN.utility.plotting import Figure, Panel

import pyNN as testpynn

spec_dict = {
"simulation_time": 25000.0, # (ms)
"n_ex": 16000, # Number of excitatory neurons
"n_in": 4000, # Number of inhibitory neurons
"r_ex": 5.0, # (Hz) Excitatory Rate
"r_in": 20.5, # (Hz) Inhibitory Rate
"ex_syn": 0.045, # (nA) Excitatory Synaptic Current Amplitude
"in_syn": -0.045, # (nA) Inhibitory Synaptic Current Amplitude
"delay": 1.0, # (ms)
"low": 15.0, # (Hz)
"high": 25.0, # (Hz)
"precision": 0.01
}

def output_rate(spec_dict, guess):

newsim = testpynn.nest
newsim.setup(timestep=0.1)
Copy link
Member

@apdavison apdavison Jun 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest moving the network creation outside the function, as is done in the PyNEST implementation. Inside the function, you just need to change the input rate, use sim.run(...), then neuron.get_data(clear=True) (the clear=True argument removes the data from the population after you've retrieved them)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@apdavison 'sim.reset()' doesn't work with NEST. This was one of the primary reason as to implement inside the function call.

Sim.run() will continue the simulation from previous checkpoint which is opposite to what I desired for.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For balanced_neuron_example, my results still differ from native NEST example? Is it fine? Is it due to the core implementation being reason for two different resultant value?


cell_params = {
"v_rest": -70.0, # (mV)
"v_reset": -70.0, # (mV)
"cm": 0.250, # (nF)
"tau_m": 10, # (ms)
"tau_refrac": 2, # (ms)
"tau_syn_E": 2, # (ms)
"tau_syn_I": 2, # (ms)
"v_thresh": -55.0, # (mV)
"i_offset": 0.0, # (nA)
}

cell_type = sim.IF_curr_alpha(**cell_params)
neuron = sim.Population(1, cell_type, label="Neuron 1")
neuron.record(["v", "spikes"])

print("Inhibitory rate estimate: %5.2f Hz" % guess)

noise_rate_ex = spec_dict["n_ex"] * spec_dict["r_ex"]
noise_rate_in = spec_dict["n_in"] * spec_dict["r_in"]
in_rate = float(abs(spec_dict["n_in"] * guess))

poisson_noise_generators = sim.Population(2, sim.SpikeSourcePoisson(rate=[noise_rate_ex, in_rate]))

syn = sim.StaticSynapse(delay=1)

prj = sim.Projection(poisson_noise_generators, neuron, sim.AllToAllConnector(), syn)
prj.setWeights([spec_dict["ex_syn"], spec_dict["in_syn"]])

newsim.run(1000)

data_spikes = neuron.get_data(clear=True).segments[0].spiketrains[0]
n_spikes = len(data_spikes)
output_rate = (n_spikes * 1000.0) / spec_dict["simulation_time"]

print(" -> Neuron rate: %6.2f Hz (goal: %4.2f Hz)" % (output_rate, spec_dict["r_ex"]))
return output_rate


in_rate = bisect(lambda guess: output_rate(spec_dict, guess) - spec_dict["r_ex"], spec_dict["low"], spec_dict["high"], xtol=spec_dict["precision"])
print("Optimal rate for the inhibitory population: %.2f Hz" % in_rate)
41 changes: 41 additions & 0 deletions examples/iaf_neuron_with_current_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import matplotlib.pyplot as plt
from pyNN.utility.plotting import Figure, Panel
import pyNN.nest as sim
import pyNN as devpynn

timesteps = [0.1, 0.5, 1.0]
fig_counter=0

for dt in timesteps:
newsim = devpynn.nest
newsim.setup(timestep=dt)

cell_params = {
"v_rest": -70.0, # (mV)
"v_reset": -70.0, # (mV)
"cm": 0.250, # (nF)
"tau_m": 10, # (ms)
"tau_refrac": 2, # (ms)
"tau_syn_E": 2, # (ms)
"tau_syn_I": 2, # (ms)
"v_thresh": -55.0, # (mV)
"i_offset": 0.376 # (nA)
}

cell_type = sim.IF_curr_alpha(**cell_params)
neuron = sim.Population(1, cell_type, label="Neuron 1")
neuron.record(["v", "spikes"])
newsim.run(1000.0)

data_v = neuron.get_data().segments[0].filter(name="v")[0]
data_spikes = neuron.get_data().segments[0].spiketrains[0]

fig_counter += 1
plt.figure(fig_counter)
plt.plot(data_v[:,0].times, data_v[:, 0])
plt.xlabel("Time (in ms)")
plt.ylabel("Membrane Potential (in mV)")
plt.savefig(f"PLOT_iaf_neuron_current_{fig_counter}")
plt.show()

print(f"\nNumber of spikes: {len(data_spikes)}")
77 changes: 77 additions & 0 deletions examples/one_neuron_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# encoding: utf-8
"""
A simple native NEST example of simulating One Neuron with the help of PyNN.


Usage: one_neuron_example.py [-h] [--plot-figure] [--debug DEBUG] simulator

positional arguments:
simulator neuron, nest, brian or another backend simulator

optional arguments:
-h, --help show this help message and exit
--plot-figure plot the simulation results to a file
--debug DEBUG print debugging information
"""

import pyNN.nest as sim
from pyNN.utility import get_simulator, init_logging, normalized_filename
from pyNN.utility.plotting import Figure, Panel

sim, options = get_simulator(("--plot-figure", "Plot the simulation results to a file.", {"action": "store_true"}),
("--debug", "Print debugging information."))


if options.debug:
init_logging(None, debug=True)

# === Define parameters ========================================================

cell_params = {
"v_rest": -70.0, # (mV)
"v_reset": -70.0, # (mV)
"cm": 0.250, # (nF)
"tau_m": 10, # (ms)
"tau_refrac": 2, # (ms)
"tau_syn_E": 2, # (ms)
"tau_syn_I": 2, # (ms)
"v_thresh": -55.0, # (mV)
"i_offset": 0.376, # (nA)
}

# === Build the network ========================================================

sim.setup(timestep=0.1) # (ms)

cell_type = sim.IF_curr_alpha(**cell_params)
neuron = sim.Population(1, cell_type, label="Neuron 1")
neuron.record("v")


# === Run simulation ===========================================================

sim.run(1000.0)

data_v = neuron.get_data().segments[0].filter(name="v")[0]

if options.plot_figure:
figure_filename = normalized_filename("Results", "one_neuron_example", "png",
options.simulator, sim.num_processes())
Figure(
Panel(
data_v[:,0],
xticks=True,
yticks=True,
xlabel="Time (in ms)",
ylabel="Membrane Potential (mV)"
),
title="One Neuron",
annotations="One Neuron Example using PyNN"
).save(figure_filename)
print(figure_filename)

# === Clean up and quit ========================================================

sim.end()


43 changes: 43 additions & 0 deletions examples/one_neuron_noise_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import pyNN.nest as sim
from pyNN.utility.plotting import Figure, Panel
import matplotlib.pyplot as plt

sim.setup(timestep=0.1) # (ms)


cell_params = {
"v_rest": -70.0, # (mV)
"v_reset": -70.0, # (mV)
"cm": 0.250, # (nF)
"tau_m": 10, # (ms)
"tau_refrac": 2, # (ms)
"tau_syn_E": 2, # (ms)
"tau_syn_I": 2, # (ms)
"v_thresh": -55.0, # (mV)
"i_offset": 0, # (nA)
}


cell_type = sim.IF_curr_alpha(**cell_params)

neuron = sim.Population(1, cell_type, label="Neuron")
neuron.record(["v", "spikes"])

poisson_noise_generators = sim.Population(2, sim.SpikeSourcePoisson(rate=[80000, 15000]))
poisson_noise_generators.record("spikes")

syn = sim.StaticSynapse(weight=0.0012, delay=1)

prj = sim.Projection(poisson_noise_generators, neuron, sim.AllToAllConnector() , syn)
prj.setWeights([0.0012, 0.001])
prj.setDelays([1, 1])

sim.run(1000)

data_v = neuron.get_data().segments[0].filter(name="v")[0]
data_spikes = neuron.get_data().segments[0].spiketrains

Figure(
Panel(data_v[:,0], xlabel="Time (in ms)", ylabel="Membrane Potential", xticks=True, yticks=True)
).show()

53 changes: 53 additions & 0 deletions examples/two_neuron_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
Two Neuron Example translations from NEST into PyNN.
"""

import pyNN.nest as sim
from pyNN.utility.plotting import Figure, Panel
import matplotlib.pyplot as plt

sim.setup(timestep=0.1) # (ms)

cell_params = {
"v_rest": -70.0, # (mV)
"v_reset": -70.0, # (mV)
"cm": 0.250, # (nF)
"tau_m": 10, # (ms)
"tau_refrac": 2, # (ms)
"tau_syn_E": 2, # (ms)
"tau_syn_I": 2, # (ms)
"v_thresh": -55.0, # (mV)
"i_offset": 0, # (nA)
}

cell_type = sim.IF_curr_alpha(**cell_params)

neuron1 = sim.Population(1, cell_type, label="Neuron 1")
neuron1.set(i_offset=0.376)
neuron1.record("v")

neuron2 = sim.Population(1, cell_type, label="Neuron 2")
neuron2.record("v")

syn = sim.StaticSynapse(weight=0.02, delay=1.0)

projection1 = sim.Projection(neuron1, neuron2, sim.AllToAllConnector(), syn)

sim.run(1000)

neuron1_data_v = neuron1.get_data().segments[0].filter(name="v")[0]
neuron2_data_v = neuron2.get_data().segments[0].filter(name="v")[0]

Figure(
Panel(neuron1_data_v[:,0],
xticks=True,
yticks=True,
xlabel="Time (in ms)",
ylabel="Membrane Potential (in mV)"),
Panel(neuron2_data_v[:,0],
xticks=True,
yticks=True,
xlabel="Time (in ms)",
ylabel="Membrane Potential (in mV)")
).show()