Beispiel #1
0
    def initialize(self, sim):
        self._spike_detector = nest.Create("spike_detector", 1, {'label': self._spike_labels, 'withtime': True,
                                                                 'withgid': True, 'to_file': True})

        nest.Connect(sim.net.gid_map.gids, self._spike_detector)
Beispiel #2
0
sd_syn_dict = {"weight": 1.0, "delay": 1.0}
i_neuron_list = []
i_receptor_list = []
var_name_list = []
for i in range(n_test):
    ngpu.Connect([neuron[randrange(n_neurons)]], [sd[i]], sd_conn_dict,
                 sd_syn_dict)
    i_neuron_list.append(sd[i])
    i_receptor_list.append(0)
    var_name_list.append("spike_height")

# create multimeter record of spikes
record = ngpu.CreateRecord("", var_name_list, i_neuron_list, i_receptor_list)

nest_sd = nest.Create('spike_detector', n_test)
nest.Connect(nest_neuron, nest_sd, sd_conn_dict, sd_syn_dict)

nest.Simulate(1000)

data_list = ngpu.GetRecordData(record)
t = [row[0] for row in data_list]
spike_height = [row[1] for row in data_list]

import matplotlib.pyplot as plt

plt.figure(1)
plt.plot(t, spike_height)

row_sum = data_list[0]
for row in data_list[1:len(data_list)]:
    for i in range(len(row_sum)):
 def setupProperty(property):
     bad_syn_spec = self.syn_spec.copy()
     bad_syn_spec.update(property)
     nest.Connect(self.pre_neuron, self.post_neuron,
                  syn_spec=bad_syn_spec)
Beispiel #4
0
                        "to_file": True,
                        "label": "my_multimeter"})

s_ex = nest.Create("spike_generator",
                   params={"spike_times": numpy.array([10.0, 20.0, 50.0])})
s_in = nest.Create("spike_generator",
                   params={"spike_times": numpy.array([15.0, 25.0, 55.0])})

###############################################################################
# Next, We connect the spike generators to the neuron with ``Connect``. Synapse
# specifications can be provided in a dictionary. In this example of a
# conductance-based neuron, the synaptic weight ``weight`` is given in nS.
# Note that the values are  positive for excitatory stimulation and negative
# for inhibitor connections.

nest.Connect(s_ex, n, syn_spec={"weight": 40.0})
nest.Connect(s_in, n, syn_spec={"weight": -20.0})
nest.Connect(m, n)

###############################################################################
# A network simulation with a duration of 100 ms is started with ``Simulate``.

nest.Simulate(100.)

###############################################################################
# After the simulation, the recordings are obtained from the multimeter via the
# key ``events`` of the status dictionary accessed by ``GetStatus``. ``times``
# indicates the recording times stored for each data point. They are recorded
# if the parameter ``withtime`` of the multimeter is set to True which is the
# default case.
Beispiel #5
0
g = nest.Create('spike_generator',
                params={
                    'spike_times':
                    sorted(
                        np.ravel([
                            np.linspace(10, 30, num=15),
                            np.linspace(50, 70, num=15),
                            np.linspace(15, 25, num=15),
                            np.linspace(120, 140, num=15)
                        ]))
                })

nest.Connect(g,
             n,
             params={
                 'weight': 10.0,
                 'delay': 1.0,
                 'receptor_type': s['AMPA']
             },
             model='hill_synapse')
nest.Connect(g,
             n,
             params={
                 'weight': 10.0,
                 'delay': 1.5,
                 'receptor_type': s['GABA_A']
             })
nest.Connect(m, n)

nest.Simulate(1000)

events = nest.GetStatus(m)[0]['events']
Beispiel #6
0
    'multimeter', params={'record_from': ['rate'], 'interval': dt})

###############################################################################
# Connections between ``siegert neurons`` are realized with the synapse model
# ``diffusion_connection``. These two parameters reflect the prefactors in
# front of the rate variable in eq. 27-29 in [1].

###############################################################################
# Connections originating from the driving neuron


syn_dict = {'drift_factor': drift_factor_ext,
            'diffusion_factor': diffusion_factor_ext,
            'synapse_model': 'diffusion_connection'}

nest.Connect(
    siegert_drive, siegert_ex + siegert_in, 'all_to_all', syn_dict)
nest.Connect(multimeter, siegert_ex + siegert_in)

###############################################################################
# Connections originating from the excitatory neuron


syn_dict = {'drift_factor': drift_factor_ex, 'diffusion_factor':
            diffusion_factor_ex, 'synapse_model': 'diffusion_connection'}
nest.Connect(siegert_ex, siegert_ex + siegert_in, 'all_to_all', syn_dict)

###############################################################################
# Connections originating from the inhibitory neuron

syn_dict = {'drift_factor': drift_factor_in, 'diffusion_factor':
            diffusion_factor_in, 'synapse_model': 'diffusion_connection'}
    "delta_tau": h
})

nest.SetDefaults('ginzburg_neuron', {
    'theta': 0.0,
    'tau_m': tau_m,
    'c_1': 0.0,
    'c_2': 2. * m_x,
    'c_3': 1.0
})
n1 = nest.Create("ginzburg_neuron")

nest.SetDefaults("mcculloch_pitts_neuron", {'theta': 0.5, 'tau_m': tau_m})
n2 = nest.Create("mcculloch_pitts_neuron")

nest.Connect(n1, n2, syn_spec={"weight": 1.0})

nest.Connect(n1, csd, syn_spec={"receptor_type": 0})
nest.Connect(n2, csd, syn_spec={"receptor_type": 1})

nest.Simulate(T)

stat = nest.GetStatus(csd)[0]

c = stat["count_covariance"]

m = np.zeros(2, dtype=float)
for i in xrange(2):
    m[i] = c[i][i][int(tau_max / h)] * (h / T)

print 'mean activities =', m
Beispiel #8
0
                         "record_from": ['V_m'],
                          "withgid": True,
                          "to_file": True,
                          "label": "multimeter_Golgi"})
m_Granular = nest.Create("multimeter",
                params = {"interval": 1.0,
                         "record_from": ['V_m'],
                          "withgid": True,
                          "to_file": True,
                          "label": "multimeter_Granular"})
# Connections
nest.CopyModel('static_synapse_hom_w',
        'excitatory', {'weight': J_E, 'delay': delay})
nest.CopyModel('static_synapse_hom_w',
        'inhibitory', {'weight': J_I*3, 'delay': delay})
nest.Connect(mossy,neu_Glomeruli)
nest.Connect(neu_Glomeruli,neu_Granular,{'rule':'fixed_indegree','indegree': C_Glo_Gra},'excitatory')
nest.Connect(neu_Golgi,neu_Granular,{'rule':'fixed_indegree','indegree': C_Gol_Gra},'inhibitory')
nest.Connect(neu_Golgi,neu_Golgi,{'rule':'fixed_indegree','indegree': C_Gol_Gol},'inhibitory')
nest.Connect(neu_Glomeruli,neu_Golgi,{'rule':'fixed_indegree','indegree': C_Glo_Gol},'excitatory')
nest.Connect(neu_Glomeruli,spk_Glomeruli)
nest.Connect(neu_Golgi,spk_Golgi)
nest.Connect(neu_Granular,spk_Granular)
nest.Connect(m_Golgi,neu_Golgi)
nest.Connect(m_Granular,neu_Granular)
nest.Simulate(time_sim)
try: nest.raster_plot.from_device(spk_Glomeruli, hist=True)
except nest.NESTError as err:
  #print err
  try: nest.raster_plot.from_device(spk_Golgi, hist=True)
