Beispiel #1
0
import nest
import pylab
import numpy
MODULE_PATH=  '/afs/nada.kth.se/home/w/u1yxbcfw/tools/NEST/dist/install-nest-2.2.2/lib/nest/ml_module'
nest.Install(MODULE_PATH) # Change ml_module to your module name

model= 'izhik_cond_exp'
n=nest.Create(model)
mm=nest.Create('multimeter')
sd=nest.Create('spike_detector')
nest.SetStatus(mm, {'interval': 0.1, 'record_from': ['V_m']})
                  
rec={}    
rec[model] = nest.GetDefaults('izhik_cond_exp')['receptor_types'] 
    
        dic['nest']['MS']['a']      =  0.01      # (E.M. Izhikevich 2007)
        dic['nest']['MS']['b_1']    = -20.       # (E.M. Izhikevich 2007)
        dic['nest']['MS']['b_2']    = -20.       # (E.M. Izhikevich 2007)
        dic['nest']['MS']['c']      = -55.       # (Humphries, Lepora, et al. 2009)
        dic['nest']['MS']['C_m']    =  15.2      # (Humphries, Lepora, et al. 2009) # C izh
        dic['nest']['MS']['d']      =  66.9      # (Humphries, Lepora, et al. 2009)
        dic['nest']['MS']['E_L']    = -81.85     # (Humphries, Lepora, et al. 2009) # v_r in izh
        dic['nest']['MS']['k']      =   1.       # (E.M. Izhikevich 2007)
        dic['nest']['MS']['V_peak'] =  40.       # (E.M. Izhikevich 2007)
        dic['nest']['MS']['V_b']    = dic['nest']['MS']['E_L']    # (E.M. Izhikevich 2007)
        dic['nest']['MS']['V_th']   = -29.7      # (Humphries, Lepora, et al. 2009)
        dic['nest']['MS']['V_m']    =  80.
    
        dic['nest']['MS']['AMPA_1_Tau_decay'] = 12.  # (Ellender 2011)
        dic['nest']['MS']['AMPA_1_E_rev']     =  0.  # (Humphries, Wood, et al. 2009)
        
Beispiel #2
0
            w1 = 0.0
    return w1


# presynaptic and postsynaptic neurons
neuron_pre = nest.Create("parrot_neuron")
neuron_post = nest.Create("parrot_neuron")

#spike generators
sg_pre = nest.Create("spike_generator")
sg_post = nest.Create("spike_generator")

# spike times
spike_times_pre = [2.0]
spike_times_post = [1.0, 3.0]
nest.SetStatus(sg_pre, {"spike_times": spike_times_pre})
nest.SetStatus(sg_post, {"spike_times": spike_times_post})

# connect spike generators to neurons
syn_dict = {"weight": 1.0, "delay": 1.0}
nest.Connect(sg_pre, neuron_pre, "one_to_one", syn_dict)
nest.Connect(sg_post, neuron_post, "one_to_one", syn_dict)

# STDP connection parameters
tau_plus = 20.0
tau_minus = 20.0
lambd = 0.01
alpha = 1.0
mu_plus = 1.0
mu_minus = 1.0
Wmax = 10.0
Beispiel #3
0
neuron2 = nest.Create('iaf_psc_exp', 1, nrn_parameter_dict)

# Create inputs
t_spike_input = 55.
t_step = 50.
step_duration = 0.5
step_amplitude = 60790.
# step_amplitude = 0.

#sine = nest.Create('ac_generator',1,{'amplitude':100.0,'frequency':2.0})
spike_gen = nest.Create("spike_generator",
                        params={"spike_times": array([t_spike_input])})
step_gen = nest.Create('step_current_generator')
nest.SetStatus(
    step_gen, {
        'amplitude_times': array([t_step, t_step + step_duration]),
        'amplitude_values': array([step_amplitude, 0.])
    })
# step_amplitude is in [pA]
# needs a large value to produce a spike

# Create voltmeter and spike recorder
voltmeter = nest.Create('voltmeter', 1, {'withgid': True})
spike_rec = nest.Create('spike_detector')

###################################
# Connect nodes
###################################

# Connect spike generator to neuron
# Note: The connection weight is given in [pA]
    def __init__(self, prefix, new_pars=[], pars_file=[]):
        '''Creates and simulates a network in NEST'''

        #Temporary way to run without the selected pars file
        pars_file = []
        start_build_net = time.time()

        if pars_file == []:  # import generic params_d file
            import params_d_hysterisis
            reload(params_d_hysterisis)
            pars = params_d_hysterisis.Parameters(new_pars)
        else:  # import specific params_d file
            fobj, pathname, description = imp.find_module(pars_file)
            params_d_sp = imp.load_module(pars_file, fobj, pathname,
                                          description)
            pars = params_d_sp.Parameters(new_pars)

        self.T_sim = pars.T_sim + pars.T_wup + pars.T_cdown
        #self.record_spikes = pars.record_spikes
        self.record_vm = pars.record_vm
        self.recorders = {}
        self.events = {'spikes': [], 'vm': []}
        self.pars = pars
        self.pars.prefix = prefix

        # INITIALIZE NETWORK -----------------------------------------------------------------------
        nest_path_tmp = tempfile.mktemp(prefix=pars.nest_path_tmp)
        os.mkdir(nest_path_tmp)
        nest.ResetKernel()
        shutil.rmtree(nest.GetStatus([0], 'data_path')[0], ignore_errors=True)
        nest.SetStatus(
            [0], {
                'resolution': pars.dt,
                'print_time': pars.print_time,
                'overwrite_files': pars.owr_files,
                'rng_seeds': [int(pars.rnd_seeds)],
                'data_path': nest_path_tmp
            })

        print '\nBuilding network...'

        # CREATE SOURCES ----------------------------------------------------------------------------
        self.pg_exc = nest.Create('poisson_generator', 1)
        self.pg_inh = nest.Create('poisson_generator', 1)
        nest.SetStatus(self.pg_exc, {
            'rate': pars.pg_rate_exc,
            'stop': pars.T_sim + pars.T_wup
        })
        nest.SetStatus(self.pg_inh, {
            'rate': pars.pg_rate_inh,
            'stop': pars.T_sim + pars.T_wup
        })

        self.dc1_exc = nest.Create('dc_generator', 1)
        nest.SetStatus(self.dc1_exc, pars.dc1_pars)

        self.dc2_exc = nest.Create('dc_generator', 1)
        nest.SetStatus(self.dc2_exc, pars.dc2_pars)

        # CREATE POPULATIONS -----------------------------------------------------------------------
        print 'Creating populations...\n'

        neurons = []
        self.pops = range(len(pars.N))
        for ii, nr in enumerate(pars.N):
            self.pops[ii] = nest.Create(pars.model_type, abs(nr))
            neurons.extend(self.pops[ii])

#  set neuron parameters	for every population independently
        for ntypes in range(len(pars.N)):
            nest.SetStatus(self.pops[ntypes], pars.neuron_params[ntypes])

        if pars.rnd_dist:
            nest.SetStatus(neurons, 'tau_m', pars.tau_m_rnd)

# Make connections -------------------------------------------------------------------------
        self.exc_pop = self.pops[0]

        #Create AC generator
        self.shu_gen = nest.Create('poisson_generator',
                                   params={
                                       'rate': self.pars.shu_input,
                                       'start': pars.st_val,
                                       'stop': pars.st_val + 7 * pars.shu_width
                                   })

        J_exc = pars.J_exc

        J_inh = pars.J_inh

        total_neu = [item for sublist in self.pops for item in sublist]

        nest.DivergentConnect(self.pg_exc,
                              self.exc_pop,
                              weight=pars.J_exc,
                              delay=pars.min_del)
        for pop in self.pops[1:]:
            nest.DivergentConnect(self.pg_inh,
                                  pop,
                                  weight=pars.J_exc,
                                  delay=pars.min_del)

        for pop2 in self.pops:
            self.n_exc = int(pars.epsilon * len(pop2))
            nest.RandomDivergentConnect(self.exc_pop,
                                        pop2,
                                        self.n_exc,
                                        weight=J_exc,
                                        delay=pars.delay)

        for pop3 in self.pops:
            self.n_inh = int(pars.epsilon * len(pop3))
            nest.RandomDivergentConnect(self.pops[1],
                                        pop3,
                                        self.n_inh,
                                        weight=J_inh,
                                        delay=pars.delay)
            if len(self.pops) > 2:
                nest.RandomDivergentConnect(self.pops[2],
                                            pop3,
                                            self.n_inh,
                                            weight=J_inh,
                                            delay=pars.delay)

#CREATE RECORDERS----------------------------------------------------------------------------
        self.record_spikes = list(
            np.arange(self.pops[0][0], self.pops[-1][-1] + 1))
        #if self.record_spikes!= []:
        sd = nest.Create('spike_detector', 1)
        nest.SetStatus(sd, {'to_file': True, 'to_memory': True})
        nest.ConvergentConnect(self.record_spikes, sd)
        self.recorders['sd'] = sd

        if self.pars.record_vm != []:
            vm = nest.Create('voltmeter', 1)
            print 'Id of vm recorder: ', vm
            nest.SetStatus(
                vm, {
                    'withtime': True,
                    'withgid': True,
                    'to_file': True,
                    'to_memory': False
                })
            nest.DivergentConnect(vm, self.pars.record_vm)
            nest.SetStatus(self.pars.record_vm,
                           {'V_th': 1000.})  # record free Vm
            self.recorders['vm'] = vm

        self.build_net_time = time.time() - start_build_net
    def test_QuantalSTPSynapse(self):
        """Compare quantal_stp_synapse with its deterministic equivalent"""
        nest.ResetKernel()
        nest.rng_seed = 1
        nest.set_verbosity(100)
        n_syn = 12  # number of synapses in a connection
        n_trials = 100  # number of measurement trials

        # parameter set for facilitation
        fac_params = {
            "U": 0.03,
            "u": 0.03,
            "tau_fac": 500.,
            "tau_rec": 200.,
            "weight": 1.
        }

        # Here we assign the parameter set to the synapse models
        t1_params = fac_params  # for tsodyks2_synapse
        t2_params = t1_params.copy()  # for furhmann_synapse

        t1_params["synapse_model"] = "tsodyks2_synapse"

        t2_params["n"] = n_syn
        t2_params["weight"] = 1. / n_syn
        t2_params["synapse_model"] = "quantal_stp_synapse"

        source = nest.Create("spike_generator")
        source.spike_times = [
            30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.,
            360., 390., 900.
        ]

        parrot = nest.Create("parrot_neuron")
        neuron = nest.Create("iaf_psc_exp",
                             2,
                             params={
                                 "tau_syn_ex": 3.,
                                 "tau_m": 70.
                             })

        # We must send spikes via parrot because devices cannot
        # connect through plastic synapses
        # See #478.
        nest.Connect(source, parrot)
        nest.Connect(parrot, neuron[:1], syn_spec=t1_params)
        nest.Connect(parrot, neuron[1:], syn_spec=t2_params)

        voltmeter = nest.Create("voltmeter", 2)

        t_tot = 1500.

        # the following is a dry run trial so that the synapse dynamics is
        # idential in all subsequent trials.

        nest.Simulate(t_tot)

        # Now we connect the voltmeters
        nest.Connect(voltmeter[:1], neuron[:1])
        nest.Connect(voltmeter[1:], neuron[1:])

        for t in range(n_trials):
            t_net = nest.biological_time
            nest.SetStatus(source, {"origin": t_net})
            nest.Simulate(t_tot)

        nest.Simulate(.1)  # flush the last voltmeter events from the queue

        vm = numpy.array(voltmeter[1].events["V_m"])
        vm_reference = numpy.array(voltmeter[0].events["V_m"])

        assert (len(vm) % n_trials == 0)
        n_steps = int(len(vm) / n_trials)
        vm.shape = (n_trials, n_steps)
        vm_reference.shape = (n_trials, n_steps)

        vm_mean = numpy.mean(vm, axis=0)
        vm_ref_mean = numpy.mean(vm_reference, axis=0)

        error = numpy.sqrt((vm_ref_mean - vm_mean)**2)
        self.assertLess(numpy.max(error), 4.0e-4)
