def run(parameters, sim_list): sim_time = parameters.sim_time spike_interval = parameters.spike_interval stgen = StGen() seed = parameters.seed stgen.seed(seed) model_parameters = ParameterSet({ 'system': parameters.system, 'input_spike_times': stgen.poisson_generator(1000.0 / spike_interval, t_stop=sim_time, array=True), 'cell_type': parameters.cell.type, 'cell_parameters': parameters.cell.params, 'plasticity': { 'short_term': None, 'long_term': None }, 'weights': parameters.weights, 'delays': parameters.delays, }) networks = MultiSim(sim_list, SimpleNetwork, model_parameters) networks.run(sim_time) spike_data = networks.get_spikes() vm_data = networks.get_v() networks.end() return spike_data, vm_data, model_parameters
def build_input(self, stim_duration=4000, omega=20, angle=0): self.mpi_print("Creating or loading the LGN input ....") f0 = 0 f1 = 60 angle = (angle/360.) * 2 * numpy.pi time = numpy.arange(0, stim_duration, 1) spk = StGen(seed=5423689) st = [] for i in range(self.N): for j in range(self.N): signal = f0 + f1*(numpy.cos(omega*.001*time+numpy.pi*(i*numpy.cos(angle) + j*numpy.sin(angle))/(self.N*1.))+1) spk_times = spk.inh_poisson_generator(signal, time, stim_duration, array=True) st.append(spk_times) for cell, spikes in zip(self.LGN, st): cell.spike_times = spikes
def build_moving_bar(self, stim_duration=4000, omega=5, save=None): if rank()==0: print "Creating or loading the LGN input ...." f0 = 100 time = numpy.arange(0, stim_duration, 1) spk = StGen(seed=5423689) st = [] for i in range(self.N): for j in range(self.N): signal = f0/(1+numpy.exp(-100*(numpy.cos(omega*.001*time+numpy.pi*i/(self.N*1.))-.95))) spk_times = spk.inh_poisson_generator(signal, time, stim_duration, array=True) st.append(spk_times) for cell,spikes in zip(self.LGN, st): cell.spike_times = spikes if save: cPickle.dump(st, open(save,'w'))
def build_static_bar(self, f0=100,stim_start=0, stim_duration=4000, phi=0, save=None): if rank()==0: print "Creating or loading the LGN input: static bar at %s rad...."%phi sx=.7*self.N sy=0.1*self.N n0=(self.N-1)/2. spk = StGen(seed=5423689) st = [] for i in range(self.N): for j in range(self.N): bar_fr=f0*np.exp(-((i-n0)*np.cos(phi)+(j-n0)*np.sin(phi))**2/sx**2-(-(i-n0)*np.sin(phi)+(j-n0)*np.cos(phi))**2/sy**2) spk_times = spk.poisson_generator(bar_fr, 0, stim_duration, array=True) st.append(spk_times) for cell,spikes in zip(self.LGN, st): cell.spike_times = spikes+stim_start if save: cPickle.dump(st, open(save,'w'))
def run(parameters, sim_list): sim_time = parameters.sim_time spike_interval = parameters.spike_interval stgen = StGen() seed = parameters.seed stgen.seed(seed) model_parameters = ParameterSet({ 'system': parameters.system, 'input_spike_times': stgen.poisson_generator(1000.0/spike_interval, t_stop=sim_time, array=True), 'cell_type': parameters.cell.type, 'cell_parameters': parameters.cell.params, 'plasticity': { 'short_term': None, 'long_term': None }, 'weights': parameters.weights, 'delays': parameters.delays, }) networks = MultiSim(sim_list, SimpleNetwork, model_parameters) networks.run(sim_time) spike_data = networks.get_spikes() vm_data = networks.get_v() networks.end() return spike_data, vm_data, model_parameters
def inh_poisson_spikes(rate, t, t_stop, n_rep=1, seed=None): ''' Returns a SpikeTrain whose spikes are a realization of an inhomogeneous poisson process (dynamic rate). The implementation uses the thinning method, as presented in the references (see neurotools). From Professor David Heeger 2000 - "Poisson Model of Spike Generation" Generating Poisson Spike Trains There are two commonly used procedures for numerically generating Poisson spike trains. The first approach is based on the approximation in Eq. 2 P{1 spike during the interval(t-dt/2,t+dt/2)}=r(t)dt (2) for the probability of a spike occurring during a short time interval. For the homogeneous Poisson process, this expression can be rewritten (removing the time dependence) as P{1 spike during dt} ~ rdt This equation can be used to generate a Poisson spike train by first subdividing time into a bunch of short intervals, each of duration dt. Then generate a sequence of random numbers x[i] , uniformly distributed between 0 and 1. For each interval, if x[i] <=rdt, generate a spike. Otherwise, no spike is generated. This procedure is appropriate only when dt is very small, i.e, only when rdt<<1. Typically, dt = 1 msec should suffice. The problem with this approach is that each spike is assigned a discrete time bin, not a continuous time value. The second approach for generating a homogeneous Poisson spike train, that circumvents this problem, is simply to choose interspike intervals randomly from the exponential distribution. Each successive spike time is given by the previous spike time plus the randomly drawn interspike interval . Now each spike is assigned a continuous time value instead of a discrete time bin. However, to do anything with the simulated spike train (e.g., use it to provide synaptic input to another simulated neuron), it is usually much more convenient to discretely sample the spike train (e.g., in 1 msec bins), which makes this approach for generating the spike times equivalent to the first approach described above. I use neruotools Inputs: rate - an array of the rates (Hz) where rate[i] is active on interval [t[i],t[i+1]] (if t=t.append(t_stop) t - an array specifying the time bins (in milliseconds) at which to specify the rate t_stop - length of time to simulate process (in ms) n_rep - number times to repeat spike pattern seed - seed random generator Returns: spike - array of spikes Examples: spike_train_dyn = misc.inh_poisson_generator(rate = np.array([50., 80., 30.]), t = [0., 1000., 2000.], t_stop = 2.5, array = False) ''' t = numpy.array(t) rate = numpy.array(rate) times = [] rates = [] for i in range(n_rep): times = concatenate((times, t + t_stop * i / n_rep), 1) rates = concatenate((rates, rate), 1) stgen = StGen(seed=seed) spikes = stgen.inh_poisson_generator(rate=rates, t=times, t_stop=t_stop, array=True) return spikes
import numpy from time import time from pyNN import nest, neuron, pcsim from pyNN.utility import MultiSim from NeuroTools.parameters import ParameterSet from NeuroTools.stgen import StGen from simple_network import SimpleNetwork from calc import STDPSynapse PLOT_FIGURES = True sim_list = [nest, neuron, pcsim] sim_time = 200.0 spike_interval = 20.0 # ms recording_interval = 1.0 stgen = StGen() seed = int(1e9 * (time() % 1)) stgen.seed(seed) parameters = ParameterSet({ 'system': { 'timestep': 0.01, 'min_delay': 0.1, 'max_delay': 10.0 }, 'input_spike_times': stgen.poisson_generator(rate=1000.0 / spike_interval, t_stop=sim_time, array=True), 'trigger_spike_times': stgen.poisson_generator(rate=1000.0 / spike_interval,
class NetManagerPyNN(NetworkHandler): log = logging.getLogger("NetManagerPyNN") logging.basicConfig(level=logging.INFO, format="%(name)-19s %(levelname)-5s - %(message)s") populations = {} projections = {} projWeightFactor = {} projSynapseDynamics = {} projConns = [] input_populations = {} input_projections = {} inputCellGroups = {} inputWeights = {} inputSynapseDynamics = {} inputConns = [] inputCount = {} my_simulator = "neuron" my_stgen = StGen() maxSimLength = -1 # Needed for generating input spike time array... def __init__(self, my_simulator="neuron"): self.log.info("Using simulator: " + my_simulator) self.my_simulator = my_simulator exec("from pyNN.%s import *" % self.my_simulator) #setup() def setSeed(self, seed): self.my_stgen.seed(seed) def setMaxSimLength(self, length): self.maxSimLength = length # # Overridden from NetworkHandler # def handlePopulation(self, cellGroup, cellType, size): exec("from pyNN.%s import *" % self.my_simulator ) # Does this really need to be imported every time? if (size >= 0): sizeInfo = ", size " + str(size) + " cells" self.log.info("Creating population: " + cellGroup + ", cell type: " + cellType + sizeInfo) standardCell = IF_cond_alpha try: # Try importing a files named after that cell exec("from %s import *" % cellGroup) self.log.info("-- Imported cell props from: " + cellGroup) exec("standardCell = %s" % cellGroup) except ImportError: self.log.info("-- Could not find file for: " + cellGroup) # Else check if it refers to a standard type if (cellType.count("IF_cond_alpha") >= 0): standardCell = IF_cond_alpha if (cellType.count("IF_cond_exp") >= 0): standardCell = IF_cond_exp #TODO: more... pop = Population((size, ), standardCell, label=cellGroup) self.populations[cellGroup] = pop else: self.log.error("Population: " + cellGroup + ", cell type: " + cellType + " specifies no size. Will lead to errors!") # # Overridden from NetworkHandler # def handleLocation(self, id, cellGroup, cellType, x, y, z): self.printLocationInformation(id, cellGroup, cellType, x, y, z) addr = int(id) self.populations[cellGroup][addr].position = (x, y, z) # # Overridden from NetworkHandler # def handleConnection(self, projName, id, source, target, synapseType, \ preCellId, \ postCellId, \ preSegId = 0, \ preFract = 0.5, \ postSegId = 0, \ postFract = 0.5, \ localInternalDelay = 0, \ localPreDelay = 0, \ localPostDelay = 0, \ localPropDelay = 0, \ localWeight = 1, \ localThreshold = 0): exec("from pyNN.%s import *" % self.my_simulator ) # Does this really need to be imported every time? self.printConnectionInformation(projName, id, source, target, synapseType, preCellId, postCellId, localWeight) if (len(self.projConns) == 0): try: exec("from %s import synapse_dynamics as sd" % synapseType) exec("from %s import gmax" % synapseType) except ImportError: sd = None gmax = 1e-7 self.projWeightFactor[ projName] = gmax * 1e3 # TODO: Check correct units!!! self.projSynapseDynamics[projName] = sd delayTotal = float(localInternalDelay) + float(localPreDelay) + float( localPostDelay) + float(localPropDelay) srcCell = self.populations[source][int(preCellId)] tgtCell = self.populations[target][int(postCellId)] weight = float(localWeight) * self.projWeightFactor[projName] self.log.info("-- Conn id: " + str(id) + ", delay: " + str(delayTotal) + ", localWeight: " + str(localWeight) + ", weight: " + str(weight) + ", threshold: " + str(localThreshold)) self.projConns.append([ self.populations[source].id_to_index(srcCell), self.populations[target].id_to_index(tgtCell), weight, delayTotal ]) # # Overridden from NetworkHandler # def finaliseProjection(self, projName, source, target): exec("from pyNN.%s import *" % self.my_simulator ) # Does this really need to be imported every time? connector = FromListConnector(self.projConns) proj = Projection(self.populations[source], self.populations[target], connector, target='excitatory', label=projName, synapse_dynamics=self.projSynapseDynamics[projName]) self.projections[projName] = proj self.projConns = [] # # Overridden from NetworkHandler # def handleInputSource(self, inputName, cellGroup, inputProps=[], size=-1): self.printInputInformation(inputName, cellGroup, inputProps, size) exec("from pyNN.%s import *" % self.my_simulator ) # Does this really need to be imported every time? if size < 0: self.log.error( "Error at handleInputSource! Need a size attribute in sites element to create spike source!" ) return if inputProps.keys().count( "synaptic_mechanism") > 0 and inputProps.keys().count( "frequency") > 0: freq = float(inputProps["frequency"]) if (self.maxSimLength < 0): raise ValueError, "The value of maxSimLength must be set!" numberExp = int(float(self.maxSimLength) * freq) print "Number of spikes expected in %f ms at %fHz: %d" % ( self.maxSimLength, freq, numberExp) spike_times = self.my_stgen.poisson_generator( rate=freq * 1000, t_stop=self.maxSimLength, array=True) #TODO: check units in nml files and put correct conversion here input_population = Population(size, SpikeSourceArray, {'spike_times': spike_times}, label=inputName) for ip in input_population: spikes = self.my_stgen.poisson_generator( rate=freq * 1000, t_stop=self.maxSimLength, array=True) ip.spike_times = spikes #print "--------------------------" #print "Spike times: "+ str(ip.spike_times) #print "--------------------------" self.inputCellGroups[inputName] = cellGroup self.input_populations[inputName] = input_population synaptic_mechanism = inputProps["synaptic_mechanism"] try: exec("from %s import synapse_dynamics as sd" % synaptic_mechanism) exec("from %s import gmax" % synaptic_mechanism) except ImportError: sd = None gmax = 1e-7 # TODO: Check correct units!!! self.inputWeights[ inputName] = gmax * 1e3 # TODO: Check correct units!!! self.inputSynapseDynamics[inputName] = sd # # Overridden from NetworkHandler # def handleSingleInput(self, inputName, cellId, segId=0, fract=0.5): exec("from pyNN.%s import *" % self.my_simulator ) # Does this really need to be imported every time? if self.inputCount.keys().count(inputName) == 0: self.inputCount[inputName] = 0 weight = float(self.inputWeights[inputName]) self.log.warn("Associating input: %i from: %s to cell %i, weight: %f" % (self.inputCount[inputName], inputName, cellId, weight)) srcInput = self.input_populations[inputName][( self.inputCount[inputName], )] tgtCell = self.populations[self.inputCellGroups[inputName]][( int(cellId), )] #TODO use max cond*weight for weight here... connTuple = ( self.input_populations[inputName].id_to_index(srcInput)[0], self.populations[self.inputCellGroups[inputName]].id_to_index( tgtCell)[0], weight, 0.1) self.inputConns.append(connTuple) self.inputCount[inputName] += 1 # # Overridden from NetworkHandler # def finaliseInputSource(self, inputName): exec("from pyNN.%s import *" % self.my_simulator ) # Does this really need to be imported every time? label = "%s_projection" % inputName input_population = self.input_populations[inputName] cellGroup = self.inputCellGroups[inputName] print self.inputConns connector = FromListConnector(self.inputConns) sd = self.inputSynapseDynamics[inputName] self.log.info( "-- Adding connections for %s: %s from %s to %s with %s" % (inputName, str(connector), str(input_population), str(self.populations[cellGroup]), str(sd))) input_proj = Projection( input_population, self.populations[cellGroup], connector, target='excitatory', label=label, synapse_dynamics=self.inputSynapseDynamics[inputName]) self.input_projections[inputName] = input_proj self.inputConns = []
if my_simulator == 'neuron' or my_simulator == 'nest' : voltDistr = RandomDistribution('uniform',[-65,-50],rng) cellsA.randomInit(voltDistr) cellsB.randomInit(voltDistr) freq = 150 # Hz number = int(tstop*freq/1000.0) print "Number of spikes expected in %d ms at %dHz: %d"%(tstop, freq, number) from NeuroTools.stgen import StGen stgen = StGen() stgen.seed(seed) spike_times = stgen.poisson_generator(rate=freq, t_stop=tstop, array=True) input_population = Population(cellNumA, SpikeSourceArray, {'spike_times': spike_times}, label="inputsToA") for i in input_population: i.spike_times = stgen.poisson_generator(rate=freq, t_stop=tstop, array=True) print "spike_times: " +str(i.spike_times) inputConns = [] for i in range(0,cellNumA): inputConns.append([i, i, 0.1, 3.0])
import numpy from time import time from pyNN import nest, neuron, pcsim from pyNN.utility import MultiSim from NeuroTools.parameters import ParameterSet from NeuroTools.stgen import StGen from simple_network import SimpleNetwork from calc import STDPSynapse PLOT_FIGURES = True sim_list = [nest, neuron, pcsim] sim_time = 200.0 spike_interval = 20.0 # ms recording_interval = 1.0 stgen = StGen() seed = int(1e9*(time()%1)) stgen.seed(seed) parameters = ParameterSet({ 'system': { 'timestep': 0.01, 'min_delay': 0.1, 'max_delay': 10.0 }, 'input_spike_times': stgen.poisson_generator(rate=1000.0/spike_interval, t_stop=sim_time, array=True), 'trigger_spike_times': stgen.poisson_generator(rate=1000.0/spike_interval, t_stop=sim_time, array=True), 'cell_type': 'IF_curr_exp', 'cell_parameters': { 'tau_refrac': 10.0, 'tau_m': 2.0, 'tau_syn_E': 1.0 }, 'plasticity': { 'short_term': None, 'long_term': { 'timing_dependence': { 'model': 'SpikePairRule', 'params': { 'tau_plus': 20.0, 'tau_minus': 20.0 }}, 'weight_dependence': { 'model': 'AdditiveWeightDependence',
if my_simulator == 'neuron' or my_simulator == 'nest': voltDistr = RandomDistribution('uniform', [-65, -50], rng) cellsA.randomInit(voltDistr) cellsB.randomInit(voltDistr) freq = 150 # Hz number = int(tstop * freq / 1000.0) print "Number of spikes expected in %d ms at %dHz: %d" % (tstop, freq, number) from NeuroTools.stgen import StGen stgen = StGen() stgen.seed(seed) spike_times = stgen.poisson_generator(rate=freq, t_stop=tstop, array=True) input_population = Population(cellNumA, SpikeSourceArray, {'spike_times': spike_times}, label="inputsToA") for i in input_population: i.spike_times = stgen.poisson_generator(rate=freq, t_stop=tstop, array=True) print "spike_times: " + str(i.spike_times) inputConns = []
def inh_poisson_spikes(rate, t, t_stop, n_rep=1 ,seed=None): ''' Returns a SpikeTrain whose spikes are a realization of an inhomogeneous poisson process (dynamic rate). The implementation uses the thinning method, as presented in the references (see neurotools). From Professor David Heeger 2000 - "Poisson Model of Spike Generation" Generating Poisson Spike Trains There are two commonly used procedures for numerically generating Poisson spike trains. The first approach is based on the approximation in Eq. 2 P{1 spike during the interval(t-dt/2,t+dt/2)}=r(t)dt (2) for the probability of a spike occurring during a short time interval. For the homogeneous Poisson process, this expression can be rewritten (removing the time dependence) as P{1 spike during dt} ~ rdt This equation can be used to generate a Poisson spike train by first subdividing time into a bunch of short intervals, each of duration dt. Then generate a sequence of random numbers x[i] , uniformly distributed between 0 and 1. For each interval, if x[i] <=rdt, generate a spike. Otherwise, no spike is generated. This procedure is appropriate only when dt is very small, i.e, only when rdt<<1. Typically, dt = 1 msec should suffice. The problem with this approach is that each spike is assigned a discrete time bin, not a continuous time value. The second approach for generating a homogeneous Poisson spike train, that circumvents this problem, is simply to choose interspike intervals randomly from the exponential distribution. Each successive spike time is given by the previous spike time plus the randomly drawn interspike interval . Now each spike is assigned a continuous time value instead of a discrete time bin. However, to do anything with the simulated spike train (e.g., use it to provide synaptic input to another simulated neuron), it is usually much more convenient to discretely sample the spike train (e.g., in 1 msec bins), which makes this approach for generating the spike times equivalent to the first approach described above. I use neruotools Inputs: rate - an array of the rates (Hz) where rate[i] is active on interval [t[i],t[i+1]] (if t=t.append(t_stop) t - an array specifying the time bins (in milliseconds) at which to specify the rate t_stop - length of time to simulate process (in ms) n_rep - number times to repeat spike pattern seed - seed random generator Returns: spike - array of spikes ''' times=[] rates=[] t=numpy.array(t) for i in range(n_rep): times=concatenate((times,t + t_stop*i/n_rep) ,1) rates=concatenate((rates,rate),1) stgen=StGen(seed=seed) spikes=stgen.inh_poisson_generator(rate = rates, t=times, t_stop=t_stop, array=True) return spikes