except nest.NESTError as err:
    def test_wb_cond_multisyn(self):

        if not os.path.exists("target"):
            os.makedirs("target")

        input_path = os.path.join(
            os.path.realpath(
                os.path.join(os.path.dirname(__file__), "../../models/neurons",
                             "wb_cond_multisyn.nestml")))
        target_path = "target"
        module_name = 'nestmlmodule'
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        suffix = '_nestml'

        to_nest(input_path=input_path,
                target_path=target_path,
                logging_level="INFO",
                suffix=suffix,
                module_name=module_name)

        install_nest(target_path, nest_path)

        nest.Install("nestmlmodule")
        model = "wb_cond_multisyn_nestml"

        dt = 0.01
        t_simulation = 1000.0
        nest.SetKernelStatus({"resolution": dt})

        neuron = nest.Create(model)
        parameters = nest.GetDefaults(model)

        neuron.set({'I_e': 75.0})
        multimeter = nest.Create("multimeter")
        multimeter.set({"record_from": ["V_m"], "interval": dt})
        spike_recorder = nest.Create("spike_recorder")
        nest.Connect(multimeter, neuron)
        nest.Connect(neuron, spike_recorder)
        nest.Simulate(t_simulation)

        dmm = nest.GetStatus(multimeter)[0]
        Voltages = dmm["events"]["V_m"]
        tv = dmm["events"]["times"]
        dSD = nest.GetStatus(spike_recorder, keys='events')[0]
        spikes = dSD['senders']
        ts = dSD["times"]

        firing_rate = len(spikes) / t_simulation * 1000
        print("firing rate is ", firing_rate)
        expected_value = np.abs(firing_rate - 50)
        tolerance_value = 5  # Hz

        if TEST_PLOTS:
            fig, ax = plt.subplots(2, figsize=(8, 6), sharex=True)
            ax[0].plot(tv, Voltages, lw=2, color="k")
            ax[1].plot(ts, spikes, 'ko')
            ax[1].set_xlabel("Time [ms]")
            ax[1].set_xlim(0, t_simulation)
            ax[1].set_ylabel("Spikes")
            ax[0].set_ylabel("v [ms]")
            ax[0].set_ylim(-100, 50)

            for i in ts:
                ax[0].axvline(x=i, lw=1., ls="--", color="gray")

            plt.savefig("resources/wb_cond_multisyn.png")
            # plt.show()

        self.assertLessEqual(expected_value, tolerance_value)
# Create and configure the stimulus which is a step current.
dc1 = nest.Create("dc_generator")  # current DC generator
dc2 = nest.Create("dc_generator", 2)
nest.SetStatus(dc1, [{"amplitude": -800.0, "start": 0.0, "stop": 400.0}])
nest.SetStatus(dc2, [{
    "amplitude": 500.0,
    "start": 0.0,
    "stop": 200.0
}, {
    "amplitude": 800.0,
    "start": 500.0,
    "stop": 1000.0
}])

# We connect the DC generator.
nest.Connect(dc1, neuron1, 'all_to_all')
nest.Connect(dc2, neuron2,
             'all_to_all')  # 'all_to_all' is not the necessary phrase here

# And add a voltmeter to record the membrane potentials.
voltmeter = nest.Create("voltmeter")

# We set the voltmeter to record in small intervals of 0.1 ms and connect
# the voltmeter to the neuron.
nest.SetStatus(voltmeter, {
    "withgid": True,
    "withtime": True,
    'interval': 0.1
})  # set lower recording resolution
nest.Connect(voltmeter, neuron1)
nest.Connect(voltmeter, neuron2)
Beispiel #11
0
                              'record_from': ['I'],
                              'interval': 0.1
                          })

# Create generators and connect
ac = nest.Create('ac_generator',
                 1,
                 params={
                     'amplitude': 500.0,
                     'frequency': 50.0,
                     'phase': 45.0,
                     'origin': 5.0,
                     'start': 2.5,
                     'stop': 40.0
                 })
nest.Connect(ac, neuron_ac)
nest.Connect(m_Vm_ac, neuron_ac)
nest.Connect(m_Inj_ac, ac)

dc = nest.Create('dc_generator',
                 1,
                 params={
                     'amplitude': 500.0,
                     'origin': 5.0,
                     'start': 2.5,
                     'stop': 40.0
                 })
nest.Connect(dc, neuron_dc)
nest.Connect(m_Vm_dc, neuron_dc)
nest.Connect(m_Inj_dc, dc)
Beispiel #12
0
# create a ``voltmeter`` for recording.

nest.SetKernelStatus({'resolution': 0.05})

neuron = nest.Create('hh_psc_alpha_gap', 2)

vm = nest.Create('voltmeter', params={'interval': 0.1})

###############################################################################
# Then we set the constant current input, modify the inital membrane
# potential of one of the neurons and connect the neurons to the ``voltmeter``.

neuron.I_e = 100.
neuron[0].V_m = -10.

nest.Connect(vm, neuron, 'all_to_all')

###############################################################################
# In order to create the ``gap_junction`` connection we employ the
# ``all_to_all`` connection rule: Gap junctions are bidirectional connections,
# therefore we need to connect `neuron[0]` to `neuron[1]` and `neuron[1]` to
# `neuron[0]`:

nest.Connect(neuron, neuron,
             {'rule': 'all_to_all', 'allow_autapses': False},
             {'synapse_model': 'gap_junction', 'weight': 0.5})

###############################################################################
# Finally we start the simulation and plot the membrane potentials of both
# neurons.
Beispiel #13
0
 def _spikes(neurons, times):
     """Trigger spike to given neurons at specified times."""
     delay = nest.GetKernelStatus('resolution')
     gen = nest.Create("spike_generator", 1,
                       {"spike_times": [t - delay for t in times]})
     nest.Connect(gen, neurons, syn_spec={"delay": delay})
Beispiel #14
0
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST.  If not, see <http://www.gnu.org/licenses/>.

import nest

# Reset kernel
nest.ResetKernel()

# Create nodes
pg = nest.Create("poisson_generator", params={"rate": 6500.})
neurons = nest.Create("iaf_psc_alpha", 100)
sr = nest.Create("spike_recorder")

# Connect nodes
nest.Connect(pg, neurons, syn_spec={"weight": 10.})
nest.Connect(neurons[::10], sr)

# Simulate
nest.Simulate(1000.)

# Get events
n_events = sr.get("n_events")
Beispiel #15
0
    'N': N[i],
    't_ref': t_ref[i],
    'tau_syn_ex': max([tau_ex, dt]),
    'tau_syn_in': max([tau_in, dt]),
    'E_L': 0.
} for i in range(M)]
nest_pops.set(params)

# connect the populations
g_syn = np.ones_like(J_syn)  # synaptic conductance
g_syn[:, 0] = C_m / tau_ex
g_syn[:, 1] = C_m / tau_in
for i in range(M):
    for j in range(M):
        nest.Connect(nest_pops[j], nest_pops[i],
                     syn_spec={'weight': J_syn[i, j] * g_syn[i, j] * pconn[i, j],
                               'delay': delay[i, j]})

###############################################################################
# To record the instantaneous population rate `Abar(t)` we use a multimeter,
# and to get the population activity `A_N(t)` we use spike recorder:

# monitor the output using a multimeter, this only records with dt_rec!
nest_mm = nest.Create('multimeter')
nest_mm.set(record_from=['n_events', 'mean'], interval=dt_rec)
nest.Connect(nest_mm, nest_pops)

# monitor the output using a spike recorder
nest_sr = []
for i in range(M):
    nest_sr.append(nest.Create('spike_recorder'))
Beispiel #16
0
    neuron = nest.Create("iaf_psc_alpha", params={"V_th": float(10**10)})

    meter = nest.Create("multimeter",
                        params={
                            "withtime": True,
                            "record_from": ["V_m"]
                        })

    detector = nest.Create("spike_detector",
                           params={
                               "withgid": True,
                               "withtime": True
                           })

    nest.Connect(generator, neuron, {"rule": "all_to_all"}, {
        "model": "static_synapse",
        "weight": weight
    })
    nest.Connect(meter, neuron)
    nest.Connect(neuron, detector)

    nest.Simulate(1000.0)

    result_meter = nest.GetStatus(meter)[0]
    result_detector = nest.GetStatus(detector)[0]

    plt.figure()
    plt.plot(result_meter["events"]["times"], result_meter["events"]["V_m"])

    plt.figure()
    plt.plot(result_detector["events"]["times"],
             result_detector["events"]["senders"], '.')
