예제 #1
0
def Run(T,
        v0,
        u0,
        bench,
        number,
        input_neurons,
        liquid_neurons,
        hidden_neurons,
        output_neurons,
        Sin,
        Sliq,
        Sa,
        Sb,
        M,
        Mv,
        Mu,
        S_in,
        S_hidden,
        S_out,
        train=False,
        letter=None):

    br.forget(Sin, Sliq)
    for i in range(len(Sa)):
        br.forget(Sa[i])
    br.forget(Sb)
    br.reinit(states=False)
    br.recall(Sin, Sliq)
    for i in range(len(Sa)):
        br.recall(Sa[i])
    br.recall(Sb)

    img, label = ReadImg(number=number, bench=bench, letter=letter)
    spikes = GetInSpikes(img, bench=bench)
    if number >= 0 and number < 4:
        input_neurons.set_spiketimes(spikes)
    else:
        input_neurons.set_spiketimes([])

    for i in range(len(liquid_neurons)):
        liquid_neurons[i].v = v0
        liquid_neurons[i].u = u0
        liquid_neurons[i].I = 0
        liquid_neurons[i].ge = 0

    for i in range(len(hidden_neurons)):
        hidden_neurons[i].v = v0
        hidden_neurons[i].u = u0
        hidden_neurons[i].I = 0
        hidden_neurons[i].ge = 0

    #pudb.set_trace()
    output_neurons.v = v0
    output_neurons.u = u0
    output_neurons.I = 0
    output_neurons.ge = 0
    br.run(T * br.msecond, report='text')

    return label
예제 #2
0
    def run_network(self, traj):
        """Top-level simulation function, pass this to the environment

        Performs an individual network run during parameter exploration.

        `run_network` does not need to be called by the user. If the top-level
        `~pypet.brian.network.run_network` method (not this one of the NetworkManager)
        is passed to an :class:`~pypet.environment.Environment` with this NetworkManager,
        `run_network` and :func:`~pypet.brian.network.NetworkManager.build`
        are automatically called for each individual experimental run.

        This function will create a new `BRIAN network`_ in case one was not pre-run.
        The execution of the network run is carried out by
        the :class:`~pypet.brian.network.NetworkRunner` and it's
        :func:`~pypet.brian.network.NetworkRunner.execute_network_run` (also take
        a look at this function's documentation to see the structure of a network run).

        .. `BRIAN network`_: http://briansimulator.org/docs/reference-network.html#brian.Network

        :param traj: Trajectory container

        """

        # Check if the network was pre-built
        if self._pre_built:
            # If yes check for multiprocessing or if a single core processing is forced
            multiproc = traj.f_get("config.environment.%s.multiproc" % traj.v_environment_name).f_get()
            if multiproc:
                self._run_network(traj)
            else:
                if self._force_single_core:
                    self._logger.warning(
                        "Running Single Core Mode. Be aware that the network "
                        "evolves over ALL your runs and is not reset. "
                        "Use this setting only for debugging purposes "
                        "because your results will be not correct in case "
                        "your trajectory contains more than a single run. "
                    )
                    self._run_network(traj)
                else:
                    raise RuntimeError(
                        "You cannot run a pre-built network without "
                        "multiprocessing.\n"
                        "The network configuration must be copied either by "
                        "pickling (using a `multiproc=True` and `use_pool=True` in "
                        "your environment) or by forking ( multiprocessing with "
                        "`use_pool=False`).\n If your network "
                        "cannot be pickled use the latter. "
                        "In order to come close to iterative processing "
                        "you could use multiprocessing with `ncores=1`. \n"
                        "If you do not care about messing up initial conditions "
                        "(i.e. you are debugging) use `force_single_core=True` "
                        "in your network manager."
                    )
        else:
            clear(True, True)
            reinit()
            self._run_network(traj)
