Exemplo n.º 1
0
def run_pop_code(pop_class, N, network_params, stimuli, trial_duration, report=None):
    simulation_clock=Clock(dt=1*ms)

    pop=pop_class(N,simulation_clock,network_params)
    pop_monitor=MultiStateMonitor(pop, vars=['x','r','e'], record=True, clock=simulation_clock)

    @network_operation(when='start', clock=simulation_clock)
    def get_pop_input():
        pop.x=0.0
        for stimulus in stimuli:
            if stimulus.start_time<simulation_clock.t<stimulus.end_time:
                pop.x+=pop.get_population_function(stimulus.x,stimulus.var)

    net=Network(pop, pop_monitor, get_pop_input)
    #reinit_default_clock()
    net.run(trial_duration, report=report)

    g_total=np.sum(np.clip(pop_monitor['e'].values,0,1) * pop_monitor['x'].values, axis=0)+0.1
    voxel_monitor=get_bold_signal(g_total, voxel.default_params, range(int(stimuli[0].start_time/simulation_clock.dt)), trial_duration)

    # There is only one peak with rapid design
    if trial_duration>6*second:
        y_max=np.max(voxel_monitor['y'][0][60000:])
    else:
        y_max=np.max(voxel_monitor['y'][0])


    return pop_monitor, voxel_monitor, y_max
Exemplo n.º 2
0
    def __init__(self, subj_id, wta_params=default_params(), pyr_params=pyr_params(), inh_params=inh_params(),
                 plasticity_params=plasticity_params(), sim_params=simulation_params()):
        self.subj_id = subj_id
        self.wta_params = wta_params
        self.pyr_params = pyr_params
        self.inh_params = inh_params
        self.plasticity_params = plasticity_params
        self.sim_params = sim_params

        self.simulation_clock = Clock(dt=self.sim_params.dt)
        self.input_update_clock = Clock(dt=1 / (self.wta_params.refresh_rate / Hz) * second)

        self.background_input = PoissonGroup(self.wta_params.background_input_size,
            rates=self.wta_params.background_freq, clock=self.simulation_clock)
        self.task_inputs = []
        for i in range(self.wta_params.num_groups):
            self.task_inputs.append(PoissonGroup(self.wta_params.task_input_size,
                rates=self.wta_params.task_input_resting_rate, clock=self.simulation_clock))

        # Create WTA network
        self.wta_network = WTANetworkGroup(params=self.wta_params, background_input=self.background_input,
            task_inputs=self.task_inputs, pyr_params=self.pyr_params, inh_params=self.inh_params,
            plasticity_params=self.plasticity_params, clock=self.simulation_clock)


        # Create network monitor
        self.wta_monitor = WTAMonitor(self.wta_network, None, None, self.sim_params, record_lfp=False,
                                      record_voxel=False, record_neuron_state=False, record_spikes=False,
                                      record_firing_rate=True, record_inputs=True, record_connections=None,
                                      save_summary_only=False, clock=self.simulation_clock)


        # Create Brian network and reset clock
        self.net = Network(self.background_input, self.task_inputs, self.wta_network,
            self.wta_network.connections.values(), self.wta_monitor.monitors.values())
Exemplo n.º 3
0
def get_bold_signal(g_total, voxel_params, baseline_range, trial_duration):
    simulation_clock = Clock(dt=1 * ms)

    voxel = Voxel(simulation_clock, params=voxel_params)
    voxel.G_base = g_total[baseline_range[0]:baseline_range[1]].mean()
    voxel_monitor = MultiStateMonitor(
        voxel,
        vars=['G_total', 's', 'f_in', 'v', 'f_out', 'q', 'y'],
        record=True,
        clock=simulation_clock)

    @network_operation(when='start', clock=simulation_clock)
    def get_input():
        idx = int(simulation_clock.t / simulation_clock.dt)
        if idx < baseline_range[0]:
            voxel.G_total = voxel.G_base
        elif idx < len(g_total):
            voxel.G_total = g_total[idx]
        else:
            voxel.G_total = voxel.G_base

    net = Network(voxel, get_input, voxel_monitor)
    #reinit_default_clock()
    bold_trial_duration = 10 * second
    if trial_duration + 6 * second > bold_trial_duration:
        bold_trial_duration = trial_duration + 6 * second
    net.run(bold_trial_duration)

    return voxel_monitor