Beispiel #17
0
# a parameter dictionary or a list of parameter dictionaries.

neurons.set(neuron_param)
dc_gen.set(amplitude=I0, start=TIstart, stop=TIend)
volts.set(label="voltmeter", interval=1.)

###############################################################################
# Sixth, the ``dc_generator`` is connected to the first neuron
# (`neurons[0]`) and the `voltmeter` is connected to the second neuron
# (`neurons[1]`). The command `Connect` has different variants. Plain
# ``Connect`` just takes the handles of pre- and postsynaptic nodes and
# uses the default values for weight and delay. Note that the connection
# direction for the ``voltmeter`` reflects the signal flow in the simulation
# kernel, because it observes the neuron instead of receiving events from it.

nest.Connect(dc_gen, neurons[0])
nest.Connect(volts, neurons[1])

###############################################################################
# Seventh, the first neuron (`neurons[0]`) is connected to the second
# neuron (`neurons[1]`).  The command ``CopyModel`` copies the
# ``tsodyks_synapse`` model to the new name ``syn`` with parameters
# ``syn_param``.  The manually defined model ``syn`` is used in the
# connection routine via the ``syn_spec`` parameter.

nest.CopyModel("tsodyks_synapse", "syn", syn_param)
nest.Connect(neurons[0], neurons[1], syn_spec="syn")

