Example #1
0
    def internal_inhibition(self, w_range=[-0.2, 0.0], d_range=[2.0, 2.0]):
        """Connect the domains populations of the same variable using inhibitory synapses.

        the connectiviy establishes a lateral inhibition circuit over the domains of each variable, so that most of the
        time only the neurons from a single domain population are active.

        args:
            w_range: range for the random distribution of synaptic weights in the form [w_min, w_max].
            d_range: range for the random distribution of synaptic delays in the form [d_min, d_max].
        """
        print msg, 'Creating lateral inhibition between domains of each variable'
        delays = RandomDistribution('uniform', d_range)
        weights = RandomDistribution('uniform', w_range)
        connections = [(m, n, 0.0 if m // self.core_size == n //
                        self.core_size else weights.next(), delays.next())
                       for n in range(self.size) for m in range(self.size)]
        for variable in range(self.variables_number):
            if self.clues_inhibition:
                synapses = p.Projection(self.var_pops[variable],
                                        self.var_pops[variable],
                                        p.FromListConnector(connections,
                                                            safe=True),
                                        target="inhibitory")
                self.internal_conns.append(synapses)
            elif variable not in self.clues:
                synapses = p.Projection(self.var_pops[variable],
                                        self.var_pops[variable],
                                        p.FromListConnector(connections,
                                                            safe=True),
                                        target="inhibitory")
                self.internal_conns.append(synapses)
Example #2
0
    def connect_cores(self, w_range=[0.6, 1.2], d_range=[1.0, 1.2]):
        """Create internal excitatory connections between the neurons of each domain subpopulation of each variable.

        In the network representing the CSP, each neural population representing a variable contains a subpopulation
        for each possible value on its domain. This method connects all-to-all the neurons of each domain population
        of each variable using escitatory synapses.

        args:
            w_range: range for the random distribution of synaptic weights in the form [w_min, w_max].
            d_range: range for the random distribution of synaptic delays in the form [d_min, d_max].
        """
        print msg, 'internally connnecting the neurons of each domain of each variable'
        delays = RandomDistribution('uniform', d_range)
        weights = RandomDistribution('uniform', w_range)
        connections = [
            (m, n, weights.next() if m // self.core_size == n // self.core_size
             and m != n else 0.0, delays.next())
            for n in range(self.domain_size * self.core_size)
            for m in range(self.domain_size * self.core_size)
        ]
        for variable in range(self.variables_number):
            synapses = p.Projection(self.var_pops[variable],
                                    self.var_pops[variable],
                                    p.FromListConnector(connections,
                                                        safe=True),
                                    target="excitatory")
            self.core_conns.append(synapses)
 def generateRandomPattern(self, rng):
     """
     """
     unordered_events = list()
     rdNeurons = RandomDistribution('uniform', [0, self.totalNeurons-1], rng)
     rdTimes   = RandomDistribution('uniform', (0, self.cycleTime-1), rng)
     randomNeurons = rdNeurons.next(self.firing)
     randomTimes   = rdTimes.next(self.firing)
     for i in range(self.firing):
         unordered_events.append((int(randomNeurons[i]), int(randomTimes[i]*10)/10.0))
     #self.events = numpy.sort(unordered_events, 0)
     self.events = unordered_events
Example #4
0
    def poisson_spike_train(rate: float,
                            start: float = 0,
                            stop: float = runtime,
                            seed: int = 4245) -> np.array:
        """
        Generates a Poisson spike train.

        :param rate: Rate of the train in Hz.
        :param stop: Stop time of the spike train in ms.
        :param start: Start time of the spike train in ms.
        :param seed: Seed to use for the random number generator.

        :return: Spike times of Poisson spike train as an array.
        """
        assert start < stop, "Start time has to be shorter than stop time"

        # Use period in us to support non-integer spike times in ms
        period = 1 / rate * 1e6  # period in us

        poisson_dist = RandomDistribution("poisson",
                                          lambda_=period,
                                          rng=NumpyRNG(seed=seed))

        # Generate spike times till the stop time is exceeded
        spikes = []
        time = start
        while True:
            time += poisson_dist.next() / 1000  # convert from us to ms
            if time > stop:
                break
            spikes.append(time)

        return np.array(sorted(spikes))
Example #5
0
def generate_stimulus(start, stop, interval):
    rd = RandomDistribution('exponential', [interval], rng=rStim)
    t = start
    times = []
    while t < stop:
        t += rd.next()
        if t < stop:
            times.append(t)
    return times
Example #6
0
    def stimulate_cores(self,
                        w_range=[1.4, 1.4],
                        d_range=[1.0, 1.0],
                        w_clues=[1.4, 1.6]):  # w_clues=[0.0, 0.2]
        """Connect stimulating noise sources to variables populations.

        args:
            w_range: range for the random distribution of synaptic weights in the form [w_min, w_max].
            d_range: range for the random distribution of synaptic delays in the form [d_min, d_max].
            w_clues: clues specific range for the random distribution of synaptic weights in the form [w_min, w_max].
        """
        p.set_number_of_neurons_per_core(p.IF_curr_exp, 150)
        print msg, 'connecting Poisson noise sources to neural populations for stimulation'
        delays = RandomDistribution('uniform', d_range)
        weights = RandomDistribution('uniform', w_range)
        weight_clues = RandomDistribution("uniform", w_clues)
        for stimulus in range(self.n_populations):
            for variable in range(self.variables_number):
                counter = 0
                if variable in self.clues[0]:
                    shift = self.clues[1][self.clues[0].index(
                        variable)] * self.core_size
                    connections = [(m, n + shift, weight_clues.next(),
                                    delays.next())
                                   for m in range(self.core_size)
                                   for n in range(self.clue_size)]
                    synapses = p.Projection(self.clues_stim[counter],
                                            self.var_pops[variable],
                                            p.FromListConnector(connections,
                                                                safe=True),
                                            target='excitatory')
                    counter += 1
                    self.stim_conns.append(synapses)
                else:
                    synapses = p.Projection(
                        self.stim_pops[stimulus][variable],
                        self.var_pops[variable],
                        p.OneToOneConnector(weights=weights, delays=delays),
                        target='excitatory')
                    self.stim_conns.append(synapses)
        self.stim_times += self.stims
