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))
def FixedTotalNumberConnect(sim, pop1, pop2, K, w_mean, w_sd, d_mean, d_sd, rng=None): n_syn = int(round(K * len(pop2))) conn = sim.FixedTotalNumberConnector(n_syn, rng=rng) d_distr = RandomDistribution('normal_clipped', [d_mean, d_sd, 0.1, np.inf], rng=rng) if pop1.annotations['type'] == 'E': conn_type = 'excitatory' w_distr = RandomDistribution('normal_clipped', [w_mean, w_sd, 0., np.inf], rng=rng) else: conn_type = 'inhibitory' w_distr = RandomDistribution('normal_clipped', [w_mean, w_sd, -np.inf, 0.], rng=rng) syn = sim.StaticSynapse(weight=w_distr, delay=d_distr) proj = sim.Projection(pop1, pop2, conn, syn, receptor_type=conn_type)
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
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
def __init__(self, name, params=(), boundaries=None, constrain='clip'): if boundaries != None: assert isinstance( boundaries, tuple ), "The boundries parameter of PyNNDistribution has to be tuple, while it is: %s" % type( boundaries) assert constrain == 'clip' or constrain == 'redraw', "The parameter constrain has to be either \'clip\' or \'redraw\'" assert isinstance( params, tuple ), "The boundries parameter of PyNNDistribution has to be tuple" RandomDistribution.__init__(self, parameters=params, boundaries=boundaries, constrain=constrain)
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
def _get_default_weights(self, conductance_based): """ Gets the default weights distribution :param conductance_based: Indicates whether the connected neurons are conductance based """ if self._parameters.get("target") == 'excitatory': weights = RandomDistribution('uniform', [0.0, 0.01]) else: if conductance_based: weights = RandomDistribution('uniform', [0.0, 0.01]) else: weights = RandomDistribution('uniform', [-0.01, -0.0]) return weights
def adjust_input_rate(self, input_rate): duration = self.config['simulation'].as_float('epochtime') for i in range(len(input_rate)): stimspike = RandomDistribution( 'uniform', low=0, high=duration).next(int(duration * input_rate[i] * 1e-3)) self.brain.Input.input_source[i].set(spike_times=stimspike)
def __init__(self, projection, weights=0.0, delays=None, allow_self_connections=True, space=Space(), safe=True): Connector.__init__(self, weights, delays, space, safe) if isinstance(projection.rng, random.NativeRNG): raise Exception("Use of NativeRNG not implemented.") else: self.rng = projection.rng self.local = numpy.ones(len(projection.pre), bool) self.N = projection.pre.size self.weights_generator = WeightGenerator(weights, self.local, projection, safe) self.delays_generator = DelayGenerator(delays, self.local, safe) self.probas_generator = ProbaGenerator( RandomDistribution('uniform', (0, 1), rng=self.rng), self.local) self.distance_matrix = DistanceMatrix(projection.pre.positions, self.space, self.local) self.projection = projection self.allow_self_connections = allow_self_connections
def get_pyNN_value(qty, unit_handler, rng): if isinstance(qty.value, SingleValue): val = unit_handler.scale_value(qty) elif isinstance(qty.value, ArrayValue): scalar = unit_handler.scalar(qty.units) val = Sequence(v * scalar for v in qty.value) elif isinstance(qty.value, RandomDistributionValue): if unit_handler.scalar(qty.units) != 1.0: raise NotImplementedError( "Cannot currently scale random distributions as required to " "get {} into the correct units".format(qty)) try: rv_name, rv_param_names = random_value_map[ qty.value.distribution.standard_library] except KeyError: raise NotImplementedError( "Sorry, '{}' random distributions are not currently supported" .format(qty.value.distribution.standard_libary)) rv_params = [ qty.value.distribution.property(n).value for n in rv_param_names] # UncertML uses 'rate' parameter whereas PyNN uses 'beta' parameter # (1/rate) to define exponential random distributions. if rv_name == 'exponential': rv_params[0] = 1.0 / rv_params[0] # FIXME: Need to scale random distribution to correct units. Should # probably derive PyNN RandomDistribution class to multiply by # when a value is drawn val = RandomDistribution(rv_name, rv_params, rng=rng) return val
def __init__(self, projection, weights=0.0, delays=None, allow_self_connections=True, space=Space(), safe=True): Connector.__init__(self, weights, delays, space, safe) if isinstance(projection.rng, random.NativeRNG): raise Exception("Use of NativeRNG not implemented.") else: self.rng = projection.rng self.local = projection.post._mask_local self.N = projection.post.size self.weights_generator = WeightGenerator(weights, self.local, projection, safe) self.delays_generator = DelayGenerator(delays, self.local, safe) self.probas_generator = ProbaGenerator( RandomDistribution('uniform', (0, 1), rng=self.rng), self.local) self._distance_matrix = None self.projection = projection self.candidates = projection.post.local_cells self.size = self.local.sum() self.allow_self_connections = allow_self_connections
def test_record_native_model(): nrn = pyNN.neuron init_logging(logfile=None, debug=True) nrn.setup() parameters = {'g_leak': 0.0003} p1 = nrn.Population(10, SimpleNeuronType, parameters) print p1.get('g_leak') p1.rset('gnabar', RandomDistribution('uniform', [0.10, 0.14])) print p1.get('gnabar') p1.initialize('v', -63.0) current_source = nrn.StepCurrentSource({ 'times': [50.0, 110.0, 150.0, 210.0], 'amplitudes': [0.4, 0.6, -0.2, 0.2] }) p1.inject(current_source) p2 = nrn.Population(1, nrn.SpikeSourcePoisson, {'rate': 100.0}) p1._record('apical(1.0).v') p1._record('soma(0.5).ina') connector = nrn.AllToAllConnector(weights=0.1) prj_alpha = nrn.Projection(p2, p1, connector, target='apical.ampa') nrn.run(250.0) assert_equal(p1.recorders['apical(1.0).v'].get().shape, (25010, 3)) id, t, v = p1.recorders['apical(1.0).v'].get().T return id, t, v
def fixed_number_pre_no_replacement(sim): sim.setup() p1 = sim.Population(5, sim.IF_cond_exp()) p2 = sim.Population(7, sim.IF_cond_exp()) synapse_type1 = sim.StaticSynapse(weight=0.5, delay=0.5) connector1 = sim.FixedNumberPreConnector(n=3, with_replacement=False, rng=NumpyRNG()) prj1 = sim.Projection(p1, p2, connector1, synapse_type1) print("Projection 1\n", connection_plot(prj1)) weights1 = prj1.get('weight', format='array', gather=False) for column in weights1.T: assert_equal((~numpy.isnan(column)).sum(), 3) column[numpy.isnan(column)] = 0 assert_equal(column.sum(), 1.5) synapse_type2 = sim.StaticSynapse(weight=RandomDistribution('gamma', k=2, theta=0.5), delay="0.2+0.3*d") prj2 = sim.Projection(p1, p2, connector1, synapse_type2) print("\nProjection 2\n", connection_plot(prj2)) weights2 = prj2.get('weight', format='array', gather=False) delays2 = prj2.get('delay', format='list', gather=False) print(weights2) print(delays2) for i, j, d in delays2: assert_almost_equal(d, 0.2 + 0.3 * abs(i - j), 9) for column in weights2.T: assert_equal((~numpy.isnan(column)).sum(), 3) column[numpy.isnan(column)] = 0 sim.end()
def test_uniform(self): # Need to do setup to get a pynn version p.setup(10) rd = SpynnakerRangeDictionary(10) rd["a"] = RandomDistribution("uniform", parameters_pos=[-65.0, -55.0]) ranges = rd["a"].get_ranges() assert 10 == len(ranges)
def connect(self, projection): """Connect-up a Projection.""" local = numpy.ones(len(projection.post), bool) self.N = projection.post.size if isinstance(projection.rng, random.NativeRNG): raise Exception("Use of NativeRNG not implemented.") else: self.rng = projection.rng self.weights_generator = WeightGenerator(self.weights, local, projection, self.safe) self.delays_generator = DelayGenerator(self.delays, local, self.safe) self.probas_generator = ProbaGenerator( RandomDistribution('uniform', (0, 1), rng=self.rng), local) self.distance_matrix = DistanceMatrix(projection.post.positions, self.space, local) self.projection = projection self.candidates = projection.post.all_cells self.size = len(projection.post) self.progressbar(len(projection.pre)) proba_generator = ProbaGenerator(self.d_expression, local) for count, src in enumerate(projection.pre.all()): self.distance_matrix.set_source(src.position) proba = proba_generator.get(self.N, self.distance_matrix).astype(float) self._smallworld_connect(src, proba, self.n_connections) self.progression(count)
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)
def scenario4(sim): """ Network with spatial structure """ init_logging(logfile=None, debug=True) sim.setup() rng = NumpyRNG(seed=76454, parallel_safe=False) input_layout = RandomStructure(boundary=Cuboid(width=500.0, height=500.0, depth=100.0), origin=(0, 0, 0), rng=rng) inputs = sim.Population(100, sim.SpikeSourcePoisson(rate=RandomDistribution('uniform', [3.0, 7.0], rng=rng)), structure=input_layout, label="inputs") output_layout = Grid3D(aspect_ratioXY=1.0, aspect_ratioXZ=5.0, dx=10.0, dy=10.0, dz=10.0, x0=0.0, y0=0.0, z0=200.0) outputs = sim.Population(200, sim.EIF_cond_exp_isfa_ista(), initial_values = {'v': RandomDistribution('normal', [-65.0, 5.0], rng=rng), 'w': RandomDistribution('normal', [0.0, 1.0], rng=rng)}, structure=output_layout, # 10x10x2 grid label="outputs") logger.debug("Output population positions:\n %s", outputs.positions) DDPC = sim.DistanceDependentProbabilityConnector input_connectivity = DDPC("0.5*exp(-d/100.0)", rng=rng) recurrent_connectivity = DDPC("sin(pi*d/250.0)**2", rng=rng) depressing = sim.TsodyksMarkramSynapse(weight=RandomDistribution('normal', (0.1, 0.02), rng=rng), delay="0.5 + d/100.0", U=0.5, tau_rec=800.0, tau_facil=0.0) facilitating = sim.TsodyksMarkramSynapse(weight=0.05, delay="0.2 + d/100.0", U=0.04, tau_rec=100.0, tau_facil=1000.0) input_connections = sim.Projection(inputs, outputs, input_connectivity, receptor_type='excitatory', synapse_type=depressing, space=Space(axes='xy'), label="input connections") recurrent_connections = sim.Projection(outputs, outputs, recurrent_connectivity, receptor_type='inhibitory', synapse_type=facilitating, space=Space(periodic_boundaries=((-100.0, 100.0), (-100.0, 100.0), None)), # should add "calculate_boundaries" method to Structure classes label="recurrent connections") outputs.record('spikes') outputs.sample(10, rng=rng).record('v') sim.run(1000.0) data = outputs.get_data() sim.end() return data
def test_connect_with_random_weights(self): connector = AllToAllConnector( weights=RandomDistribution("uniform", [0.3, 0.4], rng=self.rng)) prj = MockProjection(self.p1, self.p2, self.rng, "excitatory") connector.connect(prj) self.assertEqual(prj.n, self.p1.size * self.p2.size) assert_arrays_almost_equal(numpy.array(prj.connection_manager.weights), numpy.arange(0, prj.n), 1e-6)
def connect(self, projection): random_map = LazyArray( RandomDistribution('uniform', (0, 1), rng=self.rng), projection.shape) connection_map = random_map < self.p_connect if not self.allow_self_connections and projection.pre == projection.post: connection_map *= LazyArray(lambda i, j: i != j, shape=projection.shape) self._connect_with_map(projection, connection_map)
def initialize(self, v_range=[-65.0, -55.0]): """Randomly initialize the membrane voltage of the neurons in the range v_range. args: v_range: range for the random distribution of membrane potentials in the form [v_min, v_max]. """ print msg, 'randomly setting the initial voltage for each variable population' for variable in self.var_pops: variable.initialize("v", RandomDistribution("uniform", v_range))
def test_convert_param_to_numpy_random_distribution(self): random = RandomDistribution("uniform", [0, 1]) single_value = utility_calls.convert_param_to_numpy(random, 1) multi_value = utility_calls.convert_param_to_numpy(random, 10) self.assertTrue(hasattr(single_value, "__iter__")) self.assertEqual(len(single_value), 1) self.assertTrue(hasattr(multi_value, "__iter__")) self.assertEqual(len(multi_value), 10)
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 do_run(self): nNeurons = 500 p.setup(timestep=1.0, min_delay=1.0) p.set_number_of_neurons_per_core(p.IF_curr_exp, 100) cm = list() i_off = list() tau_m = list() tau_re = list() tau_syn_e = list() tau_syn_i = list() v_reset = list() v_rest = list() for atom in range(0, nNeurons): cm.append(0.25) i_off.append(0.0 + atom * 0.01) tau_m.append(10.0 + atom // 2 * 0.1) tau_re.append(2.0 + atom % 2 * 0.01) tau_syn_e.append(0.5) tau_syn_i.append(0.5 + atom * 0.01) v_reset.append(-65.0 + atom // 2 * 0.01) v_rest.append(-65.0 + atom % 2 * 0.01) gbar_na_distr = RandomDistribution('normal', (20.0, 2.0), rng=NumpyRNG(seed=85524)) cell_params_lif = { 'cm': 0.25, 'i_offset': i_off, 'tau_m': tau_m, 'tau_refrac': tau_re, 'v_thresh': gbar_na_distr } pop_1 = p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_1') pop_1.set(tau_syn_E=0.5) pop_1.set(tau_syn_I=tau_syn_i) pop_1.set(v_reset=v_reset, v_rest=v_rest) p.run(1) self.assertEqual(cm, pop_1.get("cm")) self.assertEqual(i_off, pop_1.get("i_offset")) self.assertEqual(tau_m, pop_1.get("tau_m")) self.assertEqual(tau_re, pop_1.get("tau_refrac")) self.assertEqual(tau_syn_e, pop_1.get("tau_syn_E")) self.assertEqual(tau_syn_i, pop_1.get("tau_syn_I")) self.assertEqual(v_reset, pop_1.get("v_reset")) self.assertEqual(v_rest, pop_1.get("v_rest")) self.assertGreater(len(set(pop_1.get("v_thresh"))), nNeurons / 2) p.end()
def test_convert_param_to_numpy_random_distribution(self): globals_variables.set_simulator(Spinnaker(timestep=1.0)) random = RandomDistribution("uniform", [0, 1]) single_value = utility_calls.convert_param_to_numpy(random, 1) multi_value = utility_calls.convert_param_to_numpy(random, 10) self.assertTrue(hasattr(single_value, "__iter__")) self.assertEqual(len(single_value), 1) self.assertTrue(hasattr(multi_value, "__iter__")) self.assertEqual(len(multi_value), 10)
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)
def depress_cores(self, w_range=[-2.0, -1.5], d_range=[2.0, 2.0]): """Connect depressing 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]. """ print msg, 'connecting Poisson noise sources to neural populations for dissipation' delays = RandomDistribution('uniform', d_range) weights = RandomDistribution('uniform', w_range) for depressor in range(self.d_populations): for variable in range(self.variables_number): if variable not in self.clues[0]: synapses = p.Projection( self.diss_pops[depressor][variable], self.var_pops[variable], p.OneToOneConnector(weights=weights, delays=delays), target='inhibitory') self.diss_conns.append(synapses) self.diss_times += self.disss
def connect(self, projection): distance_map = self._generate_distance_map(projection) probability_map = self.distance_function(distance_map) random_map = LazyArray( RandomDistribution('uniform', (0, 1), rng=self.rng), projection.shape) connection_map = random_map < probability_map if not self.allow_self_connections and projection.pre == projection.post: connection_map *= LazyArray(lambda i, j: i != j, shape=projection.shape) self._connect_with_map(projection, connection_map, distance_map)
def build_network(sim, order=1000, epsilon=0.1, delay=1.5, J=0.1, theta=20.0, tau=20.0, tau_syn=0.1, tau_refrac=2.0, v_reset=10.0, R=1.5, g=5, eta=2, seed=None): NE = 4 * order NI = 1 * order CE = int(epsilon * NE) # number of excitatory synapses per neuron CI = int(epsilon * NI) # number of inhibitory synapses per neuron CMem = tau/R J_unit = psp_height(tau, R, tau_syn) J_ex = J / J_unit J_in = -g * J_ex nu_th = theta / (J_ex * CE * R * tau_syn) nu_ex = eta * nu_th p_rate = 1000.0 * nu_ex * CE assert seed is not None rng = NumpyRNG(seed) neuron_params = { "nrn_tau": tau, "nrn_v_threshold": theta, "nrn_refractory_period": tau_refrac, "nrn_v_reset": v_reset, "nrn_R": R, "syn_tau": tau_syn } celltype = Dynamics(name='iaf', subnodes={'nrn': read("sources/BrunelIaF.xml")['BrunelIaF'], 'syn': read("sources/AlphaPSR.xml")['AlphaPSR']}) celltype.connect_ports('syn.i_synaptic', 'nrn.i_synaptic') exc = sim.Population(NE, nineml_cell_type('BrunelIaF', celltype, {'syn': 'syn_weight'})(**neuron_params)) inh = sim.Population(NI, nineml_cell_type('BrunelIaF', celltype, {'syn': 'syn_weight'})(**neuron_params)) all = exc + inh all.initialize(v=RandomDistribution('uniform', (0.0, theta), rng=rng)) stim = sim.Population(NE + NI, nineml_cell_type('Poisson', read("sources/Poisson.xml")['Poisson'], {})(rate=p_rate)) print("Connecting network") exc_synapse = sim.StaticSynapse(weight=J_ex, delay=delay) inh_synapse = sim.StaticSynapse(weight=J_in, delay=delay) input_connections = sim.Projection(stim, all, sim.OneToOneConnector(), exc_synapse, receptor_type="syn") exc_connections = sim.Projection(exc, all, sim.FixedNumberPreConnector(n=CE), exc_synapse, receptor_type="syn") # check is Pre not Post inh_connections = sim.Projection(inh, all, sim.FixedNumberPreConnector(n=CI), inh_synapse, receptor_type="syn") return stim, exc, inh
def all_to_all_static_no_self(sim): sim.setup() p = sim.Population(5, sim.IF_cond_exp()) synapse_type = sim.StaticSynapse(weight=RandomDistribution('gamma', k=2.0, theta=0.5), delay="0.2+0.3*d") prj = sim.Projection(p, p, sim.AllToAllConnector(allow_self_connections=False), synapse_type) weights = prj.get('weight', format='array', gather=False) print(weights) delays = prj.get('delay', format='list', gather=False) i, j, d = numpy.array(delays).T assert_arrays_almost_equal(d, 0.2 + 0.3 * abs(i - j), 1e-9) assert_equal(d.size, p.size * (p.size - 1)) sim.end()
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 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 __init__(self,name,**params): RandomDistribution.__init__(self,name,**params)
def __init__(self, name, params=()): assert isinstance(params, tuple) RandomDistribution.__init__(self, name, params)
"cm": 0.25, "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, } 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)))
def __init__(self,name,params=(),boundaries=None,constrain='clip'): if boundaries != None: assert isinstance(boundaries,tuple) , "The boundries parameter of PyNNDistribution has to be tuple, while it is: %s" % type(boundaries) assert constrain == 'clip' or constrain == 'redraw', "The parameter constrain has to be either \'clip\' or \'redraw\'" assert isinstance(params,tuple) , "The boundries parameter of PyNNDistribution has to be tuple" RandomDistribution.__init__(self,parameters=params,boundaries=boundaries,constrain=constrain)
else: print "%d Initialising the simulator with single thread..." %(rank) # Small function to display information only on node 1 def nprint(s): if (rank == 0): print s 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)