###############################################################################
# Finally, we simulate the configuration using the command ``Simulate``,
# where the simulation time `Tend` is passed as the argument.  We plot the
Beispiel #18
0
def simulation(Params):

    #! =================
    #! Import network
    #! =================

    import importlib
    import time

    #network_names = ['network_full_keiko',  'network_full_leonardo']
    network_names = ['network_full_keiko', 'network_full_keiko']

    colors = [[0, 0, 1, .5], [0, 1, 0, .5]]
    fig, axs = plt.subplots(2, 2)
    for (inet, netname) in enumerate(network_names):

        # NEST Kernel and Network settings
        nest.ResetKernel()
        nest.ResetNetwork()
        nest.SetKernelStatus({
            "local_num_threads": Params['threads'],
            'resolution': Params['resolution']
        })
        nest.SetStatus([0], {'print_time': True})

        # initialize random seed
        msd = int(round(time.time() * 1000))
        nest.SetKernelStatus({'grng_seed': msd})
        nest.SetKernelStatus({
            'rng_seeds':
            range(msd + Params['threads'] + 1, msd + 2 * Params['threads'] + 1)
        })

        network = importlib.import_module(netname)
        reload(network)
        models, layers, conns = network.get_Network(Params)
        # import network_full_keiko
        # reload(network_full_keiko)
        # models, layers, conns  = network_full_keiko.get_Network(Params)

        # Create models
        for m in models:
            nest.CopyModel(m[0], m[1], m[2])

        # Create layers, store layer info in Python variable
        for l in layers:
            exec '%s = tp.CreateLayer(l[1])' % l[0]

        # Create connections, need to insert variable names
        for c in conns:
            eval('tp.ConnectLayers(%s,%s,c[2])' % (c[0], c[1]))

        if Params.has_key('show_V4_num_conn_figure'
                          ) and Params['show_V4_num_conn_figure']:

            horizontal_nodes = nest.GetLeaves(Vp_horizontal,
                                              properties={'model': 'L4_exc'},
                                              local_only=True)[0]
            vertical_nodes = nest.GetLeaves(Vp_vertical,
                                            properties={'model': 'L4_exc'},
                                            local_only=True)[0]

            print('Ploting #1')
            n_conns_hor = []
            for (idx, horizontal_node) in enumerate(horizontal_nodes):
                tgt_map = []
                this_conns = nest.GetConnections([horizontal_node],
                                                 horizontal_nodes,
                                                 synapse_model='AMPA_syn')
                tgt_map.extend([conn[1] for conn in this_conns])
                n_conns_hor.append(len(tgt_map))

            plt.axes(axs[0, 0])
            plt.hist(n_conns_hor,
                     range(0, max(n_conns_hor + [30])),
                     fc=colors[inet])
            plt.title('# of connections Vp(h) L4pyr -> Vp(h) L4Pyr')

            print('Ploting #2')
            n_conns_hor = []
            for (idx, horizontal_node) in enumerate(horizontal_nodes):
                tgt_map = []
                this_conns = nest.GetConnections([horizontal_node],
                                                 vertical_nodes,
                                                 synapse_model='AMPA_syn')
                tgt_map.extend([conn[1] for conn in this_conns])
                n_conns_hor.append(len(tgt_map))

                # nest.DisconnectOneToOne(tp_node, tgt_map[0], {"synapse_model": "AMPA_syn"})
                #nest.Disconnect([tp_node], tgt_map, 'one_to_one', {"synapse_model": "AMPA_syn"})

            plt.axes(axs[0, 1])
            plt.hist(n_conns_hor,
                     range(0, max(n_conns_hor + [30])),
                     fc=colors[inet])
            plt.title('# of connections Vp(h) L4pyr -> Vp(v) L4Pyr')

            print('Ploting #3')
            n_conns_ver = []
            for (idx, vertical_node) in enumerate(vertical_nodes):
                tgt_map = []
                this_conns = nest.GetConnections([vertical_node],
                                                 vertical_nodes,
                                                 synapse_model='AMPA_syn')
                tgt_map.extend([conn[1] for conn in this_conns])
                n_conns_ver.append(len(tgt_map))

            plt.axes(axs[1, 1])
            plt.hist(n_conns_ver,
                     range(0, max(n_conns_ver + [30])),
                     fc=colors[inet])
            plt.title('# of connections Vp(v) L4pyr -> Vp(v) L4Pyr')

            print('Ploting #4')
            n_conns_ver = []
            for (idx, vertical_node) in enumerate(vertical_nodes):
                tgt_map = []
                this_conns = nest.GetConnections([vertical_node],
                                                 horizontal_nodes,
                                                 synapse_model='AMPA_syn')
                tgt_map.extend([conn[1] for conn in this_conns])
                n_conns_ver.append(len(tgt_map))

            plt.axes(axs[1, 0])
            plt.hist(n_conns_ver,
                     range(0, max(n_conns_ver + [30])),
                     fc=colors[inet])
            plt.title('# of connections Vp(v) L4pyr -> Vp(h) L4Pyr')

    plt.show()

    # Check connections

    # Connections from Retina to TpRelay
    # tp.PlotTargets(tp.FindCenterElement(Retina_layer), Tp_layer)

    if Params.has_key('show_V4_connectivity_figure'
                      ) and Params['show_V4_connectivity_figure']:

        Vp_hor_gids = tp.GetElement(Vp_horizontal, [0, 0])
        n_Vp_hor = len(Vp_hor_gids)

        f = []
        for idx in range(n_Vp_hor):
            f.append(plt.figure())

        positions = range(0, 41, 10)
        positions[-1] -= 1
        for xi in range(len(positions)):
            for yi in range(len(positions)):
                print("Position [%d,%d] : %d" % (xi, yi, yi *
                                                 (len(positions)) + xi + 1))
                x = positions[xi]
                y = positions[yi]
                Vp_hor_gids = tp.GetElement(Vp_horizontal, [x, y])
                Vp_hor_status = nest.GetStatus(Vp_hor_gids)
                for (idx, n) in enumerate(Vp_hor_status):
                    if n['Tau_theta'] == 2.0:
                        print idx
                        try:
                            f[idx].add_subplot(len(positions), len(positions),
                                               yi * (len(positions)) + xi + 1)
                            tp.PlotTargets([Vp_hor_gids[idx]], Vp_horizontal,
                                           'L4_exc', 'AMPA_syn', f[idx])
                        except:
                            print('%i bad' % Vp_hor_gids[idx])
        plt.show()

    # Connections from TpRelay to L4pyr in Vp (horizontally tuned)
    #topo.PlotTargets(topo.FindCenterElement(Tp), Vp_h, 'L4pyr', 'AMPA')
    #pylab.title('Connections TpRelay -> Vp(h) L4pyr')
    #pylab.show()

    # Connections from TpRelay to L4pyr in Vp (vertically tuned)
    #topo.PlotTargets(topo.FindCenterElement(Tp), Vp_v, 'L4pyr', 'AMPA')
    #pylab.title('Connections TpRelay -> Vp(v) L4pyr')
    #pylab.show()
    '''
    # pablo
    # Create vertical grating
    for n in nest.GetLeaves(Retina_layer)[0]:
            retina_0 = (nest.GetLeaves(Retina_layer)[0])[0]
            col = (n-retina_0)/Params['Np']

            cells_per_degree = Params['Np']/Params['visSize']
            cells_per_cycle = cells_per_degree/Params['spatial_frequency']

            nest.SetStatus([n], { "phase": col * 360/(cells_per_cycle-1) })
    '''
    ### keiko
    if Params['lambda_dg'] >= 0:
        [
            nest.SetStatus(
                [n], {
                    "phase":
                    phaseInit(
                        tp.GetPosition([n])[0], Params["lambda_dg"],
                        Params["phi_dg"])
                }) for n in nest.GetLeaves(Retina_layer)[0]
        ]
    else:
        # Leonardo: Random retina input
        [
            nest.SetStatus(
                [n], {
                    "phase":
                    phaseInit(
                        tp.GetPosition([n])[0], np.pi * np.random.rand(),
                        np.pi * np.random.rand())
                }) for n in nest.GetLeaves(Retina_layer)[0]
        ]

    # --------------------------------------------------------------------#
    # ---------- SET IB NEURONS ----------------------------------------- #
    # --------------------------------------------------------------------#

    # 30% of Cortex L56 excitatory neurons are intrinsically bursting(IB) neuron.
    # That is achieved by setting pacemaker current I_h.
    # So select 30% of L56_exc neuron, and change h_g_peak from 0.0 to 1.0.
    # (Other cortical neuron do not have I_h, thus h_g_peak=0.0)

    L56_vertical_idx = [
        nd for nd in nest.GetLeaves(Vp_vertical)[0]
        if nest.GetStatus([nd], 'model')[0] == 'L56_exc'
    ]
    L56_horizontal_idx = [
        nd for nd in nest.GetLeaves(Vp_horizontal)[0]
        if nest.GetStatus([nd], 'model')[0] == 'L56_exc'
    ]

    num_neuron = len(L56_vertical_idx)
    num_ib = int(num_neuron * 0.3)

    ridx_vertical = np.random.randint(num_neuron, size=(1, num_ib))[0]
    ridx_horizontal = np.random.randint(num_neuron, size=(1, num_ib))[0]

    for i in range(1, num_ib, 1):
        nest.SetStatus([L56_vertical_idx[ridx_vertical[i]]], {'h_g_peak': 1.0})
        nest.SetStatus([L56_horizontal_idx[ridx_horizontal[i]]],
                       {'h_g_peak': 1.0})

    # initiate network activity
    #nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'rate': Params['ret_rate']})
    nest.SetStatus(
        nest.GetLeaves(Retina_layer)[0], {'rate': Params['ret_rate']})
    nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'amplitude': 0.0})
    nest.Simulate(500.0)

    #! =================
    #! Recording devices
    #! =================

    nest.CopyModel(
        'multimeter',
        'RecordingNode',
        params={
            'interval':
            Params['resolution'],
            #'record_from': ['V_m'],
            'record_from': [
                'V_m', 'I_syn_AMPA', 'I_syn_NMDA', 'I_syn_GABA_A',
                'I_syn_GABA_B', 'g_AMPA', 'g_NMDA', 'g_GABAA', 'g_GABAB',
                'I_NaP', 'I_KNa', 'I_T', 'I_h'
            ],
            'record_to': ['memory'],
            'withgid':
            True,
            'withtime':
            True
        })

    recorders = []
    '''
    for population, model in [(Retina_layer, 'Retina'),
                              (Tp_layer  , 'Tp_exc'),
                              (Tp_layer  , 'Tp_inh'),
                              (Rp_layer  , 'Rp'),
                              (Vp_vertical, 'L23_exc'),
                              (Vp_horizontal, 'L23_exc'),
                              (Vp_vertical, 'L23_inh'),
                              (Vp_horizontal, 'L23_inh'),
                              (Vp_vertical, 'L4_exc'),
                              (Vp_horizontal, 'L4_exc'),
                              (Vp_vertical, 'L4_inh'),
                              (Vp_horizontal, 'L4_inh'),
                              (Vp_vertical, 'L56_exc'),
                              (Vp_horizontal, 'L56_exc'),
                              (Vp_vertical, 'L56_inh'),
                              (Vp_horizontal, 'L56_inh'),
                              (Vs_vertical, 'L23_exc'),
                              (Vs_horizontal, 'L23_exc'),
                              (Vs_vertical, 'L23_inh'),
                              (Vs_horizontal, 'L23_inh'),
                              (Vs_vertical, 'L4_exc'),
                              (Vs_horizontal, 'L4_exc'),
                              (Vs_vertical, 'L4_inh'),
                              (Vs_horizontal, 'L4_inh'),
                              (Vs_vertical, 'L56_exc'),
                              (Vs_horizontal, 'L56_exc'),
                              (Vs_vertical, 'L56_inh'),
                              (Vs_horizontal, 'L56_inh')]:
    '''
    for population, model in [(Retina_layer, 'Retina'), (Tp_layer, 'Tp_exc'),
                              (Tp_layer, 'Tp_inh'), (Vp_vertical, 'L4_exc'),
                              (Vp_vertical, 'L4_inh'),
                              (Vp_horizontal, 'L4_exc'),
                              (Vp_vertical, 'L23_exc'),
                              (Vp_horizontal, 'L23_exc'),
                              (Vp_vertical, 'L56_exc'), (Rp_layer, 'Rp')]:
        rec = nest.Create('RecordingNode')
        recorders.append([rec, population, model])
        if (model == 'Retina'):
            nest.SetStatus(rec, {'record_from': ['rate']})
        tgts = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]
        nest.Connect(rec, tgts)

    #! =================
    #! Spike detector
    #! =================
    detectors = []
    '''
    for population, model in [(Retina_layer, 'Retina'),
                              (Tp_layer  , 'Tp_exc'),
                              (Tp_layer  , 'Tp_inh'),
                              (Rp_layer  , 'Rp'),
                              (Vp_vertical, 'L23_exc'),
                              (Vp_horizontal, 'L23_exc'),
                              (Vp_vertical, 'L23_inh'),
                              (Vp_horizontal, 'L23_inh'),
                              (Vp_vertical, 'L4_exc'),
                              (Vp_horizontal, 'L4_exc'),
                              (Vp_vertical, 'L4_inh'),
                              (Vp_horizontal, 'L4_inh'),
                              (Vp_vertical, 'L56_exc'),
                              (Vp_horizontal, 'L56_exc'),
                              (Vp_vertical, 'L56_inh'),
                              (Vp_horizontal, 'L56_inh'),
                              (Vs_vertical, 'L23_exc'),
                              (Vs_horizontal, 'L23_exc'),
                              (Vs_vertical, 'L23_inh'),
                              (Vs_horizontal, 'L23_inh'),
                              (Vs_vertical, 'L4_exc'),
                              (Vs_horizontal, 'L4_exc'),
                              (Vs_vertical, 'L4_inh'),
                              (Vs_horizontal, 'L4_inh'),
                              (Vs_vertical, 'L56_exc'),
                              (Vs_horizontal, 'L56_exc'),
                              (Vs_vertical, 'L56_inh'),
                              (Vs_horizontal, 'L56_inh')]:
        '''

    for population, model in [(Retina_layer, 'Retina'), (Tp_layer, 'Tp_exc'),
                              (Tp_layer, 'Tp_inh'), (Vp_vertical, 'L4_exc'),
                              (Vp_horizontal, 'L4_exc')]:
        rec = nest.Create('spike_detector',
                          params={
                              "withgid": True,
                              "withtime": True
                          })
        #rec = nest.Create('spike_detector')
        detectors.append([rec, population, model])
        tgts = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]
        if model == 'Retina':
            for t in tgts:
                try:
                    nest.Connect([t], rec)
                    print('connected %d' % t)
                except:
                    print('%d did not work' % t)
        else:
            nest.Connect(tgts, rec)

    #! ====================
    #! Simulation
    #! ====================
    '''
    # change gKL to 0.8 in all populations (necessary to get a little stronger evoked response)
    for l in layers:
            sim_elements = l[1]['elements']
            for m in np.arange(0,np.size(sim_elements),1):

                    if(np.size(sim_elements)==1):
                        sim_model = sim_elements
                    else:
                        sim_model = sim_elements[m]

                    exec("la = %s" % l[0])
                    pop = [nd for nd in nest.GetLeaves(la)[0] if nest.GetStatus([nd], 'model')[0]==sim_model]
                    if (l[0]!='Retina_layer'):
                            for cell in pop:
                                    nest.SetStatus([cell], {'g_KL':0.8})
    '''
    # Simulate
    for t in Params['intervals']:

        #if (t == 250.0):  # Stimulus ON
        #    # if (t == 1500.0):  # Stimulus ON
        #    nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'amplitude': 45.0})
        #else:  # Stimulus OFF
        #    nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'amplitude': 0.0})

        if Params['input_flag'] == True:
            nest.SetStatus(
                nest.GetLeaves(Retina_layer)[0],
                {'amplitude': Params['ret_rate']})
        else:
            nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'amplitude': 0.0})

        nest.Simulate(t)

    #! ====================
    #! Plot Results
    #! ====================

    if Params.has_key('show_main_figure') and Params['show_main_figure']:
        print "plotting..."

        rows = 9
        cols = 2

        fig = plt.figure()
        fig.subplots_adjust(hspace=0.4)

        # Plot A: membrane potential rasters

        recorded_models = [(Retina_layer, 'Retina'), (Vp_vertical, 'L23_exc'),
                           (Vp_vertical, 'L4_exc'), (Vp_vertical, 'L56_exc'),
                           (Rp_layer, 'Rp'), (Tp_layer, 'Tp_exc')]

        #plotting.potential_raster(fig,recorders,recorded_models,0,Params['Np'],np.sum(Params['intervals']),Params['resolution'],rows,cols,0)
        plotting.potential_raster(fig, recorders, recorded_models, 0,
                                  Params['Np'], np.sum(Params['intervals']),
                                  Params['resolution'], rows, cols, 0)
        #starting_neuron = 800+1
        #plotting.potential_raster(fig,recorders,recorded_models,starting_neuron,Params['Np'],np.sum(Params['intervals']),Params['resolution'],rows,cols,0)

        plt.title('Evoked')

        # Plot B: individual intracellular traces

        recorded_models = [(Vp_vertical, 'L4_exc'), (Vp_vertical, 'L4_inh')]

        #plotting.intracellular_potentials(fig, recorders, recorded_models, 21, rows, cols, 6) #original
        # keiko
        total_time = 0.0
        for t in Params['intervals']:
            total_time += t

        #draw_neuron = (Params['Np']*Params['Np']/2)
        #plotting.intracellular_potentials(fig, recorders, recorded_models, draw_neuron, rows, cols, 6, total_time)
        plotting.intracellular_potentials(fig, recorders, recorded_models, 21,
                                          rows, cols, 6, total_time)
        #plotting.intracellular_potentials(fig, recorders, recorded_models, 820, rows, cols, 6, total_time)

        # Plot C: topographical activity of the vertical and horizontal layers

        recorded_models = [(Vp_vertical, 'L23_exc')]

        labels = ["Vertical"]
        start = 130.0
        stop = 140.0
        #start = 650.0
        #stop = 660.0
        plotting.topographic_representation(fig, recorders, recorded_models,
                                            labels, Params['Np'],
                                            np.sum(Params['intervals']),
                                            Params['resolution'], rows, cols,
                                            start, stop, 8, 0)

        recorded_models = [(Vp_horizontal, 'L23_exc')]

        labels = ["Horizontal"]
        start = 130.0
        stop = 140.0
        #start = 650.0
        #stop = 660.0

        plotting.topographic_representation(fig, recorders, recorded_models,
                                            labels, Params['Np'],
                                            np.sum(Params['intervals']),
                                            Params['resolution'], rows, cols,
                                            start, stop, 8, 1)

        plt.show()

    # Plot D: movie

    #labels = ["Evoked_Vp_L23_Vertical","Evoked_Vp_L23_Horizontal"]
    #recorded_models = [(Vp_vertical,'L23_exc'),(Vp_horizontal,'L23_exc')]
    #plotting.makeMovie(fig,recorders,recorded_models,labels,Params['Np'],np.sum(Params['intervals']),Params['resolution'])

    #! ====================
    #! Save Results
    #! ====================

    print('save recorders data')
    # Set folder
    #rootdir = '/home/kfujii2/newNEST2/ht_model_pablo_based/data/'
    #expdir = 'random/'
    # expdir = 'random_full/'
    # expdir = 'structured_full/'
    # data_folder = rootdir + expdir
    data_folder = Params['data_folder']

    if not os.path.isdir(data_folder):
        os.makedirs(data_folder)

    # To save spike data, set pairs of population id and its name
    population_name = [{
        'population': Retina_layer,
        'name': 'Retina'
    }, {
        'population': Vp_vertical,
        'name': 'Vp_v'
    }, {
        'population': Vp_horizontal,
        'name': 'Vp_h'
    }, {
        'population': Rp_layer,
        'name': 'Rp'
    }, {
        'population': Tp_layer,
        'name': 'Tp'
    }, {
        'population': Vs_vertical,
        'name': 'Vs_v'
    }, {
        'population': Vs_horizontal,
        'name': 'Vs_h'
    }]

    for rec, population, model in recorders:

        # Get name of population
        for p in range(0, len(population_name), 1):
            if population_name[p]['population'] == population:
                p_name = population_name[p]['name']

        data = nest.GetStatus(rec)[0]['events']

        if model == 'Retina':
            scipy.io.savemat(data_folder + '/recorder_' + p_name + '_' +
                             model + '.mat',
                             mdict={
                                 'senders': data['senders'],
                                 'rate': data['rate']
                             })
        else:
            scipy.io.savemat(data_folder + '/recorder_' + p_name + '_' +
                             model + '.mat',
                             mdict={
                                 'senders': data['senders'],
                                 'V_m': data['V_m'],
                                 'I_syn_AMPA': data['I_syn_AMPA'],
                                 'I_syn_NMDA': data['I_syn_NMDA'],
                                 'I_syn_GABA_A': data['I_syn_GABA_A'],
                                 'I_syn_GABA_B': data['I_syn_GABA_B'],
                                 'g_AMPA': data['g_AMPA'],
                                 'g_NMDA': data['g_NMDA'],
                                 'g_GABAA': data['g_GABAA'],
                                 'g_GABAB': data['g_GABAB']
                             })

    print('save raster images')
    plt.close()
    for rec, population, model in detectors:
        spikes = nest.GetStatus(rec, 'events')[0]

        # Get name of population
        for p in range(0, len(population_name), 1):
            if population_name[p]['population'] == population:
                p_name = population_name[p]['name']

        if len(nest.GetStatus(rec)[0]['events']['senders']) > 3:
            raster = raster_plot.from_device(rec, hist=True)
            pylab.title(p_name + '_' + model)
            f = raster[0].figure
            f.set_size_inches(15, 9)
            f.savefig(data_folder + 'spikes_' + p_name + '_' + model + '.png',
                      dpi=100)
            plt.close()

            # Set filename and save spike data
            filename = data_folder + 'spike_' + p_name + '_' + model + '.pickle'
            pickle.dump(spikes, open(filename, 'w'))
            scipy.io.savemat(data_folder + '/spike_' + p_name + '_' + model +
                             '.mat',
                             mdict={
                                 'senders': spikes['senders'],
                                 'times': spikes['times']
                             })
            '''
            filename_AMPA = data_folder + 'connection_' + p_name + '_AMPA_syn' + '.dat'
            filename_NMDA = data_folder + 'connection_' + p_name + '_NMDA_syn' + '.dat'
            filename_GABAA = data_folder + 'connection_' + p_name + '_GABA_A_syn' + '.dat'
            filename_GABAB = data_folder + 'connection_' + p_name + '_GABA_B_syn' + '.dat'
            tp.DumpLayerConnections(population, 'AMPA_syn', filename_AMPA)
            tp.DumpLayerConnections(population, 'NMDA_syn', filename_NMDA)
            tp.DumpLayerConnections(population, 'GABA_A_syn', filename_GABAA)
            tp.DumpLayerConnections(population, 'GABA_B_syn', filename_GABAB)
            '''
    '''
    for p in range(0, len(population_name), 1):

        population = population_name[p]['population']
        p_name = population_name[p]['name']
        filename_nodes = data_folder + '/gid_' + p_name + '.dat'

        tp.DumpLayerNodes(population, filename_nodes)
    '''

    network_script = Params['network'] + '.py'
    shutil.copy2(network_script, Params['data_folder'] + network_script)

    print('end')