Example #7
0
 def _generate_random_values(
         self, values, n_connections, pre_vertex_slice, post_vertex_slice):
     """
     :param ~pyNN.random.NumpyRNG values:
     :param int n_connections:
     :param ~pacman.model.graphs.common.Slice pre_vertex_slice:
     :param ~pacman.model.graphs.common.Slice post_vertex_slice:
     :rtype: ~numpy.ndarray
     """
     key = (id(pre_vertex_slice), id(post_vertex_slice), id(values))
     seed = self.__param_seeds.get(key, None)
     if seed is None:
         seed = int(values.rng.next() * 0x7FFFFFFF)
         self.__param_seeds[key] = seed
     new_rng = NumpyRNG(seed)
     copy_rd = RandomDistribution(
         values.name, parameters_pos=None, rng=new_rng,
         **values.parameters)
     if n_connections == 1:
         return numpy.array([copy_rd.next(1)], dtype="float64")
     return copy_rd.next(n_connections)
    def buildStream(self, numSources=None, patterns=None, interPatternGap=10, rng=None, offset=0.0, order=None, noise=None, printTimes = False):
        """
        """
        # Establish a list of times at which pattern start firing:
        patternTimes = list()
        recallStartTime = 0
        # Create empty streams, one per source neuron:
        for i in range(numSources):
             self.streams.append(list())

        # Go through order parameter, which is a list of the patterns to be appended.
        # For each one, append it.
        timePtr = 0
        jitterDistribution = RandomDistribution('normal', (0.0, patterns[0].jitterSD), rng = rng)
        for entry in order:
            if entry < 0:
                # Add blank entry:
                patternEntry = [entry, timePtr]
                patternTimes.append(patternEntry)
                # Create a gap (20ms):
                timePtr += 20
                if entry == -1:
                    recallStartTime = timePtr
            else:
                if printTimes:
                    print "Pattern ", entry, " starts at time ", timePtr
                if entry >= len(patterns):
                    print "ERROR: Pattern set requested pattern ", entry, \
                          " and pattern set has only ", len(patterns), " patterns"
                    return -1
                patternEntry = [entry, timePtr]
                patternTimes.append(patternEntry)
                pattern = patterns[entry]
                biggestTimestamp = 0
                for element in pattern.events:
                    index, timestamp = element
                    timestamp += offset
                    if patterns[0].jitterSD > 0:
                        newNum = jitterDistribution.next(1)
                        #print "Base T: ", timestamp, " : ", newNum,
                        timestamp += newNum
                        if timestamp < 0:
                           timestamp = 0.0
                        #print ", new: ", timestamp
                    biggestTimestamp = max(biggestTimestamp, timestamp)
                    self.streams[index].append(timePtr + timestamp)
                timePtr += pattern.cycleTime + interPatternGap
        self.endTime = timePtr
        return recallStartTime, patternTimes
Example #9
0
    def connect(self, projection):
        # This implementation is not "parallel safe" for random numbers.
        # todo: support the `parallel_safe` flag.

        # Determine number of processes and current rank
        rank = projection._simulator.state.mpi_rank
        num_processes = projection._simulator.state.num_processes

        # Assume that targets are equally distributed over processes
        targets_per_process = int(len(projection.post) / num_processes)

        # Calculate the number of synapses on each process
        bino = RandomDistribution(
            'binomial', [self.n, targets_per_process / len(projection.post)],
            rng=self.rng)
        num_conns_on_vp = numpy.zeros(num_processes, dtype=int)
        sum_dist = 0
        sum_partitions = 0
        for k in range(num_processes):
            p_local = targets_per_process / (len(projection.post) - sum_dist)
            bino.parameters['p'] = p_local
            bino.parameters['n'] = self.n - sum_partitions
            num_conns_on_vp[k] = bino.next()
            sum_dist += targets_per_process
            sum_partitions += num_conns_on_vp[k]

        # Draw random sources and targets
        connections = [[] for i in range(projection.post.size)]
        possible_targets = numpy.arange(
            projection.post.size)[projection.post._mask_local]
        for i in range(num_conns_on_vp[rank]):
            source_index = self.rng.next(1,
                                         'uniform_int', {
                                             "low": 0,
                                             "high": projection.pre.size
                                         },
                                         mask=None)[0]
            target_index = self.rng.choice(possible_targets, size=1)[0]
            connections[target_index].append(source_index)

        def build_source_masks(mask=None):
            if mask is None:
                return [numpy.array(x) for x in connections]
            else:
                return [numpy.array(x) for x in numpy.array(connections)[mask]]

        self._standard_connect(projection, build_source_masks)
Example #10
0
    def connect(self, projection):
        # Determine number of processes and current rank
        rank, num_processes = get_mpi_config()

        # Assume that targets are equally distributed over processes
        targets_per_process = int(len(projection.post) / num_processes)

        # Calculate the number of synapses on each process
        bino = RandomDistribution(
            'binomial', [self.n, targets_per_process / len(projection.post)],
            rng=self.rng)
        num_conns_on_vp = numpy.zeros(num_processes)
        sum_dist = 0
        sum_partitions = 0
        for k in xrange(num_processes):
            p_local = targets_per_process / (len(projection.post) - sum_dist)
            bino.parameters['p'] = p_local
            bino.parameters['n'] = self.n - sum_partitions
            num_conns_on_vp[k] = bino.next()
            sum_dist += targets_per_process
            sum_partitions += num_conns_on_vp[k]

        # Draw random sources and targets
        while num_conns_on_vp[rank] > 0:
            s_index = self.rng.rng.randint(low=0,
                                           high=len(projection.pre.all_cells))
            t_index = self.rng.rng.randint(low=0,
                                           high=len(
                                               projection.post.local_cells))
            t_index = numpy.where(projection.post.all_cells == int(
                projection.post.local_cells[t_index]))[0][0]

            # Evaluate the lazy arrays containing the synaptic parameters
            parameter_space = self._parameters_from_synapse_type(projection)
            connection_parameters = {}
            for name, map in parameter_space.items():
                if map.is_homogeneous:
                    connection_parameters[name] = map.evaluate(simplify=True)
                else:
                    connection_parameters[name] = map[source_mask, col]

            projection._convergent_connect(numpy.array([s_index]), t_index,
                                           **connection_parameters)
            num_conns_on_vp[rank] -= 1
Example #11
0
    def connect(self, projection):
        # This implementation is not "parallel safe" for random numbers.
        # todo: support the `parallel_safe` flag.

        # Determine number of processes and current rank
        rank = projection._simulator.state.mpi_rank
        num_processes = projection._simulator.state.num_processes

        # Assume that targets are equally distributed over processes
        targets_per_process = int(len(projection.post) / num_processes)
            
        # Calculate the number of synapses on each process
        bino = RandomDistribution('binomial',
                                  [self.n, targets_per_process / len(projection.post)],
                                  rng=self.rng)
        num_conns_on_vp = numpy.zeros(num_processes, dtype=int)
        sum_dist = 0
        sum_partitions = 0
        for k in range(num_processes):
            p_local = targets_per_process / (len(projection.post) - sum_dist)
            bino.parameters['p'] = p_local
            bino.parameters['n'] = self.n - sum_partitions
            num_conns_on_vp[k] = bino.next()
            sum_dist += targets_per_process
            sum_partitions += num_conns_on_vp[k]

        # Draw random sources and targets 
        connections = [[] for i in range(projection.post.size)]
        possible_targets = numpy.arange(projection.post.size)[projection.post._mask_local]
        for i in range(num_conns_on_vp[rank]):
            source_index = self.rng.next(1, 'uniform_int',
                                         {"low": 0, "high": projection.pre.size},
                                         mask_local=False)[0]
            target_index = self.rng.choice(possible_targets, size=1)[0]
            connections[target_index].append(source_index)

        def build_source_masks(mask=None):
            if mask is None:
                return [numpy.array(x) for x in connections]
            else:
                return [numpy.array(x) for x in numpy.array(connections)[mask]]
        self._standard_connect(projection, build_source_masks)