Exemplo n.º 4
0
    def run(self, **param_values):
        delays = param_values.pop('delays', zeros(self.neurons))
        
#        print self.refractory,self.max_refractory
        if self.max_refractory is not None:
            refractory = param_values.pop('refractory', zeros(self.neurons))
        else:
            refractory = self.refractory*ones(self.neurons)
            
        tau_metric = param_values.pop('tau_metric', zeros(self.neurons))
        self.update_neurongroup(**param_values)

        # repeat spike delays and refractory to take slices into account
        delays = kron(delays, ones(self.slices))
        refractory = kron(refractory, ones(self.slices))
        tau_metric = kron(tau_metric, ones(self.slices))
        # TODO: add here parameters to criterion_params if a criterion must use some parameters
        criterion_params = dict(delays=delays)

        if self.criterion.__class__.__name__ == 'Brette':
            criterion_params['tau_metric'] = tau_metric
    
        
        self.update_neurongroup(**param_values)
        self.initialize_criterion(**criterion_params)
        
        if self.use_gpu:
            # Reinitializes the simulation object
            self.mf.reinit_vars(self.criterion_object,
                                self.inputs_inline, self.inputs_offset,
                                self.spikes_inline, self.spikes_offset,
                                self.traces_inline, self.traces_offset,
                                delays, refractory
                                )
            # LAUNCHES the simulation on the GPU
            self.mf.launch(self.sliced_duration, self.stepsize)
            # Synchronize the GPU values with a call to gpuarray.get()
            self.criterion_object.update_gpu_values()
        else:
            # set the refractory period
            if self.max_refractory is not None:
                self.group.refractory = refractory
            # Launch the simulation on the CPU
            self.group.clock.reinit()
            net = Network(self.group, self.criterion_object)
            if self.statemonitor_var is not None:
                self.statemonitors = []
                for state in self.statemonitor_var:
                    monitor = StateMonitor(self.group, state, record=True)
                    self.statemonitors.append(monitor)
                    net.add(monitor)
            net.run(self.sliced_duration)
        
        sliced_values = self.criterion_object.get_values()
        combined_values = self.combine_sliced_values(sliced_values)
        values = self.criterion_object.normalize(combined_values)
        return values
Exemplo n.º 5
0
 def generate_data():
     g = NeuronGroup(1, model=equations, reset=0, threshold=1)
     g.I = TimedArray(input, dt=.1 * ms)
     g.tau = 25 * ms
     g.R = 3e9
     SpM = SpikeMonitor(g)
     StM = StateMonitor(g, 'V', record=True)
     net = Network(g, SpM, StM)
     net.run(1 * second)
     return StM.values[0], SpM.spikes
Exemplo n.º 6
0
def fun(sigma, args):
    """
    This function computes the mean firing rate of a LIF neuron with
    white noise input current (OU process with threshold).
    """
    if not isscalar(sigma):
        raise Exception('sigma must be a scalar')
    N = args['N']
    tau = args['tau']
    model = args['model']
    reset = args['reset']
    threshold = args['threshold']
    duration = args['duration']
    G = NeuronGroup(N, model=model, reset=reset, threshold=threshold)
    M = SpikeCounter(G)
    net = Network(G, M)
    net.run(duration)
    r = M.nspikes * 1.0 / N
    return r
