def test_network_copy(): x = Counter() net = Network(x) net2 = Network() for obj in net.objects: net2.add(obj) net2.run(1*ms) assert_equal(x.count, 10) net.run(1*ms) assert_equal(x.count, 20)
def test_network_copy(): x = Counter() net = Network(x) net2 = Network() for obj in net.objects: net2.add(obj) net2.run(1 * ms) assert_equal(x.count, 10) net.run(1 * ms) assert_equal(x.count, 20)
def test_network_from_dict(): # Check that a network from a dictionary works x = Counter() y = Counter() d = dict(a=x, b=y) net = Network() net.add(d) net.run(1 * ms) assert_equal(len(net.objects), 2) assert_equal(x.count, 10) assert_equal(y.count, 10)
def test_network_from_dict(): # Check that a network from a dictionary works x = Counter() y = Counter() d = dict(a=x, b=y) net = Network() net.add(d) net.run(1*ms) assert_equal(len(net.objects), 2) assert_equal(x.count, 10) assert_equal(y.count, 10)
def test_network_two_objects(): # Check that a network with two objects and the same clock function correctly x = Counter(order=5) y = Counter(order=6) net = Network() net.add([x, [y]]) # check that a funky way of adding objects work correctly assert_equal(net.objects[0].order, 5) assert_equal(net.objects[1].order, 6) assert_equal(len(net.objects), 2) net.run(1*ms) assert_equal(x.count, 10) assert_equal(y.count, 10)
def test_network_stop(): # test that Network.stop and global stop() work correctly net = Network() x = Stopper(10, net.stop) net.add(x) net.run(10*ms) assert_equal(defaultclock.t, 1*ms) x = Stopper(10, stop) net = Network(x) net.run(10*ms) assert_equal(defaultclock.t, 1*ms)
def test_simple_syntax(): """ Simple example """ set_device('markdown') N = 10 tau = 10 * ms v_th = 0.9 * volt v_rest = -79 * mV eqn = 'dv/dt = (v_th - v)/tau :volt' refractory = 'randn() * tau / N' rates = 'rand() * 5 * Hz' group = NeuronGroup(N, eqn, method='euler', threshold='v > v_th', reset='v = v_rest; v = rand() * v_rest', refractory=refractory, events={'custom': 'v > v_th + 10 * mV', 'custom_1': 'v > v_th - 10 * mV'}) group.run_on_event('custom', 'v = v_rest') group.run_on_event('custom_1', 'v = v_rest - 0.001 * mV') spikegen = SpikeGeneratorGroup(N, [0, 1, 2], [1, 2, 3] * ms, period=5 * ms) po_grp = PoissonGroup(N - 1, rates=rates) syn = Synapses(spikegen, group, model='w :volt', on_pre='v = rand() * w + v_th; v = rand() * w', on_post='v = rand() * w + v_rest; v = rand() * w', delay=tau, method='euler') group.v[:] = v_rest group.v['i%2 == 0'] = 'rand() * v_rest' group.v[0:5] = 'v_rest + 10 * mV' condition = 'abs(i-j)<=5' syn.connect(condition=condition, p=0.999, n=2) syn.w = '1 * mV' net = Network(group, spikegen, po_grp, syn) mon = StateMonitor(syn, 'w', record=True) mon2 = SpikeMonitor(po_grp) mon3 = EventMonitor(group, 'custom') net.add(mon, mon2, mon3) net.run(0.01 * ms) md_str = device.md_text assert _markdown_lint(md_str) check = 'randn({sin({$w$}|$v_rest$ - $v$|/{\tau}})})' assert _markdown_lint(check) # check invalid strings with pytest.raises(SyntaxError): check = '**Initializing values at starting:*' assert _markdown_lint(check) check = '- Variable v$ of with $-79. mV$ to all members' assert _markdown_lint(check) check = 'randn({sin(})})' assert _markdown_lint(check) check = 'randn({sin({$w$}|$v_rest$ - $v$|/{\tau})})' assert _markdown_lint(check) device.reinit()
def test_incorrect_network_use(): '''Test some wrong uses of `Network` and `MagicNetwork`''' assert_raises(TypeError, lambda: Network(name='mynet', anotherkwd='does not exist')) assert_raises(TypeError, lambda: Network('not a BrianObject')) net = Network() assert_raises(TypeError, lambda: net.add('not a BrianObject')) assert_raises(ValueError, lambda: MagicNetwork()) G = NeuronGroup(10, 'v:1') net.add(G) assert_raises(TypeError, lambda: net.remove(object())) assert_raises(MagicError, lambda: magic_network.add(G)) assert_raises(MagicError, lambda: magic_network.remove(G))
def test_ExportDevice_options(): """ Test the run and build options of ExportDevice """ # test1 set_device('exporter') grp = NeuronGroup(10, 'eqn = 1:1', method='exact') run(100 * ms) _ = StateMonitor(grp, 'eqn', record=False) with pytest.raises(RuntimeError): run(100 * ms) # test2 device.reinit() with pytest.raises(RuntimeError): device.build() # test3 start_scope() net = Network() set_device('exporter', build_on_run=False) grp = NeuronGroup(10, 'eqn = 1:1', method='exact') net.add(grp) net.run(10 * ms) pogrp = PoissonGroup(10, rates=10 * Hz) net.add(pogrp) net.run(10 * ms) mon = StateMonitor(grp, 'eqn', record=False) net.add(mon) net.run(10 * ms) device.build() device.reinit()
def run_net(traj): """Creates and runs BRIAN network based on the parameters in `traj`.""" eqs = traj.eqs # Create a namespace dictionairy namespace = traj.Net.f_to_dict(short_names=True, fast_access=True) # Create the Neuron Group neuron = NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset=traj.reset, namespace=namespace) neuron.vm = traj.EL neuron.w = traj.a * (neuron.vm - traj.EL) neuron.Vr = linspace(-48.3 * mV, -47.7 * mV, traj.N) # bifurcation parameter # Run the network initially for 100 milliseconds print('Initial Run') net = Network(neuron) net.run(100 * ms, report='text') # we discard the first spikes # Create a Spike Monitor MSpike = SpikeMonitor(neuron) net.add(MSpike) # Create a State Monitor for the membrane voltage, record from neurons 1-3 MStateV = StateMonitor(neuron, variables=['vm'], record=[1, 2, 3]) net.add(MStateV) # Now record for 500 milliseconds print('Measurement run') net.run(500 * ms, report='text') # Add the BRAIN monitors traj.v_standard_result = Brian2MonitorResult traj.f_add_result('SpikeMonitor', MSpike) traj.f_add_result('StateMonitorV', MStateV)
class Neuron(object): def __init__(self, group=None): if group is None: # default to Izhikevich model neuron eq = '''dv/dt = (0.04*active/ms/mV + 0.04/ms/mV)*v**2+(5/ms)*v+140*mV/ms-w + I : volt (unless refractory) dw/dt = (0.02/ms)*((0.2/ms)*v-w) : volt/second active : 1 I : volt/second''' # create 1 neuron with 1 output self.group = Neuron( NeuronGroup(1, eq, threshold='v > 50*mV', reset='v = -50*mV', refractory=10 * ms, method='rk2')) else: self.group = group self.state_monitor = StateMonitor(self.group, 'v', record=True) # monitor voltages self.spike_monitor = SpikeMonitor(self.group) self.operator = NetworkOperation(self.update_active, dt=100 * ms) # initialise network object for neuron to run in and add elements self.network = Network() self.network.add(self.group) self.network.add(self.state_monitor) self.network.add(self.spike_monitor) self.network.add(self.operator) self.input = 0 # function for updating neuron state def update_active(self): self.group.active = self.input def update( self, input=0, dt=100, pip=None, fs=44100 ): #run simulation for dt milliseconds, return number of spikes which occur self.input = input prev = self.spike_monitor.num_spikes self.network.run(dt * ms) spikes = self.spike_monitor.num_spikes - prev if pip is not None and spikes > 0: # if there is a sound to play, play it sd.play(np.tile(pip, spikes + 1)) return spikes def history(self, length): # returns last 'length' samples of state monitor state_len = len(self.state_monitor.v[0]) v_history = self.state_monitor.v[0][max(state_len - length, 0):state_len] if state_len - length < 0: pad = np.zeros(length - state_len) v_history = np.concatenate([pad, v_history]) return v_history
def run_task_hierarchical(task_info, taskdir, tempdir): # imports from brian2 import defaultclock, set_device, seed, TimedArray, Network, profiling_summary from brian2.monitors import SpikeMonitor, PopulationRateMonitor, StateMonitor from brian2.synapses import Synapses from brian2.core.magic import start_scope from brian2.units import second, ms, amp from integration_circuit import mk_intcircuit from sensory_circuit import mk_sencircuit, mk_sencircuit_2c, mk_sencircuit_2cplastic from burstQuant import spks2neurometric from scipy import interpolate # if you want to put something in the taskdir, you must create it first os.mkdir(taskdir) print(taskdir) # parallel code and flag to start set_device('cpp_standalone', directory=tempdir) #prefs.devices.cpp_standalone.openmp_threads = max_tasks start_scope() # simulation parameters seedcon = task_info['simulation']['seedcon'] runtime = task_info['simulation']['runtime'] runtime_ = runtime / second settletime = task_info['simulation']['settletime'] settletime_ = settletime / second stimon = task_info['simulation']['stimon'] stimoff = task_info['simulation']['stimoff'] stimoff_ = stimoff / second stimdur = stimoff - stimon smoothwin = task_info['simulation']['smoothwin'] nummethod = task_info['simulation']['nummethod'] # ------------------------------------- # Construct hierarchical network # ------------------------------------- # set connection seed seed( seedcon ) # set specific seed to test the same network, this way we also have the same synapses! # decision circuit Dgroups, Dsynapses, Dsubgroups = mk_intcircuit(task_info) decE = Dgroups['DE'] decI = Dgroups['DI'] decE1 = Dsubgroups['DE1'] decE2 = Dsubgroups['DE2'] # sensory circuit, ff and fb connections eps = 0.2 # connection probability d = 1 * ms # transmission delays of E synapses if task_info['simulation']['2cmodel']: if task_info['simulation']['plasticdend']: # plasticity rule in dendrites --> FB synapses will be removed from the network! Sgroups, Ssynapses, Ssubgroups = mk_sencircuit_2cplastic(task_info) else: # 2c model (Naud) Sgroups, Ssynapses, Ssubgroups = mk_sencircuit_2c(task_info) senE = Sgroups['soma'] dend = Sgroups['dend'] senI = Sgroups['SI'] senE1 = Ssubgroups['soma1'] senE2 = Ssubgroups['soma2'] dend1 = Ssubgroups['dend1'] dend2 = Ssubgroups['dend2'] # FB wDS = 0.003 # synaptic weight of FB synapses, 0.0668 nS when scaled by gleakE of sencircuit_2c synDE1SE1 = Synapses(decE1, dend1, model='w : 1', method=nummethod, on_pre='x_ea += w', delay=d) synDE2SE2 = Synapses(decE2, dend2, model='w : 1', method=nummethod, on_pre='x_ea += w', delay=d) else: # normal sensory circuit (Wimmer) Sgroups, Ssynapses, Ssubgroups = mk_sencircuit(task_info) senE = Sgroups['SE'] senI = Sgroups['SI'] senE1 = Ssubgroups['SE1'] senE2 = Ssubgroups['SE2'] # FB wDS = 0.004 # synaptic weight of FB synapses, 0.0668 nS when scaled by gleakE of sencircuit synDE1SE1 = Synapses(decE1, senE1, model='w : 1', method=nummethod, on_pre='x_ea += w', delay=d) synDE2SE2 = Synapses(decE2, senE2, model='w : 1', method=nummethod, on_pre='x_ea += w', delay=d) # feedforward synapses from sensory to integration wSD = 0.0036 # synaptic weight of FF synapses, 0.09 nS when scaled by gleakE of intcircuit synSE1DE1 = Synapses(senE1, decE1, model='w : 1', method=nummethod, on_pre='g_ea += w', delay=d) synSE1DE1.connect(p='eps') synSE1DE1.w = 'wSD' synSE2DE2 = Synapses(senE2, decE2, model='w : 1', method=nummethod, on_pre='g_ea += w', delay=d) synSE2DE2.connect(p='eps') synSE2DE2.w = 'wSD' # feedback synapses from integration to sensory b_fb = task_info['bfb'] # feedback strength, between 0 and 6 wDS *= b_fb # synaptic weight of FB synapses, 0.0668 nS when scaled by gleakE of sencircuit synDE1SE1.connect(p='eps') synDE1SE1.w = 'wDS' synDE2SE2.connect(p='eps') synDE2SE2.w = 'wDS' # ------------------------------------- # Create stimuli # ------------------------------------- if task_info['stimulus']['replicate']: # replicated stimuli across iters() np.random.seed(task_info['seed']) # numpy seed for OU process else: # every trials has different stimuli np.random.seed() # Note that in standalone we need to specify np seed because it's not taken care with Brian's seed() function! if task_info['simulation']['2cmodel']: I0 = task_info['stimulus']['I0s'] last_muOUd = np.loadtxt("last_muOUd.csv") # save the mean else: I0 = task_info['stimulus'][ 'I0'] # mean input current for zero-coherence stim c = task_info['c'] # stim coherence (between 0 and 1) mu1 = task_info['stimulus'][ 'mu1'] # av. additional input current to senE1 at highest coherence (c=1) mu2 = task_info['stimulus'][ 'mu2'] # av. additional input current to senE2 at highest coherence (c=1) sigma = task_info['stimulus'][ 'sigma'] # amplitude of temporal modulations of stim sigmastim = 0.212 * sigma # std of modulation of stim inputs sigmaind = 0.212 * sigma # std of modulations in individual inputs taustim = task_info['stimulus'][ 'taustim'] # correlation time constant of Ornstein-Uhlenbeck process # generate stim from OU process N_stim = int(senE1.__len__()) z1, z2, zk1, zk2 = generate_stim(N_stim, stimdur, taustim) # stim2exc i1 = I0 * (1 + c * mu1 + sigmastim * z1 + sigmaind * zk1) i2 = I0 * (1 + c * mu2 + sigmastim * z2 + sigmaind * zk2) stim_dt = 1 * ms i1t = np.concatenate((np.zeros((int(stimon / ms), N_stim)), i1.T, np.zeros((int( (runtime - stimoff) / stim_dt), N_stim))), axis=0) i2t = np.concatenate((np.zeros((int(stimon / ms), N_stim)), i2.T, np.zeros((int( (runtime - stimoff) / stim_dt), N_stim))), axis=0) Irec = TimedArray(np.concatenate((i1t, i2t), axis=1) * amp, dt=stim_dt) # ------------------------------------- # Simulation # ------------------------------------- # set initial conditions (different for evert trial) seed() decE.g_ea = '0.2 * rand()' decI.g_ea = '0.2 * rand()' decE.V = '-52*mV + 2*mV * rand()' decI.V = '-52*mV + 2*mV * rand()' # random initialization near 0, prevent an early decision! senE.g_ea = '0.05 * (1 + 0.2*rand())' senI.g_ea = '0.05 * (1 + 0.2*rand())' senE.V = '-52*mV + 2*mV*rand()' # random initialization near Vt, avoid initial bump! senI.V = '-52*mV + 2*mV*rand()' if task_info['simulation']['2cmodel']: dend.g_ea = '0.05 * (1 + 0.2*rand())' dend.V_d = '-72*mV + 2*mV*rand()' dend.muOUd = np.tile(last_muOUd, 2) * amp # create monitors rateDE1 = PopulationRateMonitor(decE1) rateDE2 = PopulationRateMonitor(decE2) rateSE1 = PopulationRateMonitor(senE1) rateSE2 = PopulationRateMonitor(senE2) subSE = int(senE1.__len__()) spksSE = SpikeMonitor(senE[subSE - 100:subSE + 100]) # last 100 of SE1 and first 100 of SE2 # construct network net = Network(Dgroups.values(), Dsynapses.values(), Sgroups.values(), Ssynapses.values(), synSE1DE1, synSE2DE2, synDE1SE1, synDE2SE2, rateDE1, rateDE2, rateSE1, rateSE2, spksSE, name='hierarchicalnet') # create more monitors for plot if task_info['simulation']['pltfig1']: # inh rateDI = PopulationRateMonitor(decI) rateSI = PopulationRateMonitor(senI) # spk monitors subDE = int(decE1.__len__() * 2) spksDE = SpikeMonitor(decE[:subDE]) spksSE = SpikeMonitor(senE) # state mons no more, just the arrays stim1 = i1t.T stim2 = i2t.T stimtime = np.linspace(0, runtime_, stim1.shape[1]) # construct network net = Network(Dgroups.values(), Dsynapses.values(), Sgroups.values(), Ssynapses.values(), synSE1DE1, synSE2DE2, synDE1SE1, synDE2SE2, spksDE, rateDE1, rateDE2, rateDI, spksSE, rateSE1, rateSE2, rateSI, name='hierarchicalnet') if task_info['simulation']['plasticdend']: # create state monitor to follow muOUd and add it to the networks dend_mon = StateMonitor(dend1, variables=['muOUd', 'Ibg', 'g_ea', 'B'], record=True, dt=1 * ms) net.add(dend_mon) # remove FB synapses! net.remove([synDE1SE1, synDE2SE2, Dsynapses.values()]) print( " FB synapses and synapses of decision circuit are ignored in this simulation!" ) # run hierarchical net net.run(runtime, report='stdout', profile=True) print(profiling_summary(net=net, show=10)) # nice plots on cluster if task_info['simulation']['pltfig1']: plot_fig1b([ rateDE1, rateDE2, rateDI, spksDE, rateSE1, rateSE2, rateSI, spksSE, stim1, stim2, stimtime ], smoothwin, taskdir) # ------------------------------------- # Burst quantification # ------------------------------------- events = np.zeros(1) bursts = np.zeros(1) singles = np.zeros(1) spikes = np.zeros(1) last_muOUd = np.zeros(1) # neurometric params dt = spksSE.clock.dt validburst = task_info['sen']['2c']['validburst'] smoothwin_ = smoothwin / second if task_info['simulation']['burstanalysis']: if task_info['simulation']['2cmodel']: last_muOUd = np.array(dend_mon.muOUd[:, -int(1e3):].mean(axis=1)) if task_info['simulation']['plasticdend']: # calculate neurometric info per population events, bursts, singles, spikes, isis = spks2neurometric( spksSE, runtime, settletime, validburst, smoothwin=smoothwin_, raster=False) # plot & save weigths after convergence eta0 = task_info['sen']['2c']['eta0'] tauB = task_info['sen']['2c']['tauB'] targetB = task_info['targetB'] B0 = tauB * targetB tau_update = task_info['sen']['2c']['tau_update'] eta = eta0 * tau_update / tauB plot_weights(dend_mon, events, bursts, spikes, [targetB, B0, eta, tauB, tau_update, smoothwin_], taskdir) plot_rasters(spksSE, bursts, targetB, isis, runtime_, taskdir) else: # calculate neurometric per neuron events, bursts, singles, spikes, isis = spks2neurometric( spksSE, runtime, settletime, validburst, smoothwin=smoothwin_, raster=True) plot_neurometric(events, bursts, spikes, stim1, stim2, stimtime, (settletime_, runtime_), taskdir, smoothwin_) plot_isis(isis, bursts, events, (settletime_, runtime_), taskdir) # ------------------------------------- # Choice selection # ------------------------------------- # population rates and downsample originaltime = rateDE1.t / second interptime = np.linspace(0, originaltime[-1], originaltime[-1] * 100) # every 10 ms fDE1 = interpolate.interp1d( originaltime, rateDE1.smooth_rate(window='flat', width=smoothwin)) fDE2 = interpolate.interp1d( originaltime, rateDE2.smooth_rate(window='flat', width=smoothwin)) fSE1 = interpolate.interp1d( originaltime, rateSE1.smooth_rate(window='flat', width=smoothwin)) fSE2 = interpolate.interp1d( originaltime, rateSE2.smooth_rate(window='flat', width=smoothwin)) rateDE = np.array([f(interptime) for f in [fDE1, fDE2]]) rateSE = np.array([f(interptime) for f in [fSE1, fSE2]]) # select the last half second of the stimulus newdt = runtime_ / rateDE.shape[1] settletimeidx = int(settletime_ / newdt) dec_ival = np.array([(stimoff_ - 0.5) / newdt, stimoff_ / newdt], dtype=int) who_wins = rateDE[:, dec_ival[0]:dec_ival[1]].mean(axis=1) # divide trls into preferred and non-preferred pref_msk = np.argmax(who_wins) poprates_dec = np.array([rateDE[pref_msk], rateDE[~pref_msk]]) # 0: pref, 1: npref poprates_sen = np.array([rateSE[pref_msk], rateSE[~pref_msk]]) results = { 'raw_data': { 'poprates_dec': poprates_dec[:, settletimeidx:], 'poprates_sen': poprates_sen[:, settletimeidx:], 'pref_msk': np.array([pref_msk]), 'last_muOUd': last_muOUd }, 'sim_state': np.zeros(1), 'computed': { 'events': events, 'bursts': bursts, 'singles': singles, 'spikes': spikes, 'isis': np.array(isis) } } return results
class BrianerClass(BaseClass): def default_init(self, _BrianingNeurongroupDict=None, _BrianingSynapsesDict=None, _BrianingConnectVariable=None, _BrianingTraceDict=None, _BrianingMoniterTuple=None, _BrianingSpikesDict=None, _BrianingTimeDimensionVariable=None, _BrianedNetworkVariable=None, _BrianedNeurongroupVariable=None, _BrianedSynapsesVariable=None, _BrianedStateMonitorVariable=None, _BrianedSpikeMonitorVariable=None, _BrianedTraceKeyStrsList=None, _BrianedSynapsesDeriveBrianersList=None, _BrianedStateDeriveBrianersList=None, _BrianedSpikeDeriveBrianersList=None, _BrianedParentNetworkDeriveBrianerVariable=None, _BrianedParentNeurongroupDeriveBrianerVariable=None, _BrianedParentDeriveTracerVariable=None, **_KwargVariablesDict ): #Call the parent __init__ method BaseClass.__init__(self,**_KwargVariablesDict) def do_brian(self): #debug self.debug( [ 'We brian here', ('self.',self,['ParentedTotalSingularListDict']) ] ) #Check if self.ParentDeriveTeamerVariable==None or 'Neurongroups' in self.TeamDict or self.ParentDeriveTeamerVariable.TeamTagStr not in [ 'Traces','Samples' ]: #/###################/# # Recorder level # structure #debug self.debug( [ 'It is a Network level', ('self.',self,[ ]) ] ) #/########################/# # Network case # #import from brian2 import Network #structure self.BrianedNetworkVariable=Network() #/########################/# # make brian the neurongroups # #structure self.structure( [ 'Neurongroups', 'Postlets', 'Traces', 'Events', 'Samples' ], None ) """ #map map( lambda __DeriveBrianer: __DeriveBrianer.brian(), self.TeamDict['Neurongroups'].ManagementDict.values() ) """ #Check elif len(self.BrianingNeurongroupDict)>0: #/##################/# # Neurongroup case # adapt the BrianingNeurongroupDict and init #debug ''' self.debug( [ 'It is a Neurongroup level, we set the Neurongroup', 'We adapt the shape of BrianingNeurongroupDict', ('self.',self,[ 'BrianingNeurongroupDict', 'TracingKeyVariable' ]) ] ) ''' #Check if 'N' not in self.BrianingNeurongroupDict: self.BrianingNeurongroupDict['N']=self.SimulatingUnitsInt else: self.SimulatingUnitsInt=self.BrianingNeurongroupDict['N'] #Check if 'model' not in self.BrianingNeurongroupDict: self.BrianingNeurongroupDict['model']='' #maybe should import from brian2 import NeuronGroup #debug ''' self.debug( [ ('self.',self,[ 'BrianingNeurongroupDict' ]) ] ) ''' #init self.BrianedNeurongroupVariable=NeuronGroup( **self.BrianingNeurongroupDict ) #debug ''' self.debug( [ 'Ok we have setted the Neurongroup', ('self.',self,[ 'BrianedNeurongroupVariable' ]) ] ) ''' #/##################/# # set the BrianedParentNeurongroupDeriveBrianerVariable # #debug ''' self.debug( [ 'We get the parent structure', 'self.TeamDict is ', SYS._str(self.TeamDict.keys()) ] ) ''' #Check if 'Networks' in self.TeamDict: if 'Brianer' in self.TeamDict['Networks'].ManagementDict: #debug ''' self.debug( [ 'Brianer neurongroup is contained in a structureing brianer structure' ] ) ''' #set self.BrianedParentNetworkDeriveBrianerVariable=self.TeamDict[ 'Networks' ].ManagementDict['Brianer'] if self.ParentDeriveTeamerVariable!=None and self.ParentDeriveTeamerVariable.TeamTagStr=='Neurongroups': #debug ''' self.debug( [ 'Brianer neurongroup is contained in a parenting brianer structure' ] ) ''' #set self.BrianedParentNetworkDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #debug ''' self.debug( [ 'We get the parent structure', ('self.',self,['BrianedParentNeurongroupDeriveBrianerVariable']) ] ) ''' #/##################/# # team States first all the brian variables # #get self.BrianedTraceKeyStrsList=self.BrianedNeurongroupVariable.equations._equations.keys() #Check if len(self.BrianedTraceKeyStrsList)>0: #debug ''' self.debug( [ 'We simulate with neurongroup', 'adapt the initial conditions of all the brian variables', 'so first we team Traces and put Tracers inside or get it and mapSet' ] ) ''' #Check if 'Traces' not in self.TeamDict: BrianedDeriveTraces=self.team( 'Traces' ).TeamedValueVariable else: BrianedDeriveTraces=self.TeamDict[ 'Traces' ] #map self.BrianedTraceDeriveBrianersList=map( lambda __ManagementKeyStr,__TraceKeyStr: BrianedDeriveTraces.manage( __ManagementKeyStr, { 'TracingKeyVariable':getattr( self.BrianedNeurongroupVariable, __TraceKeyStr ), 'TraceKeyStr':__TraceKeyStr } ).ManagedValueVariable if __ManagementKeyStr not in BrianedDeriveTraces.ManagementDict else BrianedDeriveTraces.ManagementDict[__ManagementKeyStr].mapSet( { 'TracingKeyVariable':getattr( self.BrianedNeurongroupVariable, __TraceKeyStr ), 'TraceKeyStr':__TraceKeyStr } ), map( lambda __BrianedTraceKeyStr: Tracer.TracerPrefixStr+__BrianedTraceKeyStr, self.BrianedTraceKeyStrsList ), self.BrianedTraceKeyStrsList ) #/##################/# # Case of one only pop without parent Network # #set BrianedNetworkBool=False #Check if 'Networks' in self.TeamDict: if 'Brianer' in self.TeamDict['Networks'].ManagementDict: #set BrianedNetworkBool=True #Check if self.ParentDeriveTeamerVariable!=None: if self.ParentDeriveTeamerVariable.TeamTagStr=='Neurongroups': #set BrianedNetworkBool=True #Check if BrianedNetworkBool==False: #/################/# # Set a structure at this place # #debug ''' self.debug( [ 'This is just one neurongroup without parent structure' ] ) ''' #import from brian2 import Network #structure self.BrianedNetworkVariable=Network() #/################/# # Maybe structure # #debug self.debug( [ 'We structure Traces,Events,Samples' ] ) #structure self.structure( [ 'Postlets', 'Traces', 'Events', 'Samples' ], None ) else: #alias self.BrianedNetworkVariable=self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable #debug ''' self.debug( [ 'Ok we know the structure ', ('self.',self,['BrianedNetworkVariable']) ] ) ''' #/##################/# # add in the net # #add self.BrianedNetworkVariable.add( self.BrianedNeurongroupVariable ) #/##################/# # We make brian the Tracers # #debug ''' self.debug( [ 'Make brian the tracers', ('self.',self,['BrianedTraceDeriveBrianersList']) ] ) ''' #map """ map( lambda __BrianedDeriveTracer: __BrianedDeriveTracer.brian(), self.BrianedTraceDeriveBrianersList ) """ #debug ''' self.debug( [ 'Ok the Tracers have brianed', 'Now we check if it is a wrapped neurongroup into a structure or not' ] ) ''' """ #/##################/# # Make brian the spikes # #debug self.debug( [ 'We make brian the Spikes' ] ) #Check if 'Events' in self.TeamDict: #map map( lambda __DeriveBrianer: __DeriveBrianer.brian(), self.TeamDict['Events'].ManagementDict.values() ) #debug self.debug( [ 'We have made brian the spikes' ] ) """ elif self.ParentDeriveTeamerVariable.TeamTagStr=='Postlets': #debug self.debug( [ 'It is a Synapser level, we set the Synapser', ('self.',self,[ 'BrianingSynapsesDict' ] ), 'self.PointToVariable.BrianedNeurongroupVariable is ', str(self.PointToVariable.BrianedNeurongroupVariable) ] ) #/####################/# # Set the BrianedParentNeurongroupDeriveBrianerVariable # #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/####################/# # Set the BrianedParentNeurongroupDeriveBrianerVariable # #import from brian2 import Synapses #init self.BrianedSynapsesVariable=Synapses( source=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable, target=self.PointToVariable.BrianedNeurongroupVariable, **self.BrianingSynapsesDict ) #/####################/# # Connect options # #connect if type(self.BrianingConnectVariable)==float: #debug self.debug( [ 'we connect with a sparsity of ', ('self.',self,[ 'BrianingConnectVariable' ]) ] ) #connect self.BrianedSynapsesVariable.connect( True, p=self.BrianingConnectVariable ) """ #/####################/# # Reshape the weigths # #Check if self.SynapsingWeigthSymbolStr!="": #debug ''' self.debug( ('self.',self,[ 'BrianedSynapsesVariable', 'SynapsingWeigthSymbolStr' ]) ) ''' #connect self.BrianedSynapsesVariable.connect(True) #get self.SynapsedWeigthFloatsArray=getattr( self.BrianedSynapsesVariable, self.SynapsingWeigthSymbolStr ) #set self.SynapsedWeigthFloatsArray[:]=np.reshape( self.SynapsingWeigthFloatsArray, self.BrianedSynapsesVariable.source.N*self.BrianedSynapsesVariable.target.N ) #debug self.debug( ('self.',self,[ 'SynapsedWeigthFloatsArray' ]) ) """ #/####################/# # add to the structure # #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedSynapsesVariable ) elif self.ParentDeriveTeamerVariable.TeamTagStr=='Traces': #debug self.debug( [ 'It is a Tracer level, we set the Samples', ('self.',self,[ #'TracingKeyVariable', 'TraceKeyStr' ]) ] ) #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #/###################/# # Build the samples and maybe one default moniter # #Check if 'Samples' not in self.TeamDict: BrianedDeriveSamples=self.team( 'Samples' ).TeamedValueVariable else: BrianedDeriveSamples=self.TeamDict[ 'Samples' ] #debug ''' self.debug( [ 'Do we have to set a default moniter ?', 'len(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedTraceKeyStrsList) is ', str(len(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedTraceKeyStrsList)) ] ) ''' #Check if len(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedTraceKeyStrsList)==1: #Check if len(BrianedDeriveSamples.ManagementDict)==0: BrianedDefaultMoniter=BrianedDeriveSamples.manage( 'Default', ).ManagedValueVariable BrianedDefaultMoniter.MoniteringLabelIndexIntsArray=[0] if self.BrianedParentNeurongroupDeriveBrianerVariable.BrianingNeurongroupDict[ 'N']>0 else [] """ #/###################/# # We trace and set to the brian value # #debug ''' self.debug( [ 'We trace and alias the init in the brian object', ('self.',self,['TracingKeyVariable']) ] ) ''' #trace self.trace() #debug ''' self.debug( [ 'We have traced, alias the init in the brian object', ('self.',self,[ 'TracedValueFloatsArray', 'TracedInitFloatsArray' ]) ] ) ''' #alias self.TracedValueFloatsArray[:]=self.TracedInitFloatsArray*self.TracedValueFloatsArray.unit #debug ''' self.debug( [ ('self.',self,['TracedValueFloatsArray']) ] ) ''' """ # """ #/###################/# # We make brian the Moniters # #debug ''' self.debug( [ 'We make brian the moniters', 'BrianedDeriveSamples.ManagementDict.keys() is ', str(BrianedDeriveSamples.ManagementDict.keys()) ] ) ''' #map map( lambda __DeriveMoniter: __DeriveMoniter.brian(), BrianedDeriveSamples.ManagementDict.values() ) #debug ''' self.debug( [ 'We have made brian the moniters', ] ) ''' """ elif self.ParentDeriveTeamerVariable.TeamTagStr=='Samples': #debug ''' self.debug( [ 'It is a State Moniter level', ('self.',self,[ 'MoniteringLabelIndexIntsArray', ]) ] ) ''' #/####################/# # Set the BrianedParentNeurongroupDeriveBrianerVariable # #get self.BrianedParentDeriveTracerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.BrianedParentDeriveTracerVariable.BrianedParentNeurongroupDeriveBrianerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/####################/# # Set the brian monitor # #debug self.debug( [ 'We set the state monitor', ('self.',self,[ #'BrianedParentNeurongroupDeriveBrianerVariable' ]), #'self.BrianedParentDeriveTracerVariable.TraceKeyStr is ', #str(self.BrianedParentDeriveTracerVariable.TraceKeyStr) 'self.ParentedTotalManagementOrderedDict.keys() is ', str(self.ParentedTotalManagementOrderedDict.keys()) ] ) #import from brian2 import StateMonitor #init self.BrianedStateMonitorVariable=StateMonitor( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable, self.BrianedParentDeriveTracerVariable.TraceKeyStr, self.MoniteringLabelIndexIntsArray, ) #debug ''' self.debug( [ 'Ok we have setted the monitor', ('self.',self,['BrianedStateMonitorVariable']), 'Now we add to the structure', 'self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNetworkVariable is ', str(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNetworkVariable) ] ) ''' #/####################/# # add to the structure # #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedStateMonitorVariable ) elif self.ParentDeriveTeamerVariable.TeamTagStr=='Events': #debug ''' self.debug( [ 'It is a Spike Moniter level', ('self.',self,[ ]) ] ) ''' #/####################/# # Set the BrianedParentNeurongroupDeriveBrianerVariable # #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/####################/# # Set the brian monitor # #debug ''' self.debug( [ 'We set the spike monitor' ] ) ''' #import from brian2 import SpikeMonitor #init self.BrianedSpikeMonitorVariable=SpikeMonitor( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable, ) #debug ''' self.debug( [ 'Ok we have setted the monitor', ('self.',self,['BrianedSpikeMonitorVariable']), 'Now we add to the structure', 'self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNetworkVariable is ', str(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNetworkVariable) ] ) ''' #/####################/# # add to the structure # #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedSpikeMonitorVariable ) def propertize_setWatchAfterParentWithParenterBool(self,_SettingValueVariable): #/##################/# # Maybe brian # #debug self.debug( [ 'We are going to parent but before', ('self.',self,['StructuringDoStr']), 'self.StructuringTopDeriveStructurerVariable!=self is ', str(self.StructuringTopDeriveStructurerVariable!=self) ] ) #Check if self.StructuringDoStr=='Brian' and self.StructuringTopDeriveStructurerVariable!=self: #record self.brian() #/##################/# # Call the base method # #debug ''' self.debug( [ 'Now we call the base setParent method' ] ) ''' #set BaseClass.propertize_setWatchAfterParentWithParenterBool(self,_SettingValueVariable) def mimic_simulate(self): #parent method BaseClass.simulate(self) #debug ''' self.debug('We start simulate in brian') ''' #Check if self.BrianingTimeDimensionVariable==None: from brian2 import ms self.BrianingTimeDimensionVariable=ms #run with the brian method self.BrianedNetworkVariable.run( self.SimulatingStopTimeFloat*self.BrianingTimeDimensionVariable ) #debug ''' self.debug('We stop running in brian') ''' def mimic_trace(self): #base method BaseClass.trace(self) #debug ''' self.debug( [ 'We have traced, alias the init in the brian object', ('self.',self,[ 'TracedValueFloatsArray', 'TracedInitFloatsArray' ]) ] ) ''' #alias self.TracedValueFloatsArray[:]=self.TracedInitFloatsArray*self.TracedValueFloatsArray.unit #debug ''' self.debug( [ ('self.',self,['TracedValueFloatsArray']) ] ) ''' def mimic_draw(self): """
def test_ExportDevice_basic(): """ Test the components and structure of the dictionary exported by ExportDevice """ start_scope() set_device('exporter') grp = NeuronGroup(10, 'dv/dt = (1-v)/tau :1', method='exact', threshold='v > 0.5', reset='v = 0', refractory=2 * ms) tau = 10 * ms rate = '1/tau' grp.v['i > 2 and i < 5'] = -0.2 pgrp = PoissonGroup(10, rates=rate) smon = SpikeMonitor(pgrp) smon.active = False netobj = Network(grp, pgrp, smon) netobj.run(100 * ms) dev_dict = device.runs # check the structure and components in dev_dict assert dev_dict[0]['duration'] == 100 * ms assert dev_dict[0]['inactive'][0] == smon.name components = dev_dict[0]['components'] assert components['spikemonitor'][0] assert components['poissongroup'][0] assert components['neurongroup'][0] initializers = dev_dict[0]['initializers_connectors'] assert initializers[0]['source'] == grp.name assert initializers[0]['variable'] == 'v' assert initializers[0]['index'] == 'i > 2 and i < 5' # TODO: why not a Quantity type? assert initializers[0]['value'] == '-0.2' with pytest.raises(KeyError): initializers[0]['identifiers'] device.reinit() start_scope() set_device('exporter', build_on_run=False) tau = 10 * ms v0 = -70 * mV vth = 800 * mV grp = NeuronGroup(10, 'dv/dt = (v0-v)/tau :volt', method='exact', threshold='v > vth', reset='v = v0', refractory=2 * ms) v0 = -80 * mV grp.v[:] = 'v0 + 2 * mV' smon = StateMonitor(grp, 'v', record=True) smon.active = False net = Network(grp, smon) net.run(10 * ms) # first run v0 = -75 * mV grp.v[3:8] = list(range(3, 8)) * mV smon.active = True net.run(20 * ms) # second run v_new = -5 * mV grp.v['i >= 5'] = 'v0 + v_new' v_new = -10 * mV grp.v['i < 5'] = 'v0 - v_new' spikemon = SpikeMonitor(grp) net.add(spikemon) net.run(5 * ms) # third run dev_dict = device.runs # check run1 assert dev_dict[0]['duration'] == 10 * ms assert dev_dict[0]['inactive'][0] == smon.name components = dev_dict[0]['components'] assert components['statemonitor'][0] assert components['neurongroup'][0] initializers = dev_dict[0]['initializers_connectors'] assert initializers[0]['source'] == grp.name assert initializers[0]['variable'] == 'v' assert initializers[0]['index'] assert initializers[0]['value'] == 'v0 + 2 * mV' assert initializers[0]['identifiers']['v0'] == -80 * mV with pytest.raises(KeyError): initializers[0]['identifiers']['mV'] # check run2 assert dev_dict[1]['duration'] == 20 * ms initializers = dev_dict[1]['initializers_connectors'] assert initializers[0]['source'] == grp.name assert initializers[0]['variable'] == 'v' assert (initializers[0]['index'] == grp.indices[slice(3, 8, None)]).all() assert (initializers[0]['value'] == list(range(3, 8)) * mV).all() with pytest.raises(KeyError): dev_dict[1]['inactive'] initializers[1]['identifiers'] # check run3 assert dev_dict[2]['duration'] == 5 * ms with pytest.raises(KeyError): dev_dict[2]['inactive'] assert dev_dict[2]['components']['spikemonitor'] initializers = dev_dict[2]['initializers_connectors'] assert initializers[0]['source'] == grp.name assert initializers[0]['variable'] == 'v' assert initializers[0]['index'] == 'i >= 5' assert initializers[0]['value'] == 'v0 + v_new' assert initializers[0]['identifiers']['v0'] == -75 * mV assert initializers[0]['identifiers']['v_new'] == -5 * mV assert initializers[1]['index'] == 'i < 5' assert initializers[1]['value'] == 'v0 - v_new' assert initializers[1]['identifiers']['v_new'] == -10 * mV with pytest.raises(IndexError): initializers[2] dev_dict[3] device.reinit()
S1.w[:] = 1 S2 = Synapses(EXT2, P_E, model='w : 1', on_pre='s_ext2 += w', method='euler') S2.connect(j='i') # one-to-one S2.w[:] = 0 # ============================================================================= # ============================================================================= M = StateMonitor(P_E, ('v_soma', 'v_dend1', 'v_dend2'), record=True) # SIMULATION RUNNING net = Network(collect()) net.add(M) net.run(simtime, report='stdout') # ============================================================================= # A N A L Y S I S o f t h e S I M U L A T I O N # ============================================================================= plt.figure(1) plt.plot(M.t/ms, M[0].v_soma, label='soma') plt.plot(M.t/ms, M[0].v_dend1, label='dend1') plt.plot(M.t/ms, M[0].v_dend2, label='dend2') plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]") plt.legend(['soma', 'dendrite 1', 'dendrite 2']) print ("The peak voltage is: ", max(M[0].v_soma)-E_L)
def run_cpp_standalone(params, network_objs): import os from numpy.fft import rfft, irfft from brian2.devices.device import CurrentDeviceProxy from brian2.units import Unit from brian2 import check_units, implementation, device, prefs, NeuronGroup, Network tempdir = os.path.join(params["program_dir"], "cpp_standalone") tempdir = os.path.join(tempdir, "c_" + str(params["sigma_c"]) + \ "_s_" + str(params["sigma_s"])) if not os.path.exists(tempdir): os.makedirs(tempdir) prefs.codegen.cpp.libraries += ['mkl_gf_lp64', # -Wl,--start-group 'mkl_gnu_thread', 'mkl_core', # -Wl,--end-group 'iomp5'] # give extra arguments and path information to the compiler extra_incs = ['-I'+os.path.expanduser(s) for s in [ tempdir, "~/intel/mkl/include"]] prefs.codegen.cpp.extra_compile_args_gcc = ['-w', '-Ofast', '-march=native'] + extra_incs # give extra arguments and path information to the linker prefs.codegen.cpp.extra_link_args += ['-L{0}/intel/mkl/lib/intel64'.format(os.path.expanduser('~')), '-L{0}/intel/lib/intel64'.format(os.path.expanduser('~')), '-m64', '-Wl,--no-as-needed'] # Path that the compiled and linked code needs at runtime os.environ["LD_LIBRARY_PATH"] = os.path.expanduser('~/intel/mkl/lib/intel64:') os.environ["LD_LIBRARY_PATH"] += os.path.expanduser('~/intel/lib/intel64:') # Variable definitions N = params["NI"] # this is the amount of neurons with variable synaptic strength Noffset = params["NE"] neurons = network_objs["neurons"] params["rho0_dt"] = params["rho_0"]/second * params["rate_interval"] mkl_threads = 1 # Includes the header files in all generated files prefs.codegen.cpp.headers += ['<sense.h>',] prefs.codegen.cpp.define_macros += [('N_REAL', int(N)), ('N_CMPLX', int(N/2+1))] path_to_sense_hpp = os.path.join(tempdir, 'sense.h') path_to_sense_cpp = os.path.join(tempdir, 'sense.cpp') with open(path_to_sense_hpp, "w") as f: header_code = ''' #ifndef SENSE_H #define SENSE_H #include <mkl_service.h> #include <mkl_vml.h> #include <mkl_dfti.h> #include <cstring> extern DFTI_DESCRIPTOR_HANDLE hand; extern MKL_Complex16 in_cmplx[N_CMPLX], out_cmplx[N_CMPLX], k_cmplx[N_CMPLX]; DFTI_DESCRIPTOR_HANDLE init_dfti(); #endif''' f.write(header_code) #MKL_Complex16 is a type (probably struct) with open(path_to_sense_cpp, "w") as f: sense_code = ''' #include <sense.h> DFTI_DESCRIPTOR_HANDLE hand; MKL_Complex16 in_cmplx[N_CMPLX], out_cmplx[N_CMPLX], k_cmplx[N_CMPLX]; DFTI_DESCRIPTOR_HANDLE init_dfti() {{ DFTI_DESCRIPTOR_HANDLE hand = 0; mkl_set_num_threads({mkl_threads}); DftiCreateDescriptor(&hand, DFTI_DOUBLE, DFTI_REAL, 1, (MKL_LONG)N_REAL); //MKL_LONG status DftiSetValue(hand, DFTI_PLACEMENT, DFTI_NOT_INPLACE); DftiSetValue(hand, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX); DftiSetValue(hand, DFTI_BACKWARD_SCALE, 1. / N_REAL); //if (0 == status) status = DftiSetValue(hand, DFTI_THREAD_LIMIT, {mkl_threads}); DftiCommitDescriptor(hand); //if (0 != status) cout << "ERROR, status = " << status << "\\n"; return hand; }} '''.format(mkl_threads=mkl_threads, ) f.write(sense_code) # device_get_array_name will be the function get_array_name() and what it does is getting # the string names of brian objects device_get_array_name = CurrentDeviceProxy.__getattr__(device, 'get_array_name') # instert_code is a function which is used to insert code into the main() # function insert_code = CurrentDeviceProxy.__getattr__(device, 'insert_code') ### Computing the kernel (Owen changed it to a gaussian kernel now) # Owen uses a trick here which is he creates a NeuronGroup which doesn't # really do anything in the Simulation. It's just a dummy NeuronGroup # to hold an array to which he would like to have access to during runtime. if params["sigma_s"] == np.infty: k = np.ones(N)/N elif params["sigma_s"] < 1e-3: k = np.zeros(N) k[0] = 1 else: intercell = params["x_NI"] length = intercell*N d = np.linspace(intercell-length/2, length/2, N) d = np.roll(d, int(N/2+1)) k = np.exp(-np.abs(d)/params["sigma_s"]) k /= k.sum() rate_vars = '''k : 1 r_hat : 1 r_hat_single : 1''' kg = NeuronGroup(N, model=rate_vars, name='kernel_rates') kg.active = False kg.k = k #kernel in the spatial domain network_objs["dummygroup"] = kg main_code = ''' hand = init_dfti(); DftiComputeForward(hand, brian::{k}, k_cmplx); '''.format(k=device_get_array_name(kg.variables['k'])) insert_code('main', main_code) # DftiComp.. writes its result into k_cmplx K = rfft(k) # Variable A is a spike counter # memset resets the array to zero (memset is defined to take voidpointers) # also the star before *brian tells it to not compute the size of the # pointer, but what the pointer points to # the _num_ thing is that whenever there's an array in brian, # it automatically creates an integer of the same name with _num_ # in front of it (and that is the size) custom_code = ''' double spatial_filter(int) {{ DftiComputeForward(hand, brian::{A}+{Noffset}, in_cmplx); vzMul(N_CMPLX, in_cmplx, k_cmplx, out_cmplx); DftiComputeBackward(hand, out_cmplx, brian::{r_hat}); memset(brian::{A}, 0, brian::_num_{A}*sizeof(*brian::{A})); return 0; }} '''.format(A=device_get_array_name(neurons.variables['A']), r_hat=device_get_array_name(kg.variables['r_hat']), Noffset=Noffset) @implementation('cpp', custom_code) @check_units(_=Unit(1), result=Unit(1), discard_units=True) def spatial_filter(_): kg.r_hat = irfft(K * rfft(neurons.A), N).real neurons.A = 0 return 0 network_objs["neurons"].run_regularly('dummy = spatial_filter()', dt=params["rate_interval"], order=1, name='filterspatial') params["spatial_filter"] = spatial_filter custom_code = ''' double update_weights(double w, int32_t i_pre) {{ w += {eta}*(brian::{r_hat}[i_pre] - {rho0_dt}); return std::max({wmin}, std::min(w, {wmax})); }} '''.format(r_hat=device_get_array_name(kg.variables['r_hat']), eta=params["eta"], rho0_dt = params["rho0_dt"], wmin=params["wmin"], wmax=params["wmax"]) @implementation('cpp', custom_code) @check_units(w=Unit(1), i_pre=Unit(1), result=Unit(1), discard_units=True) def update_weights(w, i_pre): del_W = params["eta"]*(kg.r_hat - rho0_dt) w += del_W[i_pre] np.clip(w, params["wmin"], params["wmax"], out=w) return w network_objs["con_ei"].run_regularly('w = update_weights(w, i)', dt=params["rate_interval"], when='end', name='weightupdate') # i is the presynaptic index (brian # knows this automatically, j would be postsynaptic) params["update_weights"] = update_weights # delete the Monitors from the network objects beacuse we don't want to # save these values (for long preparation time it would take too much # space in memory). monitors = network_objs["monitors"] network_objs.pop("monitors") net = Network(list(set(network_objs.values()))) if not params["do_run"]: print("Running the network was not desired") return if params["prep_time"]/second > 0: print("Prep time run was desired, adding prep time simulation for " \ + str(params["prep_time"]/second) + " seconds.") net.run(params["prep_time"], report='text', namespace = params) # Add the Monitors only now so we don't record unnecessarily much. network_objs.update(monitors) net.add(list(set(monitors.values()))) print("Adding recorded simulation time " + str(params["simtime"]/second) + " seconds") net.run(params["simtime"], report='text', namespace = params) additional_source_files = [path_to_sense_cpp,] build = CurrentDeviceProxy.__getattr__(device, 'build') build(directory=tempdir, compile=True, run=True, debug=False, additional_source_files=additional_source_files)
def __init__(self, neuron_eqs, threshold_eqs, reset_eqs, sim_headings, sim_velocities, mem_gain_outbound, decay_outbound, mem_gain_inbound, decay_inbound, acceleration=0.3, drag=0.15, speed_multiplier=0, rotation_factor=0.01, max_velocity=12, time_step=20, T_outbound=1500, T_inbound=1500, headings_method='vonmises', cpu4_method=1, only_tuned_network=False, follow_stone_rotation=False, cx_log=None): ###################################### ### PARAMETERS ###################################### self.T_outbound = T_outbound self.T_inbound = T_inbound self.T = T_outbound + T_inbound self.time_step = time_step self.mem_gain_outbound = mem_gain_outbound self.mem_gain_inbound = mem_gain_inbound self.decay_outbound = decay_outbound self.decay_inbound = decay_inbound self.rotation_factor = rotation_factor self.max_velocity = max_velocity self.cpu4_method = cpu4_method self.acceleration = acceleration self.drag = drag self.speed_multiplier = speed_multiplier self.follow_stone_rotation = follow_stone_rotation # if self.follow_stone_rotation: # self.rotation_factor = 1 if cx_log: self.cx_log = cx_log if self.follow_stone_rotation and not cx_log: print('To follow rotation you need to provide a rate-based cx_log') self.populations_size() ###################################### ### INPUTS ###################################### self.headings_method = headings_method if self.headings_method == 'vonmises': headings = self.construct_headings_vonmises( sim_headings, sim_velocities) elif self.headings_method == 'cosine': headings = self.construct_headings_cosine(sim_headings, sim_velocities) else: print('No headings_method selected') return flow = self.construct_flow(sim_headings, sim_velocities) self.inputs = [headings, flow] self.inputs_spike_monitors = self.create_inputs_spike_monitors() ###################################### ### MEMORY ###################################### memory_accumulator, spm_memory_accumulator = self.initialise_memory_accumulator( ) self.inputs.append(memory_accumulator) self.inputs_spike_monitors.append(spm_memory_accumulator) ###################################### ### NETWORK ###################################### self.connectivity_matrices() self.neural_populations = self.construct_neural_populations( neuron_eqs, threshold_eqs, reset_eqs) self.populations_spike_monitors = self.create_populations_spike_monitors( ) self.synapses = self.construct_synapses() ###################################### ### NETWORK OPERATIONS ###################################### self.network_operations_utilities() self.network_operations = self.construct_network_operations( self.cpu4_method) ###################################### ### PLOTTING ###################################### self.bee_coords = np.zeros((self.T, 2)) self.update_bee_position_net_op = NetworkOperation( self.update_bee_position, dt=self.time_step * ms, when='end', order=4, name='update_bee_position') self.network_operations.append(self.update_bee_position_net_op) net = Network() net.add(self.inputs, self.inputs_spike_monitors, self.neural_populations, self.populations_spike_monitors, self.synapses, self.network_operations) self.net = net if only_tuned_network: self.only_tuned_network() self.net.store('initialised')
class BrianerClass(BaseClass): def default_init(self, _BrianingTimeDimensionVariable=None, _BrianingPrintRunIsBool=True, _BrianedNetworkVariable=None, _BrianedDeriveNeurongroupersList=None, _BrianedDeriveSynapsersList=None, _BrianedStepTimeFloatsList=None, _BrianedClocksList=None, _BrianedSimulationClock=None, _BrianedNeuronGroupsList=None, _BrianedStateMonitorsList=None, _BrianedSpikeMonitorsList=None, _BrianedSynapsesList=None, **_KwargVariablesDict ): #Call the parent __init__ method BaseClass.__init__(self,**_KwargVariablesDict) """ def mimic_run(self): #parent method BaseClass.run(self) #debug self.debug('We start running in brian') #run with the brian method self.BrianedNetworkVariable.run( self.RunningStopTimeFloat*self.BrianingTimeDimensionVariable ) #debug self.debug('We stop running in brian') """ def mimic_simulate(self): #parent method BaseClass.simulate(self) #debug ''' self.debug('We start simulate in brian') ''' #run with the brian method self.BrianedNetworkVariable.run( self.SimulatingStopTimeFloat*self.BrianingTimeDimensionVariable ) #debug ''' self.debug('We stop running in brian') ''' def do_brian(self): #/###################/# # Flat the neurongroups and connections # #get self.BrianedDeriveNeurongroupersList=self.TeamDict[ BrianPopulationTeamKeyStr ].ManagementDict.values() #flat self.BrianedDeriveSynapsersList=SYS.flat( map( lambda __BrianedDeriveNeurongrouper: __BrianedDeriveNeurongrouper.TeamDict[ Neurongrouper.NeurongroupPostTeamKeyStr ].ManagementDict.values() if Neurongrouper.NeurongroupPostTeamKeyStr in __BrianedDeriveNeurongrouper.TeamDict else [], self.BrianedDeriveNeurongroupersList ) ) #debug """ self.debug( [ 'map(self.BrianedDeriveSynapsersList)' ('self',self,['BrianedDeriveSynapsersList']) ] ) """ """ #populate map( lambda __NetworkedDeriveConnecter: __NetworkedDeriveConnecter.populate(), self.NetworkedDeriveConnectersList ) """ """ #set the different times self.BrianedStepTimeFloatsList=list( set( SYS.flat( map( lambda __BrianingDerivePopulater: SYS.unzip( __BrianingDerivePopulater.MoniteringStateArgumentVariablesList, [2] ) if len( __BrianingDerivePopulater.MoniteringStateArgumentVariablesList )>0 else [], self.NetworkedDeriveConnectersList ) ) ) ) """ #debug ''' self.debug(('self.',self,['BrianedStepTimeFloatsList'])) ''' #import from brian2 import Clock,Network,ms #Check if self.BrianingTimeDimensionVariable==None: self.BrianingTimeDimensionVariable=ms #init self.BrianedNetworkVariable=Network() #set the clocks self.BrianedSimulationClock=Clock( dt=self.SimulatingStepTimeFloat*self.BrianingTimeDimensionVariable ) self.BrianedClocksDict=dict( map( lambda __BrianedStepTimeFloat: ( str(__BrianedStepTimeFloat), Clock( dt=__BrianedStepTimeFloat*self.BrianingTimeDimensionVariable ) ), self.BrianedStepTimeFloatsList ) ,**{ str( self.SimulatingStepTimeFloat ):self.BrianedSimulationClock } ) #debug ''' self.debug(('self.',self,['BrianedClocksDict'])) ''' #map populate and neurongroup self.BrianedNeuronGroupsList=map( lambda __BrianedDeriveNeurongrouper: __BrianedDeriveNeurongrouper.neurongroup( dict( { 'clock':self.BrianedSimulationClock, #Don't forget to replace the '/' by '_' because brian doesn't like them 'name':__BrianedDeriveNeurongrouper.ParentTagStr.replace( '/','_')+'_'+__BrianedDeriveNeurongrouper.ManagementTagStr }, **__BrianedDeriveNeurongrouper.NeurongroupingBrianKwargDict ) ).NeurongroupedBrianVariable, self.BrianedDeriveNeurongroupersList ) #map ''' map( lambda __BrianedNeuronGroup: __BrianedNeuronGroup.clock.__setattr__( 'dt', self.BrianedSimulationClock.dt ), self.BrianedNeuronGroupsList ) ''' #flat the spike monitors self.BrianedSpikeMonitorsList=SYS.flat( map( lambda __BrianedDerivePopulater: __BrianedDerivePopulater.NeurongroupedSpikeMonitorsList, self.BrianedDeriveNeurongroupersList ) ) #debug ''' self.debug(('self.',self,['BrianedSpikeMonitorsList'])) ''' #flat the state monitors self.BrianedStateMonitorsList=SYS.flat( map( lambda __BrianedDeriveNeurongrouper: __BrianedDeriveNeurongrouper.NeurongroupedStateMonitorsList, self.BrianedDeriveNeurongroupersList ) ) #debug ''' self.debug( [ ('self.',self,['BrianedStateMonitorsList']), 'Now we synapse...' ] ) ''' #map synapse self.BrianedSynapsesList=map( lambda __BrianedDeriveSynapser: __BrianedDeriveSynapser.synapse( dict( __BrianedDeriveSynapser.SynapsingKwargVariablesDict if __BrianedDeriveSynapser.SynapsingKwargVariablesDict!=None else {}, **{ 'source':__BrianedDeriveSynapser.CatchFromPointVariable.NeurongroupedBrianVariable, 'target':__BrianedDeriveSynapser.CatchToPointVariable.NeurongroupedBrianVariable, #'name':( # __BrianedDeriveSynapser.CatchFromPointVariable.NetworkKeyStr+'To'+__BrianedDeriveSynapser.CatchToPointVariable.NetworkKeyStr).replace('/','_') 'name':( __BrianedDeriveSynapser.SynapsingTagStr if __BrianedDeriveSynapser.SynapsingTagStr!="" else __BrianedDeriveSynapser.CatchKeyStr.replace('>','_').replace('<','_') ) } ) ).SynapsedBrianVariable, self.BrianedDeriveSynapsersList ) #debug ''' self.debug(('self.',self,['BrianedSynapsesList'])) ''' #map the add map( lambda __BrianedVariable: self.BrianedNetworkVariable.add(__BrianedVariable), self.BrianedNeuronGroupsList+self.BrianedSynapsesList+self.BrianedStateMonitorsList+self.BrianedSpikeMonitorsList ) """