Example #12
0
    def connect(self, projection):
        # Determine number of processes and current rank
        rank, num_processes = get_mpi_config()

        # Assume that targets are equally distributed over processes
        targets_per_process = int(len(projection.post)/num_processes)
            
        # Calculate the number of synapses on each process
        bino = RandomDistribution('binomial',[self.n,targets_per_process/len(projection.post)], rng=self.rng)
        num_conns_on_vp = numpy.zeros(num_processes)
        sum_dist = 0
        sum_partitions = 0
        for k in xrange(num_processes) :
            p_local = targets_per_process / ( len(projection.post) - sum_dist)
            bino.parameters['p'] = p_local
            bino.parameters['n'] = self.n - sum_partitions
            num_conns_on_vp[k] = bino.next()
            sum_dist += targets_per_process
            sum_partitions += num_conns_on_vp[k]

        # Draw random sources and targets 
        while num_conns_on_vp[rank] > 0 :
            s_index = self.rng.rng.randint(low=0, high=len(projection.pre.all_cells))
            t_index = self.rng.rng.randint(low=0, high=len(projection.post.local_cells))
            t_index = numpy.where(projection.post.all_cells == int(projection.post.local_cells[t_index]))[0][0]

            # Evaluate the lazy arrays containing the synaptic parameters
            parameter_space = self._parameters_from_synapse_type(projection)
            connection_parameters = {}
            for name, map in parameter_space.items():
                if map.is_homogeneous:
                    connection_parameters[name] = map.evaluate(simplify=True)
                else:
                    connection_parameters[name] = map[source_mask, col]
            
            projection._convergent_connect(numpy.array([s_index]),t_index, **connection_parameters)
            num_conns_on_vp[rank] -=1
def obtain_synapses(wiring_plan):

    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)
    weight_distr = RandomDistribution('normal', [45, 1e-1], rng=rng)


    flat_iter = [ (i,j,k,xaxis) for i,j in enumerate(filtered) for k,xaxis in enumerate(j) ]
    index_exc = list(set( source for (source,j,target,xaxis) in flat_iter if xaxis==1 or xaxis == 2 ))
    index_inh = list(set( source for (source,j,target,xaxis) in flat_iter if xaxis==-1 or xaxis == -2 ))

    EElist = []
    IIlist = []
    EIlist = []
    IElist = []
    for (source,j,target,xaxis) in flat_iter:
        delay = delay_distr.next()
        weight = 1.0 # will be updated later.
        if xaxis==1 or xaxis == 2:
            if target in index_inh:
                EIlist.append((source,target,delay,weight))
            else:
                EElist.append((source,target,delay,weight))

        if xaxis==-1 or xaxis == -2:
            if target in index_exc:
                IElist.append((source,target,delay,weight))
            else:
                IIlist.append((source,target,delay,weight))

    conn_ee = sim.FromListConnector(EElist)
    conn_ie = sim.FromListConnector(IElist)
    conn_ei = sim.FromListConnector(EIlist)
    conn_ii = sim.FromListConnector(IIlist)

    return (conn_ee, conn_ie, conn_ei, conn_ii,index_exc,index_inh)
Example #14
0
delay_distr = RandomDistribution('normal', [45, 1e-1], rng=rng)

index_exc = [i for i, d in enumerate(dfm) if '+' in d[0]]
index_inh = [i for i, d in enumerate(dfm) if '-' in d[0]]

EElist = []
IIlist = []
EIlist = []
IElist = []