Beispiel #19
0
vol2 = nest.Create('volume_transmitter')
pool1 = nest.Create('iaf_psc_exp', 100)
pool2 = nest.Create('iaf_psc_exp', 100)

if active_pool == 1:
    neuro_mod1 = nest.Create('poisson_generator', 1, {'rate': 950.0})
    neuro_mod2 = nest.Create('poisson_generator', 1, {'rate': 0.0})
    ap = '1'
else:
    neuro_mod1 = nest.Create('poisson_generator', 1, {'rate': 0.0})
    neuro_mod2 = nest.Create('poisson_generator', 1, {'rate': 950.0})
    ap = '2'

conn_dict = {'rule': 'all_to_all'}
syn_dict = {'weight': 100., 'delay': 1.0}  #50,
nest.Connect(neuro_mod1, pool1, conn_spec=conn_dict, syn_spec=syn_dict)
nest.Connect(neuro_mod2, pool2, conn_spec=conn_dict, syn_spec=syn_dict)

nest.Connect(pool1, vol1)
nest.Connect(pool2, vol2)

print vol1, vol2
nest.CopyModel('stdp_dopamine_synapse', 'IC1', {
    "receptor_type": 1,
    "vt": vol1[0]
})
nest.CopyModel('stdp_dopamine_synapse', 'IC2', {
    "receptor_type": 1,
    "vt": vol2[0]
})
def synchrony_influence(weight=10., resolution=0.1, dt=20):
    nest.ResetKernel()
    print(resolution)
    nest.SetKernelStatus({'resolution': resolution, 'print_time': True})
    print(nest.GetStatus([0]))
    neuron_model = 'izhikevich'
    nest.CopyModel(
        neuron_model, 'inh_Izhi', {
            'consistent_integration': False,
            'U_m': -0.2 * 65.0,
            'b': 0.2,
            'c': -65.0,
            'a': 0.1,
            'd': 2.0,
            'tau_minus': 20.
        })
    nest.CopyModel(
        neuron_model, 'ex_Izhi', {
            'consistent_integration': False,
            'U_m': -0.2 * 65.0,
            'b': 0.2,
            'c': -65.0,
            'a': 0.02,
            'd': 8.0,
            'tau_minus': 20.
        })

    nest.CopyModel("static_synapse", "EX", {'weight': weight, 'delay': 1.0})

    ex_neuron = nest.Create('ex_Izhi', dt)
    spike_gen = nest.Create('spike_generator', dt)
    for i in range(dt):
        nest.SetStatus([spike_gen[i]],
                       {'spike_times': [250., 250 + i * resolution]})

    mm = nest.Create("multimeter",
                     params={
                         'record_from': ['V_m'],
                         'interval': resolution,
                         'withgid': True,
                         'withtime': True,
                         'to_memory': True,
                         'to_file': False,
                         'label': 'mem_pot'
                     })

    spk_det = nest.Create("spike_detector",
                          params={
                              'to_memory': True,
                              'to_file': False,
                              'label': 'spk_det'
                          })

    nest.SetStatus(ex_neuron, 'V_m', -70.)
    nest.SetStatus(ex_neuron, 'U_m', -70. * .2)

    nest.Connect(mm, ex_neuron, 'all_to_all')
    nest.Connect(spike_gen, ex_neuron, 'one_to_one', 'EX')
    nest.Connect(ex_neuron, spk_det, 'all_to_all', 'EX')

    nest.Simulate(500.)
    return nest.GetStatus(mm)[0]['events'], nest.GetStatus(
        spk_det)[0]['events']
