def connect_two_intfires(): """Connect two IntFire neurons so that spike events in one gets transmitted to synapse of the other.""" if1 = moose.IntFire('if1') if2 = moose.IntFire('if2') sf1 = moose.SimpleSynHandler('if1/sh') moose.connect(sf1, 'activationOut', if1, 'activation') sf1.synapse.num = 1 syn1 = moose.element(sf1.synapse) # Connect the spike message of if2 to the first synapse on if1 moose.connect(if2, 'spikeOut', syn1, 'addSpike')
def connect_spikegen(): """Connect a SpikeGen object to an IntFire neuron such that spike events in spikegen get transmitted to the synapse of the IntFire neuron.""" if3 = moose.IntFire('if3') sf3 = moose.SimpleSynHandler('if3/sh') moose.connect(sf3, 'activationOut', if3, 'activation') sf3.synapse.num = 1 sg = moose.SpikeGen('sg') syn = moose.element(sf3.synapse) moose.connect(sg, 'spikeOut', syn, 'addSpike')
def make_model(): sinePeriod = 50 maxFiringRate = 10 refractT = 0.05 for i in range(20): moose.setClock(i, dt) ############### Create objects ############### stim = moose.StimulusTable('stim') spike = moose.RandSpike('spike') syn = moose.SimpleSynHandler('syn') fire = moose.IntFire('fire') stats1 = moose.SpikeStats('stats1') stats2 = moose.Stats('stats2') plots = moose.Table('plots') plot1 = moose.Table('plot1') plot2 = moose.Table('plot2') plotf = moose.Table('plotf') ############### Set up parameters ############### stim.vector = [ maxFiringRate * numpy.sin(x * 2 * numpy.pi / sinePeriod) for x in range(sinePeriod) ] stim.startTime = 0 stim.stopTime = sinePeriod stim.loopTime = sinePeriod stim.stepSize = 0 stim.stepPosition = 0 stim.doLoop = 1 spike.refractT = refractT syn.synapse.num = 1 syn.synapse[0].weight = 1 syn.synapse[0].delay = 0 fire.thresh = 100 # Don't want it to spike, just to integrate fire.tau = 1.0 / maxFiringRate stats1.windowLength = int(1 / dt) stats2.windowLength = int(1 / dt) ############### Connect up circuit ############### moose.connect(stim, 'output', spike, 'setRate') moose.connect(spike, 'spikeOut', syn.synapse[0], 'addSpike') moose.connect(spike, 'spikeOut', stats1, 'addSpike') moose.connect(syn, 'activationOut', fire, 'activation') moose.connect(stats2, 'requestOut', fire, 'getVm') moose.connect(plots, 'requestOut', stim, 'getOutputValue') moose.connect(plot1, 'requestOut', stats1, 'getWmean') moose.connect(plot2, 'requestOut', stats2, 'getWmean') moose.connect(plotf, 'requestOut', fire, 'getVm')
def setup_synapse(): """Create an intfire object and create two synapses on it.""" if4 = moose.IntFire('if4') sf4 = moose.SimpleSynHandler('if4/sh') sg1 = moose.SpikeGen('sg1') sg2 = moose.SpikeGen('sg2') sf4.synapse.num = 2 # set synapse count to 2 sf4.synapse[0].weight = 0.5 sf4.synapse[0].delay = 1e-3 sf4.synapse[1].weight = 2.0 sf4.synapse[1].delay = 2e-3 moose.connect(sg1, 'spikeOut', sf4.synapse[0], 'addSpike') moose.connect(sg2, 'spikeOut', sf4.synapse[1], 'addSpike')
def createNetwork(self): '''setting up of the cells and their connections''' hopfield = moose.Neutral('/hopfield') pg = moose.PulseGen('/hopfield/inPulGen') pgTable = moose.Table('/hopfield/inPulGen/pgTable') moose.connect(pgTable, 'requestOut', pg, 'getOutputValue') pg.firstDelay = 10e-3 pg.firstWidth = 2e-03 pg.firstLevel = 3.0 pg.secondDelay = 1.0 for i in range(self.numNeurons): cellPath = '/hopfield/cell_' + str(i) cell = moose.IntFire(cellPath) cell.setField('tau', 10e-3) cell.setField('refractoryPeriod', 5e-3) cell.setField('thresh', 0.99) cell.synapse.num = self.numNeurons #definite firing everytime ip is given cell.synapse[i].weight = 1.00 #synapse i = input synapse cell.synapse[i].delay = 0.0 #1e-3 #instantaneous #VmVals = moose.Table(cellPath+'/Vm_cell_'+str(i)) #moose.connect(VmVals, 'requestOut', cell, 'getVm') spikeVals = moose.Table(cellPath + '/spike_cell_' + str(i)) moose.connect(cell, 'spike', spikeVals, 'input') inSpkGen = moose.SpikeGen(cellPath + '/inSpkGen') inSpkGen.setField('edgeTriggered', True) inSpkGen.setField('threshold', 2.0) moose.connect(pg, 'output', inSpkGen, 'Vm') #inTable = moose.Table(cellPath+'/inSpkGen/inTable') #moose.connect(inTable, 'requestOut', inSpkGen, 'getHasFired') moose.connect(inSpkGen, 'spikeOut', cell.synapse[i], 'addSpike') #self connection is the input self.inSpike.append(inSpkGen) #self.inTables.append(inTable) #self.Vms.append(VmVals) self.cells.append(cell) self.allSpikes.append(spikeVals) for ii in range(self.numNeurons): for jj in range(self.numNeurons): if ii == jj: continue self.cells[jj].synapse[ii].weight = 0 self.cells[jj].synapse[ii].delay = 20e-3 moose.connect(self.cells[ii], 'spike', self.cells[jj].synapse[ii], 'addSpike')
def main(): """This is to show a 'raw' way of traversing messages.""" connectionProbability = 0.5 net = moose.IntFire('/net1', 10) syn = moose.SimpleSynHandler( '/net1/sh', 10 ) moose.connect( syn, 'activationOut', net, 'activation', 'OneToOne' ) synapse = syn.synapse.vec mid = moose.connect(net, 'spikeOut', synapse, 'addSpike', 'Sparse') # This creates a `Sparse` message from `spikeOut` source of net to `addSpike` destination on synapse. msg = moose.element(mid) msg.setRandomConnectivity(connectionProbability, 5) for n in net.vec: print(('Messages from %s.spikeOut' % (n.path))) node = moose.element(n) for dest, df in zip(node.msgDests['spikeOut'], node.msgDestFunctions['spikeOut']): print(('\t--> %s.%s' % (dest.path, df)))
def make_network(): """ This snippet sets up a recurrent network of IntFire objects, using SimpleSynHandlers to deal with spiking events. It isn't very satisfactory as activity runs down after a while. It is a good example for using the IntFire, setting up random connectivity, and using SynHandlers. """ global all_done_ done = mp.Value('i', 0) q = mp.Queue() th = mp.Process(target=streamer_handler, args=(done, q)) th.start() size = 1024 dt = 0.2 runsteps = 10 delayMin = 0 delayMax = 4 weightMax = 1 Vmax = 1.0 thresh = 0.4 refractoryPeriod = 0.4 tau = 0.5 connectionProbability = 0.01 random.seed(123) np.random.seed(456) t0 = time.time() network = moose.IntFire('network', size) syns = moose.SimpleSynHandler('/network/syns', size) moose.connect(syns, 'activationOut', network, 'activation', 'OneToOne') moose.le('/network') syns.vec.numSynapses = [1] * size sv = moose.vec('/network/syns/synapse') print('before connect t = %.3f' % (time.time() - t0)) mid = moose.connect(network, 'spikeOut', sv, 'addSpike', 'Sparse') print('after connect t = %.3f' % (time.time() - t0)) #print mid.destFields m2 = moose.element(mid) m2.setRandomConnectivity(connectionProbability, 5489) print('after setting connectivity, t=%.3f' % (time.time() - t0)) #network.vec.Vm = [(Vmax*random.random()) for r in range(size)] network.vec.Vm = np.random.rand(size) * Vmax network.vec.thresh = thresh network.vec.refractoryPeriod = refractoryPeriod network.vec.tau = tau numSynVec = syns.vec.numSynapses print('Middle of setup, t = %.3f' % (time.time() - t0)) numTotSyn = sum(numSynVec) print((numSynVec.size, ', tot = ', numTotSyn, ', numSynVec = ', numSynVec)) for item in syns.vec: h = moose.element(item) h.synapse.delay = delayMin + (delayMax - delayMin) * np.random.rand( len(h.synapse)) h.synapse.weight = np.random.rand(len(h.synapse)) * weightMax print('After setup, t = %.3f' % (time.time() - t0)) numStats = 100 stats = moose.SpikeStats('/stats', numStats) stats.vec.windowLength = 1 # timesteps to put together. plots = moose.Table('/plot', numStats) convergence = size // numStats for i in range(numStats): for j in range(size // numStats): k = i * convergence + j moose.connect(network.vec[k], 'spikeOut', stats.vec[i], 'addSpike') moose.connect(plots, 'requestOut', stats, 'getMean', 'OneToOne') t1 = time.time() moose.reinit() print('reinit time t = %.3f' % (time.time() - t1)) network.vec.Vm = np.random.rand(size) * Vmax print('setting Vm , t = %.3f' % (time.time() - t1)) t1 = time.time() moose.start(runsteps * dt, 1) time.sleep(0.1) done.value = 1 print('runtime, t = %.3f' % (time.time() - t1)) print(network.vec.Vm[99:103], network.vec.Vm[900:903]) res = q.get() for tabPath in res: aWithTime = res[tabPath] a = aWithTime[1::2] b = moose.element(tabPath).vector print(tabPath, len(a), len(b)) if len(a) == len(b): assert np.equal(a, b).all() else: print("Table did not equal size. The last table is allowed to " " have fewer entries.") th.join() print('All done')
def createNetwork(synWeights, inputGiven): """synWeights : 2D array. synWeights[ii][jj] is the weight of connection from cell [ii] to cell [jj].""" global cell global vmtable global spikegen global intable # start = datetime.now() numberOfCells = synWeights.shape[0] hopfield = moose.Neutral('/hopfield') data = moose.Neutral('/data') pg = moose.PulseGen('/hopfield/inPulGen') pgTable = moose.Table('/hopfield/inPulGen/pgTable') moose.connect(pgTable, 'requestOut', pg, 'getOutputValue') # pg.firstDelay = 10e-3 # pg.firstWidth = 2e-03 # pg.firstLevel = 3 # pg.secondDelay = 1.0 pg.count = 1 pg.level[0] = 3 pg.width[0] = 2e-03 pg.delay[0] = 50e-03 #every 50ms # start1 = datetime.now() for ii in range(numberOfCells): cell.append(moose.IntFire('/hopfield/cell_%d' % (ii))) cell[ii].tau = 10e-3 cell[ii].Vm = -0.07 cell[ii].synapse.num = numberOfCells cell[ii].synapse[ii].delay = 1e-3 cell[ii].synapse[ii].weight = 1.0 cell[ii].setField('thresh', 0.98) vmtable.append(moose.Table('/data/Vm_%d' % (ii))) moose.connect(vmtable[ii], 'requestOut', cell[ii], 'getVm') spikegen.append(moose.SpikeGen('/hopfield/inSpkGen_%d' % (ii))) if inputGiven[ii] == 0: spikegen[ii].threshold = 4.0 else: spikegen[ii].threshold = 2.0 spikegen[ii].edgeTriggered = True # Redundant intable[ii] = moose.Table('/data/inTable_%d' % (ii)) moose.connect(pg, 'output', spikegen[ii], 'Vm') # No self connection - so we can use the synapse [ii] for input delivery moose.connect(spikegen[ii], 'spikeOut', cell[ii].synapse[ii], 'addSpike') moose.connect(intable[ii], 'requestOut', spikegen[ii], 'getHasFired') # end1 = datetime.now() for ii in range(numberOfCells): for jj in range(numberOfCells): if ii == jj: continue cell[jj].synapse[ii].weight = float(synWeights[ii, jj] / 2.0) cell[jj].synapse[ii].delay = 20e-3 moose.connect(cell[ii], 'spike', cell[jj].synapse[ii], 'addSpike') # end2 = datetime.now() # delta = end2 - start # print 'createNetwork: Total time:', delta.seconds + delta.microseconds * 1e-6 # delta = end1 - start1 # print 'createNetwork: create cells:', delta.seconds + delta.microseconds * 1e-6 # delta = end2 - end1 # print 'createNetwork: connect cells:', delta.seconds + delta.microseconds * 1e-6 return (cell, vmtable, pgTable, spikegen, intable)
def setUp(self): self.x = moose.Neutral('/x', 10) self.y = moose.IntFire('/x[5]/y', 10) self.z = moose.PulseGen('/x[5]/z', 3) self.u = moose.IntFire('/x[5]/z[2]/u', 10)
#!/usr/bin/env python """This is to show a _raw_ way of traversing messages.""" import sys sys.path.append('../../python') import moose connectionProbability = 0.5 net = moose.IntFire('/net1', 10) syn = moose.SimpleSynHandler('/net1/sh', 10) moose.connect(syn, 'activationOut', net, 'activation', 'OneToOne') synapse = syn.synapse.vec mid = moose.connect( net, 'spikeOut', synapse, 'addSpike', 'Sparse' ) # This creates a `Sparse` message from `spikeOut` source of net to `addSpike` destination on synapse. msg = moose.element(mid) msg.setRandomConnectivity(connectionProbability, 5) for n in net.vec: print 'Messages from %s.spikeOut' % (n.path) node = moose.element(n) for dest, df in zip(node.msgDests['spikeOut'], node.msgDestFunctions['spikeOut']): print '\t--> %s.%s' % (dest.path, df)
pg.firstWidth = 2e-03 pg.firstLevel = 3 pg.secondDelay = 1.0 cellPath = '/cell' # cell = moose.LeakyIaF(cellPath) # cell.setField('Cm',1e-6) # cell.setField('Rm',1e4) # cell.setField('Em',-0.07) # cell.setField('initVm',-0.05) # cell.setField('Vreset',-0.07) # cell.setField('Vthreshold',0.0) # cell.setField('refractoryPeriod',0.01) cell = moose.IntFire(cellPath) cell.setField('tau', 10e-3) #cell.setField('Vm', 1.0) cell.setField('refractoryPeriod', 5e-3) cell.setField('thresh', 0.9) cell.synapse.num = 1 cell.synapse[0].weight = 0.91 cell.synapse[0].delay = 10e-3 #this cell fires only when synaptic weight reaching it exceeds threshold - resets to neg and resets to 0 in refractoryPeriod time #else, goes back to 0 in tau time VmVal = moose.Table(cellPath + '/Vm_cell') print(('table>cellVm:', moose.connect(VmVal, 'requestOut', cell, 'getVm'))) spikeTime = moose.Table(cellPath + '/spikeTimes') print(('table>cellSpike:', moose.connect(cell, 'spike', spikeTime, 'input')))
def main(): """ In this example we walk through creation of a vector of IntFire elements and setting up synaptic connection between them. Synapse on IntFire elements is an example of ElementField - elements that do not exist on their own, but only as part of another element. This example also illustrates various operations on `vec` objects and ElementFields. """ size = 1024 # number of IntFire objects in a vec delayMin = 0 delayMax = 4 Vmax = 1.0 thresh = 0.8 refractoryPeriod = 0.4 connectionProbability = 0.1 weightMax = 0.5 # The above sets the constants we shall use in this example. Now we create a vector of IntFire elements of size `size`. net = moose.IntFire('/network', size) # This creates a `vec` of `IntFire` elements of size 1024 and returns the first `element`, i.e. "/network[0]". net = moose.element('/network[0]') # You need now to provide synaptic input to the network synh = moose.SimpleSynHandler('/network/synh', size) # These need to be connected to the nodes in the network moose.connect(synh, 'activationOut', net, 'activation', 'OneToOne') # You can access the underlying vector of elements using the `vec` field on any element. This is very useful for vectorized field access: net.vec.Vm = [thresh / 2.0] * size # The right part of the assigment creates a Python list of length `size` with each element set to `thresh/2.0`, which is 0.4. You can index into the `vec` to access individual elements' field: print((net.vec[1].Vm)) # `SimpleSynHandler` class has an `ElementField` called `synapse`. It is just like a `vec` above in terms of field access, but by default its size is 0. print((len(synh.synapse))) # To actually create synapses, you can explicitly assign the `num` field of this, or set the `numSynapses` field of the `IntFire` element. There are some functions which can implicitly set the size of the `ElementField`. synh.numSynapses = 3 print((len(synh.synapse))) synh.synapse.num = 4 print((len(synh.synapse))) # Now you can index into `net.synapse` as if it was an array. print(('Before:', synh.synapse[0].delay)) synh.synapse[0].delay = 1.0 print(('After:', synh.synapse[0].delay)) # You could do the same vectorized assignment as with `vec` directly: synh.synapse.weight = [0.2] * len(synh.synapse) print((synh.synapse.weight)) # You can create the synapses and assign the weights and delays using loops: for syn in synh.vec: syn.synapse.num = random.randint(1, 10) # create synapse fields with random size between 1 and 10, end points included # Below is one (inefficient) way of setting the individual weights of the elements in 'synapse' for ii in range(len(syn.synapse)): syn.synapse[ii].weight = random.random() * weightMax # This is a more efficient way - rhs of `=` is list comprehension in Python and rather fast syn.synapse.delay = [ delayMin + random.random() * delayMax for ii in range(len(syn.synapse)) ] # An even faster way will be to use numpy.random.rand(size) which produces array of random numbers uniformly distributed between 0 and 1 syn.synapse.delay = delayMin + nprand.rand(len(syn.synapse)) * delayMax # Now display the results, we use slice notation on `vec` to show the values of delay and weight for the first 5 elements in `/network` for syn in synh.vec[:5]: print(('Delays for synapses on ', syn.path, ':', syn.synapse.delay)) print(('Weights for synapses on ', syn.path, ':', syn.synapse.weight))
ElementFields.""" import moose size = 1024 # number of IntFire objects in a vec delayMin = 0 delayMax = 4 Vmax = 1.0 thresh = 0.8 refractoryPeriod = 0.4 connectionProbability = 0.1 weightMax = 0.5 # The above sets the constants we shall use in this example. Now we create a vector of IntFire elements of size `size`. net = moose.IntFire('/network', size) # This creates a `vec` of `IntFire` elements of size 1024 and returns the first `element`, i.e. "/network[0]". net = moose.element('/network[0]') # You need now to provide synaptic input to the network synh = moose.SimpleSynHandler('/network/synh', size) # These need to be connected to the nodes in the network moose.connect(synh, 'activationOut', net, 'activation', 'OneToOne') # You can access the underlying vector of elements using the `vec` field on any element. This is very useful for vectorized field access:
def make_network(): size = 1024 timestep = 0.2 runtime = 100.0 delayMin = timestep delayMax = 4 weightMax = 0.02 Vmax = 1.0 thresh = 0.2 tau = 1 # Range of tau tau0 = 0.5 # minimum tau refr = 0.3 refr0 = 0.2 connectionProbability = 0.1 random.seed(123) nprand.seed(456) t0 = time.time() clock = moose.element('/clock') network = moose.IntFire('network', size, 1) network.vec.bufferTime = [delayMax * 2] * size moose.le('/network') network.vec.numSynapses = [1] * size # Interesting. This fails because we haven't yet allocated # the synapses. I guess it is fair to avoid instances of objects that # don't have allocations. #synapse = moose.element( '/network/synapse' ) sv = moose.vec('/network/synapse') print('before connect t = ', time.time() - t0) mid = moose.connect(network, 'spikeOut', sv, 'addSpike', 'Sparse') print('after connect t = ', time.time() - t0) #print mid.destFields m2 = moose.element(mid) m2.setRandomConnectivity(connectionProbability, 5489) print('after setting connectivity, t = ', time.time() - t0) network.vec.Vm = [(Vmax * random.random()) for r in range(size)] network.vec.thresh = thresh network.vec.refractoryPeriod = [(refr0 + refr * random.random()) for r in range(size)] network.vec.tau = [(tau0 + tau * random.random()) for r in range(size)] numSynVec = network.vec.numSynapses print('Middle of setup, t = ', time.time() - t0) numTotSyn = sum(numSynVec) for item in network.vec: neuron = moose.element(item) neuron.synapse.delay = [(delayMin + random.random() * delayMax) for r in range(len(neuron.synapse))] neuron.synapse.weight = nprand.rand(len(neuron.synapse)) * weightMax print('after setup, t = ', time.time() - t0, ", numTotSyn = ", numTotSyn) """ netvec = network.vec for i in range( size ): synvec = netvec[i].synapse.vec synvec.weight = [ (random.random() * weightMax) for r in range( synvec.len )] synvec.delay = [ (delayMin + random.random() * delayMax) for r in range( synvec.len )] """ #moose.useClock( 9, '/postmaster', 'process' ) moose.useClock(0, '/network', 'process') moose.setClock(0, timestep) moose.setClock(9, timestep) t1 = time.time() moose.reinit() print('reinit time t = ', time.time() - t1) network.vec.Vm = [(Vmax * random.random()) for r in range(size)] print('setting Vm , t = ', time.time() - t1) t1 = time.time() print('starting') moose.start(runtime) print('runtime, t = ', time.time() - t1) print('Vm100:103', network.vec.Vm[100:103]) print('Vm900:903', network.vec.Vm[900:903]) print('weights 100:', network.vec[100].synapse.delay[0:5]) print('weights 900:', network.vec[900].synapse.delay[0:5])
moose.useClock( '/network', 'process', 0 ) moose.setClock( 0, timestep ) moose.setClock( 9, timestep ) moose.reinit() network.vec.Vm = [(Vmax*random.random()) for r in range(size)] moose.start(runtime) print network.vec[100].Vm, network.vec[900].Vm ''' import os import moose # Create an IntFire vec containing 10 elements, a refers to alpha[0] a = moose.IntFire('alpha', 10) print(('a=', a)) for i in range(10): syn = moose.SimpleSynHandler('alpha[' + str(i) + ']/sh') moose.connect(syn, 'activationOut', a.vec[i], 'activation') syn = moose.SimpleSynHandler('alpha/sh', 10) moose.connect(syn, 'activationOut', a, 'activation', 'OneToOne') ############################### # FieldElement identity ############################### x = syn.synapse # x is an ElementField alpha[0].synapse print('x=', x) print('x.num=', x.num) # Initially there are no synapses, so this will be 0 syn.synapse.num = 3 # We set number of field elements to 3 print('x.num=', x.num) # x refers to a.synapse, so this should be 3
def make_network(): size = 1024 dt = 0.2 runsteps = 50 delayMin = 0 delayMax = 4 weightMax = 1 Vmax = 1.0 thresh = 0.4 refractoryPeriod = 0.4 tau = 0.5 connectionProbability = 0.01 random.seed( 123 ) nprand.seed( 456 ) t0 = time.time() network = moose.IntFire( 'network', size ); syns = moose.SimpleSynHandler( '/network/syns', size ); moose.connect( syns, 'activationOut', network, 'activation', 'OneToOne' ) moose.le( '/network' ) syns.vec.numSynapses = [1] * size sv = moose.vec( '/network/syns/synapse' ) print(('before connect t = ', time.time() - t0)) mid = moose.connect( network, 'spikeOut', sv, 'addSpike', 'Sparse') print(('after connect t = ', time.time() - t0)) #print mid.destFields m2 = moose.element( mid ) m2.setRandomConnectivity( connectionProbability, 5489 ) print(('after setting connectivity, t = ', time.time() - t0)) #network.vec.Vm = [(Vmax*random.random()) for r in range(size)] network.vec.Vm = nprand.rand( size ) * Vmax network.vec.thresh = thresh network.vec.refractoryPeriod = refractoryPeriod network.vec.tau = tau numSynVec = syns.vec.numSynapses print(('Middle of setup, t = ', time.time() - t0)) numTotSyn = sum( numSynVec ) print((numSynVec.size, ', tot = ', numTotSyn, ', numSynVec = ', numSynVec)) for item in syns.vec: sh = moose.element( item ) sh.synapse.delay = delayMin + (delayMax - delayMin ) * nprand.rand( len( sh.synapse ) ) #sh.synapse.delay = [ (delayMin + random.random() * (delayMax - delayMin ) for r in range( len( sh.synapse ) ) ] sh.synapse.weight = nprand.rand( len( sh.synapse ) ) * weightMax print(('after setup, t = ', time.time() - t0)) numStats = 100 stats = moose.SpikeStats( '/stats', numStats ) stats.vec.windowLength = 1 # timesteps to put together. plots = moose.Table( '/plot', numStats ) convergence = size / numStats for i in range( numStats ): for j in range( size/numStats ): k = i * convergence + j moose.connect( network.vec[k], 'spikeOut', stats.vec[i], 'addSpike' ) moose.connect( plots, 'requestOut', stats, 'getMean', 'OneToOne' ) #moose.useClock( 0, '/network/syns,/network', 'process' ) moose.useClock( 0, '/network/syns', 'process' ) moose.useClock( 1, '/network', 'process' ) moose.useClock( 2, '/stats', 'process' ) moose.useClock( 3, '/plot', 'process' ) moose.setClock( 0, dt ) moose.setClock( 1, dt ) moose.setClock( 2, dt ) moose.setClock( 3, dt ) moose.setClock( 9, dt ) t1 = time.time() moose.reinit() print(('reinit time t = ', time.time() - t1)) network.vec.Vm = nprand.rand( size ) * Vmax print(('setting Vm , t = ', time.time() - t1)) t1 = time.time() print('starting') moose.start(runsteps * dt) print(('runtime, t = ', time.time() - t1)) print((network.vec.Vm[99:103], network.vec.Vm[900:903])) t = [i * dt for i in range( plots.vec[0].vector.size )] i = 0 for p in plots.vec: pylab.plot( t, p.vector, label=str( i) ) i += 1 pylab.xlabel( "Time (s)" ) pylab.ylabel( "Vm (mV)" ) pylab.legend() pylab.show()
def test_synapse(): """ In this example we walk through creation of a vector of IntFire elements and setting up synaptic connection between them. Synapse on IntFire elements is an example of ElementField - elements that do not exist on their own, but only as part of another element. This example also illustrates various operations on `vec` objects and ElementFields. """ size = 1024 # number of IntFire objects in a vec delayMin = 0 delayMax = 4 thresh = 0.8 weightMax = 0.5 # The above sets the constants we shall use in this example. Now we create # a vector of IntFire elements of size `size`. net = moose.IntFire("/network", size) # This creates a `vec` of `IntFire` elements of size 1024 and returns the # first `element`, i.e. "/network[0]". net = moose.element("/network[0]") # You need now to provide synaptic input to the network synh = moose.SimpleSynHandler("/network/synh", size) # These need to be connected to the nodes in the network moose.connect(synh, "activationOut", net, "activation", "OneToOne") # You can access the underlying vector of elements using the `vec` field on # any element. This is very useful for vectorized field access: _vm = [thresh / 2.0] * size net.vec.Vm = _vm assert np.allclose(net.vec.Vm, _vm) # The right part of the assigment creates a Python list of length `size` # with each element set to `thresh/2.0`, which is 0.4. You can index into # the `vec` to access individual elements' field: print(net.vec[1].Vm) assert net.vec[1].Vm == 0.4 # `SimpleSynHandler` class has an `ElementField` called `synapse`. It is # just like a `vec` above in terms of field access, but by default its size # is 0. assert len(synh.synapse) == 0 print(len(synh.synapse)) # To actually create synapses, you can explicitly assign the `num` field of # this, or set the `numSynapses` field of the `IntFire` element. There are # some functions which can implicitly set the size of the `ElementField`. synh.numSynapses = 3 assert len(synh.synapse) == 3 print(len(synh.synapse)) synh.numSynapses = 4 print(synh.synapse, 111) assert len(synh.synapse) == 4, (4, len(synh.synapse)) print(len(synh.synapse)) # Now you can index into `net.synapse` as if it was an array. print("Before:", synh.synapse[0].delay) assert synh.synapse[0].delay == 0.0 synh.synapse[0].delay = 1.0 assert synh.synapse[0].delay == 1.0 print("After:", synh.synapse[0].delay) # You could do the same vectorized assignment as with `vec` directly: syns = synh.synapse.vec syns.weight = [0.2] * len(syns) assert np.allclose(syns.weight, 0.2), syns.weight print(syns.weight) # You can create the synapses and assign the weights and delays using loops: for syn in synh.vec: syn.numSynapses = random.randint(1, 10) # create synapse fields with random size between 1 and 10, end points # included. Below is one (inefficient) way of setting the individual weights of # the elements in 'synapse' syns = syn.synapse for ii in range(len(syns)): syns[ii].weight = random.random() * weightMax # This is a more efficient way - rhs of `=` is list comprehension in # Python and rather fast. syns.delay = [ delayMin + random.random() * delayMax for ii in range(len(syn.synapse)) ] # An even faster way will be to use numpy.random.rand(size) which # produces array of random numbers uniformly distributed between 0 and # 1 syns.delay = delayMin + np.random.rand(len(syn.synapse)) * delayMax # Now display the results, we use slice notation on `vec` to show the # values of delay and weight for the first 5 elements in `/network` for syn in synh.vec[:5]: print("Delays for synapses on ", syn.path, ":", syn.synapse.vec.delay) print("Weights for synapses on ", syn.path, ":", syn.synapse.vec.weight)