for i, j in enumerate(filtered):
    for k, xaxis in enumerate(j):
        if xaxis == 1 or xaxis == 2:
            source = i
            target = k
            delay = delay_distr.next()
            weight = 11.0
            if target in index_inh:
                EIlist.append((source, target, delay, weight))
            else:
                EElist.append((source, target, delay, weight))

        if xaxis == -1 or xaxis == -2:
            source = i
            target = k
            delay = delay_distr.next()
            weight = 11.0
            if target in index_exc:
                IElist.append((source, target, delay, weight))
            else:
                IIlist.append((source, target, delay, weight))
    # Initialising membrane potential to random values
    vrest_sd = 5
    vrest_distr = RandomDistribution('uniform', [
        Vrest_Pyr - numpy.sqrt(3) * vrest_sd,
        Vrest_Pyr + numpy.sqrt(3) * vrest_sd
    ], rng)

    Pyr_net = []

    for sp in range(NP):
        print "%d Creating pyramidal cell population %d  with %d neurons." % (
            rank, sp, N_Pyr)
        Pyr_subnet = Population((N_Pyr, ), IF_cond_exp, cell_params_Pyr)
        for cell in Pyr_subnet:
            vrest_rval = vrest_distr.next(1)
            cell.set_parameters(v_rest=vrest_rval)
        Pyr_net.append(Pyr_subnet)

    print "%d Creating basket cell population with %d neurons." % (rank, N_Bas)
    Bas_net = Population((N_Bas, ), IF_cond_exp, cell_params_Bas)

    print "%d Creating slow inhibitory population with %d neurons." % (rank,
                                                                       N_Sli)
    Sli_net = Population((N_Sli, ), IF_cond_exp, cell_params_Sli)

    # Creating external input - is this correct on multiple threads?
    Pyr_input = []

    for sp in range(NP):
        print "%d Creating pyramidal cell external input %d with rate %g spikes/s." % (
Example #16
0
def sim_runner(wg):

    #import pyNN.neuron as sim
    try:
        import pyNN.spiNNaker as sim
    except:
        import pyNN.neuron as sim

    nproc = sim.num_processes()
    node = sim.rank()
    print(nproc)

    #import mpi4py
    #threads  = sim.rank()
    threads = 1
    rngseed = 98765
    parallel_safe = False
    #extra = {'threads' : threads}

    # Get some hippocampus connectivity data, based on a conversation with
    # academic researchers on GH:
    # https://github.com/Hippocampome-Org/GraphTheory/issues?q=is%3Aissue+is%3Aclosed
    # scrape hippocamome connectivity data, that I intend to use to program neuromorphic hardware.
    # conditionally get files if they don't exist.

    # This is literally the starting point of the connection map
    path_xl = '_hybrid_connectivity_matrix_20171103_092033.xlsx'

    if not os.path.exists(path_xl):
        os.system(
            'wget https://github.com/Hippocampome-Org/GraphTheory/files/1657258/_hybrid_connectivity_matrix_20171103_092033.xlsx'
        )

    xl = pd.ExcelFile(path_xl)

    dfall = xl.parse()
    dfall.loc[0].keys()
    dfm = dfall.as_matrix()

    rcls = dfm[:, :1]  # real cell labels.
    rcls = rcls[1:]
    rcls = {k: v
            for k, v in enumerate(rcls)
            }  # real cell labels, cast to dictionary
    import pickle

    with open('cell_names.p', 'wb') as f:
        pickle.dump(rcls, f)
    pd.DataFrame(rcls).to_csv('cell_names.csv', index=False)

    filtered = dfm[:, 3:]
    filtered = filtered[1:]
    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)
    weight_distr = RandomDistribution('normal', [45, 1e-1], rng=rng)

    sanity_e = []
    sanity_i = []

    EElist = []
    IIlist = []
    EIlist = []
    IElist = []

    with open('wire_map_online.p', 'wb') as f:
        pickle.dump(filtered, f)

    for i, j in enumerate(filtered):
        for k, xaxis in enumerate(j):
            if xaxis == 1 or xaxis == 2:
                source = i
                sanity_e.append(i)
                target = k

            if xaxis == -1 or xaxis == -2:
                sanity_i.append(i)
                source = i
                target = k

    index_exc = list(set(sanity_e))
    index_inh = list(set(sanity_i))
    import pickle
    with open('cell_indexs.p', 'wb') as f:
        returned_list = [index_exc, index_inh]
        pickle.dump(returned_list, f)
    '''
    import numpy
    a = numpy.asarray(index_exc)
    numpy.savetxt('pickles/'+str(k)+'excitatory_nunber_labels.csv', a, delimiter=",")
    a = numpy.asarray(index_inh)
    numpy.savetxt('pickles/'+str(k)+'inhibitory_nunber_labels.csv', a, delimiter=",")
    '''
    for i, j in enumerate(filtered):
        for k, xaxis in enumerate(j):
            if xaxis == 1 or xaxis == 2:
                source = i
                sanity_e.append(i)
                target = k
                delay = delay_distr.next()
                weight = 1.0
                if target in index_inh:
                    EIlist.append((source, target, delay, weight))
                else:
                    EElist.append((source, target, delay, weight))

            if xaxis == -1 or xaxis == -2:
                sanity_i.append(i)

                source = i
                target = k
                delay = delay_distr.next()
                weight = 1.0
                if target in index_exc:
                    IElist.append((source, target, delay, weight))
                else:
                    IIlist.append((source, target, delay, weight))

    internal_conn_ee = sim.FromListConnector(EElist)
    ee = internal_conn_ee.conn_list

    ee_srcs = ee[:, 0]
    ee_tgs = ee[:, 1]

    internal_conn_ie = sim.FromListConnector(IElist)
    ie = internal_conn_ie.conn_list
    ie_srcs = set([int(e[0]) for e in ie])
    ie_tgs = set([int(e[1]) for e in ie])

    internal_conn_ei = sim.FromListConnector(EIlist)
    ei = internal_conn_ei.conn_list
    ei_srcs = set([int(e[0]) for e in ei])
    ei_tgs = set([int(e[1]) for e in ei])

    internal_conn_ii = sim.FromListConnector(IIlist)
    ii = internal_conn_ii.conn_list
    ii_srcs = set([int(e[0]) for e in ii])
    ii_tgs = set([int(e[1]) for e in ii])

    for e in internal_conn_ee.conn_list:
        assert e[0] in ee_srcs
        assert e[1] in ee_tgs

    for i in internal_conn_ii.conn_list:
        assert i[0] in ii_srcs
        assert i[1] in ii_tgs

    ml = len(filtered[1]) + 1
    pre_exc = []
    post_exc = []
    pre_inh = []
    post_inh = []

    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)

    plot_EE = np.zeros(shape=(ml, ml), dtype=bool)
    plot_II = np.zeros(shape=(ml, ml), dtype=bool)
    plot_EI = np.zeros(shape=(ml, ml), dtype=bool)
    plot_IE = np.zeros(shape=(ml, ml), dtype=bool)

    for i in EElist:
        plot_EE[i[0], i[1]] = int(0)
        if i[0] != i[1]:  # exclude self connections
            plot_EE[i[0], i[1]] = int(1)
            pre_exc.append(i[0])
            post_exc.append(i[1])

    assert len(pre_exc) == len(post_exc)
    for i in IIlist:
        plot_II[i[0], i[1]] = int(0)
        if i[0] != i[1]:
            plot_II[i[0], i[1]] = int(1)
            pre_inh.append(i[0])
            post_inh.append(i[1])

    for i in IElist:
        plot_IE[i[0], i[1]] = int(0)
        if i[0] != i[1]:  # exclude self connections
            plot_IE[i[0], i[1]] = int(1)
            pre_inh.append(i[0])
            post_inh.append(i[1])

    for i in EIlist:
        plot_EI[i[0], i[1]] = int(0)
        if i[0] != i[1]:
            plot_EI[i[0], i[1]] = int(1)
            pre_exc.append(i[0])
            post_exc.append(i[1])

    plot_excit = plot_EI + plot_EE
    plot_inhib = plot_IE + plot_II

    assert len(pre_inh) == len(post_inh)

    num_exc = [i for i, e in enumerate(plot_excit) if sum(e) > 0]
    num_inh = [y for y, i in enumerate(plot_inhib) if sum(i) > 0]

    # the network is dominated by inhibitory neurons, which is unusual for modellers.
    assert num_inh > num_exc
    assert np.sum(plot_inhib) > np.sum(plot_excit)
    assert len(num_exc) < ml
    assert len(num_inh) < ml
    # # Plot all the Projection pairs as a connection matrix (Excitatory and Inhibitory Connections)

    nproc = sim.num_processes()
    nproc = 8
    host_name = socket.gethostname()
    node_id = sim.setup(timestep=0.01, min_delay=1.0)  #, **extra)
    print("Host #%d is on %s" % (node_id + 1, host_name))
    rng = NumpyRNG(seed=64754)

    all_cells = sim.Population(
        len(index_exc) + len(index_inh),
        sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0))
    pop_exc = sim.PopulationView(all_cells, index_exc)
    pop_inh = sim.PopulationView(all_cells, index_inh)

    for pe in pop_exc:
        pe = all_cells[pe]
        r = random.uniform(0.0, 1.0)
        pe.set_parameters(a=0.02,
                          b=0.2,
                          c=-65 + 15 * r,
                          d=8 - r**2,
                          i_offset=0)

    for pi in index_inh:
        pi = all_cells[pi]
        r = random.uniform(0.0, 1.0)
        pi.set_parameters(a=0.02 + 0.08 * r,
                          b=0.25 - 0.05 * r,
                          c=-65,
                          d=2,
                          i_offset=0)

    NEXC = len(num_exc)
    NINH = len(num_inh)

    exc_syn = sim.StaticSynapse(weight=wg, delay=delay_distr)
    assert np.any(internal_conn_ee.conn_list[:, 0]) < ee_srcs.size
    prj_exc_exc = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ee,
                                 exc_syn,
                                 receptor_type='excitatory')
    prj_exc_inh = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ei,
                                 exc_syn,
                                 receptor_type='excitatory')
    inh_syn = sim.StaticSynapse(weight=wg, delay=delay_distr)
    delay_distr = RandomDistribution('normal', [1, 100e-3], rng=rng)
    prj_inh_inh = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ii,
                                 inh_syn,
                                 receptor_type='inhibitory')
    prj_inh_exc = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ie,
                                 inh_syn,
                                 receptor_type='inhibitory')
    inh_distr = RandomDistribution('normal', [1, 2.1e-3], rng=rng)

    ext_Connector = OneToOneConnector(callback=progress_bar)
    ext_syn = StaticSynapse(weight=JE, delay=dt)
    '''
    print("%d Connecting excitatory population with connection probability %g, weight %g nA and delay %g ms." % (rank, epsilon, JE, delay))
    E_to_E = Projection(E_net, E_net, connector, E_syn, receptor_type="excitatory")
    print("E --> E\t\t", len(E_to_E), "connections")
    I_to_E = Projection(I_net, E_net, connector, I_syn, receptor_type="inhibitory")
    print("I --> E\t\t", len(I_to_E), "connections")
    input_to_E = Projection(expoisson, E_net, ext_Connector, ext_syn, receptor_type="excitatory")
    print("input --> E\t", len(input_to_E), "connections")

    print("%d Connecting inhibitory population with connection probability %g, weight %g nA and delay %g ms." % (rank, epsilon, JI, delay))
    E_to_I = Projection(E_net, I_net, connector, E_syn, receptor_type="excitatory")
    print("E --> I\t\t", len(E_to_I), "connections")
    I_to_I = Projection(I_net, I_net, connector, I_syn, receptor_type="inhibitory")
    print("I --> I\t\t", len(I_to_I), "connections")
    input_to_I = Projection(inpoisson, I_net, ext_Connector, ext_syn, receptor_type="excitatory")
    print("input --> I\t", len(input_to_I), "connections")
    '''
    def prj_change(prj, wg):
        prj.setWeights(wg)

    prj_change(prj_exc_exc, wg)
    prj_change(prj_exc_inh, wg)
    prj_change(prj_inh_exc, wg)
    prj_change(prj_inh_inh, wg)

    def prj_check(prj):
        for w in prj.weightHistogram():
            for i in w:
                print(i)

    prj_check(prj_exc_exc)
    prj_check(prj_exc_inh)
    prj_check(prj_inh_exc)
    prj_check(prj_inh_inh)

    #print(rheobase['value'])
    #print(float(rheobase['value']),1.25/1000.0)
    '''Old values that worked
    noise = sim.NoisyCurrentSource(mean=0.85/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_exc.inject(noise)
    #1000.0 pA


    noise = sim.NoisyCurrentSource(mean=1.740/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_inh.inject(noise)
    #1750.0 pA
    '''

    noise = sim.NoisyCurrentSource(mean=0.74 / 1000.0,
                                   stdev=4.00 / 1000.0,
                                   start=0.0,
                                   stop=2000.0,
                                   dt=1.0)
    pop_exc.inject(noise)
    #1000.0 pA

    noise = sim.NoisyCurrentSource(mean=1.440 / 1000.0,
                                   stdev=4.00 / 1000.0,
                                   start=0.0,
                                   stop=2000.0,
                                   dt=1.0)
    pop_inh.inject(noise)

    ##
    # Setup and run a simulation. Note there is no current injection into the neuron.
    # All cells in the network are in a quiescent state, so its not a surprise that xthere are no spikes
    ##

    sim = pyNN.neuron
    arange = np.arange
    import re
    all_cells.record(['v', 'spikes'])  # , 'u'])
    all_cells.initialize(v=-65.0, u=-14.0)
    # === Run the simulation =====================================================
    tstop = 2000.0
    sim.run(tstop)
    data = None
    data = all_cells.get_data().segments[0]

    if not os.path.exists("pickles"):
        os.mkdir("pickles")

    #print(len(data.analogsignals[0].times))
    with open('pickles/qi' + str(wg) + '.p', 'wb') as f:
        pickle.dump(data, f)
    # make data none or else it will grow in a loop
    all_cells = None
    data = None
    noise = None