for (s_t_pre, s_t_post) in zip(spike_times_pre, spike_times_post):
    nest.ResetKernel()
    nest.SetKernelStatus({"resolution": resolution})

    # Create one neuron
    nrn = nest.Create("aeif_psc_delta_clopath", 1, nrn_params)

    # We need a parrot neuron since spike generators can only
    # be connected with static connections
    prrt_nrn = nest.Create("parrot_neuron", 1)

    # Create and connect spike generators
    spike_gen_pre = nest.Create("spike_generator", 1, {"spike_times": s_t_pre})

    nest.Connect(spike_gen_pre, prrt_nrn, syn_spec={"delay": resolution})

    spike_gen_post = nest.Create("spike_generator", 1,
                                 {"spike_times": s_t_post})

    nest.Connect(spike_gen_post,
                 nrn,
                 syn_spec={
                     "delay": resolution,
                     "weight": 80.0
                 })

    # Create weight recorder
    wr = nest.Create('weight_recorder', 1)

    # Create Clopath connection with weight recorder
nest.ResetKernel()
nest.SetKernelStatus({'resolution': 1.0})

neuron_low_res = nest.Create("izhikevich", 1, neuron_params_low_res)
neuron_high_res = nest.Create("izhikevich", 1, neuron_params_high_res)

nest.SetStatus(neuron_low_res, {"I_e": 4.})
nest.SetStatus(neuron_high_res, {"I_e": 4.})

mm = nest.Create('multimeter', 1, {
    'record_from': ['V_m', 'U_m'],
    'interval': 1.0
})
sd = nest.Create('spike_detector', 1)

nest.Connect(neuron_low_res, sd)
nest.Connect(neuron_high_res, sd)

nest.Connect(mm, neuron_low_res + neuron_high_res)

nest.Simulate(1000.)

ev = nest.GetStatus(sd, 'events')[0]

neuron0_mask = np.where(ev['senders'] == 1)[0]
neuron1_mask = np.where(ev['senders'] == 2)[0]

neuron0_times = ev['times'][neuron0_mask]
neuron1_times = ev['times'][neuron1_mask]

isi0 = np.diff(neuron0_times)
# current input to the neuron. We also want to record the global id of
# the observed nodes and set the withgid flag of the voltmeter to
# True.

nest.SetStatus(neuron, "I_e", 376.0)
nest.SetStatus(voltmeter, [{"withgid": True}])

# Fourth, the neuron is connected to the voltmeter. The command
# `Connect()` has different variants. Plain `Connect()` just takes the
# handles of pre- and post-synaptic nodes and uses the default values
# for weight and delay. `ConvergentConnect()` takes four arguments:
# lists of pre- and post-synaptic nodes and lists of weights and
# delays. Note that the connection direction for the voltmeter is
# reversed compared to the spike detector, because it observes the
# neuron instead of receiving events from it. Thus, `Connect()`
# reflects the direction of signal flow in the simulation kernel
# rather than the physical process of inserting an electrode into the
# neuron. The latter semantics is presently not available in NEST.

nest.Connect(voltmeter, neuron)

