Skip to content

Commit

Permalink
Merge pull request #475 from apdavison/stochastic-synapses
Browse files Browse the repository at this point in the history
Stochastic synapses
  • Loading branch information
apdavison committed May 4, 2017
2 parents 1a883af + f9cde5c commit 77b48ee
Show file tree
Hide file tree
Showing 29 changed files with 2,011 additions and 31 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
x86_64
i386
i686
_build

# Python files
build
Expand Down
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
include pyNN/neuron/nmodl/*.mod
include pyNN/nest/extensions/*.h
include pyNN/nest/extensions/*.cpp
include pyNN/nest/extensions/CMakeLists.txt
include pyNN/nest/extensions/sli/*
include pyNN/descriptions/templates/*/*.txt
include test/parameters/*
include test/system/*.py
Expand Down
4 changes: 2 additions & 2 deletions doc/data_handling.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ top-level data container, which contains one or more :class:`Segment`\s. Each
:class:`Segment` is a container for data sharing a common time basis - a new
:class:`Segment` is added every time the :func:`reset` function is called.

A :class:`Segment` can contain lists of :class:`AnalogSignal`,
:class:`AnalogSignalArray` and :class:`SpikeTrain` objects. These data objects
A :class:`Segment` can contain lists of :class:`AnalogSignal` and :class:`SpikeTrain` objects.
These data objects
inherit from NumPy's array class, and so can be treated in further processing
(analysis, visualization, etc.) in exactly the same way as NumPy arrays, but in
addition they carry metadata about units, sampling interval, etc.
Expand Down
4 changes: 2 additions & 2 deletions doc/neurons.txt
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,8 @@ or written to file using :meth:`write_data()`:
Neo see the documentation at http://packages.python.org/neo. Here, it will
suffice to note that a :class:`Block` is the top-level container, and contains
one or more :class:`Segments`. Each :class:`Segment` is a container for data
that share a common time basis, and can contain lists of :class:`AnalogSignal`,
:class:`AnalogSignalArray` and :class:`SpikeTrain` objects. These data objects
that share a common time basis, and can contain lists of :class:`AnalogSignal`
and :class:`SpikeTrain` objects. These data objects
inherit from NumPy array, and so can be treated in further processing (analysis,
visualization, etc.) in exactly the same way as plain arrays, but in addition
they carry metadata about units, sampling interval, etc.
Expand Down
111 changes: 111 additions & 0 deletions examples/multiquantal_synapses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# encoding: utf-8
"""
...
"""

import matplotlib
matplotlib.use('Agg')
import numpy as np
import neo
from pyNN.utility import get_simulator, init_logging, normalized_filename


# === Configure the simulator ================================================

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)

sim.setup(quit_on_end=False)


# === Build and instrument the network =======================================

spike_times = np.hstack((np.arange(10, 100, 10), np.arange(250, 350, 10)))
spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=spike_times))

connector = sim.AllToAllConnector()

depressing = dict(U=0.8, tau_rec=100.0, tau_facil=0.0, weight=0.01, delay=0.5)
facilitating = dict(U=0.04, tau_rec=50.0, tau_facil=200.0, weight=0.01, delay=0.5)

synapse_types = {
'depressing, n=1': sim.MultiQuantalSynapse(n=1, **depressing),
'depressing, n=5': sim.MultiQuantalSynapse(n=5, **depressing),
'facilitating, n=1': sim.MultiQuantalSynapse(n=1, **facilitating),
'facilitating, n=5': sim.MultiQuantalSynapse(n=5, **facilitating),
}

populations = {}
projections = {}
for label in synapse_types:
populations[label] = sim.Population(1000, sim.IF_cond_exp(e_rev_I=-75, tau_syn_I=4.3), label=label)
populations[label].record('gsyn_inh')
projections[label] = sim.Projection(spike_source, populations[label], connector,
receptor_type='inhibitory',
synapse_type=synapse_types[label])
projections[label].initialize(a=synapse_types[label].parameter_space['n'], u=synapse_types[label].parameter_space['U'])

spike_source.record('spikes')

if "nest" in sim.__name__:
print(sim.nest.GetStatus([projections['depressing, n=5'].nest_connections[0]]))

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

sim.run(400.0)


# === Save the results, optionally plot a figure =============================

for label, p in populations.items():
filename = normalized_filename("Results", "multiquantal_synapses_%s" % label,
"pkl", options.simulator)
p.write_data(filename, annotations={'script_name': __file__})


if options.plot_figure:
from pyNN.utility.plotting import Figure, Panel
#figure_filename = normalized_filename("Results", "multiquantal_synapses",
# "png", options.simulator)
figure_filename = "Results/multiquantal_synapses_{}.png".format(options.simulator)

data = {}
for label in synapse_types:
data[label] = populations[label].get_data().segments[0]
gsyn = data[label].filter(name='gsyn_inh')[0]
gsyn_mean = neo.AnalogSignal(gsyn.mean(axis=1).reshape(-1, 1),
sampling_rate=gsyn.sampling_rate,
channel_index=np.array([0]))
gsyn_mean.name = 'gsyn_inh_mean'
data[label].analogsignals.append(gsyn_mean)
#import pdb; pdb.set_trace()

def make_panel(population, label):
return Panel(population.get_data().segments[0].filter(name='gsyn_inh')[0],
data_labels=[label], yticks=True)
labels = sorted(synapse_types)
panels = [
Panel(data[label].filter(name='gsyn_inh_mean')[0],
data_labels=[label], yticks=True)
for label in labels
]
# add ylabel to top panel in each group
panels[0].options.update(ylabel=u'Synaptic conductance (µS)')
##panels[len(synapse_types)].options.update(ylabel='Membrane potential (mV)')
# add xticks and xlabel to final panel
panels[-1].options.update(xticks=True, xlabel="Time (ms)")

Figure(*panels,
title="Example of facilitating and depressing multi-quantal release synapses",
annotations="Simulated with %s" % options.simulator.upper()
).save(figure_filename)
print(figure_filename)


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

sim.end()
118 changes: 118 additions & 0 deletions examples/stochastic_deterministic_comparison.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# encoding: utf-8
"""
...
"""

import matplotlib
matplotlib.use('Agg')
import numpy as np
import neo
from pyNN.utility import get_simulator, init_logging, normalized_filename


# === Configure the simulator ================================================

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)

sim.setup(quit_on_end=False)


# === Build and instrument the network =======================================

spike_times = np.hstack((np.arange(10, 100, 10), np.arange(250, 350, 10)))
spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=spike_times))

connector = sim.AllToAllConnector()

depressing = dict(U=0.8, tau_rec=100.0, tau_facil=0.0, weight=0.01, delay=0.5)
facilitating = dict(U=0.04, tau_rec=50.0, tau_facil=200.0, weight=0.01, delay=0.5)

synapse_types = {
'depressing, deterministic': sim.TsodyksMarkramSynapse(**depressing),
'depressing, stochastic': sim.StochasticTsodyksMarkramSynapse(**depressing),
'facilitating, deterministic': sim.TsodyksMarkramSynapse(**facilitating),
'facilitating, stochastic': sim.StochasticTsodyksMarkramSynapse(**facilitating),
}

populations = {}
projections = {}
for label in synapse_types:
populations[label] = sim.Population(1000, sim.IF_cond_exp(e_rev_I=-75, tau_syn_I=4.3), label=label)
populations[label].record('gsyn_inh')
projections[label] = sim.Projection(spike_source, populations[label], connector,
receptor_type='inhibitory',
synapse_type=synapse_types[label])

spike_source.record('spikes')


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

sim.run(400.0)


# === Save the results, optionally plot a figure =============================

for label, p in populations.items():
filename = normalized_filename("Results", "stochastic_comparison_%s" % label,
"pkl", options.simulator)
p.write_data(filename, annotations={'script_name': __file__})


if options.plot_figure:
from pyNN.utility.plotting import Figure, Panel
#figure_filename = normalized_filename("Results", "stochastic_comparison",
# "png", options.simulator)
figure_filename = "Results/stochastic_comparison_{}.png".format(options.simulator)

data = {}
for label in synapse_types:
data[label] = populations[label].get_data().segments[0]
if 'stochastic' in label:
gsyn = data[label].filter(name='gsyn_inh')[0]
gsyn_mean = neo.AnalogSignal(gsyn.mean(axis=1).reshape(-1, 1),
sampling_rate=gsyn.sampling_rate)
gsyn_mean.channel_index = neo.ChannelIndex(np.array([0]))
gsyn_mean.name = 'gsyn_inh_mean'
data[label].analogsignals.append(gsyn_mean)
#import pdb; pdb.set_trace()

def make_panel(population, label):
return Panel(population.get_data().segments[0].filter(name='gsyn_inh')[0],
data_labels=[label], yticks=True)
panels = [
Panel(data['depressing, deterministic'].filter(name='gsyn_inh')[0][:, 0],
data_labels=['depressing, deterministic'], yticks=True,
ylim=[0, 0.008]),
Panel(data['depressing, stochastic'].filter(name='gsyn_inh_mean')[0],
data_labels=['depressing, stochastic mean'], yticks=True,
ylim=[0, 0.008]),
Panel(data['facilitating, deterministic'].filter(name='gsyn_inh')[0][:, 0],
data_labels=['facilitating, deterministic'], yticks=True,
ylim=[0, 0.002]),
Panel(data['facilitating, stochastic'].filter(name='gsyn_inh_mean')[0],
data_labels=['facilitating, stochastic mean'], yticks=True,
ylim=[0, 0.002]),

]
# add ylabel to top panel in each group
panels[0].options.update(ylabel=u'Synaptic conductance (µS)')
##panels[len(synapse_types)].options.update(ylabel='Membrane potential (mV)')
# add xticks and xlabel to final panel
panels[-1].options.update(xticks=True, xlabel="Time (ms)")

Figure(*panels,
title="Example of facilitating and depressing synapses in deterministic and stochastic versions",
annotations="Simulated with %s" % options.simulator.upper()
).save(figure_filename)
print(figure_filename)


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

sim.end()
87 changes: 87 additions & 0 deletions examples/stochastic_synapses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# encoding: utf-8
"""
docstring needed
"""

import matplotlib
matplotlib.use('Agg')
import numpy
from pyNN.utility import get_simulator, init_logging, normalized_filename


# === Configure the simulator ================================================

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)

sim.setup(quit_on_end=False)


# === Build and instrument the network =======================================

spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=numpy.arange(10, 100, 10)))

connector = sim.AllToAllConnector()

synapse_types = {
'static': sim.StaticSynapse(weight=0.01, delay=0.5),
'stochastic': sim.SimpleStochasticSynapse(p=0.5, weight=0.02, delay=0.5)
}

populations = {}
projections = {}
for label in 'static', 'stochastic':
populations[label] = sim.Population(1, sim.IF_cond_exp(), label=label)
populations[label].record(['v', 'gsyn_inh'])
projections[label] = sim.Projection(spike_source, populations[label], connector,
receptor_type='inhibitory',
synapse_type=synapse_types[label])

spike_source.record('spikes')


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

sim.run(200.0)


# === Save the results, optionally plot a figure =============================

for label, p in populations.items():
filename = normalized_filename("Results", "stochastic_synapses_%s" % label,
"pkl", options.simulator)
p.write_data(filename, annotations={'script_name': __file__})


if options.plot_figure:
from pyNN.utility.plotting import Figure, Panel
figure_filename = normalized_filename("Results", "stochastic_synapses_",
"png", options.simulator)
panels = []
for variable in ('gsyn_inh', 'v'):
for population in populations.values():
panels.append(
Panel(population.get_data().segments[0].filter(name=variable)[0],
data_labels=[population.label], yticks=True),
)
# add ylabel to top panel in each group
panels[0].options.update(ylabel=u'Synaptic conductance (µS)')
panels[3].options.update(ylabel='Membrane potential (mV)')
# add xticks and xlabel to final panel
panels[-1].options.update(xticks=True, xlabel="Time (ms)")

Figure(*panels,
title="Example of simple stochastic synapses",
annotations="Simulated with %s" % options.simulator.upper()
).save(figure_filename)
print(figure_filename)


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

sim.end()
Loading

0 comments on commit 77b48ee

Please sign in to comment.