Example #17
0
def sim_runner(wgf):
    wg = wgf

    import pyNN.neuron as sim
    nproc = sim.num_processes()
    node = sim.rank()
    print(nproc)
    import matplotlib
    matplotlib.use('Agg')

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    mpl.rcParams.update({'font.size':16})

    #import mpi4py
    #threads  = sim.rank()
    threads = 1
    rngseed  = 98765
    parallel_safe = False
    #extra = {'threads' : threads}
    import os
    import pandas as pd
    import sys
    import numpy as np
    from pyNN.neuron import STDPMechanism
    import copy
    from pyNN.random import RandomDistribution, NumpyRNG
    import pyNN.neuron as neuron
    from pyNN.neuron import h
    from pyNN.neuron import StandardCellType, ParameterSpace
    from pyNN.random import RandomDistribution, NumpyRNG
    from pyNN.neuron import STDPMechanism, SpikePairRule, AdditiveWeightDependence, FromListConnector, TsodyksMarkramSynapse
    from pyNN.neuron import Projection, OneToOneConnector
    from numpy import arange
    import pyNN
    from pyNN.utility import get_simulator, init_logging, normalized_filename
    import random
    import socket
    #from neuronunit.optimization import get_neab
    import networkx as nx
    sim = pyNN.neuron

    # Get some hippocampus connectivity data, based on a conversation with
    # academic researchers on GH:
    # https://github.com/Hippocampome-Org/GraphTheory/issues?q=is%3Aissue+is%3Aclosed
    # scrape hippocamome connectivity data, that I intend to use to program neuromorphic hardware.
    # conditionally get files if they don't exist.


    path_xl = '_hybrid_connectivity_matrix_20171103_092033.xlsx'
    if not os.path.exists(path_xl):
        os.system('wget https://github.com/Hippocampome-Org/GraphTheory/files/1657258/_hybrid_connectivity_matrix_20171103_092033.xlsx')

    xl = pd.ExcelFile(path_xl)
    dfEE = xl.parse()
    dfEE.loc[0].keys()
    dfm = dfEE.as_matrix()

    rcls = dfm[:,:1] # real cell labels.
    rcls = rcls[1:]
    rcls = { k:v for k,v in enumerate(rcls) } # real cell labels, cast to dictionary
    import pickle
    with open('cell_names.p','wb') as f:
        pickle.dump(rcls,f)
    import pandas as pd
    pd.DataFrame(rcls).to_csv('cell_names.csv', index=False)

    filtered = dfm[:,3:]
    filtered = filtered[1:]
    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)
    weight_distr = RandomDistribution('normal', [45, 1e-1], rng=rng)


    sanity_e = []
    sanity_i = []

    EElist = []
    IIlist = []
    EIlist = []
    IElist = []

    for i,j in enumerate(filtered):
      for k,xaxis in enumerate(j):
        if xaxis == 1 or xaxis == 2:
          source = i
          sanity_e.append(i)
          target = k

        if xaxis ==-1 or xaxis == -2:
          sanity_i.append(i)
          source = i
          target = k

    index_exc = list(set(sanity_e))
    index_inh = list(set(sanity_i))
    import pickle
    with open('cell_indexs.p','wb') as f:
        returned_list = [index_exc, index_inh]
        pickle.dump(returned_list,f)

    import numpy
    a = numpy.asarray(index_exc)
    numpy.savetxt('pickles/'+str(k)+'excitatory_nunber_labels.csv', a, delimiter=",")
    import numpy
    a = numpy.asarray(index_inh)
    numpy.savetxt('pickles/'+str(k)+'inhibitory_nunber_labels.csv', a, delimiter=",")

    for i,j in enumerate(filtered):
      for k,xaxis in enumerate(j):
        if xaxis==1 or xaxis == 2:
          source = i
          sanity_e.append(i)
          target = k
          delay = delay_distr.next()
          weight = 1.0
          if target in index_inh:
             EIlist.append((source,target,delay,weight))
          else:
             EElist.append((source,target,delay,weight))

        if xaxis==-1 or xaxis == -2:
          sanity_i.append(i)

          source = i
          target = k
          delay = delay_distr.next()
          weight = 1.0
          if target in index_exc:
              IElist.append((source,target,delay,weight))
          else:
              IIlist.append((source,target,delay,weight))


    internal_conn_ee = sim.FromListConnector(EElist)
    ee = internal_conn_ee.conn_list

    ee_srcs = ee[:,0]
    ee_tgs = ee[:,1]

    internal_conn_ie = sim.FromListConnector(IElist)
    ie = internal_conn_ie.conn_list
    ie_srcs = set([ int(e[0]) for e in ie ])
    ie_tgs = set([ int(e[1]) for e in ie ])

    internal_conn_ei = sim.FromListConnector(EIlist)
    ei = internal_conn_ei.conn_list
    ei_srcs = set([ int(e[0]) for e in ei ])
    ei_tgs = set([ int(e[1]) for e in ei ])

    internal_conn_ii = sim.FromListConnector(IIlist)
    ii = internal_conn_ii.conn_list
    ii_srcs = set([ int(e[0]) for e in ii ])
    ii_tgs = set([ int(e[1]) for e in ii ])

    for e in internal_conn_ee.conn_list:
        assert e[0] in ee_srcs
        assert e[1] in ee_tgs

    for i in internal_conn_ii.conn_list:
        assert i[0] in ii_srcs
        assert i[1] in ii_tgs


    ml = len(filtered[1])+1
    pre_exc = []
    post_exc = []
    pre_inh = []
    post_inh = []


    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)

    plot_EE = np.zeros(shape=(ml,ml), dtype=bool)
    plot_II = np.zeros(shape=(ml,ml), dtype=bool)
    plot_EI = np.zeros(shape=(ml,ml), dtype=bool)
    plot_IE = np.zeros(shape=(ml,ml), dtype=bool)

    for i in EElist:
        plot_EE[i[0],i[1]] = int(0)
        #plot_ss[i[0],i[1]] = int(1)

        if i[0]!=i[1]: # exclude self connections
            plot_EE[i[0],i[1]] = int(1)

            pre_exc.append(i[0])
            post_exc.append(i[1])



    assert len(pre_exc) == len(post_exc)
    for i in IIlist:
        plot_II[i[0],i[1]] = int(0)
        if i[0]!=i[1]:
            plot_II[i[0],i[1]] = int(1)
            pre_inh.append(i[0])
            post_inh.append(i[1])

    for i in IElist:
        plot_IE[i[0],i[1]] = int(0)
        if i[0]!=i[1]: # exclude self connections
            plot_IE[i[0],i[1]] = int(1)
            pre_inh.append(i[0])
            post_inh.append(i[1])

    for i in EIlist:
        plot_EI[i[0],i[1]] = int(0)
        if i[0]!=i[1]:
            plot_EI[i[0],i[1]] = int(1)
            pre_exc.append(i[0])
            post_exc.append(i[1])

    plot_excit = plot_EI + plot_EE
    plot_inhib = plot_IE + plot_II

    assert len(pre_inh) == len(post_inh)

    num_exc = [ i for i,e in enumerate(plot_excit) if sum(e) > 0 ]
    num_inh = [ y for y,i in enumerate(plot_inhib) if sum(i) > 0 ]

    # the network is dominated by inhibitory neurons, which is unusual for modellers.
    assert num_inh > num_exc
    assert np.sum(plot_inhib) > np.sum(plot_excit)
    assert len(num_exc) < ml
    assert len(num_inh) < ml
    # # Plot all the Projection pairs as a connection matrix (Excitatory and Inhibitory Connections)

    import pickle
    with open('graph_inhib.p','wb') as f:
       pickle.dump(plot_inhib,f, protocol=2)


    import pickle
    with open('graph_excit.p','wb') as f:
       pickle.dump(plot_excit,f, protocol=2)


    #with open('cell_names.p','wb') as f:
    #    pickle.dump(rcls,f)
    import pandas as pd
    pd.DataFrame(plot_EE).to_csv('ee.csv', index=False)

    import pandas as pd
    pd.DataFrame(plot_IE).to_csv('ie.csv', index=False)

    import pandas as pd
    pd.DataFrame(plot_II).to_csv('ii.csv', index=False)

    import pandas as pd
    pd.DataFrame(plot_EI).to_csv('ei.csv', index=False)


    from scipy.sparse import coo_matrix
    m = np.matrix(filtered[1:])

    bool_matrix = np.add(plot_excit,plot_inhib)
    with open('bool_matrix.p','wb') as f:
       pickle.dump(bool_matrix,f, protocol=2)

    if not isinstance(m, coo_matrix):
        m = coo_matrix(m)

    Gexc_ud = nx.Graph(plot_excit)
    avg_clustering = nx.average_clustering(Gexc_ud)#, nodes=None, weight=None, count_zeros=True)[source]

    rc = nx.rich_club_coefficient(Gexc_ud,normalized=False)
    print('This graph structure as rich as: ',rc[0])
    gexc = nx.DiGraph(plot_excit)

    gexcc = nx.betweenness_centrality(gexc)
    top_exc = sorted(([ (v,k) for k, v in dict(gexcc).items() ]), reverse=True)

    in_degree = gexc.in_degree()
    top_in = sorted(([ (v,k) for k, v in in_degree.items() ]))
    in_hub = top_in[-1][1]
    out_degree = gexc.out_degree()
    top_out = sorted(([ (v,k) for k, v in out_degree.items() ]))
    out_hub = top_out[-1][1]
    mean_out = np.mean(list(out_degree.values()))
    mean_in = np.mean(list(in_degree.values()))

    mean_conns = int(mean_in + mean_out/2)

    k = 2 # number of neighbouig nodes to wire.
    p = 0.25 # probability of instead wiring to a random long range destination.
    ne = len(plot_excit)# size of small world network
    small_world_ring_excit = nx.watts_strogatz_graph(ne,mean_conns,0.25)



    k = 2 # number of neighbouring nodes to wire.
    p = 0.25 # probability of instead wiring to a random long range destination.
    ni = len(plot_inhib)# size of small world network
    small_world_ring_inhib   = nx.watts_strogatz_graph(ni,mean_conns,0.25)


    nproc = sim.num_processes()
    nproc = 8
    host_name = socket.gethostname()
    node_id = sim.setup(timestep=0.01, min_delay=1.0)#, **extra)
    print("Host #%d is on %s" % (node_id + 1, host_name))
    rng = NumpyRNG(seed=64754)

    #pop_size = len(num_exc)+len(num_inh)
    #num_exc = [ i for i,e in enumerate(plot_excit) if sum(e) > 0 ]
    #num_inh = [ y for y,i in enumerate(plot_inhib) if sum(i) > 0 ]
    #pop_exc =  sim.Population(len(num_exc), sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0))
    #pop_inh = sim.Population(len(num_inh), sim.Izhikevich(a=0.02, b=0.25, c=-65, d=2, i_offset=0))


    #index_exc = list(set(sanity_e))
    #index_inh = list(set(sanity_i))
    all_cells = sim.Population(len(index_exc)+len(index_inh), sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0))
    #all_cells = None
    #all_cells = pop_exc + pop_inh
    pop_exc = sim.PopulationView(all_cells,index_exc)
    pop_inh = sim.PopulationView(all_cells,index_inh)
    #print(pop_exc)
    #print(dir(pop_exc))
    for pe in pop_exc:
        print(pe)
        #import pdb
        pe = all_cells[pe]
        #pdb.set_trace()
        #pe = all_cells[i]
        r = random.uniform(0.0, 1.0)
        pe.set_parameters(a=0.02, b=0.2, c=-65+15*r, d=8-r**2, i_offset=0)
        #pop_exc.append(pe)

    #pop_exc = sim.Population(pop_exc)
    for pi in index_inh:
        pi = all_cells[pi]
        #print(pi)
        #pi = all_cells[i]
        r = random.uniform(0.0, 1.0)
        pi.set_parameters(a=0.02+0.08*r, b=0.25-0.05*r, c=-65, d= 2, i_offset=0)
        #pop_inh.append(pi)
    #pop_inh = sim.Population(pop_inh)

    '''
    for pe in pop_exc:
        r = random.uniform(0.0, 1.0)
        pe.set_parameters(a=0.02, b=0.2, c=-65+15*r, d=8-r**2, i_offset=0)

    for pi in pop_inh:
        r = random.uniform(0.0, 1.0)
        pi.set_parameters(a=0.02+0.08*r, b=0.25-0.05*r, c=-65, d= 2, i_offset=0)
    '''
    NEXC = len(num_exc)
    NINH = len(num_inh)

    exc_syn = sim.StaticSynapse(weight = wg, delay=delay_distr)
    assert np.any(internal_conn_ee.conn_list[:,0]) < ee_srcs.size
    prj_exc_exc = sim.Projection(all_cells, all_cells, internal_conn_ee, exc_syn, receptor_type='excitatory')
    prj_exc_inh = sim.Projection(all_cells, all_cells, internal_conn_ei, exc_syn, receptor_type='excitatory')
    inh_syn = sim.StaticSynapse(weight = wg, delay=delay_distr)
    delay_distr = RandomDistribution('normal', [1, 100e-3], rng=rng)
    prj_inh_inh = sim.Projection(all_cells, all_cells, internal_conn_ii, inh_syn, receptor_type='inhibitory')
    prj_inh_exc = sim.Projection(all_cells, all_cells, internal_conn_ie, inh_syn, receptor_type='inhibitory')
    inh_distr = RandomDistribution('normal', [1, 2.1e-3], rng=rng)


    def prj_change(prj,wg):
        prj.setWeights(wg)
    prj_change(prj_exc_exc,wg)
    prj_change(prj_exc_inh,wg)
    prj_change(prj_inh_exc,wg)
    prj_change(prj_inh_inh,wg)

    def prj_check(prj):
        for w in prj.weightHistogram():
            for i in w:
                print(i)
    prj_check(prj_exc_exc)
    prj_check(prj_exc_inh)
    prj_check(prj_inh_exc)
    prj_check(prj_inh_inh)

    #print(rheobase['value'])
    #print(float(rheobase['value']),1.25/1000.0)
    '''Old values that worked
    noise = sim.NoisyCurrentSource(mean=0.85/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_exc.inject(noise)
    #1000.0 pA


    noise = sim.NoisyCurrentSource(mean=1.740/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_inh.inject(noise)
    #1750.0 pA
    '''

    noise = sim.NoisyCurrentSource(mean=0.74/1000.0, stdev=4.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_exc.inject(noise)
    #1000.0 pA


    noise = sim.NoisyCurrentSource(mean=1.440/1000.0, stdev=4.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_inh.inject(noise)

    ##
    # Setup and run a simulation. Note there is no current injection into the neuron.
    # All cells in the network are in a quiescent state, so its not a surprise that xthere are no spikes
    ##

    sim = pyNN.neuron
    arange = np.arange
    import re
    all_cells.record(['v','spikes'])  # , 'u'])
    all_cells.initialize(v=-65.0, u=-14.0)
    # === Run the simulation =====================================================
    tstop = 2000.0
    sim.run(tstop)
    data = None
    data = all_cells.get_data().segments[0]

    #print(len(data.analogsignals[0].times))
    with open('pickles/qi'+str(wg)+'.p', 'wb') as f:
        pickle.dump(data,f)
    # make data none or else it will grow in a loop
    all_cells = None
    data = None
    noise = None
Example #18
0
    def apply_constraints(self,
                          kind="inhibitory",
                          w_range=[-0.2, -0.0],
                          d_range=[2.0, 2.0],
                          random_cons=False,
                          pAF=0.5):
        """Map constraints list to inhibitory or excitatory connections between neural populations.

        The clues_inhibition class variable determines whether clues should receive inhibitory connections or not.

        args:
            kind: whether constraints are inhibitory or excitatory.
            w_range: range for the random distribution of synaptic weights in the form [w_min, w_max].
            d_range: range for the random distribution of synaptic delays in the form [d_min, d_max].
            random_cons: whether constraints are randomly choosen to be inhibitory or excitatory with probability pAF.
            pAF: probability of inhibitory connections, as a probability it should be between 0.0 and 1.0. It only works
                when random_cons is True.
         """
        delays = RandomDistribution('uniform', d_range)
        weights = RandomDistribution('uniform', w_range)  # 1.8 2.0 spin_system
        if 'weight' in self.constraints[0]:
            print msg, '''creating constraints between CSP variables with specified weights and randomly distributed
                        delays'''
        else:
            print msg, '''creating constraints between CSP variables with random and  uniformelly distributed delays
                       and weights'''
        for constraint in self.constraints:
            source = constraint['source']
            target = constraint['target']
            if random_cons:
                kind = np.random.choice(['inhibitory', 'excitatory'],
                                        p=[pAF, 1 - pAF])
            #TODO find a way of reducing the next two conditionals, they're equal except for conditioning on target...
            #TODO ... being a clue.
            if self.clues_inhibition:
                connections = []
                for n in range(self.size):
                    for m in range(self.size):
                        if 'weight' in constraint:
                            weight = constraint['weight']
                        else:
                            weight = weights.next()
                        connections.append(
                            (m, n, weight if m // self.core_size == n //
                             self.core_size else 0.0, delays.next()))
                synapses = p.Projection(self.var_pops[source],
                                        self.var_pops[target],
                                        p.FromListConnector(connections,
                                                            safe=True),
                                        target=kind)
                self.constraint_conns.append(synapses)
                if self.directed == False:
                    synapses = p.Projection(self.var_pops[target],
                                            self.var_pops[source],
                                            p.FromListConnector(connections,
                                                                safe=True),
                                            target=kind)
                    self.constraint_conns.append(synapses)
            elif target not in self.clues[0]:
                connections = []
                for n in range(self.size):
                    for m in range(self.size):
                        if 'weight' in constraint:
                            weight = constraint['weight']
                        else:
                            weight = weights.next()
                        connections.append(
                            (m, n, weight if m // self.core_size == n //
                             self.core_size else 0.0, delays.next()))
                synapses = p.Projection(self.var_pops[source],
                                        self.var_pops[target],
                                        p.FromListConnector(connections,
                                                            safe=True),
                                        target=kind)
                self.constraint_conns.append(synapses)
                if self.directed == False:
                    synapses = p.Projection(self.var_pops[target],
                                            self.var_pops[source],
                                            p.FromListConnector(connections,
                                                                safe=True),
                                            target=kind)
                    self.constraint_conns.append(synapses)
    "tau_syn_E": 5.0,
    "tau_syn_I": 5.0,
    "v_reset": -70.0,
    "v_rest": -65.0,
    "v_thresh": -50.0,
}

populations = list()
projections = list()

weight_to_spike = 2.0
delay = RandomDistribution("uniform", parameters=[1, max_delay])

loopConnections = list()
for i in range(0, nNeurons):
    delay_value = delay.next()
    singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay_value)
    loopConnections.append(singleConnection)