# Now we simulate the network using `Simulate()`, which takes the
# desired simulation time in milliseconds.

nest.Simulate(1000.0)

# Finally, we plot the neuron's membrane potential as a function of
# time.

nest.voltage_trace.from_device(voltmeter)
Beispiel #24
0
    def run_synapse_test(
            self,
            neuron_model_name,
            ref_neuron_model_name,
            synapse_model_name,
            ref_synapse_model_name,
            resolution=1.,  # [ms]
            delay=1.,  # [ms]
            sim_time=None,  # if None, computed from pre and post spike times
            pre_spike_times=None,
            post_spike_times=None,
            fname_snip=""):

        if pre_spike_times is None:
            pre_spike_times = []

        if post_spike_times is None:
            post_spike_times = []

        if sim_time is None:
            sim_time = max(np.amax(pre_spike_times),
                           np.amax(post_spike_times)) + 5 * delay

        nest.set_verbosity("M_ALL")
        nest.ResetKernel()
        nest.Install("nestml_jit_module")
        nest.Install("nestml_non_jit_module")

        print("Pre spike times: " + str(pre_spike_times))
        print("Post spike times: " + str(post_spike_times))

        nest.set_verbosity("M_WARNING")

        nest.ResetKernel()
        nest.SetKernelStatus({'resolution': resolution})

        wr = nest.Create('weight_recorder')
        wr_ref = nest.Create('weight_recorder')
        nest.CopyModel(
            synapse_model_name, "stdp_nestml_rec", {
                "weight_recorder": wr[0],
                "w": 1.,
                "the_delay": 1.,
                "receptor_type": 0,
                "lambda": .001
            })
        if sim_ref:
            nest.CopyModel(
                ref_synapse_model_name, "stdp_ref_rec", {
                    "weight_recorder": wr_ref[0],
                    "weight": 1.,
                    "delay": 1.,
                    "receptor_type": 0,
                    "lambda": .001
                })

        # create spike_generators with these times
        pre_sg = nest.Create("spike_generator",
                             params={"spike_times": pre_spike_times})
        post_sg = nest.Create("spike_generator",
                              params={
                                  "spike_times": post_spike_times,
                                  'allow_offgrid_times': True
                              })

        # create parrot neurons and connect spike_generators
        if sim_mdl:
            pre_neuron = nest.Create("parrot_neuron")
            post_neuron = nest.Create(neuron_model_name)

        if sim_ref:
            pre_neuron_ref = nest.Create("parrot_neuron")
            post_neuron_ref = nest.Create(ref_neuron_model_name)

        if sim_mdl:
            spikedet_pre = nest.Create("spike_recorder")
            spikedet_post = nest.Create("spike_recorder")
            mm = nest.Create(
                "multimeter",
                params={"record_from": ["V_m", self.post_trace_var]})
        if sim_ref:
            spikedet_pre_ref = nest.Create("spike_recorder")
            spikedet_post_ref = nest.Create("spike_recorder")
            mm_ref = nest.Create("multimeter", params={"record_from": ["V_m"]})

        if sim_mdl:
            nest.Connect(pre_sg,
                         pre_neuron,
                         "one_to_one",
                         syn_spec={"delay": 1.})
            nest.Connect(post_sg,
                         post_neuron,
                         "one_to_one",
                         syn_spec={
                             "delay": 1.,
                             "weight": 9999.
                         })
            nest.Connect(pre_neuron,
                         post_neuron,
                         "all_to_all",
                         syn_spec={'synapse_model': 'stdp_nestml_rec'})
            nest.Connect(mm, post_neuron)
            nest.Connect(pre_neuron, spikedet_pre)
            nest.Connect(post_neuron, spikedet_post)
        if sim_ref:
            nest.Connect(pre_sg,
                         pre_neuron_ref,
                         "one_to_one",
                         syn_spec={"delay": 1.})
            nest.Connect(post_sg,
                         post_neuron_ref,
                         "one_to_one",
                         syn_spec={
                             "delay": 1.,
                             "weight": 9999.
                         })
            nest.Connect(pre_neuron_ref,
                         post_neuron_ref,
                         "all_to_all",
                         syn_spec={'synapse_model': ref_synapse_model_name})
            nest.Connect(mm_ref, post_neuron_ref)
            nest.Connect(pre_neuron_ref, spikedet_pre_ref)
            nest.Connect(post_neuron_ref, spikedet_post_ref)

        # get STDP synapse and weight before protocol
        if sim_mdl:
            syn = nest.GetConnections(source=pre_neuron,
                                      synapse_model="stdp_nestml_rec")
        if sim_ref:
            syn_ref = nest.GetConnections(source=pre_neuron_ref,
                                          synapse_model=ref_synapse_model_name)

        t = 0.
        t_hist = []
        if sim_mdl:
            w_hist = []
        if sim_ref:
            w_hist_ref = []
        state = 0
        while t <= sim_time:
            if t > sim_time / 6. and state == 0:
                post_neuron.set({"I_dend": 1.})
                state = 1
            if t > 2 * sim_time / 6 and state == 1:
                post_neuron.set({"I_dend": 1.})
            if t > 2 * sim_time / 3. and state == 1:
                state = 2
            nest.Simulate(resolution)
            t += resolution
            t_hist.append(t)
            if sim_ref:
                w_hist_ref.append(nest.GetStatus(syn_ref)[0]['weight'])
            if sim_mdl:
                w_hist.append(nest.GetStatus(syn)[0]['w'])

        third_factor_trace = nest.GetStatus(mm,
                                            "events")[0][self.post_trace_var]
        timevec = nest.GetStatus(mm, "events")[0]["times"]

        if TEST_PLOTS:
            fig, ax = plt.subplots(nrows=2)
            ax1, ax2 = ax

            if sim_mdl:
                V_m = nest.GetStatus(mm, "events")[0]["V_m"]
                ax2.plot(timevec, third_factor_trace, label="I_dend_post")
                ax1.plot(timevec, V_m, alpha=.7, linestyle=":")
            if sim_ref:
                pre_ref_spike_times_ = nest.GetStatus(spikedet_pre_ref,
                                                      "events")[0]["times"]
                timevec_ = nest.GetStatus(mm_ref, "events")[0]["times"]
                V_m_ = nest.GetStatus(mm_ref, "events")[0]["V_m"]
                ax1.plot(timevec_, V_m_, label="nest ref", alpha=.7)
            ax1.set_ylabel("V_m")

            for _ax in ax:
                _ax.grid(which="major", axis="both")
                _ax.grid(which="minor", axis="x", linestyle=":", alpha=.4)
                # _ax.minorticks_on()
                _ax.set_xlim(0., sim_time)
                _ax.legend()
            fig.savefig("/tmp/stdp_triplet_synapse_test" + fname_snip +
                        "_V_m.png",
                        dpi=300)

        if TEST_PLOTS:
            fig, ax = plt.subplots(nrows=5)
            ax1, ax2, ax3, ax4, ax5 = ax

            if sim_mdl:
                pre_spike_times_ = nest.GetStatus(spikedet_pre,
                                                  "events")[0]["times"]
                print("Actual pre spike times: " + str(pre_spike_times_))
            if sim_ref:
                pre_ref_spike_times_ = nest.GetStatus(spikedet_pre_ref,
                                                      "events")[0]["times"]
                print("Actual pre ref spike times: " +
                      str(pre_ref_spike_times_))

            if sim_mdl:
                n_spikes = len(pre_spike_times_)
                for i in range(n_spikes):
                    ax1.plot(2 * [pre_spike_times_[i] + delay], [0, 1],
                             linewidth=2,
                             color="blue",
                             alpha=.4)

            if sim_mdl:
                post_spike_times_ = nest.GetStatus(spikedet_post,
                                                   "events")[0]["times"]
                print("Actual post spike times: " + str(post_spike_times_))
            if sim_ref:
                post_ref_spike_times_ = nest.GetStatus(spikedet_post_ref,
                                                       "events")[0]["times"]
                print("Actual post ref spike times: " +
                      str(post_ref_spike_times_))

            if sim_ref:
                n_spikes = len(pre_ref_spike_times_)
                for i in range(n_spikes):
                    ax1.plot(2 * [pre_ref_spike_times_[i] + delay], [0, 1],
                             linewidth=2,
                             color="cyan",
                             alpha=.4)
            ax1.set_ylabel("Pre spikes")

            if sim_mdl:
                n_spikes = len(post_spike_times_)
                for i in range(n_spikes):
                    if i == 0:
                        _lbl = "nestml"
                    else:
                        _lbl = None
                    ax[-4].plot(2 * [post_spike_times_[i]], [0, 1],
                                linewidth=2,
                                color="black",
                                alpha=.4,
                                label=_lbl)
            if sim_ref:
                n_spikes = len(post_ref_spike_times_)
                for i in range(n_spikes):
                    if i == 0:
                        _lbl = "nest ref"
                    else:
                        _lbl = None
                    ax[-4].plot(2 * [post_ref_spike_times_[i]], [0, 1],
                                linewidth=2,
                                color="red",
                                alpha=.4,
                                label=_lbl)
            ax[-4].set_ylabel("Post spikes")

            ax[-3].plot(timevec, third_factor_trace)
            ax[-3].set_ylabel("3rd factor")

            ax[-2].plot(t_hist[:-1], np.diff(w_hist), marker="o", label=u"Δw")
            ax[-2].set_ylabel(u"Δw")

            ax[-1].plot(t_hist, w_hist, marker="o")
            if sim_ref:
                ax[-1].plot(t_hist,
                            w_hist_ref,
                            linestyle="--",
                            marker="x",
                            label="ref")
            ax[-1].set_ylabel("w")

            ax[-1].set_xlabel("Time [ms]")
            for _ax in ax:
                if not _ax == ax[-1]:
                    _ax.set_xticklabels([])
                _ax.grid(which="major", axis="both")
                _ax.xaxis.set_major_locator(
                    matplotlib.ticker.FixedLocator(
                        np.arange(0, np.ceil(sim_time))))
                _ax.set_xlim(0., sim_time)
            fig.savefig("/tmp/stdp_third_factor_synapse_test" + fname_snip +
                        ".png",
                        dpi=300)

        # verify
        MAX_ABS_ERROR = 1E-6
        idx = np.where(np.abs(third_factor_trace) < 1E-3)[
            0]  # find where third_factor_place is (almost) zero
        times_dw_should_be_zero = timevec[idx]
        for time_dw_should_be_zero in times_dw_should_be_zero:
            _idx = np.argmin((time_dw_should_be_zero - np.array(t_hist))**2)
            assert np.abs(np.diff(w_hist)[_idx]) < MAX_ABS_ERROR

        assert np.any(np.abs(np.array(w_hist) -
                             1) > MAX_ABS_ERROR), "No change in the weight!"