Exemplo n.º 7
0
def run_restricted_pop_code(pop_class, N, network_params, stimuli, trial_duration, report=None):
    simulation_clock=Clock(dt=1*ms)

    pop=pop_class(N, simulation_clock, network_params)
    #pop_monitor=MultiStateMonitor(pop, vars=['x','r','e','total_e','total_r'], record=True)
    pop_monitor=MultiStateMonitor(pop, vars=['x','r','e'], record=True, clock=simulation_clock)

    @network_operation(when='start', clock=simulation_clock)
    def get_pop_input():
        pop.x=0.0
        for stimulus in stimuli:
            if stimulus.start_time<simulation_clock.t<stimulus.end_time:
                pop.x+=pop.get_population_function(stimulus.x,stimulus.var)

    net=Network(pop, pop_monitor, get_pop_input)
    #reinit_default_clock()
    net.run(trial_duration, report=report)

    g_total=np.sum(np.clip(pop_monitor['e'].values,0,1) * pop_monitor['x'].values, axis=0)+0.1
    voxel_monitor=get_bold_signal(g_total, voxel.default_params, range(int(stimuli[0].start_time/simulation_clock.dt)), trial_duration)

    return voxel_monitor
Exemplo n.º 8
0
def test_stim_pyramidal_impact():
    simulation_clock = Clock(dt=.5 * ms)
    trial_duration = 1 * second
    dcs_start_time = .5 * second

    stim_levels = [-8, -6, -4, -2, -1, -.5, -.25, 0, .25, .5, 1, 2, 4, 6, 8]
    voltages = np.zeros(len(stim_levels))
    for idx, stim_level in enumerate(stim_levels):
        print('testing stim_level %.3fpA' % stim_level)
        eqs = exp_IF(default_params.C, default_params.gL, default_params.EL,
                     default_params.VT, default_params.DeltaT)

        # AMPA conductance - recurrent input current
        eqs += exp_synapse('g_ampa_r', default_params.tau_ampa, siemens)
        eqs += Current('I_ampa_r=g_ampa_r*(E-vm): amp',
                       E=default_params.E_ampa)

        # AMPA conductance - background input current
        eqs += exp_synapse('g_ampa_b', default_params.tau_ampa, siemens)
        eqs += Current('I_ampa_b=g_ampa_b*(E-vm): amp',
                       E=default_params.E_ampa)

        # AMPA conductance - task input current
        eqs += exp_synapse('g_ampa_x', default_params.tau_ampa, siemens)
        eqs += Current('I_ampa_x=g_ampa_x*(E-vm): amp',
                       E=default_params.E_ampa)

        # Voltage-dependent NMDA conductance
        eqs += biexp_synapse('g_nmda', default_params.tau1_nmda,
                             default_params.tau2_nmda, siemens)
        eqs += Equations('g_V = 1/(1+(Mg/3.57)*exp(-0.062 *vm/mV)) : 1 ',
                         Mg=default_params.Mg)
        eqs += Current('I_nmda=g_V*g_nmda*(E-vm): amp',
                       E=default_params.E_nmda)

        # GABA-A conductance
        eqs += exp_synapse('g_gaba_a', default_params.tau_gaba_a, siemens)
        eqs += Current('I_gaba_a=g_gaba_a*(E-vm): amp',
                       E=default_params.E_gaba_a)

        eqs += InjectedCurrent('I_dcs: amp')

        group = NeuronGroup(1,
                            model=eqs,
                            threshold=-20 * mV,
                            refractory=pyr_params.refractory,
                            reset=default_params.Vr,
                            compile=True,
                            freeze=True,
                            clock=simulation_clock)
        group.C = pyr_params.C
        group.gL = pyr_params.gL

        @network_operation(clock=simulation_clock)
        def inject_current(c):
            if simulation_clock.t > dcs_start_time:
                group.I_dcs = stim_level * pA

        monitor = StateMonitor(group, 'vm', simulation_clock, record=True)
        net = Network(group, monitor, inject_current)
        net.run(trial_duration, report='text')
        voltages[idx] = monitor.values[0, -1] * 1000

    voltages = voltages - voltages[7]
    plt.figure()
    plt.plot(stim_levels, voltages)
    plt.xlabel('Stimulation level (pA)')
    plt.ylabel('Voltage Change (mV)')
    plt.show()
