1# encoding: utf-8
2"""
3Example of depressing and facilitating synapses
4
5Usage: stochastic_tsodyksmarkram.py [-h] [--plot-figure] [--debug DEBUG] simulator
6
7positional arguments:
8  simulator      neuron, nest, brian or another backend simulator
9
10optional arguments:
11  -h, --help     show this help message and exit
12  --plot-figure  Plot the simulation results to a file.
13  --debug DEBUG  Print debugging information
14
15"""
16
17import matplotlib
18matplotlib.use('Agg')
19import numpy as np
20from pyNN.utility import get_simulator, init_logging, normalized_filename
21
22
23# === Configure the simulator ================================================
24
25sim, options = get_simulator(("--plot-figure", "Plot the simulation results to a file.", {"action": "store_true"}),
26                             ("--debug", "Print debugging information"))
27
28if options.debug:
29    init_logging(None, debug=True)
30
31sim.setup(quit_on_end=False)
32
33
34# === Build and instrument the network =======================================
35
36spike_times = np.hstack((np.arange(10, 100, 10), np.arange(250, 350, 10)))
37spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=spike_times))
38
39connector = sim.AllToAllConnector()
40
41depressing = dict(U=0.8, tau_rec=100.0, tau_facil=0.0, weight=0.01, delay=0.5)
42facilitating = dict(U=0.04, tau_rec=50.0, tau_facil=200.0, weight=0.01, delay=0.5)
43
44synapse_types = {
45    'depressing, deterministic':   sim.TsodyksMarkramSynapse(**depressing),
46    'depressing, stochastic':      sim.StochasticTsodyksMarkramSynapse(**depressing),
47    'facilitating, deterministic': sim.TsodyksMarkramSynapse(**facilitating),
48    'facilitating, stochastic':    sim.StochasticTsodyksMarkramSynapse(**facilitating),
49}
50
51populations = {}
52projections = {}
53for label in synapse_types:
54    populations[label] = sim.Population(3, sim.IF_cond_exp(e_rev_I=-75, tau_syn_I=[1.2, 6.7, 4.3]), label=label)
55    populations[label].record(['v', 'gsyn_inh'])
56    projections[label] = sim.Projection(spike_source, populations[label], connector,
57                                        receptor_type='inhibitory',
58                                        synapse_type=synapse_types[label])
59
60spike_source.record('spikes')
61
62
63# === Run the simulation =====================================================
64
65sim.run(400.0)
66
67
68# === Save the results, optionally plot a figure =============================
69
70for label, p in populations.items():
71    filename = normalized_filename("Results", "stochastic_tsodyksmarkram_%s" % label,
72                                   "pkl", options.simulator)
73    p.write_data(filename, annotations={'script_name': __file__})
74
75
76if options.plot_figure:
77    from pyNN.utility.plotting import Figure, Panel
78    #figure_filename = normalized_filename("Results", "stochastic_tsodyksmarkram",
79    #                                      "png", options.simulator)
80    figure_filename = "Results/stochastic_tsodyksmarkram_{}.png".format(options.simulator)
81    panels = []
82    for variable in ('gsyn_inh',):  # 'v'):
83        for population in sorted(populations.values(), key=lambda p: p.label):
84            panels.append(
85                Panel(population.get_data().segments[0].filter(name=variable)[0],
86                      data_labels=[population.label], yticks=True),
87            )
88    # add ylabel to top panel in each group
89    panels[0].options.update(ylabel=u'Synaptic conductance (µS)')
90    ##panels[len(synapse_types)].options.update(ylabel='Membrane potential (mV)')
91    # add xticks and xlabel to final panel
92    panels[-1].options.update(xticks=True, xlabel="Time (ms)")
93
94    Figure(*panels,
95           title="Example of facilitating and depressing synapses in deterministic and stochastic versions",
96           annotations="Simulated with %s" % options.simulator.upper()
97    ).save(figure_filename)
98    print(figure_filename)
99
100
101# === Clean up and quit ========================================================
102
103sim.end()
104