Beispiel #6
0
def simulateMultiareaNetwork(simtime, dt, master_seed, num_threads,
                             V0_mean, V0_std, network_config):
    """Build a multi-area network and simulate it.

    Parameters:
        simtime             simulation time in ms
        dt                  simulation timestep in ms
        master_seed         master seed for random numbers
        num_threads         number of threads per MPI process
        V0_mean             mean initial membrane potential
        V0_std              standard deviation of initial membrane potential
        network_config      keyword arguments for buildBrunel

    Returns:
        spikes:             dict of spike senders / spike times of all
                            neurons in all populations
    """
    # configure kernel
    nest.ResetKernel()
    nest.SetKernelStatus({
        'local_num_threads': num_threads, 'resolution': dt, 'print_time': False
    })

    # seed all random number generators
    if nest.Rank() == 0:
        print('Master seed: %i ' % master_seed)
    N_tp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
    if nest.Rank() == 0:
        print('Total number of processes: %i' % N_tp)
    pyrng_seeds = list(range(master_seed, master_seed+N_tp))
    grng_seed = master_seed + N_tp
    rng_seeds = list(range(master_seed+1+N_tp, master_seed+1+2*N_tp))
    pyrngs = [np.random.RandomState(s) for s in pyrng_seeds]
    nest.SetKernelStatus({'grng_seed': grng_seed, 'rng_seeds': rng_seeds})

    # build the Brunel network
    _, neurons, spike_detectors = buildMultiareaNetwork(**network_config)

    # distribute initial voltages
    for thread in np.arange(nest.GetKernelStatus('local_num_threads')):
        # Using GetNodes is a work-around until NEST 3.0 is released. It
        # will issue a deprecation warning.
        local_nodes = nest.GetNodes([0], {'model': 'iaf_psc_exp',
                                          'thread': thread},
                                    local_only=True)[0]
        vp = nest.GetStatus(local_nodes)[0]['vp']
        # vp is the same for all local nodes on the same thread
        nest.SetStatus(
            local_nodes, 'V_m', pyrngs[vp].normal(
                V0_mean, V0_std, len(local_nodes)
            )
        )
        if nest.Rank() == 0:
            print('Number of local nodes: %i' % len(local_nodes))

    # simulate
    nest.Simulate(simtime)

    # read out spikes from spikedetectors
    spikes = {}
    for pop in spike_detectors:
        data = nest.GetStatus(spike_detectors[pop], 'events')[0]
        spikes[pop] = {
            'ids': data['senders'], 'times': data['times'],
            'min_id': neurons[pop][0], 'max_id': neurons[pop][-1]
        }

    return spikes