def runsim(neuron_model, 
           # sim params
           dt, simtime, prerun, monitors, recvars,
           # stimulation params
           fstim, r0_bg, r0_stim, stim_starts, stim_stops, stim_odors, stim_amps, stim_start_var,
           # network params
           beeid, N_glu, N_KC, ORNperGlu, PNperKC, PN_I0, LN_I0,
           # network weights
           wi, wORNLN, wORNPN, wPNKC,
           # default params
           V0min, inh_struct=None, Winh=None, timestep=500, report=None):

    np.random.seed() #needed for numpy/brian when runing parallel sims
    define_default_clock(dt=dt)    
    
    inh_on_off = 0 if (wi == 0) or (wi is None) or (wORNLN is None) else 1    
    
    
    
    #########################     NEURONGROUPS     #########################
    NG = dict()

    # ORN Input
    
    # For each glumerolus, random temporal response jitter can be added.
    # The jitter is added to the response onset. Maximum jitter is given by stim_start_var.
    # stim_start_jittered is a vector containing the jittered stim start tims
    
    # orn_activation returns a booolean vector of stim presence given time t
    
    # Total ORN rate: Baseline componenent equal for all units,
    # and individual activationa.
    
    jitter = np.random.uniform(0,stim_start_var,N_glu)
    
    stim_tun       = lambda odorN: fstim(N_glu=N_glu, odorN=odorN) * r0_stim
    orn_activation = lambda t: np.sum([
                     a*stim_tun(odorN=o)*np.logical_and(np.greater(t,prerun+stim_start+jitter), np.less(t,prerun+stim_stop))
                     for stim_start,stim_stop,o,a in zip(stim_starts, stim_stops, stim_odors, stim_amps)], 0)                         
    orn_rates      = lambda t: np.repeat(r0_bg + orn_activation(t),repeats = ORNperGlu)
    
    NG['ORN'] = PoissonGroup(ORNperGlu*N_glu, rates=orn_rates)
    NG['PN'] = NeuronGroup(N_glu, **neuron_model)
    NG['LN'] = NeuronGroup(N_glu*inh_on_off, **neuron_model)
    if 'KC' in monitors: NG['KC'] = NeuronGroup(N_KC, **neuron_model)

    #########################     CONNECTIONS       #########################
    c = dict()
    
    c['ORNPN'] = Connection(NG['ORN'],NG['PN'],'ge')
    
    for i in np.arange(N_glu): c['ORNPN'].connect_full(NG['ORN'].subgroup(ORNperGlu),NG['PN'][i],weight=wORNPN)

    if inh_on_off:
        print('-- inhibiting --',wi)
        
        c['ORNLN'] = Connection(NG['ORN'],NG['LN'],'ge')
        c['LNPN'] = Connection(NG['LN'],NG['PN'],'gi',weight=(wi*35)/N_glu)
        
        for i in np.arange(N_glu):
            c['ORNLN'].connect_full(NG['ORN'][ i*ORNperGlu : (i+1)*ORNperGlu ],
                                NG['LN'][i],
                                weight = wORNLN)
        if inh_struct: c['LNPN'].connect(NG['LN'],NG['PN'],Winh)
    
    if 'KC' in monitors:
        c['KC'] = Connection(NG['PN'],NG['KC'],'ge')
        c['KC'].connect_random(NG['PN'],NG['KC'],p=PNperKC/float(N_glu),weight=wPNKC,seed=beeid)
    
    #########################     INITIAL VALUES     #########################
    VT = neuron_model['threshold']
    
    NG['PN'].vm    = np.random.uniform(V0min,VT,size=len(NG['PN']))
    if inh_on_off:
        NG['LN'].vm= np.random.uniform(V0min,VT,size=len(NG['LN']))
    if 'KC' in monitors:
        NG['KC'].vm= np.random.uniform(V0min,VT,size=len(NG['KC']))
    
    net = Network(NG.values(), c.values())
    
    #### Compensation currents ###
    NG['PN'].I0 = PN_I0
    NG['LN'].I0 = LN_I0
    ##########################################################################

    #########################         PRE-RUN        #########################    
    net.run(prerun)
    #########################     MONITORS     #########################
    spmons = [SpikeMonitor(NG[mon], record=True) for mon in monitors]
    net.add(spmons)
    
    if len(recvars) > 0:
        mons = [MultiStateMonitor(NG[mon], vars=recvars, record=True, timestep=timestep) for mon in monitors]
        net.add(mons)
    else:
        mons = None
    #########################           RUN          #########################
    net = run(simtime, report=report)
    

    out_spikes = dict( (monitors[i],np.array(sm.spikes)) for i,sm in enumerate(spmons) )
    
    if mons is not None:
        out_mons = dict( (mon,dict((var,statemon.values) for var,statemon in m.iteritems())) for mon,m in zip(monitors,mons))
    else:
        out_mons = None

    #subtract the prerun from spike times, if there are any
    for spikes in out_spikes.itervalues():
        if len(spikes) != 0:
            spikes[:,1] -= prerun
    
    return out_spikes, out_mons