injectionConnection = [(0, 0, weight_to_spike, 1)]
spikeArray = {"spike_times": [[0]]}
populations.append(p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label="pop_1"))
populations.append(p.Population(1, p.SpikeSourceArray, spikeArray, label="inputSpikes_1"))

projections.append(p.Projection(populations[0], populations[0], p.FromListConnector(loopConnections)))
projections.append(p.Projection(populations[1], populations[0], p.FromListConnector(injectionConnection)))

populations[0].record_v()
populations[0].record_gsyn()
populations[0].record()
                   'i_offset': 0.0,
                   'tau_m': 20.0,
                   'tau_refrac': 2.0,
                   'tau_syn_E': 5.0,
                   'tau_syn_I': 5.0,
                   'v_reset': -70.0,
                   'v_rest': -65.0,
                   'v_thresh': -50.0
                   }

weight_to_spike = 2.0
delay = RandomDistribution("uniform", low=1, high=max_delay)

loopConnections = list()
for i in range(0, nNeurons):
    delay_value = delay.next()
    singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay_value)
    loopConnections.append(singleConnection)

injectionConnection = [(0, 0, weight_to_spike, 1)]
spikeArray = {'spike_times': [[0]]}
main_pop = p.Population(
    nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1')
input_pop = p.Population(
    1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1')

p.Projection(main_pop, main_pop, p.FromListConnector(loopConnections))
p.Projection(input_pop, main_pop, p.FromListConnector(injectionConnection))

main_pop.record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes'])
Example #21
0
#import numpy
from pyNN.random import RandomDistribution, NumpyRNG, GSLRNG, NativeRNG
rng = NumpyRNG(seed=824756)
print(rng.next(5, 'normal', {'mu': 1.0, 'sigma': 0.2}))
'''
rng = GSLRNG(seed=824756, type='ranlxd2')  # RANLUX algorithm of Luescher
rng.next(5, 'normal', {'mu': 1.0, 'sigma': 0.2})
#fail to import 
#error: Cannot import pygsl
#need pygsl package, cannot be installed with pip
'''

gamma = RandomDistribution('gamma', (2.0, 0.3), rng=NumpyRNG(seed=72386))
print(gamma.next(5))
#by name
gamma = RandomDistribution('gamma', k=2.0, theta=0.3, rng=NumpyRNG(seed=72386))
#differece
print(gamma.next())
print(gamma.next(1))

norm = NativeRNG(seed=72386)
print(norm.next(5))
	timer.start() # start timer on construction    

	print "%d Setting up random number generator" %rank
	rng = NumpyRNG(kernelseed, parallel_safe=True)

        # Initialising membrane potential to random values
	vrest_sd = 5
	vrest_distr = RandomDistribution('uniform', [Vrest_Pyr - numpy.sqrt(3)*vrest_sd, Vrest_Pyr + numpy.sqrt(3)*vrest_sd], rng)

	Pyr_net = []

	for sp in range(NP):
		print "%d Creating pyramidal cell population %d  with %d neurons." % (rank, sp, N_Pyr)
		Pyr_subnet = Population((N_Pyr,),IF_cond_exp,cell_params_Pyr)
		for cell in Pyr_subnet:
			vrest_rval = vrest_distr.next(1)
			cell.set_parameters(v_rest=vrest_rval)
		Pyr_net.append(Pyr_subnet)

	print "%d Creating basket cell population with %d neurons." % (rank, N_Bas)
	Bas_net = Population((N_Bas,),IF_cond_exp,cell_params_Bas)

	print "%d Creating slow inhibitory population with %d neurons." % (rank, N_Sli)
	Sli_net = Population((N_Sli,),IF_cond_exp,cell_params_Sli)

	# Creating external input - is this correct on multiple threads?
	Pyr_input = []

	for sp in range(NP):
		print "%d Creating pyramidal cell external input %d with rate %g spikes/s." % (rank, sp, p_rate_pyr)
		pyr_poisson = Population((N_Pyr,), SpikeSourcePoisson, {'rate': p_rate_pyr})
Example #23
0
import pylab as plt
from signal_prep import *
from pyNN.random import NumpyRNG, RandomDistribution
import numpy as np

sim_duration = 10000.  #46349.#
w_max = 0.25  #10.

varying_weights = numpy.load("./weights_to_belt.npy")
ids = RandomDistribution('uniform', (0, 99))
chosen = ids.next(n=12)
chosen_int = [int(id) for id in chosen]
#chosen_int = [380]#single target id

vary_weight_plot(varying_weights,
                 chosen_int, [],
                 sim_duration,
                 plt,
                 np=numpy,
                 num_recs=int(np.ceil(sim_duration / 4000)),
                 ylim=w_max + (w_max / 10.))

weight_dist_plot(varying_weights, 1, plt)

#[spike_trains,duration,Fs]=numpy.load("/home/rjames/Dropbox (The University of Manchester)/EarProject/spike_trains_10sp_2num_5rep.npy")
#spikes_train_an_ms = [(neuron_id,int(1000*(1./22050.)*spike_time)) for (neuron_id,spike_time) in spike_trains]
#psth_plot(plt, numpy.arange(1000), spikes_train_an_ms, bin_width=0.001, duration=sim_duration / 1000.,
#         scale_factor=0.001, title="PSTH_AN")

plt.show()