예제 #3
0
    def run_network(self, traj):
        """Top-level simulation function, pass this to the environment

        Performs an individual network run during parameter exploration.

        `run_network` does not need to be called by the user. If the top-level
        `~pypet.brian.network.run_network` method (not this one of the NetworkManager)
        is passed to an :class:`~pypet.environment.Environment` with this NetworkManager,
        `run_network` and :func:`~pypet.brian.network.NetworkManager.build`
        are automatically called for each individual experimental run.

        This function will create a new `BRIAN network`_ in case one was not pre-run.
        The execution of the network run is carried out by
        the :class:`~pypet.brian.network.NetworkRunner` and it's
        :func:`~pypet.brian.network.NetworkRunner.execute_network_run` (also take
        a look at this function's documentation to see the structure of a network run).

        .. `BRIAN network`_: http://briansimulator.org/docs/reference-network.html#brian.Network

        :param traj: Trajectory container

        """

        # Check if the network was pre-built
        if self._pre_built:
            # If yes check for multiprocessing or if a single core processing is forced
            multiproc = traj.f_get('config.environment.%s.multiproc' %
                                   traj.v_environment_name).f_get()
            if multiproc:
                self._run_network(traj)
            else:
                if self._force_single_core:
                    self._logger.warning(
                        'Running Single Core Mode. Be aware that the network '
                        'evolves over ALL your runs and is not reset. '
                        'Use this setting only for debugging purposes '
                        'because your results will be not correct in case '
                        'your trajectory contains more than a single run. ')
                    self._run_network(traj)
                else:
                    raise RuntimeError(
                        'You cannot run a pre-built network without '
                        'multiprocessing.\n'
                        'The network configuration must be copied either by '
                        'pickling (using a `multiproc=True` and `use_pool=True` in '
                        'your environment) or by forking ( multiprocessing with '
                        '`use_pool=False`).\n If your network '
                        'cannot be pickled use the latter. '
                        'In order to come close to iterative processing '
                        'you could use multiprocessing with `ncores=1`. \n'
                        'If you do not care about messing up initial conditions '
                        '(i.e. you are debugging) use `force_single_core=True` '
                        'in your network manager.')
        else:
            clear(True, True)
            reinit()
            self._run_network(traj)
예제 #4
0
def run_sim(number_neurons=default_number_neurons,
            connection_probability=default_connection_probability,
            synaptic_weights=default_synaptic_weights,
            synaptic_time_constant=default_synaptic_time_constant,
            tend=300):
    '''run a simulation of a population of leaky integrate-and-fire excitatory neurons that are
    randomly connected. The population is injected with a transient current.'''

    from brian.units import mvolt, msecond, namp, Mohm
    import brian
    brian.clear()

    El = 0 * mvolt
    tau_m = 30 * msecond
    tau_syn = synaptic_time_constant * msecond
    R = 20 * Mohm
    v_threshold = 30 * mvolt
    v_reset = 0 * mvolt
    tau_refractory = 4 * msecond

    eqs = brian.Equations('''
    dv/dt = (-(v - El) + R*I)/tau_m : volt
    I = I_syn + I_stim : amp
    dI_syn/dt = -I_syn/tau_syn : amp
    I_stim : amp
    ''')

    external_current = np.zeros(tend)
    external_current[np.arange(0, 100)] = 5 * namp

    group = brian.NeuronGroup(
        model=eqs,
        N=number_neurons, threshold=v_threshold, reset=v_reset, refractory=tau_refractory)

    group.I_stim = brian.TimedArray(external_current, dt=1*msecond)

    connections = brian.Connection(group, group, 'I_syn')
    connections.connect_random(sparseness=connection_probability, weight=synaptic_weights*namp)

    spike_monitor = brian.SpikeMonitor(group)
    population_rate_monitor = brian.PopulationRateMonitor(group, bin=10*msecond)

    brian.reinit()
    brian.run(tend * msecond)

    return spike_monitor, population_rate_monitor
예제 #5
0
def poisson_input(active, N_input, r, time_input, t1, t2):
    "function to built a poisson input"
    "with no zero firing rates"
    from brian import PoissonGroup,SpikeMonitor,reinit,clear,run,Hz,second
    import random as pyrandom

    reinit(states = True)
    clear(erase   = True, all = True)

    N  = 1000
    P  = PoissonGroup(N)
    S = SpikeMonitor(P)

    run(t1)

    P.rate = r
    run(time_input)

    P.rate = 0*Hz
    run(t2)

    s = []
    remove = []
    for i in xrange(N):
        s.append(len(S[i]))
        if len(S[i]) == 0:
            remove.append(i)

    pos = [x for x in range(N) if x not in remove]
    pos = pyrandom.sample(pos, len(active))

    C =  []
    for ii in xrange(len(pos)):
        D = list(S.spiketimes[pos[ii]])
        D = [(active[ii],x) for x in D]
        C += D

    C = [(i,t *second) for (i,t) in C]
    C = sorted(C, key=lambda x: x[1])

    reinit(states = True)
    clear(erase   = True, all = True)

    return C
예제 #6
0
import brian
import numpy as np
import os, sys

nruns = int(sys.argv[1])