Exemplo n.º 10
0
def run_simulation(realizations=1, trials=1, t=3000 * ms, alpha=1, ree=1,
                   k=50, winlen = 50 * ms, verbose=True, t_stim = 0):
    """
    Run the whole simulation with the specified parameters. All model parameter are set in the function.

    Keyword arguments:
    :param realizations: number of repititions of the whole simulation, number of network instances
    :param trials: number of trials for network instance
    :param t: simulation time
    :param alpha: scaling factor for number of neurons in the network
    :param ree: clustering coefficient
    :param k: number of clusters
    :param t_stim : duration of stimulation of a subset of clusters
    :param winlen: length of window in ms
    :param verbose: plotting flag
    :return: numpy matrices with spike times
    """

    # The equations defining our neuron model
    eqs_string = '''
                dV/dt = (mu - V)/tau + x: volt
                dx/dt = -1.0/tau_2*(x - y/tau_1) : volt/second
                dy/dt = -y/tau_1 : volt
                mu : volt
                tau: second
                tau_2: second
                tau_1: second
                '''
    # Model parameters
    n_e = int(4000 * alpha)  # number of exc neurons
    n_i = int(1000 * alpha)  # number of inh neurons
    tau_e = 15 * ms  # membrane time constant (for excitatory synapses)
    tau_i = 10 * ms  # membrane time constant (for inhibitory synapses)
    tau_syn_2_e = 3 * ms  # exc synaptic time constant tau2 in paper
    tau_syn_2_i = 2 * ms  # inh synaptic time constant tau2 in paper
    tau_syn_1 = 1 * ms  # exc/inh synaptic time constant tau1 in paper
    vt = -50 * mV  # firing threshold
    vr = -65 * mV  # reset potential
    dv = vt - vr # delta v
    refrac = 5 * ms  # absolute refractory period

    # scale the weights to ensure same variance in the inputs
    wee = 0.024 * dv * np.sqrt(1. / alpha)
    wie = 0.014 * dv * np.sqrt(1. / alpha)
    wii = -0.057 * dv * np.sqrt(1. / alpha)
    wei = -0.045 * dv * np.sqrt(1. / alpha)

    # Connection probability
    p_ee = 0.2
    p_ii = 0.5
    p_ie = 0.5
    p_ei = 0.5
    
    # determine probs for inside and outside of clusters
    p_in, p_out = get_cluster_connection_probs(ree, k, p_ee)

    mu_min_e, mu_max_e = 1.1, 1.2
    mu_min_i, mu_max_i = 1.0, 1.05

    # increase cluster weights if there are clusters
    wee_cluster = wee if p_in == p_out else 1.9 * wee

    # define numpy array for data storing
    all_data = np.zeros((realizations, trials, n_e+n_i, int(t/winlen)//2))

    for realization in range(realizations):
        # clear workspace to make sure that is a new realization of the network
        clear(True, True)
        reinit()

        # set up new random bias parameter for every type of neuron
        mu_e = vr + np.random.uniform(mu_min_e, mu_max_e, n_e) * dv  # bias for excitatory neurons
        mu_i = vr + np.random.uniform(mu_min_i, mu_max_i, n_i) * dv  # bias for excitatory neurons

        # Let's create an equation object from our string and parameters
        model_eqs = Equations(eqs_string)

        # Let's create 5000 neurons
        all_neurons = NeuronGroup(N=n_e + n_i,
                                  model=model_eqs,
                                  threshold=vt,
                                  reset=vr,
                                  refractory=refrac,
                                  freeze=True,
                                  method='Euler',
                                  compile=True)

        # Divide the neurons into excitatory and inhibitory ones
        neurons_e = all_neurons[0:n_e]
        neurons_i = all_neurons[n_e:n_e + n_i]

        # set the bias
        neurons_e.mu = mu_e
        neurons_i.mu = mu_i
        neurons_e.tau = tau_e
        neurons_i.tau = tau_i
        neurons_e.tau_2 = tau_syn_2_e
        neurons_i.tau_2 = tau_syn_2_i
        all_neurons.tau_1 = tau_syn_1

        # set up connections
        connections = Connection(all_neurons, all_neurons, 'y')

        # do the cluster connection like cross validation: cluster neuron := test idx; other neurons := train idx
        kf = KFold(n=n_e, n_folds=k)
        for idx_out, idx_in in kf:  # idx_out holds all other neurons; idx_in holds all cluster neurons
            # connect current cluster to itself
            connections.connect_random(all_neurons[idx_in[0]:idx_in[-1]], all_neurons[idx_in[0]:idx_in[-1]],
                                       sparseness=p_in, weight=wee_cluster)
            # connect current cluster to other neurons
            connections.connect_random(all_neurons[idx_in[0]:idx_in[-1]], all_neurons[idx_out[0]:idx_out[-1]],
                                       sparseness=p_out, weight=wee)

        # connect all excitatory to all inhibitory, irrespective of clustering
        connections.connect_random(all_neurons[0:n_e], all_neurons[n_e:(n_e + n_i)], sparseness=p_ie, weight=wie)
        # connect all inhibitory to all excitatory
        connections.connect_random(all_neurons[n_e:(n_e + n_i)], all_neurons[0:n_e], sparseness=p_ei, weight=wei)
        # connect all inhibitory to all inhibitory
        connections.connect_random(all_neurons[n_e:(n_e + n_i)], all_neurons[n_e:(n_e + n_i)], sparseness=p_ii,
                                   weight=wii)

        # set up spike monitors
        spike_mon_e = SpikeMonitor(neurons_e)
        spike_mon_i = SpikeMonitor(neurons_i)
        # set up network with monitors
        network = Network(all_neurons, connections, spike_mon_e, spike_mon_i)

        # run this network for some number of trials, every time with
        for trial in range(trials):
            # different initial values
            all_neurons.V = vr + (vt - vr) * np.random.rand(len(all_neurons)) * 1.4

            # Calibration phase
            # run for the first half of the time to let the neurons adapt
            network.run(t/2)

            # reset monitors to start recording phase
            spike_mon_i.reinit()
            spike_mon_e.reinit()

            # stimulation if duration is given
            # define index variable for the stimulation possibility (is 0 for stimulation time=0)
            t_stim_idx = int(t_stim / (winlen/ms))
            if not(t_stim==0):
                # Stimulation phase, increase input to subset of clusters
                all_neurons[:400].mu += 0.07 * dv
                network.run(t_stim * ms, report='text')
                # set back to normal
                all_neurons[:400].mu -= 0.07 * dv
                # save data
                all_data[realization, trial, :n_e, :t_stim_idx] = spikes_counter(spike_mon_e, winlen)
                all_data[realization, trial, n_e:, :t_stim_idx] = spikes_counter(spike_mon_i, winlen)
                # reset monitors
                spike_mon_e.reinit()
                spike_mon_i.reinit()
            # run the remaining time of the simulation
            network.run((t/2) - t_stim*ms, report='text')

            # save results
            all_data[realization, trial, :n_e, t_stim_idx:] = spikes_counter(spike_mon_e, winlen)
            all_data[realization, trial, n_e:, t_stim_idx:] = spikes_counter(spike_mon_i, winlen)

            if verbose:
                plt.ion()
                plt.figure()
                raster_plot(spike_mon_e)
                plt.title('Excitatory neurons')

            spike_mon_e.reinit()
            spike_mon_i.reinit()

    return all_data