Beispiel #7
0
def column(setdegree, LGN):
    """"
    Visual Cortex (V1) Oriented Column -

    This function creates a cortical column trained with a specific orientation (pre-trained 'soma_exc' IE values)

    The column is composed by:
        - Pyramidal (Pyr)               layer 2/3
        - Inhibitory interneurons(inh)  layer 2/3
        - Spiny Stellate Cells(SS)      layer 4
        - Inhibitory interneurons       layer 4
        - Pyramidal                     layer 5
        - Inhibitory interneurons       layer 5
        - Pyramidal                     layer 6
        - Inhibitory interneurons       layer 6

    """
    import matplotlib.pyplot as plt
    import matplotlib
    import pickle
    import gzip
    import numpy
    import nest
    import nest.raster_plot
    import numpy as np

    import scipy.io
    import pickle
    if not 'lifl_psc_exp_ie' in nest.Models():
        nest.Install('LIFL_IEmodule')

    SS4 = nest.Create(
        'lifl_psc_exp_ie',
        324,
        {
            'I_e': 0.0,  # 122.1
            'V_m': -70.0,
            'E_L': -65.0,
            'V_th': -50.0,
            'V_reset': -65.0,
            'C_m': 250.0,
            'tau_m': 10.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 2.0,
            'std_mod': False,
            'lambda': 0.0005,
            'tau': 12.5,
        })

    lgn2v1_delay = 1.0  # Delay from LGN to Cortex

    nest.Connect(LGN, SS4, {'rule': 'one_to_one'}, {
        "weight": 15000.0,
        "delay": lgn2v1_delay
    })

    # Target neuron. Connections are set in order to produce a target spike only in pattern detection.
    Pyr23 = nest.Create(
        'aeif_psc_exp_peak', 324, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 2.0,
            'g_L': 980.0
        })
    for idn in Pyr23:
        nest.SetStatus([idn], {'V_m': (-65.0 + np.random.rand() * 10.0)})

    Pyr5 = nest.Create(
        'aeif_psc_exp_peak', 81, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 2.0,
            'g_L': 980.0
        })
    for idn in Pyr5:
        nest.SetStatus([idn], {'V_m': (-65.0 + np.random.rand() * 10.0)})
    Pyr6 = nest.Create(
        'aeif_psc_exp_peak', 243, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 2.0,
            'g_L': 980.0
        })
    for idn in Pyr6:
        nest.SetStatus([idn], {'V_m': (-65.0 + np.random.rand() * 10.0)})

    # Poisson Noise Generators
    poisson_activityL23 = nest.Create('poisson_generator', 1)
    nest.SetStatus(poisson_activityL23, {'rate': 1721500.0})
    poisson_activityL5 = nest.Create('poisson_generator', 1)
    nest.SetStatus(poisson_activityL5, {'rate': 1740000.0})
    poisson_activityL6 = nest.Create('poisson_generator', 1)
    nest.SetStatus(poisson_activityL6, {'rate': 1700000.0})
    poisson_activityInh = nest.Create('poisson_generator', 1)
    nest.SetStatus(poisson_activityInh, {'rate': 1750000.0})
    nest.Connect(poisson_activityL23, Pyr23, {'rule': 'all_to_all'},
                 {"weight": 5.0})
    nest.Connect(poisson_activityL5, Pyr5, {'rule': 'all_to_all'},
                 {"weight": 5.0})
    nest.Connect(poisson_activityL6, Pyr6, {'rule': 'all_to_all'},
                 {"weight": 5.0})

    # FeedForward
    nest.Connect(Pyr23, Pyr5, {
        'rule': 'fixed_indegree',
        'indegree': 15
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(Pyr5, Pyr6, {
        'rule': 'fixed_indegree',
        'indegree': 20
    }, {
        "weight": 100.0,
        "delay": 1.0
    })

    ## Connections between layers
    nest.Connect(Pyr23, Pyr23, {
        'rule': 'fixed_indegree',
        'indegree': 36
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(Pyr5, Pyr5, {
        'rule': 'fixed_indegree',
        'indegree': 10
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(Pyr6, Pyr6, {
        'rule': 'fixed_indegree',
        'indegree': 20
    }, {
        "weight": 100.0,
        "delay": 1.0
    })

    In4 = nest.Create(
        'aeif_psc_exp_peak', 65, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 1.0,
            'g_L': 980.0
        })
    nest.Connect(poisson_activityInh, In4, {'rule': 'all_to_all'},
                 {"weight": 4.9})
    nest.Connect(SS4, In4, {
        'rule': 'fixed_indegree',
        'indegree': 32
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(In4, SS4, {
        'rule': 'fixed_indegree',
        'indegree': 6
    }, {
        "weight": -100.0,
        "delay": 1.0
    })
    nest.Connect(In4, In4, {
        'rule': 'fixed_indegree',
        'indegree': 6
    }, {
        "weight": -100.0,
        "delay": 1.0
    })

    poisson_activity_inh = nest.Create('poisson_generator', 1)
    nest.SetStatus(poisson_activity_inh, {'rate': 340000.0})
    In23 = nest.Create(
        'aeif_psc_exp_peak', 65, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 1.0,
            'g_L': 980.0
        })

    nest.Connect(poisson_activityInh, In23, {'rule': 'all_to_all'},
                 {"weight": 5.0})
    nest.Connect(Pyr23, In23, {
        'rule': 'fixed_indegree',
        'indegree': 35
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(In23, Pyr23, {
        'rule': 'fixed_indegree',
        'indegree': 8
    }, {
        "weight": -100.0,
        "delay": 1.0
    })
    nest.Connect(In23, In23, {
        'rule': 'fixed_indegree',
        'indegree': 8
    }, {
        "weight": -100.0,
        "delay": 1.0
    })

    In5 = nest.Create(
        'aeif_psc_exp_peak', 16, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 1.0,
            'g_L': 980.0
        })

    nest.Connect(poisson_activityInh, In5, {'rule': 'all_to_all'},
                 {"weight": 5.0})
    nest.Connect(Pyr5, In5, {
        'rule': 'fixed_indegree',
        'indegree': 30
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(In5, Pyr5, {
        'rule': 'fixed_indegree',
        'indegree': 8
    }, {
        "weight": -100.0,
        "delay": 1.0
    })
    nest.Connect(In5, In5, {
        'rule': 'fixed_indegree',
        'indegree': 8
    }, {
        "weight": -100.0,
        "delay": 1.0
    })

    In6 = nest.Create(
        'aeif_psc_exp_peak', 49, {
            'I_e': 0.0,
            'V_m': -70.0,
            'E_L': -70.0,
            'V_th': -50.0,
            'V_reset': -55.0,
            'C_m': 250.0,
            'tau_syn_ex': 2.0,
            'tau_syn_in': 2.0,
            't_ref': 1.0,
            'g_L': 980.0
        })
    nest.Connect(poisson_activityInh, In6, {'rule': 'all_to_all'},
                 {"weight": 5.0})
    nest.Connect(Pyr6, In6, {
        'rule': 'fixed_indegree',
        'indegree': 32
    }, {
        "weight": 100.0,
        "delay": 1.0
    })
    nest.Connect(In6, Pyr6, {
        'rule': 'fixed_indegree',
        'indegree': 6
    }, {
        "weight": -100.0,
        "delay": 1.0
    })
    nest.Connect(In6, In6, {
        'rule': 'fixed_indegree',
        'indegree': 6
    }, {
        "weight": -100.0,
        "delay": 1.0
    })

    # Here we load the Soma_exc (IE value) trained before for each preferred angle.
    exec('file = "./files/soma_exc_15_' + str(setdegree) + '.pckl"', None,
         globals())
    with open(file, 'rb') as f:
        u = pickle._Unpickler(f)
        u.encoding = 'latin1'
        SS4_soma_exc_raw = u.load()
        SS4_soma_exc = SS4_soma_exc_raw[:]
        del SS4_soma_exc_raw, setdegree

    for i in range(0, 324):
        nest.SetStatus([SS4[i]], {'soma_exc': SS4_soma_exc[i]})

    k = 0
    for j in range(0, 324, 36):
        for i in range(0, 18, 2):

            # Set stimulator (i.e. Neuromodulator) of each SS cell
            nest.SetStatus([SS4[i + j]],
                           {'stimulator': [SS4[i + j + 1], SS4[i + j + 18]]})
            nest.SetStatus([SS4[i + j + 1]],
                           {'stimulator': [SS4[i + j], SS4[i + j + 19]]})
            nest.SetStatus([SS4[i + j + 18]],
                           {'stimulator': [SS4[i + j], SS4[i + j + 19]]})
            nest.SetStatus([SS4[i + j + 19]],
                           {'stimulator': [SS4[i + j + 18], SS4[i + j + 1]]})

            # Connect betwen neuromodulators of SS cell (groups of 4 SS)
            nest.Connect([SS4[i + j]], [SS4[i + j + 1]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j]], [SS4[i + j + 18]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j + 1]], [SS4[i + j]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j + 1]], [SS4[i + j + 19]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j + 18]], [SS4[i + j]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j + 18]], [SS4[i + j + 19]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j + 19]], [SS4[i + j + 1]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })
            nest.Connect([SS4[i + j + 19]], [SS4[i + j + 18]],
                         {"rule": "one_to_one"}, {
                             "model": "stdp_synapse",
                             'delay': 0.1
                         })

            # Connect each group of 4 SS to 4 layer 2/3 Pyramidal Cells so that each pyramidal only fire on polychrony arrival of SS fires
            nest.Connect(
                [SS4[i + j], SS4[i + j + 1], SS4[i + j + 18], SS4[i + j + 19]],
                [
                    Pyr23[i + j], Pyr23[i + j + 1], Pyr23[i + j + 2],
                    Pyr23[i + j + 3]
                ], {"rule": "all_to_all"}, {
                    "weight": 100.0,
                    "delay": 1.0
                })

            k += 1

    # We create a Detector so that we can get spike times and raster plot
    Detector = nest.Create('spike_detector')
    nest.Connect(Pyr5, Detector)
    nest.Connect(Pyr6, Detector)
    nest.Connect(SS4, Detector)
    nest.Connect(Pyr23, Detector)
    nest.Connect(In23, Detector)
    nest.Connect(In4, Detector)
    nest.Connect(In5, Detector)
    nest.Connect(In6, Detector)

    Spikes = nest.Create('spike_detector')
    nest.Connect(Pyr23, Spikes)
    nest.Connect(Pyr5, Spikes)
    nest.Connect(Pyr6, Spikes)

    Multimeter = nest.Create('multimeter',
                             params={
                                 'withtime': True,
                                 'record_from': ['V_m', 'I_syn_ex'],
                                 'interval': 0.1
                             })
    nest.Connect(Multimeter, Pyr23)
    nest.Connect(Multimeter, Pyr5)
    nest.Connect(Multimeter, SS4)
    nest.Connect(Multimeter, Pyr6)

    SomaMultimeter = nest.Create('multimeter',
                                 params={
                                     'withtime': True,
                                     'record_from': ['soma_exc'],
                                     'interval': 0.1
                                 })
    nest.Connect(SomaMultimeter, SS4)

    return Detector, Spikes, Multimeter, SomaMultimeter, Pyr23, SS4, Pyr5, Pyr6, In23, In4, In5, In6
Beispiel #8
0
neuronparams = {
    'tau_m': 20.,
    'V_th': 20.,
    'E_L': 10.,
    't_ref': 2.,
    'V_reset': 0.,
    'C_m': 200.,
    'V_m': 0.
}

neurons = nest.Create('iaf_psc_alpha', N)
sd = nest.Create('spike_detector')
noise = nest.Create('noise_generator')
drive = nest.Create('ac_generator')

nest.SetStatus(drive, driveparams)
nest.SetStatus(noise, noiseparams)
nest.SetStatus(neurons, neuronparams)
nest.SetStatus(neurons, [{
    'I_e': (n * (bias_end - bias_begin) / N + bias_begin)
} for n in neurons])

nest.SetStatus(sd, {"withgid": True, "withtime": True})

nest.DivergentConnect(drive, neurons)
nest.DivergentConnect(noise, neurons)
nest.ConvergentConnect(neurons, sd)

nest.Simulate(T)

nest.raster_plot.from_device(sd, hist=True)
Beispiel #9
0
    def _convergent_connect(self, presynaptic_indices, postsynaptic_index,
                            **connection_parameters):
        """
        Connect a neuron to one or more other neurons with a static connection.

        `presynaptic_indices` - 1D array of presynaptic indices
        `postsynaptic_index` - integer - the index of the postsynaptic neuron
        `connection_parameters` - dict whose keys are native NEST parameter names. Values may be scalars or arrays.
        """
        # Clean the connection parameters by removing parameters that are
        # used by PyNN but should not be passed to NEST
        connection_parameters.pop(
            'tau_minus',
            None)  # TODO: set tau_minus on the post-synaptic cells
        connection_parameters.pop('dendritic_delay_fraction', None)
        connection_parameters.pop('w_min_always_zero_in_NEST', None)

        syn_dict = {
            'synapse_model': self.nest_synapse_model,
            'synapse_label': self.nest_synapse_label,
        }

        # Weights require some special handling
        if self.receptor_type == 'inhibitory' and self.post.conductance_based:
            connection_parameters[
                'weight'] *= -1  # NEST wants negative values for inhibitory weights, even if these are conductances
            if "stdp" in self.nest_synapse_model:
                syn_dict[
                    "Wmax"] = -1.2345e6  # just some very large negative value to avoid
                # NEST complaining about weight and Wmax having different signs
                # (see https://github.com/NeuralEnsemble/PyNN/issues/636)
                # Will be overwritten below.
                connection_parameters["Wmax"] *= -1
        if hasattr(self.post, "celltype") and hasattr(
                self.post.celltype,
                "receptor_scale"):  # this is a bit of a hack
            connection_parameters[
                'weight'] *= self.post.celltype.receptor_scale  # needed for the Izhikevich model

        # Prepare connections. NodeCollections can't have repeated values, so for some
        # connector types we need to split the presynaptic cells into groups that
        # don't have such repeats.

        # note that NEST needs sorted indices
        sort_indices = presynaptic_indices.argsort()
        presynaptic_indices = presynaptic_indices[sort_indices]
        for name, value in connection_parameters.items():
            if isinstance(value, np.ndarray):
                connection_parameters[name] = value[sort_indices]

        try:
            presynaptic_cell_groups = [
                self.pre.node_collection[presynaptic_indices]
            ]
            connection_parameter_groups = [connection_parameters]
        except ValueError as err:
            if "All node IDs in a NodeCollection have to be unique" in str(
                    err):
                presynaptic_index_groups, connection_parameter_groups = \
                    split_array_to_avoid_repeats(presynaptic_indices, **connection_parameters)
                presynaptic_cell_groups = [
                    self.pre.node_collection[i]
                    for i in presynaptic_index_groups
                ]
            else:
                raise
        postsynaptic_cell = self.post[postsynaptic_index]

        # Create connections and set parameters
        for presynaptic_cells, connection_parameter_group in zip(
                presynaptic_cell_groups, connection_parameter_groups):
            self._sources.update(presynaptic_cells.tolist())
            try:
                weights = connection_parameter_group.pop('weight')
                delays = connection_parameter_group.pop('delay')
                # nest.Connect expects a 2D array
                if not np.isscalar(weights):
                    weights = np.array([weights])
                if not np.isscalar(delays):
                    delays = np.array([delays])
                syn_dict.update({'weight': weights, 'delay': delays})

                if postsynaptic_cell.celltype.standard_receptor_type:
                    # For Tsodyks-Markram synapses models we set the "tau_psc" parameter to match
                    # the relevant "tau_syn" parameter from the post-synaptic neuron.
                    if 'tsodyks' in self.nest_synapse_model:
                        if self.receptor_type == 'inhibitory':
                            param_name = postsynaptic_cell.celltype.translations[
                                'tau_syn_I']['translated_name']
                        elif self.receptor_type == 'excitatory':
                            param_name = postsynaptic_cell.celltype.translations[
                                'tau_syn_E']['translated_name']
                        else:
                            raise NotImplementedError()
                        syn_dict["tau_psc"] = nest.GetStatus(
                            postsynaptic_cell.node_collection, param_name)[0]
                else:
                    syn_dict.update({
                        "receptor_type":
                        postsynaptic_cell.celltype.get_receptor_type(
                            self.receptor_type)
                    })

                # For parameters other than weight and delay, we need to know if they are "common"
                # parameters (the same for all synapses) or "local" (different synapses can have
                # different values), as this affects how they are set.
                #
                # To introspect which parameters are common, we need an existing connection, so
                # the first time we create connections we pass just the weight and delay, and set
                # the other parameters later. We then get the list of common parameters and cache
                # it so that in subsequent Connect() calls we can pass all of the local
                # (non-common) parameters.

                if self._common_synapse_property_names is None:
                    nest.Connect(presynaptic_cells,
                                 postsynaptic_cell.node_collection,
                                 'all_to_all', syn_dict)
                    self._identify_common_synapse_properties()

                    # Retrieve connections so that we can set additional
                    # parameters using nest.SetStatus
                    connections = nest.GetConnections(
                        source=presynaptic_cells,
                        target=postsynaptic_cell.node_collection,
                        synapse_model=self.nest_synapse_model,
                        synapse_label=self.nest_synapse_label)
                    for name, value in connection_parameter_group.items():
                        if name not in self._common_synapse_property_names:
                            value = make_sli_compatible(value)
                            if isinstance(value, np.ndarray):
                                nest.SetStatus(connections, name,
                                               value.tolist())
                            else:
                                nest.SetStatus(connections, name, value)
                        else:
                            self._set_common_synapse_property(name, value)
                else:
                    # Since we know which parameters are common, we can set the non-common
                    # parameters directly in the nest.Connect call
                    syn_dict = self._update_syn_params(
                        syn_dict, connection_parameter_group)
                    nest.Connect(presynaptic_cells,
                                 postsynaptic_cell.node_collection,
                                 'all_to_all', syn_dict)
                    # and then set the common parameters
                    for name, value in connection_parameter_group.items():
                        if name in self._common_synapse_property_names:
                            self._set_common_synapse_property(name, value)

            except nest.kernel.NESTError as e:
                errmsg = "%s. presynaptic_cells=%s, postsynaptic_cell=%s, weights=%s, delays=%s, synapse model='%s'" % (
                    e, presynaptic_cells, postsynaptic_cell, weights, delays,
                    self.nest_synapse_model)
                raise errors.ConnectionError(errmsg)

        # Reset the caching of the connection list, since this will have to be recalculated
        self._connections = None
        self._simulator.state.stale_connection_cache = True
Beispiel #10
0
import pyNN.nest as sim
import numpy
import nest
__population_views = {}


pop1 = sim.Population(10, sim.IF_cond_alpha())
__population_views['pop1'] = pop1

source = sim.Population(1, sim.SpikeSourcePoisson(rate=1000000.0))

nest_source = nest.Create('poisson_generator')
nest.SetStatus(nest_source, {'rate': 100000.0})
nest.Connect(nest_source, map(int, pop1.all_cells), 'all_to_all')

print "Network loaded"


Beispiel #11
0
'''

nest.CopyModel("static_synapse", "spike_det", {
    "weight": var.JE,
    "delay": var.delay
})
'''
Creates a spike detector layer. Each population is read out simultaneously and added to the
file - ::file:: - whilst reading out note the neural order.
'''

pop_A1, pop_A2, excRec, inhRec, noise = tools.layerNet()

nest.SetStatus(excRec, [{
    'label': "Excitatory-" + var.date + "_" + var.time,
    "withtime": True,
    "withgid": True,
    "to_file": True
}])
nest.SetStatus(inhRec, [{
    'label': "Inhibitory-" + var.date + "_" + var.time,
    "withtime": True,
    "withgid": True,
    "to_file": True
}])

print("Finished Preparing Defaults")
'''
The nodes from each topology layer are read out using nest.GetNodes, the resulting list
is used to establish a connection between neurons given the adjacency dictionary created
in truConnect
'''
#! layer, since they will differ from layer to layer. We will add them
#! below by updating the ``'elements'`` dictionary entry for each
#! population.

#! Retina
#! ------
layerProps.update({'elements': 'RetinaNode'})
retina = topo.CreateLayer(layerProps)

#! Now set phases of retinal oscillators; we use a list comprehension instead
#! of a loop.
[
    nest.SetStatus(
        [n], {
            "phi":
            phiInit(
                topo.GetPosition([n])[0], Params["lambda_dg"],
                Params["phi_dg"])
        }) for n in nest.GetLeaves(retina)[0]
]

#! Thalamus
#! --------

#! We first introduce specific neuron models for the thalamic relay
#! cells and interneurons. These have identical properties, but by
#! treating them as different models, we can address them specifically
#! when building connections.
#!
#! We use a list comprehension to do the model copies.
[
Beispiel #13
0
import nest

from sklearn.svm import LinearSVC
from scipy.special import erf

print("heloooooo")

neuron = nest.Create("iaf_psc_alpha")
#neuron2=nest.Create("iaf_psc_alpha")     checking how the id numbers goes for nodes in order of creation
#voltmeter=nest.Create("voltmeter")
#neuron3=nest.Create("iaf_psc_alpha")

cu = nest.GetStatus(neuron, "I_e")
vth = nest.GetStatus(neuron, ["V_m", "V_th"])

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

nest.Connect(multimeter, neuron)

nest.Simulate(1000)
Beispiel #14
0
        with open(file, 'rb') as f:
            #with open('/Users/alex/Documents/IJASEIT Implementation of MNSD in NEST/Vision Pattern Decodificator/spikes_gabor_18_Final_rnd/spikes_gabor_18_randn02_19.pckl', 'rb') as f:
            u = pickle._Unpickler(f)
            u.encoding = 'latin1'
            resultados = u.load()
        senders = resultados['senders']
        times = resultados[
            'times']  # We give some randomness to spike times. (Avoiding spikes to be equal)

        GCells = len(senders)
        spikingGanglion = range(min(senders),
                                max(senders) + 1, 1)
        inputs = nest.Create("spike_generator", GCells)
        for i in range(0, GCells):
            spike_time = times[senders == spikingGanglion[i]]
            nest.SetStatus([inputs[i]], {'spike_times': spike_time.tolist()})
            print(i, times[senders == spikingGanglion[i]])

        Ganglions = nest.Create('parrot_neuron', GCells)
        nest.Connect(inputs, Ganglions, 'one_to_one')

        Decoders = nest.Create('lif_psc_alpha_sl_ip', GCells, {
            'tau_syn': 0.5,
            'lambda': 0.0006,
            'tau_decay': 0.02,
            'tau': 50.0
        })
        nest.Connect(
            Ganglions, Decoders, {'rule': 'one_to_one'}, {"weight": 3700.0}
        )  # 3100.0  tuple(np.random.permutation(Decoders)) //// We can permutate the connections to biologically randomice pixel-detector.
Beispiel #15
0
    def create_populations(self):
        """ Creates the neuronal populations.

        The neuronal populations are created and the parameters are assigned
        to them. The initial membrane potential of the neurons is drawn from a
        normal distribution. Scaling of the number of neurons and of the
        synapses is performed. If scaling is performed extra DC input is added
        to the neuronal populations.

        """
        self.N_full = self.net_dict['N_full']
        self.N_scaling = self.net_dict['N_scaling']
        self.K_scaling = self.net_dict['K_scaling']
        self.synapses = get_total_number_of_synapses(self.net_dict)
        self.synapses_scaled = self.synapses * self.K_scaling
        self.nr_neurons = self.N_full * self.N_scaling
        self.K_ext = self.net_dict['K_ext'] * self.K_scaling
        self.background_pool_size = self.net_dict[
            'background_pool_size'] * self.K_scaling
        self.w_from_PSP = get_weight(self.net_dict['PSP_e'], self.net_dict)
        self.weight_mat = get_weight(self.net_dict['PSP_mean_matrix'],
                                     self.net_dict)
        self.weight_mat_std = self.net_dict['PSP_std_matrix']
        self.w_ext = self.w_from_PSP
        # self.w_input = get_weight(self.net_dict['input_conn_params']['JE'], self.net_dict)
        # self.w_input = self.net_dict['input_conn_params']['JE']
        self.w_input = self.net_dict['input_conn_params'][
            'JE'] * self.net_dict['neuron_params'][
                'tau_syn_ex'] / self.net_dict['neuron_params']['C_m'] * 1e6
        print('w_input', self.w_input)
        # if self.net_dict['poisson_input']:
        #     self.DC_amp_e = np.zeros(len(self.net_dict['populations']))
        # else:
        #     if nest.Rank() == 0:
        #         print(
        #             '''
        #             no poisson input provided
        #             calculating dc input to compensate
        #             '''
        #             )
        self.DC_amp_e = compute_DC(self.net_dict,
                                   self.w_ext)  # always use external input

        if self.net_dict['poisson_input'] or self.net_dict[
                'poisson_pool_input'] or self.net_dict['network_input']:
            KE_ext = self.K_ext * self.net_dict['input_conn_params']['gamma']
            KI_ext = self.K_ext * (1. -
                                   self.net_dict['input_conn_params']['gamma'])
            # if self.net_dict['network_input']:
            offset = KE_ext * self.w_input * self.net_dict['network_rate'] * self.net_dict['neuron_params']['tau_syn_ex'] + \
                     -1. * KI_ext * self.net_dict['input_conn_params']['g'] * self.w_input * self.net_dict['network_rate'] * self.net_dict['neuron_params']['tau_syn_in']
            # else:
            #     offset = KE_ext * JE_ext * self.net_dict['bg_rate'] * self.net_dict['neuron_params']['tau_syn_ex'] + \
            #              -1. * KI_ext * JI_ext * self.net_dict['bg_rate'] * self.net_dict['neuron_params']['tau_syn_in']
            # print(self.DC_amp_e, offset * 1e-3)
            # exit()
            self.DC_amp_e -= (offset * 1e-3)

        if nest.Rank() == 0:
            print('The number of neurons is scaled by a factor of: %.2f' %
                  self.N_scaling)
            print('The number of synapses is scaled by a factor of: %.2f' %
                  self.K_scaling)

        # Scaling of the synapses.
        if self.K_scaling != 1:
            synapses_indegree = self.synapses / (
                self.N_full.reshape(len(self.N_full), 1) * self.N_scaling)
            self.weight_mat, self.w_ext, self.DC_amp_e = adj_w_ext_to_K(
                synapses_indegree, self.K_scaling, self.weight_mat,
                self.w_from_PSP, self.DC_amp_e, self.net_dict, self.stim_dict)

        # Create cortical populations.
        self.pops = []
        pop_file = open(os.path.join(self.data_path, 'population_GIDs.dat'),
                        'w+')
        for i, pop in enumerate(self.net_dict['populations']):
            population = nest.Create(self.net_dict['neuron_model'],
                                     int(self.nr_neurons[i]))
            nest.SetStatus(
                population, {
                    'tau_syn_ex': self.net_dict['neuron_params']['tau_syn_ex'],
                    'tau_syn_in': self.net_dict['neuron_params']['tau_syn_in'],
                    'E_L': self.net_dict['neuron_params']['E_L'],
                    'V_th': self.net_dict['neuron_params']['V_th'],
                    'V_reset': self.net_dict['neuron_params']['V_reset'],
                    't_ref': self.net_dict['neuron_params']['t_ref'],
                    'I_e': self.DC_amp_e[i]
                })
            self.pops.append(population)
            pop_file.write('%d  %d \n' % (population[0], population[-1]))
        pop_file.close()
        for thread in np.arange(nest.GetKernelStatus('local_num_threads')):
            # Using GetNodes is a work-around until NEST 3.0 is released. It
            # will issue a deprecation warning.
            local_nodes = nest.GetNodes([0], {
                'model': self.net_dict['neuron_model'],
                'thread': thread
            },
                                        local_only=True)[0]
            vp = nest.GetStatus(local_nodes)[0]['vp']
            # vp is the same for all local nodes on the same thread
            nest.SetStatus(
                local_nodes, 'V_m', self.pyrngs[vp].normal(
                    self.net_dict['neuron_params']['V0_mean'],
                    self.net_dict['neuron_params']['V0_sd'], len(local_nodes)))
Beispiel #16
0
 def _set_initial_value_array(self, variable, value):
     local_value = value.evaluate(simplify=True)
     nest.SetStatus(self.nest_connections, variable, local_value)
Beispiel #17
0
"""Init File. Imports nest and sets up a poisson generator, neuron, and voltmeter"""

import nest
import nest.voltage_trace

nest.set_verbosity("M_WARNING")
nest.ResetKernel()

neuron = nest.Create("iaf_psc_alpha")
noise = nest.Create("poisson_generator", 2)
voltmeter = nest.Create("voltmeter")

nest.SetStatus(noise, {"rate": 80000.0, "rate": 15000.0})

nest.Connect(noise, neuron, syn_spec={'weight': [[1.2, -1.0]], 'delay': 1.0})
nest.Connect(voltmeter, neuron)
Beispiel #18
0
def runNetwork(wf=0.5, ws=0.5, wpfc=0.5, seed_mice=0, w_inc_pfc_i=0.5, weight_gain_i=30, w_io_bf_i=500., w_io_bs_i=500., w_cs_stim=0.5, w_inc_pfc_i_nsp=0.00001, weight_k_increment_i_s=0.00001, weight_k_increment_i_f=0.00001, Ie_pfc_random = 370., Ie_m1_random = 370.,  w_n_nd_f_to_n_m1 = 100., w_n_nd_s_to_n_pfc=100.): 
    #==============================================================================
    #     ISI - interstimulus interval - the time distance in ms between GC spikes and IO spikes
    #     wf - weight fast line
    #     ws- weight slow line
    #     wpfc- weight pfc to m1
    #     seed_mice - seed
    #     w_inc_pfc_i - weigth incrementi pfc to m1
    #     w_inc_pfc_i_nsp=  weigth incrementi pfc to m1 no spike
    #     weight_k_increment_i_s weigth increment gc -> pj slow
    #     weight_k_increment_i_f weigth increment gc -> pj fast
    #     weight_gain_i- correction kernel
    #     w_io_bf_i weight io on purkinje fast line
    #     w_io_bs_i weight io on purkinje slow line 
    #     w_cs_stim weight Mossy fiber(stim) to Dentate Nucleus
    #==============================================================================
  
    #==============================================================================
    # Setup Parameters 
    #==============================================================================
    
    
    print ("EXP ---- W_FAST ----- >>>>> " + str(wf))
    print ("EXP ---- W_SLOW ----- >>>>> " + str(ws))
    print ("EXP ---- W_PFC ----- >>>>> " + str(wpfc))
        
    
    nt.ResetKernel() # reset nest
    nt.SetKernelStatus({'grng_seed': seed_mice})
    nt.SetKernelStatus({"local_num_threads": 4})
                
    #number of neuron test                                                     
    nNeuronGR_Fast = 512
    nNeuronGR_Slow = 512
    
    nNeuronPJ_Fast = 16 
    nNeuronPJ_Slow = 16   

    nNeuronND_Fast = 8 
    nNeuronND_Slow = 8 

    nNeuronIO_Fast = 16
    nNeuronIO_Slow = 16

    nNeuronM1 = 8
    nNeuronPFC =8
    
               
    # neuron type
    neuron_Type= 'iaf_psc_alpha'

    ISI = 250
    wnd=0.40 # kernel window
    version = 10    
    start_network = datetime.datetime.today() #start elaboration time
   
    #loop parameter
    dcfrom = 0 #start
    dcstep = 10 #rate
    dcto = 2500 #end
    
    weight_k_increment_pfc_to_m1 = w_inc_pfc_i #costant increment weight pfc to m1
    weight_k_increment_pfc_to_m1_no_spike =  w_inc_pfc_i_nsp
    weight_k_increment_s = weight_k_increment_i_s #costant increment weight Granular cells to PJ
    weight_k_increment_f = weight_k_increment_i_f #costant increment weight Granular cells to PJ
    
    weight_gain= weight_gain_i #normalization parallel fiber
    sum_w_fast=sum_w_slow=sum_w_pfc= 0
    
    # Initialization w
    wi_af_bf = wf
    wi_as_bs = ws
    wi_pfc_m1 = wpfc                
    w_io_bf = w_io_bf_i
    w_io_bs = w_io_bs_i
    
    #variables
    w_fast=[]
    w_slow=[]
    t_chart_fast= []
    w_chart_fast= []
    t_chart_slow= []
    w_chart_slow= []
    t_chart_pfc= []
    w_chart_pfc= []
    w_pfc_to_m1=[]
    w_pfc_to_m1_no_spike=[]
    buffer_kernel_k_fast=[]
    buffer_kernel_t_fast=[]
    buffer_kernel_k_slow=[]
    buffer_kernel_t_slow=[]
    spike_pfc_count=[]
    spike_io_count_f = 0
    spike_io_count_s = 0
    spike_pj_count_f=0
    spike_pj_count_s=0
    spike_pfc_count=0
    spike_m1_count=0    
     
    def generateSpikeTrainIO(step=10, start=1050+ISI, dStim=20, isiStim=530, sTrain=2500):         
         # Train of impulse on IO  
        s_io= []
        for i in range(sTrain/isiStim) :    
             s_io += SpikeGenerator(map(float,(range(start, start+dStim, step))))
             start += isiStim+dStim    
        return s_io
         
    
    def generateSpikeTrainGR(step=10, start=1000, dStim=50, isiStim=500, sTrain=2500):         
         # Train of impulse on Granular Cells CS         
        s_gr= []
        for i in range(sTrain/isiStim) :    
             s_gr += SpikeGenerator(map(float,(range(start, start+dStim, step))))
             start += isiStim+dStim    
        return s_gr
        
    s_io = generateSpikeTrainIO()
    
    s_gc = generateSpikeTrainGR()
    
    #single shot CS
    s_gc_base = generateSpikeTrainGR(10, 100, 50, 500, 600)
     
    noise_in = nt.Create("poisson_generator")
    nt.SetStatus(noise_in, {"rate": 2500.0, "start": 1., "stop": 2500.})
    
   
    # Spike detectors
    spike_det_gc_f = nt.Create("spike_detector")
    spike_det_gc_s = nt.Create("spike_detector")
    spike_det_nb_f = nt.Create("spike_detector")
    spike_det_nb_s = nt.Create("spike_detector")    
    spike_det_nio_f = nt.Create("spike_detector")
    spike_det_nio_s = nt.Create("spike_detector")
    spike_det_m1 = nt.Create("spike_detector")
    spike_det_pfc = nt.Create("spike_detector")
    
    # Voltmeters granular cells
    vm_gc_f = nt.Create('voltmeter', params={'to_file': False, 'withgid': True, 'withtime': True, 'interval': 0.1})
    nt.SetStatus(vm_gc_f, {'n_events': 0})
    vm_gc_s = nt.Create('voltmeter', params={'to_file': False, 'withgid': True, 'withtime': True, 'interval': 0.1})
    nt.SetStatus(vm_gc_s, {'n_events': 0})

    # Voltmeters purkinje cells
    vm_pjf = nt.Create('voltmeter', params={'to_file': False, 'withgid': True, 'withtime': True, 'interval': 0.1})
    nt.SetStatus(vm_pjf, {'n_events': 0})

    vm_pjL = nt.Create('voltmeter', params={'to_file': False, 'withgid': True, 'withtime': True, 'interval': 0.1})
    nt.SetStatus(vm_pjL, {'n_events': 0})
    
    #==============================================================================
    # Create nodes 
    #==============================================================================
    
    # Granular Cells
    n_a_f = nt.Create(neuron_Type, nNeuronGR_Fast)
    n_a_s = nt.Create(neuron_Type, nNeuronGR_Slow)
    nt.SetStatus(n_a_f,  {'I_e': 370.0, "tau_m": 10., "V_th": -55.0})
    nt.SetStatus(n_a_s,  {'I_e': 370.0, "tau_m": 10., "V_th": -55.0})

    #Purkinje
    n_b_f = nt.Create(neuron_Type, nNeuronPJ_Fast)
    n_b_s = nt.Create(neuron_Type, nNeuronPJ_Slow)
    nt.SetStatus(n_b_f,  {'I_e': 380.0, "tau_m": 10.0, "V_th": -55.0})	
    nt.SetStatus(n_b_s,  {'I_e': 380.0, "tau_m": 10.0, "V_th": -55.0})
    
    # Inferior Olive
    n_io_f = nt.Create(neuron_Type, nNeuronIO_Fast)
    n_io_s = nt.Create(neuron_Type, nNeuronIO_Slow)
    nt.SetStatus(n_io_f,  {'I_e': 370.0, "tau_m": 10.0, "V_th": -55.0})
    nt.SetStatus(n_io_s,  {'I_e': 370.0, "tau_m": 10.0, "V_th": -55.0})
    
    # Dentate Nucleus
    n_nd_f = nt.Create(neuron_Type, nNeuronND_Fast)
    n_nd_s = nt.Create(neuron_Type, nNeuronND_Slow)
    nt.SetStatus(n_nd_f,  {'I_e': 370.0, "tau_m": 10.0, "V_th": -55.0})
    nt.SetStatus(n_nd_s,  {'I_e': 370.0, "tau_m": 10.0, "V_th": -55.0})
    
    # Motor primary cortex
    n_m1 = nt.Create(neuron_Type, nNeuronM1)
    nt.SetStatus(n_m1,  {'I_e': Ie_m1_random, "tau_m": 10. , "V_th": -55.0})
    
    # prefrontal cortex
    n_pfc = nt.Create(neuron_Type, nNeuronPFC)
    nt.SetStatus(n_pfc,  {'I_e': Ie_pfc_random , "tau_m": 10., "V_th": -55.0})
    
    
    #==============================================================================
    # Connections
    #==============================================================================
      
    nt.Connect(s_gc, n_a_f, syn_spec={'model': 'static_synapse', 'weight': 500.}) #CS to GCf
    nt.Connect(s_gc, n_a_s, syn_spec={'model': 'static_synapse', 'weight': 500.}) #CS to GCs
    nt.Connect(s_gc, n_nd_f, syn_spec={'model': 'static_synapse', 'weight': w_cs_stim})  #CS to ND
    nt.Connect(s_gc, n_nd_s, syn_spec={'model': 'static_synapse', 'weight': w_cs_stim})  #CS to ND

    nt.Connect(s_gc_base, n_a_f, syn_spec={'model': 'static_synapse', 'weight': 500.}) #CS to GCf
    nt.Connect(s_gc_base, n_a_s, syn_spec={'model': 'static_synapse', 'weight': 500.}) #CS to GCs   
    nt.Connect(s_gc_base, n_nd_f, syn_spec={'model': 'static_synapse', 'weight': w_cs_stim})  #CS to ND
    nt.Connect(s_gc_base, n_nd_s, syn_spec={'model': 'static_synapse', 'weight': w_cs_stim})  #CS to ND
    
    nt.Connect(s_io, n_io_f, syn_spec={'model': 'static_synapse', 'weight': 100.}) #US to IO
    nt.Connect(s_io, n_io_s, syn_spec={'model': 'static_synapse', 'weight': 100.}) #US to IO
    nt.Connect(n_io_f, n_b_f, 'one_to_one', syn_spec={'model': 'static_synapse', 'weight': w_io_bf}) #IO to PJ
    nt.Connect(n_io_s, n_b_s, 'one_to_one', syn_spec={'model': 'static_synapse', 'weight': w_io_bs}) #IO to PJ 
    nt.Connect(n_io_f, n_nd_f, syn_spec={'model': 'static_synapse', 'weight': 60.}) #Io to ND 
    nt.Connect(n_io_s, n_nd_s, syn_spec={'model': 'static_synapse', 'weight': 60.}) #Io to ND 
    
    # Connect PJ to ND divide by 2
    nt.Connect(n_b_f, n_nd_f, syn_spec={'model': 'static_synapse', 'weight': -7})
    nt.Connect(n_b_s, n_nd_s, syn_spec={'model': 'static_synapse', 'weight': -7})  
    
    nt.Connect(n_nd_f, n_m1, syn_spec={'model': 'static_synapse', 'weight': w_n_nd_f_to_n_m1 }) #w dentate nucleus to m1 and pfc
    nt.Connect(n_nd_s, n_pfc, syn_spec={'model': 'static_synapse', 'weight': w_n_nd_s_to_n_pfc }) #w dentate nucleus to m1 and pfc
    nt.Connect(noise_in, n_nd_f, syn_spec={'model': 'static_synapse', 'weight': round(random.uniform(0.1, 0.5), 2)}) #w dentate nucleus to m1 and pfc	
    nt.Connect(noise_in, n_nd_s, syn_spec={'model': 'static_synapse', 'weight': round(random.uniform(0.1, 0.5), 2)}) #w dentate nucleus to m1 and pfc
 
    
    # Connect voltimeters to neurons
    nt.Connect(vm_gc_f, n_a_f, 'all_to_all')
    nt.Connect(vm_gc_s, n_a_s, 'all_to_all')
    nt.Connect(vm_pjf, n_b_f, 'all_to_all') #purkinie line fast
    nt.Connect(vm_pjL, n_b_s, 'all_to_all') #purkinie line slow

    # Connect spike detector to neurons   
    nt.Connect(n_a_f, spike_det_gc_f)    
    nt.Connect(n_a_s, spike_det_gc_s)
    nt.Connect(n_b_f, spike_det_nb_f)
    nt.Connect(n_b_s, spike_det_nb_s)
    nt.Connect(n_io_f, spike_det_nio_f)
    nt.Connect(n_io_s, spike_det_nio_s)
    nt.Connect(n_m1, spike_det_m1)
    nt.Connect(n_pfc, spike_det_pfc)
    
    #==============================================================================
    # Loop
    #==============================================================================
    for i, sim in enumerate(range(dcfrom, dcto, dcstep)):
    
        # Membrane potential and time Granular Cells Fast
        t_gc_f = nt.GetStatus(vm_gc_f, 'events')[0]['times']
        v_gc_f = nt.GetStatus(vm_gc_s, 'events')[0]['V_m']
        
        # Membrane potential and time Granular Cells Slow
        t_gc_s = nt.GetStatus(vm_gc_f, 'events')[0]['times']
        v_gc_s = nt.GetStatus(vm_gc_s, 'events')[0]['V_m']
        
        # Membrane potential and time putkinje line fast
        t_pjf = nt.GetStatus(vm_pjf, 'events')[0]['times']
        v_pjf = nt.GetStatus(vm_pjf, 'events')[0]['V_m']
        
        # Membrane potential and time putkinje line fast
        t_pjL = nt.GetStatus(vm_pjL, 'events')[0]['times']
        v_pjL = nt.GetStatus(vm_pjL, 'events')[0]['V_m']
                    
        dSD_gc_f = nt.GetStatus(spike_det_gc_f, keys="events")[0]
        evs_gc_f = dSD_gc_f["senders"]
        ts_gc_f = dSD_gc_f["times"]
 
        dSD_gc_s = nt.GetStatus(spike_det_gc_s, keys="events")[0]
        evs_gc_s = dSD_gc_s["senders"]
        ts_gc_s = dSD_gc_s["times"]       
            
        # Spike Purkinje Cells
        dSD_b_f = nt.GetStatus(spike_det_nb_f, keys="events")[0]
        evs_b_f = dSD_b_f["senders"]
        ts_b_f = dSD_b_f["times"]    
                                
        dSD_b_s = nt.GetStatus(spike_det_nb_s, keys="events")[0]
        evs_b_s = dSD_b_s["senders"]
        ts_b_s = dSD_b_s["times"]
    
        # Spike Inferior Olive
        dSD_io_f = nt.GetStatus(spike_det_nio_f, keys="events")[0]
        evs_io_f = dSD_io_f["senders"]
        ts_io_f = dSD_io_f["times"]
    
        # Spike Inferior Olive
        dSD_io_s = nt.GetStatus(spike_det_nio_s, keys="events")[0]
        evs_io_s = dSD_io_s["senders"]
        ts_io_s = dSD_io_s["times"]
  
    
        # Spike M1
        dSD_m1 = nt.GetStatus(spike_det_m1, keys="events")[0]
        evs_m1 = dSD_m1["senders"]
        ts_m1 = dSD_m1["times"]
    
        # Spike pfC
        dSD_pfc = nt.GetStatus(spike_det_pfc, keys="events")[0]
        evs_pfc = dSD_pfc["senders"]
        ts_pfc = dSD_pfc["times"]
        

        ####################################################
        #################### LINE FAST ####################
        ####################################################
    
        if len(evs_gc_f) >=1 :
            #print ("LF1")

     
            # Record all time Spike of Granular Cells
            tm_f = np.unique(ts_gc_f*0.001)
        
            # Time Spike Inferior Olive e Purkinje
            TIO_f =  (float(nt.GetStatus(n_io_f, 't_spike')[0])*0.001)
            TPJ_f =  (float(nt.GetStatus(n_b_f, 't_spike')[0])*0.001) 
                                
                                    
            # If inferior olive send a Spike
            if  np.count_nonzero(evs_io_f) > spike_io_count_f:
                
                # Current number spike of inferior olive 
                spike_io_count_f = np.count_nonzero(evs_io_f)
                
    
                # For each Granular spike in the interval between TIO and TIO-tm_i
                for tm_i in tm_f:
             
                    if (TIO_f - tm_i) <= wnd :
                       
                        # Calculate the time in the range -800 / 0
                        window_tm_f = window(TIO_f, tm_i)

                        # Create an array of weights calculated with the kernel fast
                        w_fast.append(kernel_fast(window_tm_f))
                                  
                        # Parameters for the chart fast
                        buffer_kernel_k_fast.append(kernel_fast(window_tm_f))
                        buffer_kernel_t_fast.append(window_tm_f)
    
    
            for tm_i in tm_f:
            
               # If pj f send a Spike
               if  np.count_nonzero(evs_b_f) > spike_pj_count_f:
    
                   # Current number spike of pj f
                   spike_pj_count_f = np.count_nonzero(evs_b_f)
     
                   if (m.fabs(TPJ_f-tm_i) > wnd and (sum_w_fast <= wi_af_bf)) : w_fast.append(-weight_k_increment_f)                          
          
                 



        ####################################################
        #################### LINE SLOW ####################
        ####################################################
    
        if len(evs_gc_s) >=1 :
                                      
            # Record all time Spike of Granular Cells
            tm_s = np.unique(ts_gc_s*0.001)
        
            # Time Spike Inferior Olive e Purkinje
            TIO_s =  (float(nt.GetStatus(n_io_s, 't_spike')[0])*0.001)
            TPJ_s =  (float(nt.GetStatus(n_b_s, 't_spike')[0])*0.001) 
                                    
                                    
            # If inferior olive send a Spike
            if  np.count_nonzero(evs_io_s) > spike_io_count_s:
                
                # Current number spike of inferior olive 
                spike_io_count_s = np.count_nonzero(evs_io_s)
                
    
                # For each Granular spike in the interval between TIO and TIO-tm_i
                for tm_i in tm_s:
                    
        
                    if (TIO_s - tm_i) <= wnd :
                        
        
                        # Calculate the time in the range
                        window_tm_s = window(TIO_s, tm_i)
                                                             
                        # Create an array of weights calculated with the kernel slow
                        w_slow.append(kernel_slow(window_tm_s))
                                    
                        # Parameters for the chart slow
                        buffer_kernel_k_slow.append(kernel_slow(window_tm_s))
                        buffer_kernel_t_slow.append(window_tm_s)
    
            for tm_i in tm_s:
    
               # If pj s send a Spike
               if  np.count_nonzero(evs_b_s) > spike_pj_count_s:
    
                   # Current number spike of pj s
                   spike_pj_count_s = np.count_nonzero(evs_b_s)
                
                   if (m.fabs(TPJ_s-tm_i) > wnd and (sum_w_slow <= wi_as_bs)) : w_slow.append(-weight_k_increment_s)                               
                    

              
        #if sum_w_fast <= wi_af_bf  : w_fast.append(-weight_k_increment) # Costant inccreaase weight if sum_w_fast <= wi_af_bf
        sum_w_fast = wi_af_bf - (sum(w_fast) *  weight_gain)

        
    
        #if sum_w_slow <= wi_as_bs : w_slow.append(-weight_k_increment) #costant increaase weight
        sum_w_slow = wi_as_bs - (sum(w_slow) * weight_gain)
        
        
                                
        #weight chart
        t_chart_fast.append(i)
        w_chart_fast.append(sum_w_fast)
        t_chart_slow.append(i)
        w_chart_slow.append(sum_w_slow)
                                
        # If pfc  send a Spike
        TM1 = np.array(nt.GetStatus(spike_det_m1, keys="events")[0]["times"])[-1:]*0.001   
        TPFC = np.array(nt.GetStatus(spike_det_pfc, keys="events")[0]["times"])[-1:]*0.001      
    
        if (np.count_nonzero(evs_pfc) > spike_pfc_count) and (np.count_nonzero(evs_m1) > spike_m1_count) and m.fabs(TM1-TPFC) < 0.40:
             spike_pfc_count = np.count_nonzero(evs_pfc)
             spike_m1_count = np.count_nonzero(evs_m1)                     
             w_pfc_to_m1.append(weight_k_increment_pfc_to_m1) #incrementare weight on array pfc 
        else:
            if  np.count_nonzero(evs_m1) > spike_m1_count:
                w_pfc_to_m1_no_spike.append(weight_k_increment_pfc_to_m1_no_spike)
                spike_m1_count = np.count_nonzero(evs_m1)
            
            
        sum_w_pfc=wi_pfc_m1 + sum(w_pfc_to_m1) - sum(w_pfc_to_m1_no_spike) # Sum array weigth
                                
        t_chart_pfc.append(i)
        w_chart_pfc.append(sum_w_pfc)
    
        syn_dict_fast= {"model": "static_synapse", "weight": sum_w_fast}
        syn_dict_slow = {"model": "static_synapse", "weight": sum_w_slow}
        syn_dict_pfc_to_m1 = {"model": "static_synapse", "weight": sum_w_pfc} #peso tra pfc e m1
    
        #  Connect GRf to PJs
        nt.Connect(n_a_f, n_b_f, syn_spec=syn_dict_fast)
        # Connect GRs to PJs
        nt.Connect(n_a_s, n_b_s, syn_spec=syn_dict_slow)
        # Connect pfc to m1
        nt.Connect(n_pfc, n_m1, syn_spec=syn_dict_pfc_to_m1)
            
        nt.Simulate(dcstep) #12/01 inserito la variabile step invece del valore fisso 1
    
     
    
    obj_returned={"timesSpikeGC_f":ts_gc_f,"sendersGC_f":evs_gc_f,
                  "timesSpikeGC_s":ts_gc_s,"sendersGC_s":evs_gc_s,
                  "potentialGC_f":np.array(v_gc_f, dtype=float),
                  "tPotentialGC_f":np.array(t_gc_f, dtype=float),
                  "potentialGC_s":np.array(v_gc_s, dtype=float),
                  "tPotentialGC_s":np.array(t_gc_s, dtype=float),                  
                  "timesSpikePjF":ts_b_f,"sendersPjF":evs_b_f, 
                  "timesSpikePjS": ts_b_s, "sendersPjS":evs_b_s, 
                  "timesSpikeIO_f": ts_io_f, "sendersIO_f":evs_io_f,
                  "timesSpikeIO_s": ts_io_s, "sendersIO_s":evs_io_s, 
                  "timesSpikeM1": ts_m1, "timesSpikePFC": ts_pfc, 
                  "timesSpikeStartNetwork": start_network,
                  "tw_chart_fast": t_chart_fast, "w_chart_fast": w_chart_fast,
                  "tw_chart_slow": t_chart_slow, "w_chart_slow": w_chart_slow,
                  "t_chart_pfc": t_chart_pfc, "w_chart_pfc": w_chart_pfc, 
                  "senderM1": evs_m1, "senderPFC": evs_pfc,
                  "potentialPjA":np.array(v_pjf, dtype=float),
                  "tPotentialPjA":np.array(t_pjf, dtype=float),
                  "potentialPjL":np.array(v_pjL, dtype=float),
                  "tPotentialPjL":np.array(t_pjL, dtype=float)}
                  

    return  obj_returned
nodes_E = nodes[:N_E]
nodes_I = nodes[N_E:]

noise = nest.Create('poisson_generator', 1, {'rate': p_rate})

spikes = nest.Create('spike_detector', 2,
                     [{'label': 'brunel_py_ex', 'to_file': data2file},
                      {'label': 'brunel_py_in', 'to_file': data2file}])
spikes_E = spikes[:1]
spikes_I = spikes[1:]

# randomize membrane potential
node_info = nest.GetStatus(nodes, ['global_id', 'vp', 'local'])
local_nodes = [(gid, vp) for gid, vp, islocal in node_info if islocal]
for gid, vp in local_nodes:
    nest.SetStatus([gid], {'V_m': pyrngs[vp].uniform(-V_th, V_th)})

# Connect nodes ------------------------------------------------

# We create a plastic excitatory synapse model for the
# excitatory-excitatory weights and a static excitatory model for
# the excitatory-inhibitory weights
nest.CopyModel('stdp_synapse_hom',
               'excitatory_plastic',
               {'alpha': STDP_alpha,
                'Wmax': STDP_Wmax})

nest.CopyModel('static_synapse', 'excitatory_static')

# weights are drawn at random while connecting
nest.Connect(nodes_E, nodes_E,
def simulate():
    '''instantiate and execute network simulation'''
    #separate model execution from parameters for safe import from other files
    nest.ResetKernel()
    '''
    Configuration of the simulation kernel by the previously defined time
    resolution used in the simulation. Setting "print_time" to True prints
    the already processed simulation time as well as its percentage of the
    total simulation time.
    '''

    nest.SetKernelStatus({
        "resolution": dt,
        "print_time": True,
        "overwrite_files": True
    })

    print("Building network")
    '''
    Configuration of the model `iaf_psc_alpha` and `poisson_generator`
    using SetDefaults(). This function expects the model to be the
    inserted as a string and the parameter to be specified in a
    dictionary. All instances of theses models created after this point
    will have the properties specified in the dictionary by default.
    '''

    nest.SetDefaults("iaf_psc_alpha", neuron_params)
    nest.SetDefaults("poisson_generator", {"rate": p_rate})
    '''
    Creation of the nodes using `Create`. We store the returned handles in
    variables for later reference. Here the excitatory and inhibitory, as
    well as the poisson generator and two spike detectors. The spike
    detectors will later be used to record excitatory and inhibitory
    spikes.
    '''

    nodes_ex = nest.Create("iaf_psc_alpha", NE)
    nodes_in = nest.Create("iaf_psc_alpha", NI)
    noise = nest.Create("poisson_generator")
    espikes = nest.Create("spike_detector")
    ispikes = nest.Create("spike_detector")

    print("first exc node: {}".format(nodes_ex[0]))
    print("first inh node: {}".format(nodes_in[0]))
    '''
    distribute membrane potentials
    '''
    nest.SetStatus(nodes_ex, "V_m",
                   random.rand(len(nodes_ex)) * neuron_params["V_th"])
    nest.SetStatus(nodes_in, "V_m",
                   random.rand(len(nodes_in)) * neuron_params["V_th"])
    '''
    Configuration of the spike detectors recording excitatory and
    inhibitory spikes using `SetStatus`, which expects a list of node
    handles and a list of parameter dictionaries. Setting the variable
    "to_file" to True ensures that the spikes will be recorded in a .gdf
    file starting with the string assigned to label. Setting "withtime"
    and "withgid" to True ensures that each spike is saved to file by
    stating the gid of the spiking neuron and the spike time in one line.
    '''

    nest.SetStatus(espikes,
                   [{
                       "label": os.path.join(spike_output_path, label + "-EX"),
                       "withtime": True,
                       "withgid": True,
                       "to_file": True,
                   }])

    nest.SetStatus(ispikes,
                   [{
                       "label": os.path.join(spike_output_path, label + "-IN"),
                       "withtime": True,
                       "withgid": True,
                       "to_file": True,
                   }])

    print("Connecting devices")
    '''
    Definition of a synapse using `CopyModel`, which expects the model
    name of a pre-defined synapse, the name of the customary synapse and
    an optional parameter dictionary. The parameters defined in the
    dictionary will be the default parameter for the customary
    synapse. Here we define one synapse for the excitatory and one for the
    inhibitory connections giving the previously defined weights and equal
    delays.
    '''

    nest.CopyModel("static_synapse", "excitatory", {
        "weight": J_ex,
        "delay": delay
    })
    nest.CopyModel("static_synapse", "inhibitory", {
        "weight": J_in,
        "delay": delay
    })
    '''
    Connecting the previously defined poisson generator to the excitatory
    and inhibitory neurons using the excitatory synapse. Since the poisson
    generator is connected to all neurons in the population the default
    rule ('all_to_all') of Connect() is used. The synaptic properties are
    inserted via syn_spec which expects a dictionary when defining
    multiple variables or a string when simply using a pre-defined
    synapse.
    '''

    if Poisson:
        nest.Connect(noise, nodes_ex, 'all_to_all', "excitatory")
        nest.Connect(noise, nodes_in, 'all_to_all', "excitatory")
    '''
    Connecting the first N_neurons nodes of the excitatory and inhibitory
    population to the associated spike detectors using excitatory
    synapses. Here the same shortcut for the specification of the synapse
    as defined above is used.
    '''

    nest.Connect(nodes_ex, espikes, 'all_to_all', "excitatory")
    nest.Connect(nodes_in, ispikes, 'all_to_all', "excitatory")

    print("Connecting network")

    print("Excitatory connections")
    '''
    Connecting the excitatory population to all neurons using the
    pre-defined excitatory synapse. Beforehand, the connection parameter
    are defined in a dictionary. Here we use the connection rule
    'fixed_indegree', which requires the definition of the indegree. Since
    the synapse specification is reduced to assigning the pre-defined
    excitatory synapse it suffices to insert a string.
    '''

    conn_params_ex = {'rule': 'fixed_indegree', 'indegree': CE}
    nest.Connect(nodes_ex, nodes_ex + nodes_in, conn_params_ex, "excitatory")

    print("Inhibitory connections")
    '''
    Connecting the inhibitory population to all neurons using the
    pre-defined inhibitory synapse. The connection parameter as well as
    the synapse paramtere are defined analogously to the connection from
    the excitatory population defined above.
    '''

    conn_params_in = {'rule': 'fixed_indegree', 'indegree': CI}
    nest.Connect(nodes_in, nodes_ex + nodes_in, conn_params_in, "inhibitory")
    '''
    Storage of the time point after the buildup of the network in a
    variable.
    '''

    endbuild = time.time()
    '''
    Simulation of the network.
    '''

    print("Simulating")

    nest.Simulate(simtime)
    '''
    Storage of the time point after the simulation of the network in a
    variable.
    '''

    endsimulate = time.time()
    '''
    Reading out the total number of spikes received from the spike
    detector connected to the excitatory population and the inhibitory
    population.
    '''

    events_ex = nest.GetStatus(espikes, "n_events")[0]
    events_in = nest.GetStatus(ispikes, "n_events")[0]
    '''
    Calculation of the average firing rate of the excitatory and the
    inhibitory neurons by dividing the total number of recorded spikes by
    the number of neurons recorded from and the simulation time. The
    multiplication by 1000.0 converts the unit 1/ms to 1/s=Hz.
    '''

    rate_ex = events_ex / simtime * 1000.0 / N_neurons
    rate_in = events_in / simtime * 1000.0 / N_neurons
    '''
    Reading out the number of connections established using the excitatory
    and inhibitory synapse model. The numbers are summed up resulting in
    the total number of synapses.
    '''

    num_synapses = nest.GetDefaults("excitatory")["num_connections"]+\
    nest.GetDefaults("inhibitory")["num_connections"]
    '''
    Establishing the time it took to build and simulate the network by
    taking the difference of the pre-defined time variables.
    '''

    build_time = endbuild - startbuild
    sim_time = endsimulate - endbuild
    '''
    Printing the network properties, firing rates and building times.
    '''

    print("Brunel network simulation (Python)")
    print("Number of neurons : {0}".format(N_neurons))
    print("Number of synapses: {0}".format(num_synapses))
    print("       Exitatory  : {0}".format(int(CE * N_neurons) + N_neurons))
    print("       Inhibitory : {0}".format(int(CI * N_neurons)))
    print("Excitatory rate   : %.2f Hz" % rate_ex)
    print("Inhibitory rate   : %.2f Hz" % rate_in)
    print("Building time     : %.2f s" % build_time)
    print("Simulation time   : %.2f s" % sim_time)
    '''
    Plot a raster of the excitatory neurons and a histogram.
    '''

    if False:
        nest.raster_plot.from_device(espikes, hist=True)
        nest.raster_plot.from_device(ispikes, hist=True)
        nest.raster_plot.show()
def test(referenceModel, testant, gsl_error_tol, tolerance=0.000001):

    spike_times = [100.0, 200.0]
    spike_weights = [1., -1.]

    nest.ResetKernel()
    neuron1 = nest.Create(referenceModel)
    neuron2 = nest.Create(testant)

    if not (gsl_error_tol is None):
        nest.SetStatus(neuron2, {"gsl_error_tol": gsl_error_tol})

    spikegenerator = nest.Create('spike_generator',
                                 params={
                                     'spike_times': spike_times,
                                     'spike_weights': spike_weights
                                 })

    nest.Connect(spikegenerator, neuron1)
    nest.Connect(spikegenerator, neuron2)

    multimeter1 = nest.Create('multimeter')
    multimeter2 = nest.Create('multimeter')

    V_m_specifier = 'V_m'  # 'delta_V_m'
    nest.SetStatus(multimeter1, {
        "withtime": True,
        "record_from": [V_m_specifier]
    })
    nest.SetStatus(multimeter2, {
        "withtime": True,
        "record_from": [V_m_specifier]
    })

    nest.Connect(multimeter1, neuron1)
    nest.Connect(multimeter2, neuron2)

    nest.Simulate(400.0)
    dmm1 = nest.GetStatus(multimeter1)[0]
    Vms1 = dmm1["events"][V_m_specifier]
    ts1 = dmm1["events"]["times"]

    dmm2 = nest.GetStatus(multimeter2)[0]
    Vms2 = dmm2["events"][V_m_specifier]
    ts2 = dmm2["events"]["times"]

    if TEST_PLOTS:
        fig, ax = plt.subplots(2, 1)
        ax[0].plot(ts1, Vms1, label="Reference " + referenceModel)
        ax[1].plot(ts2, Vms2, label="Testant " + testant)
        for _ax in ax:
            _ax.legend(loc='upper right')
            _ax.grid()
        plt.savefig("/tmp/nestml_nest_integration_test_[" + referenceModel +
                    "]_[" + testant + "].png")

    for index in range(0, len(Vms1)):
        if abs(Vms1[index] - Vms2[index]) > tolerance \
         or np.isnan(Vms1[index]) \
         or np.isnan(Vms2[index]):
            print(
                str(Vms1[index]) + " differs from  " + str(Vms2[index]) +
                " at iteration: " + str(index) + " of overall iterations: " +
                str(len(Vms1)))
            raise Exception(testant + ": TEST FAILED")

    print(testant + " PASSED")
nest.Connect(pg,
             neurons,
             'all_to_all',
             syn_spec={
                 'model': 'static_synapse',
                 'weight': j_exc,
                 'delay': delay
             })
"""
Then the neurons are connected to the `spike_detector` and the initial
membrane potential of each neuron is set randomly between -40 and -80 mV.
"""
nest.Connect(neurons, sd)

for i in range(n_neuron):
    nest.SetStatus([neurons[i]], {'V_m': (-40. - 40. * random.random())})
"""
Finally gap junctions are added to the network.
(60*500)/2 `gap_junction` connections are added randomly
resulting in an average of 60 gap-junction connections per neuron.
We must not use the `fixed_indegree` oder `fixed_outdegree` functionality of
`nest.Connect()` to create the connections, as `gap_junction` connections are
bidirectional connections and we need to make sure that the same neurons
are connected in both ways. This is achieved by creating the connections on
the Python level with the `random` module of the Python Standard Library
and connecting the neurons using the `make_symmetric` flag for
`one_to_one` connections.
"""
n_connection = int(n_neuron * gap_per_neuron / 2)
connections = numpy.transpose(
    [random.sample(neurons, 2) for _ in range(n_connection)])
Beispiel #23
0
for ii in range(npop):
    source = ii, p.nrow, p.ncol, p.nrow, p.ncol, p.ncon, p.kappa, p.theta
    targets, delay = lcrn.lcrn_gamma_targets(*source)
    if landscape is not None:  # asymmetry
        targets = (targets + p.shift * move[landscape[ii] % len(move)]) % npop
    # no selfconnections
    targets = targets[targets != ii]
    nest.Connect([pop[ii]], (targets + offset).tolist(),
                 syn_spec={'weight': p.Ji})

# Connect noise input device to all neurons
nest.Connect(noise, pop)

# Connect spike detector to population of all neurons
nest.Connect(pop, sd)
"""
Warming up
"""

# Preparation for simulation
nest.SetStatus(noise, params={'std': 500.})
nest.Simulate(p.wuptime / 2)
nest.SetStatus(noise, params=p.noise)
nest.Simulate(p.wuptime / 2)
"""
Start simulation
"""

# Run simulation
nest.Simulate(p.simtime)
Beispiel #24
0
def _set_status(obj, parameters):
    """Wrapper around nest.SetStatus() to add a more informative error message."""
    try:
        nest.SetStatus(obj, parameters)
    except nest.hl_api.NESTError as e:
        raise nest.hl_api.NESTError("%s. Parameter dictionary was: %s" % (e, parameters))
Beispiel #25
0
noise = nest.Create("poisson_generator")
espikes = nest.Create("spike_detector")
ispikes = nest.Create("spike_detector")

###############################################################################
# Configuration of the spike detectors recording excitatory and inhibitory
# spikes using `SetStatus`, which expects a list of node handles and a list
# of parameter dictionaries. Setting the variable "to_file" to True ensures
# that the spikes will be recorded in a .gdf file starting with the string
# assigned to label. Setting "withtime" and "withgid" to True ensures that
# each spike is saved to file by stating the gid of the spiking neuron and
# the spike time in one line.

nest.SetStatus(espikes, [{
    "label": "brunel-py-ex",
    "withtime": True,
    "withgid": True,
    "to_file": True
}])

nest.SetStatus(ispikes, [{
    "label": "brunel-py-in",
    "withtime": True,
    "withgid": True,
    "to_file": True
}])

print("Connecting devices")

###############################################################################
# Definition of a synapse using `CopyModel`, which expects the model name of
# a pre-defined synapse, the name of the customary synapse and an optional
Beispiel #26
0
 def _set_sampling_interval(self, value):
     if value is not None:
         nest.SetStatus(self._multimeter.device, {"interval": value})
Beispiel #27
0
    def _convergent_connect(self, presynaptic_indices, postsynaptic_index,
                            **connection_parameters):
        """
        Connect a neuron to one or more other neurons with a static connection.

        `sources`  -- a 1D array of pre-synaptic cell IDs
        `target`   -- the ID of the post-synaptic cell.

        TO UPDATE
        """
        #logger.debug("Connecting to index %s from %s with %s" % (postsynaptic_index, presynaptic_indices, connection_parameters))
        presynaptic_cells = self.pre.all_cells[presynaptic_indices]
        postsynaptic_cell = self.post[postsynaptic_index]
        assert presynaptic_cells.size == presynaptic_indices.size
        assert len(presynaptic_cells) > 0, presynaptic_cells

        weights = connection_parameters.pop('weight')
        if self.receptor_type == 'inhibitory' and self.post.conductance_based:
            weights *= -1  # NEST wants negative values for inhibitory weights, even if these are conductances
        if hasattr(self.post, "celltype") and hasattr(
                self.post.celltype,
                "receptor_scale"):  # this is a bit of a hack
            weights *= self.post.celltype.receptor_scale  # needed for the Izhikevich model
        delays = connection_parameters.pop('delay')

        # Create connections, with weights and delays
        # Setting other connection parameters is done afterwards
        if postsynaptic_cell.celltype.standard_receptor_type:
            try:
                nest.ConvergentConnect(
                    presynaptic_cells.astype(int).tolist(),
                    [int(postsynaptic_cell)], listify(weights),
                    listify(delays), self.nest_synapse_model)
            except nest.NESTError as e:
                raise errors.ConnectionError(
                    "%s. presynaptic_cells=%s, postsynaptic_cell=%s, weights=%s, delays=%s, synapse model='%s'"
                    % (e, presynaptic_cells, postsynaptic_cell, weights,
                       delays, self.nest_synapse_model))
        else:
            receptor_type = postsynaptic_cell.celltype.get_receptor_type(
                self.receptor_type)
            if numpy.isscalar(weights):
                weights = repeat(weights)
            if numpy.isscalar(delays):
                delays = repeat(delays)
            for pre, w, d in zip(presynaptic_cells, weights, delays):
                nest.Connect(
                    [pre], [postsynaptic_cell], 'one_to_one', {
                        'weight': w,
                        'delay': d,
                        'receptor_type': receptor_type,
                        'model': self.nest_synapse_model
                    })

        # Book-keeping
        self._connections = None  # reset the caching of the connection list, since this will have to be recalculated
        self._sources.extend(presynaptic_cells)

        # Clean the connection parameters
        connection_parameters.pop(
            'tau_minus',
            None)  # TODO: set tau_minus on the post-synaptic cells
        connection_parameters.pop('dendritic_delay_fraction', None)
        connection_parameters.pop('w_min_always_zero_in_NEST', None)

        # We need to distinguish between common synapse parameters and local ones
        # We just get the parameters of the first connection (is there an easier way?)
        if self._common_synapse_property_names is None:
            self._identify_common_synapse_properties()

        # Set connection parameters other than weight and delay
        if connection_parameters:
            #logger.debug(connection_parameters)
            sort_indices = numpy.argsort(presynaptic_cells)
            connections = nest.GetConnections(
                source=numpy.unique(presynaptic_cells.astype(int)).tolist(),
                target=[int(postsynaptic_cell)],
                synapse_model=self.nest_synapse_model)
            for name, value in connection_parameters.items():
                value = make_sli_compatible(value)
                if name not in self._common_synapse_property_names:
                    #logger.debug("Setting %s=%s for connections %s" % (name, value, connections))
                    if isinstance(value, numpy.ndarray):
                        # the str() is to work around a bug handling unicode names in SetStatus in NEST 2.4.1 when using Python 2
                        nest.SetStatus(connections, str(name),
                                       value[sort_indices].tolist())
                    else:
                        nest.SetStatus(connections, str(name), value)
                else:
                    self._set_common_synapse_property(name, value)
Beispiel #28
0
        # Readout Spikedetector before phase: --------------------------------------------------------------------------
        RGC_senders_before_phase = list(
            nest.GetStatus(spikedetector)[0]['events']['senders'])
        RGC_times_before_phase = list(
            nest.GetStatus(spikedetector)[0]['events']['times'])

        # Set voltage according to sensor response: --------------------------------------------------------------------

        print('Defining sensor voltage')
        rates = (scaling_factor / max(responses)) * np.array(responses)
        amplitudes = []
        for rate in rates:
            amplitude = dict([['amplitude', rate]])
            amplitudes.append(amplitude)

        nest.SetStatus(sensors, amplitudes)

        # Simulate Network: --------------------------------------------------------------------------------------------
        simstart = time.time()

        nest.Simulate(P.simtime)

        simstop = time.time()
        print('Simulation took: ' + str(simstop - simstart))

        # Readout Spikedetector after phase: ---------------------------------------------------------------------------
        RGC_senders_after_phase = list(
            nest.GetStatus(spikedetector)[0]['events']['senders'])
        RGC_times_after_phase = list(
            nest.GetStatus(spikedetector)[0]['events']['times'])
Beispiel #29
0
 nest.Connect(BS_HC1, PYR_MC3, conn_dict_PYR_TO_BS,syn_spec = {'model':'i2e_synapse'})
 #PYR_TO_PYR(recurrent connections)
 nest.Connect(PYR_MC3, PYR_MC3, conn_dict_PYR_TO_PYR,syn_spec = {'model':'AMPA_synapse_short_delay'})
 #PYR3_TO_DBC0_DBC2
 nest.Connect(PYR_MC3, DBC_MC0, conn_dict_PYR_TO_DBC,syn_spec = {'model':'AMPA_synapse2DBC_larger_delay'})
 nest.Connect(PYR_MC3, DBC_MC2, conn_dict_PYR_TO_DBC,syn_spec = {'model':'AMPA_synapse2DBC_short_delay'})
 #PYR_TO_PYR(DIFFERENT HYPERCOLUMNS)
 nest.Connect(PYR_MC3, PYR_MC1, conn_dict_PYR_TO_PYR_DIFF_HC,syn_spec = {'model':'AMPA_synapse_larger_delay'})
 
 
 
 # STIMULATIONS 
 # ZERO MEAN NOISE 
 zmn_nodes_L23e=nest.Create('poisson_generator', params={'rate'  : ST['L23e_zmn_rate']})
 zmn_nodes_L23i=nest.Create('poisson_generator', params={'rate'  : ST['L23e_zmn_rate']})
 nest.SetStatus(zmn_nodes_L23e, {"start": 0.0})
 nest.SetStatus(zmn_nodes_L23e, {"stop": 5000.0})
 
 nest.SetStatus(zmn_nodes_L23i, {"start": 0.0})
 nest.SetStatus(zmn_nodes_L23i, {"stop":5000.0})
 
 syn_dict_e = {'model': 'zmn_synapse', 'weight': +ST['zmn_weight'], 'delay': ST['zmn_delay']}
 syn_dict_i = {'model': 'zmn_synapse', 'weight': -ST['zmn_weight'], 'delay': ST['zmn_delay']}
 val=0.12
 nest.DivergentConnect(zmn_nodes_L23e, PYR_MC0, model=syn_dict_e['model'],weight=syn_dict_e['weight'],delay=syn_dict_e['delay'])  #adjusted for nest 2.2.2 
 nest.DivergentConnect(zmn_nodes_L23i, PYR_MC0, model=syn_dict_i['model'],weight=syn_dict_i['weight'],delay=syn_dict_i['delay'])  #adjusted for nest 2.2.2 
 
 nest.DivergentConnect(zmn_nodes_L23e, DBC_MC0, model=syn_dict_e['model'],weight=val,delay=syn_dict_e['delay'])  #adjusted for nest 2.2.2 
 nest.DivergentConnect(zmn_nodes_L23i, DBC_MC0, model=syn_dict_i['model'],weight=val,delay=syn_dict_i['delay'])  #adjusted for nest 2.2.2 
 
 nest.DivergentConnect(zmn_nodes_L23e, PYR_MC1, model=syn_dict_e['model'],weight=syn_dict_e['weight'],delay=syn_dict_e['delay'])  #adjusted for nest 2.2.2 
import nest
import matplotlib.pyplot as plt

nest.Install("retinamodule")
nest.SetKernelStatus({"resolution": 1.0})

neurons = nest.Create("stbrst_gc_conv",2)
params = [ 
	{
	'totAHPinit':i,
	'seed':s,
	'gnoise':gnoise,
	} for i,s,gnoise in zip(rnd.random(2),rnd.randint(32535,size=2),[2E-7,0.]) 
]

nest.SetStatus(neurons,params )

res=["Vm","synconv","spont","conCa","fAHP","sAHP", "ICa", "IAHP","ISyn"]
multimeter = nest.Create("multimeter")
nest.SetStatus(multimeter, {"withtime":True, "record_from":res})
nest.Connect(multimeter,neurons)

#sd = nest.Create("spike_detector")
#nest.Connect(neurons,sd)

nest.Connect((neurons[0],),(neurons[1],),syn_spec={"weight": 0.24, "delay":2., 'model':"Convolution"})


nest.Simulate(2000.0)

dmm = nest.GetStatus(multimeter)[0]