Beispiel #25
0
            temp = nest.Create(zin, cell_n)
            All_cells[key1].append(temp)
            ext_key = xin[:2] + yin + zin
            temp_d = nest.Create('poisson_generator', 1,
                                 {'rate': Ext[ext_key]})
            external_list[ext_key].append(temp_d)
            temp_sd = nest.Create('spike_detector', 1, {
                "label": key1,
                "withtime": True,
                "withgid": True,
                "to_file": False
            })
            sd_list[key1].append(temp_sd)
            conn_dict = {'rule': 'all_to_all'}
            syn_dict = {'model': 'Frompyr', 'weight': 100, 'delay': 1.0}  #50,
            nest.Connect(temp_d, temp, conn_spec=conn_dict, syn_spec=syn_dict)
            nest.Connect(temp, temp_sd)

    for yin in alltypes:
        sourcetypes = xin + yin
        source_list = list(All_cells[xin + yin][0])
        for zin in alltypes:
            targettypes = xin + zin
            target_list = list(All_cells[xin + zin][0])
            conn_keys = yin + '_' + zin
            if area == 'V1':
                exception = V1_exceptions
                weights = V1_weights
            elif area == 'LM':
                exception = LM_exceptions
                weights = LM_weights
Beispiel #26
0
    "label": "voltmeter",
    "withtime": True,
    "withgid": True,
    "interval": 1.
})

###############################################################################
# Sixth, the `dc_generator` is connected to the first neuron
# (``neurons[0]``) and the `voltmeter` is connected to the second neuron
# (``neurons[1]``). The command `Connect` has different variants. Plain
# `Connect` just takes the handles of pre- and post-synaptic nodes and uses
# the default values for weight and delay. Note that the connection
# direction for the `voltmeter` reflects the signal flow in the simulation
# kernel, because it observes the neuron instead of receiving events from it.

nest.Connect(dc_gen, [neurons[0]])
nest.Connect(volts, [neurons[1]])

###############################################################################
# Seventh, the first neuron (``neurons[0]``) is connected to the second
# neuron (``neurons[1]``).  The command `CopyModel` copies the
# `tsodyks_synapse` model to the new name ``syn`` with parameters
# ``syn_param``.  The manually defined model ``syn`` is used in the
# connection routine via the ``syn_spec`` parameter.

nest.CopyModel("tsodyks_synapse", "syn", syn_param)
nest.Connect([neurons[0]], [neurons[1]], syn_spec="syn")

###############################################################################
# Finally, we simulate the configuration using the command `Simulate`,
# where the simulation time ``Tend`` is passed as the argument.  We plot the
    def _connect(self):
        """Connect populations."""

        nest.Connect(self._ls, self._lt, self._conndict)
soma_inh_inp = g_inh(ampl_inh, t_start, t_end)

'''
dendritic input
create spike pattern by recording the spikes of a simulation of n_pg
poisson generators. The recorded spike times are then given to spike
generators.
'''
n_pg = 200                 # number of poisson generators
p_rate = 10.0              # rate in Hz

pgs = nest.Create('poisson_generator', n=n_pg, params={'rate': p_rate})

prrt_nrns_pg = nest.Create('parrot_neuron', n_pg)

nest.Connect(pgs, prrt_nrns_pg, {'rule': 'one_to_one'})

sd = nest.Create('spike_detector', n_pg)
nest.Connect(prrt_nrns_pg, sd, {'rule': 'one_to_one'})

nest.Simulate(pattern_duration)
t_sds = []
for i, ssd in enumerate(nest.GetStatus(sd)):
    t_sd = ssd['events']['times']
    t_sds.append(t_sd)

nest.ResetKernel()
nest.SetKernelStatus({'resolution': resolution})

'''
neuron and devices
 def generateSpikes(self, neuron, times):
     """Trigger spike to given neuron at specified times."""
     delay = 1.
     gen = nest.Create("spike_generator", 1, {
                       "spike_times": [t - delay for t in times]})
     nest.Connect(gen, neuron, syn_spec={"delay": delay})
Beispiel #30
0
    }
}
ie_conn_dict = {'rule': 'pairwise_bernoulli', 'p': pI, 'autapses': False}

ii_syn_dict = {
    "model": "ii",
    "weight": wII,
    "delay": {
        "distribution": "uniform",
        "low": 0.1,
        "high": 2.0
    }
}
ii_conn_dict = {'rule': 'pairwise_bernoulli', 'p': pI, 'autapses': False}

nest.Connect(exc, exc, ee_conn_dict, ee_syn_dict)
nest.Connect(exc, inh, ei_conn_dict, ei_syn_dict)
nest.Connect(inh, exc, ie_conn_dict, ie_syn_dict)
nest.Connect(inh, inh, ii_conn_dict, ii_syn_dict)

# create poisson noise
noiseExc = nest.Create('poisson_generator', nExc)
noiseInh = nest.Create('poisson_generator', nInh)
# don't know rate, should be "to every neuron" ie one-to-one
nest.SetStatus(noiseExc, [{
    "rate": 90.0,
    "origin": 0.0,
    "start": 0.0,
    "stop": 100.0
}])
nest.SetStatus(noiseInh, [{