for nrun in xrange(1, nruns + 1):
    brian.seed(nrun)
    print 'RUN: ' + str(nrun)
    brian.reinit(states=True)
    brian.clear(erase=True, all=True)
    rate = int(sys.argv[2])
    foldername = 'rate' + str(rate) + '/run_' + str(nrun)
    os.system('mkdir -p -v ' + foldername)

    N = 1000
    time_input = 23000 * brian.ms
    P = brian.PoissonGroup(N)
    S = brian.SpikeMonitor(P)

    P.rate = rate * brian.Hz
    brian.run(time_input, report='text', report_period=10 * brian.second)

    fname = 'noise_'
    for s in xrange(len(S.spiketimes)):
        spiketimes = [round(1000 * x, 1) + 50 for x in list(S.spiketimes[s])]
        np.savetxt(foldername + '/' + fname + str(s) + '.txt',
                   spiketimes,
                   fmt='%10.1f',
                   newline='\n')
예제 #7
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.0 / alpha)
    wie = 0.014 * dv * np.sqrt(1.0 / alpha)
    wii = -0.057 * dv * np.sqrt(1.0 / alpha)
    wei = -0.045 * dv * np.sqrt(1.0 / 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
예제 #8
0
import string
import struct

from brian import Network, Equations, NeuronGroup, Connection,\
    SpikeMonitor, raster_plot, StateMonitor, clear, reinit
from brian.stdunits import ms, mV, nS, pA, pF, Hz

for i in range(len(sys.argv)):
  if sys.argv[i] == "-rEE":
    rEE = float(sys.argv[i+1])

#%matplotlib inline
pylab.rcParams['figure.figsize'] = 12, 8  # changes figure size (width, height) for larger images

clear(True, True) 
reinit()# To reinit brain clocks and remove all old brian objects from namespace,
# it's usually a good idea to put this at the beginning of a script



# The equations defining our neuron model

eqs_string = ''' dV/dt = (1.0/tau)*(myu-V) + Isyn : 1
             Isyn =  Isyne - Isyni : hertz
             dIsyne/dt = -(1/tau1)*(Isyne + ye) : hertz
             dye/dt = -(1/tau2)*ye : hertz
             dIsyni/dt = -(1/tau1)*(Isyni + yi) : hertz
             dyi/dt = -(1/tau2)*yi : hertz
             myu : 1
             '''
예제 #9
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
예제 #10
0
    def _return_generator(self, simulation):
        '''
        Defines a simulation using a python generator.
        '''

        import brian
        import numpy

        print "Starting the simulation!"

        print "Reseting the Brian Simulation object...",
        brian.reinit(
        )  # This is only necessary when using the same enviroment over and over (like with iPython).
        print "Done!"

        clock_mult = self.step_size
        brian.defaultclock.dt = clock_mult * brian.ms

        print "Initial simulation time:", brian.defaultclock.t
        print "Simulation step:", brian.defaultclock.dt

        # Calls the user function with the Brian objects to be used in the simulation
        Input_layer, Output_layer, pop_objects, syn_objects, monitors_objects = simulation(
            brian.defaultclock, brian)

        output_spikes = []
        output_spikes_time = []

        # Every time spikes occur at the SpikeMonitor related to the output neuron group, this function is called
        def output_spikes_proc(spikes):
            if len(spikes):
                output_spikes.append(spikes.tolist(
                ))  # Saves the indexes of the neurons who generated spikes
                output_spikes_time.append(
                    1000 * float(brian.defaultclock.t)
                )  # Converts and save the actual time in ms
                # The spike monitor and all this code could be replaced by the .get_spikes() method of neurongroups.
                # I need to check what is fastest way!

        OutputMonitor = brian.SpikeMonitor(Output_layer,
                                           record=False,
                                           function=output_spikes_proc)
        # Because it is not saving, the system is not going to run out of memory after a long simulation.

        net = brian.Network(pop_objects + syn_objects + monitors_objects +
                            [OutputMonitor])

        r = 0
        while True:
            spiketimes = yield  # Receives the content from the Python generator method .send()
            if spiketimes:
                spiketimes = [
                    (i, brian.defaultclock.t) for i in spiketimes
                ]  # The spikes received are inserted as the last simulated time
                Input_layer.set_spiketimes(spiketimes)
            net.run(clock_mult * brian.ms
                    )  # I'm running one step each time this function is called
            r += 1
            yield (
                r,
                float(brian.defaultclock.t) * 1000,
                numpy.array(Input_layer.get_spiketimes()).astype(
                    dtype=numpy.float
                ),  # I'm doing this way to prove the spikes were received
                output_spikes,
                output_spikes_time
            )  # After the .send method, the generator executes this line and stops here

            output_spikes = [
            ]  # Cleans the output_spikes list so only the last spikes generated are sent
            output_spikes_time = [
            ]  # Cleans the output_spikes list so only the last spikes generated are sent