def run_network(traj): """Runs brian network consisting of 200 inhibitory IF neurons""" eqs = ''' dv/dt=(v0-v)/(5*ms) : volt (unless refractory) v0 : volt ''' group = NeuronGroup(100, model=eqs, threshold='v>10 * mV', reset='v = 0*mV', refractory=5 * ms) group.v0 = traj.par.v0 group.v = np.random.rand(100) * 10.0 * mV syn = Synapses(group, group, on_pre='v-=1*mV') syn.connect('i != j', p=0.2) spike_monitor = SpikeMonitor(group, variables=['v']) voltage_monitor = StateMonitor(group, 'v', record=True) pop_monitor = PopulationRateMonitor(group, name='pop' + str(traj.v_idx)) net = Network(group, syn, spike_monitor, voltage_monitor, pop_monitor) net.run(0.25 * second, report='text') traj.f_add_result(Brian2MonitorResult, 'spikes', spike_monitor) traj.f_add_result(Brian2MonitorResult, 'v', voltage_monitor) traj.f_add_result(Brian2MonitorResult, 'pop', pop_monitor)
def brian2(self) -> BrianObject: model = Equations( ''' w : 1 s_post = w * s : 1 (summed) ds / dt = - s / tau + alpha * x * (1 - s) : 1 (clock-driven) dx / dt = - x / tau_rise : 1 (clock-driven) ''', s_post=f'{self.post_variable_name_tot}_post', s=self.post_variable_name, x=self.post_nonlinear_name, tau=self[IP.TAU], tau_rise=self[IP.TAU_NMDA_RISE], alpha=self[IP.ALPHA], ) eqs_pre = f''' {self.post_nonlinear_name} += 1 ''' C = Synapses( self.origin.brian2, self.target.brian2, method='euler', model=model, on_pre=eqs_pre, name=self.ref, ) C.connect() C.w[:] = 1 return C
def test_store_restore_magic(): source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', pre='v+=w', connect='i==j') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) store() # default time slot run(10*ms) store('second') run(10*ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ restore() # Go back to beginning assert magic_network.t == 0*ms run(20*ms) assert defaultclock.t == 20*ms assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle restore('second') assert magic_network.t == 10*ms run(10*ms) assert defaultclock.t == 20*ms assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:])
def brian2(self) -> BrianObject: model = Equations(''' x : 1 u : 1 w : 1 ''') U = self[IP.U] tauf = self[IP.TAU_F] taud = self[IP.TAU_D] on_pre = f''' u = {U} + (u - {U}) * exp(- (t - lastupdate) / ({tauf / units.ms} * ms)) x = 1 + (x - 1) * exp(- (t - lastupdate) / ({taud / units.ms} * ms)) {self.post_variable_name} += w * u * x x *= (1 - u) u += {U} * (1 - u) ''' syn = Synapses(source=self.origin.brian2, target=self.target.brian2, method='euler', model=model, on_pre=on_pre, name=self.ref) self.connection.simulation(syn) syn.w[:] = self[IP.W] syn.x[:] = 1 syn.u[:] = 1 return syn
def run_network(traj): """Runs brian network consisting of 200 inhibitory IF neurons""" eqs = ''' dv/dt=(v0-v)/(5*ms) : volt (unless refractory) v0 : volt ''' group = NeuronGroup(100, model=eqs, threshold='v>10 * mV', reset='v = 0*mV', refractory=5*ms) group.v0 = traj.par.v0 group.v = np.random.rand(100) * 10.0 * mV syn = Synapses(group, group, on_pre='v-=1*mV') syn.connect('i != j', p=0.2) spike_monitor = SpikeMonitor(group, variables=['v']) voltage_monitor = StateMonitor(group, 'v', record=True) pop_monitor = PopulationRateMonitor(group, name='pop' + str(traj.v_idx)) net = Network(group, syn, spike_monitor, voltage_monitor, pop_monitor) net.run(0.25*second, report='text') traj.f_add_result(Brian2MonitorResult, 'spikes', spike_monitor) traj.f_add_result(Brian2MonitorResult, 'v', voltage_monitor) traj.f_add_result(Brian2MonitorResult, 'pop', pop_monitor)
def create_net(): # Use a bit of a complicated spike and connection pattern with # heterogeneous delays # Note: it is important that all objects have the same name, this would # be the case if we were running this in a new process but to not rely # on garbage collection we will assign explicit names here source = SpikeGeneratorGroup( 5, np.arange(5).repeat(3), [3, 4, 1, 2, 3, 7, 5, 4, 1, 0, 5, 9, 7, 8, 9] * ms, name='source') target = NeuronGroup(10, 'v:1', name='target') synapses = Synapses(source, target, model='w:1', pre='v+=w', connect='j>=i', name='synapses') synapses.w = 'i*1.0 + j*2.0' synapses.delay = '(5-i)*ms' state_mon = StateMonitor(target, 'v', record=True, name='statemonitor') input_spikes = SpikeMonitor(source, name='input_spikes') net = Network(source, target, synapses, state_mon, input_spikes) return net
def build(self, traj, brian_list, network_dict): if not self.pre_built: group = network_dict['group'] syn = Synapses(group, group, on_pre=traj.pre) syn.connect('i != j', p=traj.prob) brian_list.append(syn) network_dict['synapses'] = syn
def get_synapses(stimulus, neuron, tau_inact, A_SE, U_SE, tau_rec, tau_facil=None): """ stimulus -- input stimulus neuron -- target neuron tau_inact -- inactivation time constant A_SE -- absolute synaptic strength U_SE -- utilization of synaptic efficacy tau_rec -- recovery time constant tau_facil -- facilitation time constant (optional) """ synapses_eqs = """ dx/dt = z/tau_rec : 1 (clock-driven) # recovered dy/dt = -y/tau_inact : 1 (clock-driven) # active A_SE : ampere U_SE : 1 tau_inact : second tau_rec : second z = 1 - x - y : 1 # inactive I_syn_post = A_SE*y : ampere (summed) """ if tau_facil: synapses_eqs += """ du/dt = -u/tau_facil : 1 (clock-driven) tau_facil : second """ synapses_action = """ u += U_SE*(1-u) y += u*x # important: update y first x += -u*x """ else: synapses_action = """ y += U_SE*x # important: update y first x += -U_SE*x """ synapses = Synapses(stimulus, neuron, model=synapses_eqs, on_pre=synapses_action, method="exponential_euler") synapses.connect() # start fully recovered synapses.x = 1 synapses.tau_inact = tau_inact synapses.A_SE = A_SE synapses.U_SE = U_SE synapses.tau_rec = tau_rec if tau_facil: synapses.tau_facil = tau_facil return synapses
def test_synapse_init(): # check initializations validity for synapse variables start_scope() set_device('exporter') eqn = 'dv/dt = -v/tau :1' tau = 1 * ms w = 1 P = NeuronGroup(5, eqn, method='euler', threshold='v>0.8') Q = NeuronGroup(10, eqn, method='euler', threshold='v>0.9') S = Synapses(P, Q, 'g :1', on_pre='v += w') S.connect() # allowable S.g['i>10'] = 10 S.g[-1] = -1 S.g[10000] = 'rand() + w + w' mon = StateMonitor(S, 'g', record=[0, 1]) run(1 * ms) # not allowable with pytest.raises(NotImplementedError): S.g[0:1000] = -1 run(0.5 * ms) with pytest.raises(NotImplementedError): S.g[0:1] = 'rand() + 10' run(0.25 * ms) with pytest.raises(NotImplementedError): _ = StateMonitor(S, 'g', S.g[0:10]) device.reinit()
def brian2(self) -> BrianObject: model = Equations('w : 1') on_pre = f'{self.post_variable_name} += w' syn = Synapses(source=self.origin.brian2, target=self.target.brian2, method='euler', model=model, on_pre=on_pre, name=self.ref) self.connection.simulation(syn) syn.w[:] = self[IP.W] return syn
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_synapse_connect_generator(): # connector test 3 start_scope() set_device('exporter', build_on_run=False) tau = 1 * ms eqn = 'dv/dt = (1 - v)/tau :1' Source = NeuronGroup(10, eqn, method='exact', threshold='v>0.9') S1 = Synapses(Source, Source) nett2 = Network(Source, S1) S1.connect(j='k for k in range(0, i+1)') nett2.run(1 * ms) connect3 = device.runs[0]['initializers_connectors'][0] assert connect3['j'] == 'k for k in range(0, i+1)' device.reinit()
def brian2(self) -> BrianObject: model = Equations(''' w1 : 1 w2 : 1 w3 : 1 w4 : 1 ''') on_pre = f''' {self.post_variable_name[0]} += w1 {self.post_variable_name[1]} += w2 {self.post_variable_name[2]} += w3 {self.post_variable_name[3]} += w4 ''' syn = Synapses( source=self.origin.brian2, target=self.target.brian2, method='euler', model=model, on_pre=on_pre, name=self.ref, ) syn.connect(j='i') syn.w1[:] = 1 syn.w2[:] = 1 syn.w3[:] = 1 syn.w4[:] = 1 return syn
def cramer_noise(tr, GExc: NeuronGroup, GInh: NeuronGroup) -> [BrianObject]: """ Noise inspired by Cramer et al. 2020 (preprint) where a certain number Kext of incoming connections to each neuron is replaced by external noise. Related parameters: - :data:`net.standard_params.cramer_noise_active` - :data:`net.standard_params.cramer_noise_Kext` - :data:`net.standard_params.cramer_noise_rate` """ namespace = tr.netw.f_to_dict(short_names=True, fast_access=True) N = tr.N_e Kext = tr.cramer_noise_Kext p_ee_target = tr.p_ee / (1 - Kext) p_ie_target = tr.p_ie / (1 - Kext) conductance_prefix = "" if tr.syn_cond_mode == "exp" else "x" GNoise = PoissonGroup(N, rates=tr.cramer_noise_rate, dt=0.1 * ms) SynNoiseE = Synapses(source=GNoise, target=GExc, on_pre=f"{conductance_prefix}ge_post += a_ee", namespace=namespace) SynNoiseE.connect(p=Kext * p_ee_target) SynNoiseI = Synapses(source=GNoise, target=GInh, on_pre=f"{conductance_prefix}ge_post += a_ie", namespace=namespace) SynNoiseI.connect(p=Kext * p_ie_target) return [GNoise, SynNoiseE, SynNoiseI]
def echo_spike(p, tStim, tTot): start_scope() prefs.codegen.target = "numpy" ################################ # Compute properties ################################ dvInpSpike = p['nu_DV'] # Voltage increase per noise spike dvExcSpike = p['LIF_DV'] # Voltage increase per lateral spike # dvExcSpike = p['LIF_T_0'] / (1.0 * p['N'] * p['p_conn']) # Voltage increase per lateral spike print("typical spike threshold", p['LIF_T_0']) print("typical potential change per noise spike", dvInpSpike) print("typical potential change per lateral spike", dvExcSpike) ################################ # Create input population ################################ nTStimPost = int(tTot / tStim) - 1 # After input switched off, 0-input will be repeated nTStimPost*tStim timesteps patternInp = (np.random.uniform(0, 1, p['N']) < p['nu_p']).astype(int) pattern0 = np.zeros(p['N']) rates_all = np.array([patternInp] + [pattern0]*nTStimPost) * p['nu_FREQ'] rateTimedArray = TimedArray(rates_all, dt=tStim) gInp = PoissonGroup(p['N'], rates="rateTimedArray(t, i)") # gInp = PoissonGroup(p['N'], p['nu_FREQ']) ################################ # Create reservoir population ################################ gExc = brian2wrapper.NeuronGroupLIF(p['N'], p['LIF_V_0'], p['LIF_T_0'], p['LIF_V_TAU']) ################################ # Create synapses ################################ sInpExc = Synapses(gInp, gExc, on_pre='v_post += dvInpSpike', method='exact') sExcExc = Synapses(gExc, gExc, on_pre='v_post += dvExcSpike', method='exact') ################################ # Connect synapses ################################ # * Input and LIF one-to-one # * LIF neurons to each other sparsely sInpExc.connect(j='i') sExcExc.connect(p=p['p_conn']) ################################ # Init Monitors ################################ #spikemonInp = SpikeMonitor(gInp) spikemonExc = SpikeMonitor(gExc) ################################ # Run simulation ################################ run(tTot) return np.array(spikemonExc.i), np.array(spikemonExc.t)
def test_store_restore_to_file(): filename = tempfile.mktemp(suffix='state', prefix='brian_test') source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', pre='v+=w', connect='i==j') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) net = Network(source, target, synapses, state_mon, spike_mon) net.store(filename=filename) # default time slot net.run(10 * ms) net.store('second', filename=filename) net.run(10 * ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ net.restore(filename=filename) # Go back to beginning assert defaultclock.t == 0 * ms assert net.t == 0 * ms net.run(20 * ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle net.restore('second', filename=filename) assert defaultclock.t == 10 * ms assert net.t == 10 * ms net.run(10 * ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) try: os.remove(filename) except OSError: pass
def test_magic_collect(): ''' Make sure all expected objects are collected in a magic network ''' P = PoissonGroup(10, rates=100*Hz) G = NeuronGroup(10, 'v:1') S = Synapses(G, G, '') G_runner = G.custom_operation('') S_runner = S.custom_operation('') state_mon = StateMonitor(G, 'v', record=True) spike_mon = SpikeMonitor(G) rate_mon = PopulationRateMonitor(G) objects = collect() assert len(objects) == 8, ('expected %d objects, got %d' % (8, len(objects)))
def do_synapse(self): # Maybe should import from brian2 import Synapses # Check if len(self.SynapsingDelayDict) > 0.0: # map map(lambda __ItemTuple: self.setDelay(*__ItemTuple), self.SynapsingDelayDict.items()) # debug """ self.debug(('self.',self,[ 'SynapsingBrianKwargDict' ])) """ # init self.SynapsedBrianVariable = Synapses(**self.SynapsingBrianKwargDict) # connect if type(self.SynapsingProbabilityVariable) == float: # debug """ self.debug('we connect with a sparsity of '+str(self.SynapsingProbabilityVariable)) """ self.SynapsedBrianVariable.connect(True, p=self.SynapsingProbabilityVariable) # Check if self.SynapsingWeigthSymbolStr != "": # debug """ self.debug( ('self.',self,[ 'SynapsedBrianVariable', 'SynapsingWeigthSymbolStr' ]) ) """ # connect self.SynapsedBrianVariable.connect(True) # get self.SynapsedWeigthFloatsArray = getattr(self.SynapsedBrianVariable, self.SynapsingWeigthSymbolStr) # set self.SynapsedWeigthFloatsArray[:] = np.reshape( self.SynapsingWeigthFloatsArray, self.SynapsedBrianVariable.source.N * self.SynapsedBrianVariable.target.N, ) # debug self.debug(("self.", self, ["SynapsedWeigthFloatsArray"]))
def test_magic_collect(): ''' Make sure all expected objects are collected in a magic network ''' P = PoissonGroup(10, rates=100 * Hz) G = NeuronGroup(10, 'v:1') S = Synapses(G, G, '') G_runner = G.custom_operation('') S_runner = S.custom_operation('') state_mon = StateMonitor(G, 'v', record=True) spike_mon = SpikeMonitor(G) rate_mon = PopulationRateMonitor(G) objects = collect() assert len(objects) == 8, ('expected %d objects, got %d' % (8, len(objects)))
def create_net(): G = NeuronGroup(10, 'v: 1', threshold='False') dependent_objects = [ StateMonitor(G, 'v', record=True), SpikeMonitor(G), PopulationRateMonitor(G), Synapses(G, G, pre='v+=1', connect=True) ] return dependent_objects
def create_net(): # Use a bit of a complicated spike and connection pattern with # heterogeneous delays # Note: it is important that all objects have the same name, this would # be the case if we were running this in a new process but to not rely # on garbage collection we will assign explicit names here source = SpikeGeneratorGroup(5, np.arange(5).repeat(3), [3, 4, 1, 2, 3, 7, 5, 4, 1, 0, 5, 9, 7, 8, 9]*ms, name='source') target = NeuronGroup(10, 'v:1', name='target') synapses = Synapses(source, target, model='w:1', pre='v+=w', connect='j>=i', name='synapses') synapses.w = 'i*1.0 + j*2.0' synapses.delay = '(5-i)*ms' state_mon = StateMonitor(target, 'v', record=True, name='statemonitor') input_spikes = SpikeMonitor(source, name='input_spikes') net = Network(source, target, synapses, state_mon, input_spikes) return net
def test_synapse_connect_ij(): # connector test 2 start_scope() set_device('exporter', build_on_run=False) tau = 10 * ms eqn = 'dv/dt = (1 - v)/tau :1' my_prob = -1 Source = NeuronGroup(10, eqn, method='exact', threshold='v>0.9') S1 = Synapses(Source, Source) nett = Network(Source, S1) S1.connect(i=[0, 1], j=[1, 2], p='my_prob') nett.run(1 * ms) connect2 = device.runs[0]['initializers_connectors'][0] assert connect2['i'] == [0, 1] assert connect2['j'] == [1, 2] assert connect2['identifiers']['my_prob'] == -1 with pytest.raises(KeyError): connect2['condition'] device.reinit()
def test_store_restore_to_file(): filename = tempfile.mktemp(suffix='state', prefix='brian_test') source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', on_pre='v+=w') synapses.connect(j='i') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) net = Network(source, target, synapses, state_mon, spike_mon) net.store(filename=filename) # default time slot net.run(10*ms) net.store('second', filename=filename) net.run(10*ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ net.restore(filename=filename) # Go back to beginning assert defaultclock.t == 0*ms assert net.t == 0*ms net.run(20*ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle net.restore('second', filename=filename) assert defaultclock.t == 10*ms assert net.t == 10*ms net.run(10*ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) try: os.remove(filename) except OSError: pass
def test_store_restore(): source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', on_pre='v+=w') synapses.connect(j='i') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) net = Network(source, target, synapses, state_mon, spike_mon) net.store() # default time slot net.run(10*ms) net.store('second') net.run(10*ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ net.restore() # Go back to beginning assert defaultclock.t == 0*ms assert net.t == 0*ms net.run(20*ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle net.restore('second') assert defaultclock.t == 10*ms assert net.t == 10*ms net.run(10*ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back again (see github issue #681) net.restore('second') assert defaultclock.t == 10 * ms assert net.t == 10 * ms
def test_plot_synapses(): set_device('runtime') group = NeuronGroup(10, 'dv/dt = -v/(10*ms) : volt', threshold='False') group.v = np.linspace(0, 1, 10)*mV synapses = Synapses(group, group, 'w : volt', on_pre='v += w') synapses.connect('i != j') synapses.w = 'i*0.1*mV' # Just checking whether the plotting does not fail with an error and that # it retuns an Axis object as promised ax = brian_plot(synapses) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = brian_plot(synapses.w) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = brian_plot(synapses.delay) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, plot_type='scatter') assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, plot_type='image') add_background_pattern(ax) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, plot_type='hexbin') assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, synapses.w) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, synapses.w, plot_type='scatter') assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, synapses.w, plot_type='image') assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_synapses(synapses.i, synapses.j, synapses.w, plot_type='hexbin') assert isinstance(ax, matplotlib.axes.Axes) plt.close() synapses.connect('i > 5') # More than one synapse per connection brian_plot(synapses) plt.close() # It should be possible to plot synaptic variables for multiple connections # with hexbin ax = plot_synapses(synapses.i, synapses.j, synapses.w, plot_type='hexbin') assert isinstance(ax, matplotlib.axes.Axes) plt.close()
def test_Subgroup(): """ Test Subgroup """ eqn = ''' dv/dt = (1 - v) / tau :1 ''' tau = 10 * ms group = NeuronGroup(10, eqn, threshold='v>10', reset='v=0', method='euler') sub_a = group[0:5] sub_b = group[0:10] syn = Synapses(sub_a, sub_b) syn.connect(p=0.8) mon = StateMonitor(group[0:7], 'v', record=1) sub_a.v = 1 sub_b.v = -1 mon_dict = collect_StateMonitor(mon) assert mon_dict['source']['group'] == group.name assert mon_dict['source']['start'] == 0 assert mon_dict['source']['stop'] == 6 syn_dict = collect_Synapses(syn, get_local_namespace(0)) assert syn_dict['source']['group'] == group.name assert syn_dict['target']['start'] == 0 assert syn_dict['source']['stop'] == 4
def test_synapse_connect_cond(): # check connectors start_scope() set_device('exporter') eqn = 'dv/dt = (1 - v)/tau :1' tau = 1 * ms P = NeuronGroup(5, eqn, method='euler', threshold='v>0.8') Q = NeuronGroup(10, eqn, method='euler', threshold='v>0.9') w = 1 tata = 2 bye = 2 my_prob = -1 S = Synapses(P, Q, on_pre='v += w') S.connect('tata > bye', p='my_prob', n=5) run(1 * ms) connect = device.runs[0]['initializers_connectors'][0] assert connect['probability'] == 'my_prob' assert connect['n_connections'] == 5 assert connect['type'] == 'connect' assert connect['identifiers']['tata'] == bye with pytest.raises(KeyError): connect['i'] connect['j'] device.reinit()
def test_magic_collect(): ''' Make sure all expected objects are collected in a magic network ''' P = PoissonGroup(10, rates=100*Hz) G = NeuronGroup(10, 'v:1', threshold='False') S = Synapses(G, G, '') state_mon = StateMonitor(G, 'v', record=True) spike_mon = SpikeMonitor(G) rate_mon = PopulationRateMonitor(G) objects = collect() assert len(objects) == 6, ('expected %d objects, got %d' % (6, len(objects)))
def SynapsesPlastic(G1, G2, plasticity_model): if plasticity_model['TYPE'][:4] == 'STDP': # # Extract parameters # TAU_PRE = plasticity_model['TAU_PRE'] # TAU_POST = plasticity_model['TAU_POST'] # DW_FORW = plasticity_model['DW_FORW'] # DW_BACK = plasticity_model['DW_BACK'] # DV_SPIKE = plasticity_model['DV_SPIKE'] # REL_W_MIN = plasticity_model['REL_W_MIN'] # REL_W_MAX = plasticity_model['REL_W_MAX'] # Two auxiliary variables track decaying trace of # presynaptic and postsynaptic spikes syn_eq = ''' dzpre/dt = -zpre/TAU_PRE : 1 (event-driven) dzpost/dt = -zpost/TAU_POST : 1 (event-driven) ''' # In case of homeostatic synaptic plasticity, the weight # also decays to baseline value over time if 'HP' in plasticity_model['TYPE']: syn_eq += 'dw/dt = (REL_W_0 - w)/TAU_HP : 1 (event-driven)' + '\n' else: syn_eq += 'w : 1' + '\n' # On spike increase decaying variable by fixed amount # Increase weight by the value of the decaying variable # from the other side of the synapse # Truncate weight if it exceeds maximum syn_pre_eq = ''' zpre += 1 w = clip(w + DW_FORW * zpost, REL_W_MIN, REL_W_MAX) v_post += DV_SPIKE * w ''' syn_post_eq = ''' zpost += 1 w = clip(w + DW_BACK * zpre, REL_W_MIN, REL_W_MAX) ''' return Synapses(G1, G1, syn_eq, on_pre=syn_pre_eq, on_post=syn_post_eq, namespace=plasticity_model) else: raise ValueError('Unexpected Plasticity type', plasticity_model['TYPE'])
def synapse_delays(syn_delay: ms, syn_delay_windowsize: ms, Syn: Synapses, shape): """ Configure pre-synaptic delays. Similar to Brunel 2000 these are uniformly distributed. The delay is the center of the uniform distribution, while the window size defines the total width of the distribution. Related parameters: - :data:`net.standard_params.synEE_delay` - :data:`net.standard_params.synEE_delay_windowsize` - :data:`net.standard_params.synEI_delay` - :data:`net.standard_params.synEI_delay_windowsize` """ # need to create these for all synapses, not only the initially active ones delays = np.random.uniform(low=syn_delay - syn_delay_windowsize / 2, high=syn_delay + syn_delay_windowsize / 2, size=shape) Syn.delay = delays return delays
def test_store_restore(): source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', on_pre='v+=w') synapses.connect(j='i') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) net = Network(source, target, synapses, state_mon, spike_mon) net.store() # default time slot net.run(10 * ms) net.store('second') net.run(10 * ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ net.restore() # Go back to beginning assert defaultclock.t == 0 * ms assert net.t == 0 * ms net.run(20 * ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle net.restore('second') assert defaultclock.t == 10 * ms assert net.t == 10 * ms net.run(10 * ms) assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back again (see github issue #681) net.restore('second') assert defaultclock.t == 10 * ms assert net.t == 10 * ms
def sim_decision_making_network(N_Excit=384, N_Inhib=96, weight_scaling_factor=5.33, t_stimulus_start=100 * b2.ms, t_stimulus_duration=9999 * b2.ms, coherence_level=0., stimulus_update_interval=30 * b2.ms, mu0_mean_stimulus_Hz=160., stimulus_std_Hz=20., N_extern=1000, firing_rate_extern=9.8 * b2.Hz, w_pos=1.90, f_Subpop_size=0.25, # .15 in publication [1] max_sim_time=1000. * b2.ms, stop_condition_rate=None, monitored_subset_size=512): """ Args: N_Excit (int): total number of neurons in the excitatory population N_Inhib (int): nr of neurons in the inhibitory populations weight_scaling_factor: When increasing the number of neurons by 2, the weights should be scaled down by 1/2 t_stimulus_start (Quantity): time when the stimulation starts t_stimulus_duration (Quantity): duration of the stimulation coherence_level (int): coherence of the stimulus. Difference in mean between the PoissonGroups "left" stimulus and "right" stimulus stimulus_update_interval (Quantity): the mean of the stimulating PoissonGroups is re-sampled at this interval mu0_mean_stimulus_Hz (float): maximum mean firing rate of the stimulus if c=+1 or c=-1. Each neuron in the populations "Left" and "Right" receives an independent poisson input. stimulus_std_Hz (float): std deviation of the stimulating PoissonGroups. N_extern (int): nr of neurons in the stimulus independent poisson background population firing_rate_extern (int): firing rate of the stimulus independent poisson background population w_pos (float): Scaling (strengthening) of the recurrent weights within the subpopulations "Left" and "Right" f_Subpop_size (float): fraction of the neurons in the subpopulations "Left" and "Right". #left = #right = int(f_Subpop_size*N_Excit). max_sim_time (Quantity): simulated time. stop_condition_rate (Quantity): An optional stopping criteria: If not None, the simulation stops if the firing rate of either subpopulation "Left" or "Right" is above stop_condition_rate. monitored_subset_size (int): max nr of neurons for which a state monitor is registered. Returns: A dictionary with the following keys (strings): "rate_monitor_A", "spike_monitor_A", "voltage_monitor_A", "idx_monitored_neurons_A", "rate_monitor_B", "spike_monitor_B", "voltage_monitor_B", "idx_monitored_neurons_B", "rate_monitor_Z", "spike_monitor_Z", "voltage_monitor_Z", "idx_monitored_neurons_Z", "rate_monitor_inhib", "spike_monitor_inhib", "voltage_monitor_inhib", "idx_monitored_neurons_inhib" """ print("simulating {} neurons. Start: {}".format(N_Excit + N_Inhib, time.ctime())) t_stimulus_end = t_stimulus_start + t_stimulus_duration N_Group_A = int(N_Excit * f_Subpop_size) # size of the excitatory subpopulation sensitive to stimulus A N_Group_B = N_Group_A # size of the excitatory subpopulation sensitive to stimulus B N_Group_Z = N_Excit - N_Group_A - N_Group_B # (1-2f)Ne excitatory neurons do not respond to either stimulus. Cm_excit = 0.5 * b2.nF # membrane capacitance of excitatory neurons G_leak_excit = 25.0 * b2.nS # leak conductance E_leak_excit = -70.0 * b2.mV # reversal potential v_spike_thr_excit = -50.0 * b2.mV # spike condition v_reset_excit = -60.0 * b2.mV # reset voltage after spike t_abs_refract_excit = 2. * b2.ms # absolute refractory period # specify the inhibitory interneurons: # N_Inhib = 200 Cm_inhib = 0.2 * b2.nF G_leak_inhib = 20.0 * b2.nS E_leak_inhib = -70.0 * b2.mV v_spike_thr_inhib = -50.0 * b2.mV v_reset_inhib = -60.0 * b2.mV t_abs_refract_inhib = 1.0 * b2.ms # specify the AMPA synapses E_AMPA = 0.0 * b2.mV tau_AMPA = 2.5 * b2.ms # specify the GABA synapses E_GABA = -70.0 * b2.mV tau_GABA = 5.0 * b2.ms # specify the NMDA synapses E_NMDA = 0.0 * b2.mV tau_NMDA_s = 100.0 * b2.ms tau_NMDA_x = 2. * b2.ms alpha_NMDA = 0.5 * b2.kHz # projections from the external population g_AMPA_extern2inhib = 1.62 * b2.nS g_AMPA_extern2excit = 2.1 * b2.nS # projectsions from the inhibitory populations g_GABA_inhib2inhib = weight_scaling_factor * 1.25 * b2.nS g_GABA_inhib2excit = weight_scaling_factor * 1.60 * b2.nS # projections from the excitatory population g_AMPA_excit2excit = weight_scaling_factor * 0.012 * b2.nS g_AMPA_excit2inhib = weight_scaling_factor * 0.015 * b2.nS g_NMDA_excit2excit = weight_scaling_factor * 0.040 * b2.nS g_NMDA_excit2inhib = weight_scaling_factor * 0.045 * b2.nS # stronger projection to inhib. # weights and "adjusted" weights. w_neg = 1. - f_Subpop_size * (w_pos - 1.) / (1. - f_Subpop_size) # We use the same postsyn AMPA and NMDA conductances. Adjust the weights coming from different sources: w_ext2inhib = g_AMPA_extern2inhib / g_AMPA_excit2inhib w_ext2excit = g_AMPA_extern2excit / g_AMPA_excit2excit # other weights are 1 # print("w_neg={}, w_ext2inhib={}, w_ext2excit={}".format(w_neg, w_ext2inhib, w_ext2excit)) # Define the inhibitory population # dynamics: inhib_lif_dynamics = """ s_NMDA_total : 1 # the post synaptic sum of s. compare with s_NMDA_presyn dv/dt = ( - G_leak_inhib * (v-E_leak_inhib) - g_AMPA_excit2inhib * s_AMPA * (v-E_AMPA) - g_GABA_inhib2inhib * s_GABA * (v-E_GABA) - g_NMDA_excit2inhib * s_NMDA_total * (v-E_NMDA)/(1.0+1.0*exp(-0.062*v/volt)/3.57) )/Cm_inhib : volt (unless refractory) ds_AMPA/dt = -s_AMPA/tau_AMPA : 1 ds_GABA/dt = -s_GABA/tau_GABA : 1 """ inhib_pop = NeuronGroup( N_Inhib, model=inhib_lif_dynamics, threshold="v>v_spike_thr_inhib", reset="v=v_reset_inhib", refractory=t_abs_refract_inhib, method="rk2") # initialize with random voltages: inhib_pop.v = rnd.uniform(v_spike_thr_inhib / b2.mV - 4., high=v_spike_thr_inhib / b2.mV - 1., size=N_Inhib) * b2.mV # Specify the excitatory population: # dynamics: excit_lif_dynamics = """ s_NMDA_total : 1 # the post synaptic sum of s. compare with s_NMDA_presyn dv/dt = ( - G_leak_excit * (v-E_leak_excit) - g_AMPA_excit2excit * s_AMPA * (v-E_AMPA) - g_GABA_inhib2excit * s_GABA * (v-E_GABA) - g_NMDA_excit2excit * s_NMDA_total * (v-E_NMDA)/(1.0+1.0*exp(-0.062*v/volt)/3.57) )/Cm_excit : volt (unless refractory) ds_AMPA/dt = -s_AMPA/tau_AMPA : 1 ds_GABA/dt = -s_GABA/tau_GABA : 1 ds_NMDA/dt = -s_NMDA/tau_NMDA_s + alpha_NMDA * x * (1-s_NMDA) : 1 dx/dt = -x/tau_NMDA_x : 1 """ # define the three excitatory subpopulations. # A: subpop receiving stimulus A excit_pop_A = NeuronGroup(N_Group_A, model=excit_lif_dynamics, threshold="v>v_spike_thr_excit", reset="v=v_reset_excit", refractory=t_abs_refract_excit, method="rk2") excit_pop_A.v = rnd.uniform(E_leak_excit / b2.mV, high=E_leak_excit / b2.mV + 5., size=excit_pop_A.N) * b2.mV # B: subpop receiving stimulus B excit_pop_B = NeuronGroup(N_Group_B, model=excit_lif_dynamics, threshold="v>v_spike_thr_excit", reset="v=v_reset_excit", refractory=t_abs_refract_excit, method="rk2") excit_pop_B.v = rnd.uniform(E_leak_excit / b2.mV, high=E_leak_excit / b2.mV + 5., size=excit_pop_B.N) * b2.mV # Z: non-sensitive excit_pop_Z = NeuronGroup(N_Group_Z, model=excit_lif_dynamics, threshold="v>v_spike_thr_excit", reset="v=v_reset_excit", refractory=t_abs_refract_excit, method="rk2") excit_pop_Z.v = rnd.uniform(v_reset_excit / b2.mV, high=v_spike_thr_excit / b2.mV - 1., size=excit_pop_Z.N) * b2.mV # now define the connections: # projections FROM EXTERNAL POISSON GROUP: #################################################### poisson2Inhib = PoissonInput(target=inhib_pop, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2inhib) poisson2A = PoissonInput(target=excit_pop_A, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2excit) poisson2B = PoissonInput(target=excit_pop_B, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2excit) poisson2Z = PoissonInput(target=excit_pop_Z, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2excit) ############################################################################################### # GABA projections FROM INHIBITORY population: ################################################ syn_inhib2inhib = Synapses(inhib_pop, target=inhib_pop, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2inhib.connect(p=1.) syn_inhib2A = Synapses(inhib_pop, target=excit_pop_A, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2A.connect(p=1.) syn_inhib2B = Synapses(inhib_pop, target=excit_pop_B, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2B.connect(p=1.) syn_inhib2Z = Synapses(inhib_pop, target=excit_pop_Z, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2Z.connect(p=1.) ############################################################################################### # AMPA projections FROM EXCITATORY A: ######################################################### syn_AMPA_A2A = Synapses(excit_pop_A, target=excit_pop_A, on_pre="s_AMPA += w_pos", delay=0.5 * b2.ms) syn_AMPA_A2A.connect(p=1.) syn_AMPA_A2B = Synapses(excit_pop_A, target=excit_pop_B, on_pre="s_AMPA += w_neg", delay=0.5 * b2.ms) syn_AMPA_A2B.connect(p=1.) syn_AMPA_A2Z = Synapses(excit_pop_A, target=excit_pop_Z, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_A2Z.connect(p=1.) syn_AMPA_A2inhib = Synapses(excit_pop_A, target=inhib_pop, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_A2inhib.connect(p=1.) ############################################################################################### # AMPA projections FROM EXCITATORY B: ######################################################### syn_AMPA_B2A = Synapses(excit_pop_B, target=excit_pop_A, on_pre="s_AMPA += w_neg", delay=0.5 * b2.ms) syn_AMPA_B2A.connect(p=1.) syn_AMPA_B2B = Synapses(excit_pop_B, target=excit_pop_B, on_pre="s_AMPA += w_pos", delay=0.5 * b2.ms) syn_AMPA_B2B.connect(p=1.) syn_AMPA_B2Z = Synapses(excit_pop_B, target=excit_pop_Z, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_B2Z.connect(p=1.) syn_AMPA_B2inhib = Synapses(excit_pop_B, target=inhib_pop, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_B2inhib.connect(p=1.) ############################################################################################### # AMPA projections FROM EXCITATORY Z: ######################################################### syn_AMPA_Z2A = Synapses(excit_pop_Z, target=excit_pop_A, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2A.connect(p=1.) syn_AMPA_Z2B = Synapses(excit_pop_Z, target=excit_pop_B, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2B.connect(p=1.) syn_AMPA_Z2Z = Synapses(excit_pop_Z, target=excit_pop_Z, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2Z.connect(p=1.) syn_AMPA_Z2inhib = Synapses(excit_pop_Z, target=inhib_pop, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2inhib.connect(p=1.) ############################################################################################### # NMDA projections FROM EXCITATORY to INHIB, A,B,Z @network_operation() def update_nmda_sum(): sum_sNMDA_A = sum(excit_pop_A.s_NMDA) sum_sNMDA_B = sum(excit_pop_B.s_NMDA) sum_sNMDA_Z = sum(excit_pop_Z.s_NMDA) # note the _ at the end of s_NMDA_total_ disables unit checking inhib_pop.s_NMDA_total_ = (1.0 * sum_sNMDA_A + 1.0 * sum_sNMDA_B + 1.0 * sum_sNMDA_Z) excit_pop_A.s_NMDA_total_ = (w_pos * sum_sNMDA_A + w_neg * sum_sNMDA_B + w_neg * sum_sNMDA_Z) excit_pop_B.s_NMDA_total_ = (w_neg * sum_sNMDA_A + w_pos * sum_sNMDA_B + w_neg * sum_sNMDA_Z) excit_pop_Z.s_NMDA_total_ = (1.0 * sum_sNMDA_A + 1.0 * sum_sNMDA_B + 1.0 * sum_sNMDA_Z) # set a self-recurrent synapse to introduce a delay when updating the intermediate # gating variable x syn_x_A2A = Synapses(excit_pop_A, excit_pop_A, on_pre="x += 1.", delay=0.5 * b2.ms) syn_x_A2A.connect(j="i") syn_x_B2B = Synapses(excit_pop_B, excit_pop_B, on_pre="x += 1.", delay=0.5 * b2.ms) syn_x_B2B.connect(j="i") syn_x_Z2Z = Synapses(excit_pop_Z, excit_pop_Z, on_pre="x += 1.", delay=0.5 * b2.ms) syn_x_Z2Z.connect(j="i") ############################################################################################### # Define the stimulus: two PoissonInput with time time-dependent mean. poissonStimulus2A = PoissonGroup(N_Group_A, 0. * b2.Hz) syn_Stim2A = Synapses(poissonStimulus2A, excit_pop_A, on_pre="s_AMPA+=w_ext2excit") syn_Stim2A.connect(j="i") poissonStimulus2B = PoissonGroup(N_Group_B, 0. * b2.Hz) syn_Stim2B = Synapses(poissonStimulus2B, excit_pop_B, on_pre="s_AMPA+=w_ext2excit") syn_Stim2B.connect(j="i") @network_operation(dt=stimulus_update_interval) def update_poisson_stimulus(t): if t >= t_stimulus_start and t < t_stimulus_end: offset_A = mu0_mean_stimulus_Hz * (0.5 + 0.5 * coherence_level) offset_B = mu0_mean_stimulus_Hz * (0.5 - 0.5 * coherence_level) rate_A = numpy.random.normal(offset_A, stimulus_std_Hz) rate_A = (max(0, rate_A)) * b2.Hz # avoid negative rate rate_B = numpy.random.normal(offset_B, stimulus_std_Hz) rate_B = (max(0, rate_B)) * b2.Hz poissonStimulus2A.rates = rate_A poissonStimulus2B.rates = rate_B # print("stim on. rate_A= {}, rate_B = {}".format(rate_A, rate_B)) else: # print("stim off") poissonStimulus2A.rates = 0. poissonStimulus2B.rates = 0. ############################################################################################### def get_monitors(pop, monitored_subset_size): """ Internal helper. Args: pop: monitored_subset_size: Returns: """ monitored_subset_size = min(monitored_subset_size, pop.N) idx_monitored_neurons = sample(range(pop.N), monitored_subset_size) rate_monitor = PopulationRateMonitor(pop) # record parameter: record=idx_monitored_neurons is not supported??? spike_monitor = SpikeMonitor(pop, record=idx_monitored_neurons) voltage_monitor = StateMonitor(pop, "v", record=idx_monitored_neurons) return rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons # collect data of a subset of neurons: rate_monitor_inhib, spike_monitor_inhib, voltage_monitor_inhib, idx_monitored_neurons_inhib = \ get_monitors(inhib_pop, monitored_subset_size) rate_monitor_A, spike_monitor_A, voltage_monitor_A, idx_monitored_neurons_A = \ get_monitors(excit_pop_A, monitored_subset_size) rate_monitor_B, spike_monitor_B, voltage_monitor_B, idx_monitored_neurons_B = \ get_monitors(excit_pop_B, monitored_subset_size) rate_monitor_Z, spike_monitor_Z, voltage_monitor_Z, idx_monitored_neurons_Z = \ get_monitors(excit_pop_Z, monitored_subset_size) if stop_condition_rate is None: b2.run(max_sim_time) else: sim_sum = 0. * b2.ms sim_batch = 100. * b2.ms samples_in_batch = int(floor(sim_batch / b2.defaultclock.dt)) avg_rate_in_batch = 0 while (sim_sum < max_sim_time) and (avg_rate_in_batch < stop_condition_rate): b2.run(sim_batch) avg_A = numpy.mean(rate_monitor_A.rate[-samples_in_batch:]) avg_B = numpy.mean(rate_monitor_B.rate[-samples_in_batch:]) avg_rate_in_batch = max(avg_A, avg_B) sim_sum += sim_batch print("sim end: {}".format(time.ctime())) ret_vals = dict() ret_vals["rate_monitor_A"] = rate_monitor_A ret_vals["spike_monitor_A"] = spike_monitor_A ret_vals["voltage_monitor_A"] = voltage_monitor_A ret_vals["idx_monitored_neurons_A"] = idx_monitored_neurons_A ret_vals["rate_monitor_B"] = rate_monitor_B ret_vals["spike_monitor_B"] = spike_monitor_B ret_vals["voltage_monitor_B"] = voltage_monitor_B ret_vals["idx_monitored_neurons_B"] = idx_monitored_neurons_B ret_vals["rate_monitor_Z"] = rate_monitor_Z ret_vals["spike_monitor_Z"] = spike_monitor_Z ret_vals["voltage_monitor_Z"] = voltage_monitor_Z ret_vals["idx_monitored_neurons_Z"] = idx_monitored_neurons_Z ret_vals["rate_monitor_inhib"] = rate_monitor_inhib ret_vals["spike_monitor_inhib"] = spike_monitor_inhib ret_vals["voltage_monitor_inhib"] = voltage_monitor_inhib ret_vals["idx_monitored_neurons_inhib"] = idx_monitored_neurons_inhib return ret_vals
def simulate_brunel_network( N_Excit=5000, N_Inhib=None, N_extern=N_POISSON_INPUT, connection_probability=CONNECTION_PROBABILITY_EPSILON, w0=SYNAPTIC_WEIGHT_W0, g=RELATIVE_INHIBITORY_STRENGTH_G, synaptic_delay=SYNAPTIC_DELAY, poisson_input_rate=POISSON_INPUT_RATE, w_external=None, v_rest=V_REST, v_reset=V_RESET, firing_threshold=FIRING_THRESHOLD, membrane_time_scale=MEMBRANE_TIME_SCALE, abs_refractory_period=ABSOLUTE_REFRACTORY_PERIOD, monitored_subset_size=100, random_vm_init=False, sim_time=100.*b2.ms): """ Fully parametrized implementation of a sparsely connected network of LIF neurons (Brunel 2000) Args: N_Excit (int): Size of the excitatory popluation N_Inhib (int): optional. Size of the inhibitory population. If not set (=None), N_Inhib is set to N_excit/4. N_extern (int): optional. Number of presynaptic excitatory poisson neurons. Note: if set to a value, this number does NOT depend on N_Excit and NOT depend on connection_probability (this is different from the book and paper. Only if N_extern is set to 'None', then N_extern is computed as N_Excit*connection_probability. connection_probability (float): probability to connect to any of the (N_Excit+N_Inhib) neurons CE = connection_probability*N_Excit CI = connection_probability*N_Inhib Cexternal = N_extern w0 (float): Synaptic strength J g (float): relative importance of inhibition. J_exc = w0. J_inhib = -g*w0 synaptic_delay (Quantity): Delay between presynaptic spike and postsynaptic increase of v_m poisson_input_rate (Quantity): Poisson rate of the external population w_external (float): optional. Synaptic weight of the excitatory external poisson neurons onto all neurons in the network. Default is None, in that case w_external is set to w0, which is the standard value in the book and in the paper Brunel2000. The purpose of this parameter is to see the effect of external input in the absence of network feedback(setting w0 to 0mV and w_external>0). v_rest (Quantity): Resting potential v_reset (Quantity): Reset potential firing_threshold (Quantity): Spike threshold membrane_time_scale (Quantity): tau_m abs_refractory_period (Quantity): absolute refractory period, tau_ref monitored_subset_size (int): nr of neurons for which a VoltageMonitor is recording Vm random_vm_init (bool): if true, the membrane voltage of each neuron is initialized with a random value drawn from Uniform(v_rest, firing_threshold) sim_time (Quantity): Simulation time Returns: (rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons) PopulationRateMonitor: Rate Monitor SpikeMonitor: SpikeMonitor for ALL (N_Excit+N_Inhib) neurons StateMonitor: membrane voltage for a selected subset of neurons list: index of monitored neurons. length = monitored_subset_size """ if N_Inhib is None: N_Inhib = int(N_Excit/4) if N_extern is None: N_extern = int(N_Excit*connection_probability) if w_external is None: w_external = w0 J_excit = w0 J_inhib = -g*w0 lif_dynamics = """ dv/dt = -(v-v_rest) / membrane_time_scale : volt (unless refractory)""" network = NeuronGroup( N_Excit+N_Inhib, model=lif_dynamics, threshold="v>firing_threshold", reset="v=v_reset", refractory=abs_refractory_period, method="linear") if random_vm_init: network.v = random.uniform(v_rest/b2.mV, high=firing_threshold/b2.mV, size=(N_Excit+N_Inhib))*b2.mV else: network.v = v_rest excitatory_population = network[:N_Excit] inhibitory_population = network[N_Excit:] exc_synapses = Synapses(excitatory_population, target=network, on_pre="v += J_excit", delay=synaptic_delay) exc_synapses.connect(p=connection_probability) inhib_synapses = Synapses(inhibitory_population, target=network, on_pre="v += J_inhib", delay=synaptic_delay) inhib_synapses.connect(p=connection_probability) external_poisson_input = PoissonInput(target=network, target_var="v", N=N_extern, rate=poisson_input_rate, weight=w_external) # collect data of a subset of neurons: monitored_subset_size = min(monitored_subset_size, (N_Excit+N_Inhib)) idx_monitored_neurons = sample(range(N_Excit+N_Inhib), monitored_subset_size) rate_monitor = PopulationRateMonitor(network) # record= some_list is not supported? :-( spike_monitor = SpikeMonitor(network, record=idx_monitored_neurons) voltage_monitor = StateMonitor(network, "v", record=idx_monitored_neurons) b2.run(sim_time) return rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons
def run_net(tr): # prefs.codegen.target = 'numpy' # prefs.codegen.target = 'cython' set_device('cpp_standalone', directory='./builds/%.4d' % (tr.v_idx), build_on_run=False) print("Started process with id ", str(tr.v_idx)) namespace = tr.netw.f_to_dict(short_names=True, fast_access=True) namespace['idx'] = tr.v_idx defaultclock.dt = tr.netw.sim.dt GExc = NeuronGroup( N=tr.N_e, model=tr.condlif_sig, threshold=tr.nrnEE_thrshld, reset=tr.nrnEE_reset, #method=tr.neuron_method, namespace=namespace) GInh = NeuronGroup( N=tr.N_i, model=tr.condlif_sig, threshold='V > Vt', reset='V=Vr_i', #method=tr.neuron_method, namespace=namespace) # set initial thresholds fixed, init. potentials uniformly distrib. GExc.sigma, GInh.sigma = tr.sigma_e, tr.sigma_i GExc.Vt, GInh.Vt = tr.Vt_e, tr.Vt_i GExc.V , GInh.V = np.random.uniform(tr.Vr_e/mV, tr.Vt_e/mV, size=tr.N_e)*mV, \ np.random.uniform(tr.Vr_i/mV, tr.Vt_i/mV, size=tr.N_i)*mV synEE_pre_mod = mod.synEE_pre synEE_post_mod = mod.synEE_post if tr.stdp_active: synEE_pre_mod = '''%s %s''' % (synEE_pre_mod, mod.synEE_pre_STDP) synEE_post_mod = '''%s %s''' % (synEE_post_mod, mod.synEE_post_STDP) if tr.synEE_rec: synEE_pre_mod = '''%s %s''' % (synEE_pre_mod, mod.synEE_pre_rec) synEE_post_mod = '''%s %s''' % (synEE_post_mod, mod.synEE_post_rec) # E<-E advanced synapse model, rest simple SynEE = Synapses( target=GExc, source=GExc, model=tr.synEE_mod, on_pre=synEE_pre_mod, on_post=synEE_post_mod, #method=tr.synEE_method, namespace=namespace) SynIE = Synapses(target=GInh, source=GExc, on_pre='ge_post += a_ie', namespace=namespace) SynEI = Synapses(target=GExc, source=GInh, on_pre='gi_post += a_ei', namespace=namespace) SynII = Synapses(target=GInh, source=GInh, on_pre='gi_post += a_ii', namespace=namespace) if tr.strct_active: sEE_src, sEE_tar = generate_full_connectivity(tr.N_e, same=True) SynEE.connect(i=sEE_src, j=sEE_tar) SynEE.syn_active = 0 else: srcs_full, tars_full = generate_full_connectivity(tr.N_e, same=True) SynEE.connect(i=srcs_full, j=tars_full) SynEE.syn_active = 0 sIE_src, sIE_tar = generate_connections(tr.N_i, tr.N_e, tr.p_ie) sEI_src, sEI_tar = generate_connections(tr.N_e, tr.N_i, tr.p_ei) sII_src, sII_tar = generate_connections(tr.N_i, tr.N_i, tr.p_ii, same=True) SynIE.connect(i=sIE_src, j=sIE_tar) SynEI.connect(i=sEI_src, j=sEI_tar) SynII.connect(i=sII_src, j=sII_tar) tr.f_add_result('sIE_src', sIE_src) tr.f_add_result('sIE_tar', sIE_tar) tr.f_add_result('sEI_src', sEI_src) tr.f_add_result('sEI_tar', sEI_tar) tr.f_add_result('sII_src', sII_src) tr.f_add_result('sII_tar', sII_tar) # if tr.strct_active: # SynEE.a = 0 # else: SynEE.a = tr.a_ee SynEE.insert_P = tr.insert_P # make synapse active at beginning #if not tr.strct_active: SynEE.run_regularly(tr.synEE_p_activate, dt=tr.T, when='start', order=-100) # synaptic scaling if tr.netw.config.scl_active: SynEE.summed_updaters['Asum_post']._clock = Clock( dt=tr.dt_synEE_scaling) SynEE.run_regularly(tr.synEE_scaling, dt=tr.dt_synEE_scaling, when='end') # intrinsic plasticity if tr.netw.config.it_active: GExc.h_ip = tr.h_ip GExc.run_regularly(tr.intrinsic_mod, dt=tr.it_dt, when='end') # structural plasticity if tr.netw.config.strct_active: SynEE.run_regularly(tr.strct_mod, dt=tr.strct_dt, when='end') # -------------- recording ------------------ #run(tr.sim.preT) GExc_recvars = [] if tr.memtraces_rec: GExc_recvars.append('V') if tr.vttraces_rec: GExc_recvars.append('Vt') if tr.getraces_rec: GExc_recvars.append('ge') if tr.gitraces_rec: GExc_recvars.append('gi') GInh_recvars = GExc_recvars GExc_stat = StateMonitor(GExc, GExc_recvars, record=[0, 1, 2], dt=tr.GExc_stat_dt) GInh_stat = StateMonitor(GInh, GInh_recvars, record=[0, 1, 2], dt=tr.GInh_stat_dt) SynEE_recvars = [] if tr.synee_atraces_rec: SynEE_recvars.append('a') if tr.synee_Apretraces_rec: SynEE_recvars.append('Apre') if tr.synee_Aposttraces_rec: SynEE_recvars.append('Apost') SynEE_stat = StateMonitor(SynEE, SynEE_recvars, record=range(tr.n_synee_traces_rec), when='end', dt=tr.synEE_stat_dt) GExc_spks = SpikeMonitor(GExc) GInh_spks = SpikeMonitor(GInh) SynEE_a = StateMonitor(SynEE, ['a', 'syn_active'], record=range(tr.N_e * (tr.N_e - 1)), dt=tr.sim.T / 10., when='end', order=100) run(tr.sim.T, report='text') SynEE_a.record_single_timestep() device.build(directory='../builds/%.4d' % (tr.v_idx)) tr.v_standard_result = Brian2MonitorResult tr.f_add_result('GExc_stat', GExc_stat) tr.f_add_result('SynEE_stat', SynEE_stat) print("Saving exc spikes... ", GExc_spks.get_states()['N']) tr.f_add_result('GExc_spks', GExc_spks) tr.f_add_result('GInh_stat', GInh_stat) print("Saving inh spikes... ", GInh_spks.get_states()['N']) tr.f_add_result('GInh_spks', GInh_spks) tr.f_add_result('SynEE_a', SynEE_a) # ----------------- add raw data ------------------------ fpath = '../builds/%.4d/' % (tr.v_idx) from pathlib import Path Path(fpath + 'turnover').touch() turnover_data = np.genfromtxt(fpath + 'turnover', delimiter=',') tr.f_add_result('turnover', turnover_data) os.remove(fpath + 'turnover') Path(fpath + 'spk_register').touch() spk_register_data = np.genfromtxt(fpath + 'spk_register', delimiter=',') tr.f_add_result('spk_register', spk_register_data) os.remove(fpath + 'spk_register')
def run_net(tr): # prefs.codegen.target = 'numpy' # prefs.codegen.target = 'cython' set_device('cpp_standalone', directory='./builds/%.4d' % (tr.v_idx), build_on_run=False) print("Started process with id ", str(tr.v_idx)) T = tr.T1 + tr.T2 + tr.T3 namespace = tr.netw.f_to_dict(short_names=True, fast_access=True) namespace['idx'] = tr.v_idx defaultclock.dt = tr.netw.sim.dt GExc = NeuronGroup( N=tr.N_e, model=tr.condlif_sig, threshold=tr.nrnEE_thrshld, reset=tr.nrnEE_reset, #method=tr.neuron_method, namespace=namespace) GInh = NeuronGroup( N=tr.N_i, model=tr.condlif_sig, threshold='V > Vt', reset='V=Vr_i', #method=tr.neuron_method, namespace=namespace) # set initial thresholds fixed, init. potentials uniformly distrib. GExc.sigma, GInh.sigma = tr.sigma_e, tr.sigma_i GExc.Vt, GInh.Vt = tr.Vt_e, tr.Vt_i GExc.V , GInh.V = np.random.uniform(tr.Vr_e/mV, tr.Vt_e/mV, size=tr.N_e)*mV, \ np.random.uniform(tr.Vr_i/mV, tr.Vt_i/mV, size=tr.N_i)*mV print("need to fix?") synEE_pre_mod = mod.synEE_pre synEE_post_mod = mod.synEE_post if tr.PInp_mode == 'pool': PInp = PoissonGroup(tr.NPInp, rates=tr.PInp_rate, namespace=namespace) sPN = Synapses(target=GExc, source=PInp, model=tr.poisson_mod, on_pre='ge_post += a_EPoi', namespace=namespace) sPN_src, sPN_tar = generate_connections(N_tar=tr.N_e, N_src=tr.NPInp, p=tr.p_EPoi) elif tr.PInp_mode == 'indep': PInp = PoissonGroup(tr.N_e, rates=tr.PInp_rate, namespace=namespace) sPN = Synapses(target=GExc, source=PInp, model=tr.poisson_mod, on_pre='ge_post += a_EPoi', namespace=namespace) sPN_src, sPN_tar = range(tr.N_e), range(tr.N_e) sPN.connect(i=sPN_src, j=sPN_tar) if tr.PInp_mode == 'pool': sPNInh = Synapses(target=GInh, source=PInp, model=tr.poisson_mod, on_pre='ge_post += a_EPoi', namespace=namespace) sPNInh_src, sPNInh_tar = generate_connections(N_tar=tr.N_i, N_src=tr.NPInp, p=tr.p_EPoi) elif tr.PInp_mode == 'indep': PInp_inh = PoissonGroup(tr.N_i, rates=tr.PInp_rate, namespace=namespace) sPNInh = Synapses(target=GInh, source=PInp_inh, model=tr.poisson_mod, on_pre='ge_post += a_EPoi', namespace=namespace) sPNInh_src, sPNInh_tar = range(tr.N_i), range(tr.N_i) sPNInh.connect(i=sPNInh_src, j=sPNInh_tar) if tr.stdp_active: synEE_pre_mod = '''%s %s''' % (synEE_pre_mod, mod.synEE_pre_STDP) synEE_post_mod = '''%s %s''' % (synEE_post_mod, mod.synEE_post_STDP) if tr.synEE_rec: synEE_pre_mod = '''%s %s''' % (synEE_pre_mod, mod.synEE_pre_rec) synEE_post_mod = '''%s %s''' % (synEE_post_mod, mod.synEE_post_rec) # E<-E advanced synapse model, rest simple SynEE = Synapses( target=GExc, source=GExc, model=tr.synEE_mod, on_pre=synEE_pre_mod, on_post=synEE_post_mod, #method=tr.synEE_method, namespace=namespace) SynIE = Synapses(target=GInh, source=GExc, on_pre='ge_post += a_ie', namespace=namespace) SynEI = Synapses(target=GExc, source=GInh, on_pre='gi_post += a_ei', namespace=namespace) SynII = Synapses(target=GInh, source=GInh, on_pre='gi_post += a_ii', namespace=namespace) if tr.strct_active: sEE_src, sEE_tar = generate_full_connectivity(tr.N_e, same=True) SynEE.connect(i=sEE_src, j=sEE_tar) SynEE.syn_active = 0 else: srcs_full, tars_full = generate_full_connectivity(tr.N_e, same=True) SynEE.connect(i=srcs_full, j=tars_full) SynEE.syn_active = 0 sIE_src, sIE_tar = generate_connections(tr.N_i, tr.N_e, tr.p_ie) sEI_src, sEI_tar = generate_connections(tr.N_e, tr.N_i, tr.p_ei) sII_src, sII_tar = generate_connections(tr.N_i, tr.N_i, tr.p_ii, same=True) SynIE.connect(i=sIE_src, j=sIE_tar) SynEI.connect(i=sEI_src, j=sEI_tar) SynII.connect(i=sII_src, j=sII_tar) tr.f_add_result('sIE_src', sIE_src) tr.f_add_result('sIE_tar', sIE_tar) tr.f_add_result('sEI_src', sEI_src) tr.f_add_result('sEI_tar', sEI_tar) tr.f_add_result('sII_src', sII_src) tr.f_add_result('sII_tar', sII_tar) SynEE.a = tr.a_ee SynEE.insert_P = tr.insert_P SynEE.p_inactivate = tr.p_inactivate # make synapse active at beginning SynEE.run_regularly(tr.synEE_p_activate, dt=T, when='start', order=-100) # synaptic scaling if tr.netw.config.scl_active: SynEE.summed_updaters['Asum_post']._clock = Clock( dt=tr.dt_synEE_scaling) SynEE.run_regularly(tr.synEE_scaling, dt=tr.dt_synEE_scaling, when='end') # intrinsic plasticity if tr.netw.config.it_active: GExc.h_ip = tr.h_ip GExc.run_regularly(tr.intrinsic_mod, dt=tr.it_dt, when='end') # structural plasticity if tr.netw.config.strct_active: if tr.strct_mode == 'zero': if tr.turnover_rec: strct_mod = '''%s %s''' % (tr.strct_mod, tr.turnover_rec_mod) else: strct_mod = tr.strct_mod SynEE.run_regularly(strct_mod, dt=tr.strct_dt, when='end') elif tr.strct_mode == 'thrs': if tr.turnover_rec: strct_mod_thrs = '''%s %s''' % (tr.strct_mod_thrs, tr.turnover_rec_mod) else: strct_mod_thrs = tr.strct_mod_thrs SynEE.run_regularly(strct_mod_thrs, dt=tr.strct_dt, when='end') # -------------- recording ------------------ #run(tr.sim.preT) GExc_recvars = [] if tr.memtraces_rec: GExc_recvars.append('V') if tr.vttraces_rec: GExc_recvars.append('Vt') if tr.getraces_rec: GExc_recvars.append('ge') if tr.gitraces_rec: GExc_recvars.append('gi') GInh_recvars = GExc_recvars GExc_stat = StateMonitor(GExc, GExc_recvars, record=[0, 1, 2], dt=tr.GExc_stat_dt) GInh_stat = StateMonitor(GInh, GInh_recvars, record=[0, 1, 2], dt=tr.GInh_stat_dt) SynEE_recvars = [] if tr.synee_atraces_rec: SynEE_recvars.append('a') if tr.synee_Apretraces_rec: SynEE_recvars.append('Apre') if tr.synee_Aposttraces_rec: SynEE_recvars.append('Apost') SynEE_stat = StateMonitor(SynEE, SynEE_recvars, record=range(tr.n_synee_traces_rec), when='end', dt=tr.synEE_stat_dt) GExc_spks = SpikeMonitor(GExc) GInh_spks = SpikeMonitor(GInh) PInp_spks = SpikeMonitor(PInp) GExc_rate = PopulationRateMonitor(GExc) GInh_rate = PopulationRateMonitor(GInh) PInp_rate = PopulationRateMonitor(PInp) SynEE_a = StateMonitor(SynEE, ['a', 'syn_active'], record=range(tr.N_e * (tr.N_e - 1)), dt=T / tr.synee_a_nrecpoints, when='end', order=100) if tr.PInp_mode == 'indep': net = Network(GExc, GInh, PInp, sPN, sPNInh, SynEE, SynEI, SynIE, SynII, GExc_stat, GInh_stat, SynEE_stat, SynEE_a, GExc_spks, GInh_spks, PInp_spks, GExc_rate, GInh_rate, PInp_rate, PInp_inh) else: net = Network(GExc, GInh, PInp, sPN, sPNInh, SynEE, SynEI, SynIE, SynII, GExc_stat, GInh_stat, SynEE_stat, SynEE_a, GExc_spks, GInh_spks, PInp_spks, GExc_rate, GInh_rate, PInp_rate) net.run(tr.sim.T1, report='text') # SynEE_a.record_single_timestep() recorders = [ GExc_spks, GInh_spks, PInp_spks, SynEE_stat, GExc_stat, GInh_stat ] rate_recorders = [GExc_rate, GInh_rate, PInp_rate] for rcc in recorders: rcc.active = False net.run(tr.sim.T2, report='text') recorders = [ SynEE_stat, GExc_stat, GInh_stat, GExc_rate, GInh_rate, PInp_rate ] for rcc in recorders: rcc.active = True if tr.spks_rec: GExc_spks.active = True GInh_spks.active = True # PInp_spks.active=True net.run(tr.sim.T3, report='text') device.build(directory='../builds/%.4d' % (tr.v_idx), clean=True) # save monitors as raws in build directory raw_dir = '../builds/%.4d/raw/' % (tr.v_idx) if not os.path.exists(raw_dir): os.makedirs(raw_dir) with open(raw_dir + 'namespace.p', 'wb') as pfile: pickle.dump(namespace, pfile) with open(raw_dir + 'gexc_stat.p', 'wb') as pfile: pickle.dump(GExc_stat.get_states(), pfile) with open(raw_dir + 'ginh_stat.p', 'wb') as pfile: pickle.dump(GInh_stat.get_states(), pfile) with open(raw_dir + 'synee_stat.p', 'wb') as pfile: pickle.dump(SynEE_stat.get_states(), pfile) with open(raw_dir + 'synee_a.p', 'wb') as pfile: pickle.dump(SynEE_a.get_states(), pfile) with open(raw_dir + 'gexc_spks.p', 'wb') as pfile: pickle.dump(GExc_spks.get_states(), pfile) with open(raw_dir + 'ginh_spks.p', 'wb') as pfile: pickle.dump(GInh_spks.get_states(), pfile) with open(raw_dir + 'pinp_spks.p', 'wb') as pfile: pickle.dump(PInp_spks.get_states(), pfile) with open(raw_dir + 'gexc_rate.p', 'wb') as pfile: pickle.dump(GExc_rate.get_states(), pfile) pickle.dump(GExc_rate.smooth_rate(width=25 * ms), pfile) with open(raw_dir + 'ginh_rate.p', 'wb') as pfile: pickle.dump(GInh_rate.get_states(), pfile) pickle.dump(GInh_rate.smooth_rate(width=25 * ms), pfile) with open(raw_dir + 'pinp_rate.p', 'wb') as pfile: pickle.dump(PInp_rate.get_states(), pfile) pickle.dump(PInp_rate.smooth_rate(width=25 * ms), pfile) # ----------------- add raw data ------------------------ fpath = '../builds/%.4d/' % (tr.v_idx) from pathlib import Path Path(fpath + 'turnover').touch() turnover_data = np.genfromtxt(fpath + 'turnover', delimiter=',') os.remove(fpath + 'turnover') with open(raw_dir + 'turnover.p', 'wb') as pfile: pickle.dump(turnover_data, pfile) Path(fpath + 'spk_register').touch() spk_register_data = np.genfromtxt(fpath + 'spk_register', delimiter=',') os.remove(fpath + 'spk_register') with open(raw_dir + 'spk_register.p', 'wb') as pfile: pickle.dump(spk_register_data, pfile)
def brianInteraction(self): #/########################/# # Postlet level # #debug self.debug( [ 'It is a Synapser level, we set the Synapser', ('self.',self,[ #'BrianingSynapsesDict' ] ) ] ) #/####################/# # Set the parent # #Check if self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable.BrianedParentSingularStr=='Interactome': #debug ''' self.debug( [ 'We are in a projectome structure' ] ) ''' #set self.BrianedParentInteractomeDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.BrianedParentInteractomeDeriveBrianerVariable.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable else: #debug ''' self.debug( [ 'There is no projectome structure' ] ) ''' #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/####################/# # Set the ConnectedTo Variable # #debug self.debug( [ 'Check if we have to get the connected to variable', ('self.',self,['ConnectedToVariable']) ] ) #Check if self.ConnectedToVariable==None: #debug self.debug( [ 'We setConnection here' ] ) #setConnection self.setConnection( self.ManagementTagStr, self, self.BrianedParentNeurongroupDeriveBrianerVariable ) #/####################/# # Set the BrianedParentNeurongroupDeriveBrianerVariable # #debug self.debug( [ 'Do we have to make parent-brian the connected variable ?', 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable) ] ) #Check if self.ConnectedToVariable.BrianedNeurongroupVariable==None: #parent brian self.ConnectedToVariable.parent( ).brian( ) #set BrianedNameStr=self.BrianedParentNeurongroupDeriveBrianerVariable.StructureTagStr+'_To_'+self.ConnectedToVariable.StructureTagStr #debug self.debug( [ 'We set the synapses', 'self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable is ', str(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable), 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable), 'Maybe we have to make brian the post', 'BrianedNameStr is '+BrianedNameStr ] ) #import from brian2 import Synapses #init self.BrianedSynapsesVariable=Synapses( source=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable, target=self.ConnectedToVariable.BrianedNeurongroupVariable, name=BrianedNameStr.replace('/','_'), **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 ) #/####################/# # add to the structure # #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedSynapsesVariable )
class SynapserClass(BaseClass): def default_init( self, _SynapsingBrianKwargDict=None, _SynapsingProbabilityVariable=None, _SynapsingTagStr="", _SynapsingWeigthSymbolStr="", _SynapsingWeigthFloatsArray=None, _SynapsingDelayDict=0.0, _SynapsedBrianVariable=None, _SynapsedWeigthFloatsArray=None, _SynapsedCustomOperationStr="", _SynapsedDelayStateStrsList="", **_KwargVariablesDict ): # init self.PostModelInsertStrsList = [] self.PostModelAddDict = {} # Call the parent __init__ method BaseClass.__init__(self, **_KwargVariablesDict) def setDelay(self, _SymbolStr, _DelayVariable): # debug """ self.debug( [ "self.SynapsingBrianKwargDict['source'].clock is ", self.SynapsingBrianKwargDict['source'].clock ] ) """ # define if type(_DelayVariable).__name__ == "Quantity": # divide DelayEquationsInt = (int)(_DelayVariable / self.SynapsingBrianKwargDict["source"].clock.dt) else: # debug """ self.debug( [ "float of dt is ", float( self.SynapsingBrianKwargDict['source'].clock.dt ) ] ) """ # divide and put that in ms...(rough) DelayEquationsInt = (int)(_DelayVariable * 0.001 / float(self.SynapsingBrianKwargDict["source"].clock.dt)) # join self.SynapsedCustomOperationStr = "\n".join( map( lambda __EquationIndexInt: _SymbolStr + "_delayer_" + str(__EquationIndexInt) + "=" + _SymbolStr + "_delayer_" + str(__EquationIndexInt - 1), xrange(DelayEquationsInt, 1, -1), ) + [_SymbolStr + "delayer_1=" + _SymbolStr] ) # debug self.debug(("self.", self, ["SynapsedCustomOperationStr"])) # custom self.SynapsingBrianKwargDict["source"].custom_operation(self.SynapsedCustomOperationStr) # join self.SynapsedDelayStateStrsListsList = map( lambda __EquationIndexInt: _SymbolStr + "_delayer_ : 1", xrange(DelayEquationsInt) ) # debug self.debug(("self.", self, ["SynapsedDelayStateStrsList"])) # add in the PreModelInsertStrsList if hasattr(self, "AttentionUpdateVariable") == False: self.AttentionUpdateVariable = {"PreModelInsertStrsList": []} self.AttentionUpdateVariable["PreModelInsertStrsList"] += self.SynapsedDelayStateStrsListsList def do_synapse(self): # Maybe should import from brian2 import Synapses # Check if len(self.SynapsingDelayDict) > 0.0: # map map(lambda __ItemTuple: self.setDelay(*__ItemTuple), self.SynapsingDelayDict.items()) # debug """ self.debug(('self.',self,[ 'SynapsingBrianKwargDict' ])) """ # init self.SynapsedBrianVariable = Synapses(**self.SynapsingBrianKwargDict) # connect if type(self.SynapsingProbabilityVariable) == float: # debug """ self.debug('we connect with a sparsity of '+str(self.SynapsingProbabilityVariable)) """ self.SynapsedBrianVariable.connect(True, p=self.SynapsingProbabilityVariable) # Check if self.SynapsingWeigthSymbolStr != "": # debug """ self.debug( ('self.',self,[ 'SynapsedBrianVariable', 'SynapsingWeigthSymbolStr' ]) ) """ # connect self.SynapsedBrianVariable.connect(True) # get self.SynapsedWeigthFloatsArray = getattr(self.SynapsedBrianVariable, self.SynapsingWeigthSymbolStr) # set self.SynapsedWeigthFloatsArray[:] = np.reshape( self.SynapsingWeigthFloatsArray, self.SynapsedBrianVariable.source.N * self.SynapsedBrianVariable.target.N, ) # debug self.debug(("self.", self, ["SynapsedWeigthFloatsArray"]))
def brianInteraction(self): # /########################/# # Postlet level # # debug """ self.debug( [ 'It is an Interaction level', ('self.',self,[ #'BrianingSynapsesDict' ] ) ] ) """ # /####################/# # Set the parent # # Check if self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable.BrianedParentSingularStr == "Interactome": # debug """ self.debug( [ 'We are in a projectome structure' ] ) """ # set self.BrianedParentInteractomeDeriveBrianerVariable = ( self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable ) # get self.BrianedParentPopulationDeriveBrianerVariable = ( self.BrianedParentInteractomeDeriveBrianerVariable.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable ) else: # debug """ self.debug( [ 'There is no projectome structure' ] ) """ # get self.BrianedParentPopulationDeriveBrianerVariable = ( self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable ) # get self.BrianedParentNetworkDeriveBrianerVariable = ( self.BrianedParentPopulationDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable ) # /####################/# # Set the ConnectedTo Variable # # debug """ self.debug( [ 'Check if we have to get the connected to variable', ('self.',self,['ConnectedToVariable']) ] ) """ # Check if self.ConnectedToVariable == None: # debug """ self.debug( [ 'We setConnection here' ] ) """ # setConnection self.setConnection(self.ManagementTagStr, self, self.BrianedParentPopulationDeriveBrianerVariable) # /####################/# # Set the BrianedParentPopulationDeriveBrianerVariable # # debug """ self.debug( [ 'Do we have to make parent-brian the connected variable ?', 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable) ] ) """ # Check if self.ConnectedToVariable.BrianedNeurongroupVariable == None: # parent brian self.ConnectedToVariable.parent().brian() # set BrianedNameStr = ( self.BrianedParentPopulationDeriveBrianerVariable.StructureTagStr + "_To_" + self.ConnectedToVariable.StructureTagStr ) # debug """ self.debug( [ 'We set the synapses', 'self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable is ', str(self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable), 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable), 'Maybe we have to make brian the post', 'BrianedNameStr is '+BrianedNameStr ] ) """ # import from brian2 import Synapses # init self.BrianedSynapsesVariable = Synapses( source=self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable, target=self.ConnectedToVariable.BrianedNeurongroupVariable, # name=BrianedNameStr.replace('/','_'), **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) # /####################/# # add to the structure # # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(self.BrianedSynapsesVariable) # /##################/# # Define a debug # # Check if self.BrianingDebugVariable > 0: # import from brian2 import network_operation, ms @network_operation( dt=self.BrianingDebugVariable * self.BrianedParentNetworkDeriveBrianerVariable.BrianedTimeQuantityVariable ) def debugSynapses(): # init PrintStr = "At time t=" + str(self.BrianedSynapsesVariable.clock.t) + ", \n" PrintStr += "In the Synapses " + self.BrianedSynapsesVariable.name + " : \n" # loop for __KeyStr in self.BrianedSynapsesVariable.equations._equations.keys(): # set PrintStr += __KeyStr + " is " + str(getattr(self.BrianedSynapsesVariable, __KeyStr)) + "\n" # add PrintStr += "\n" # print print PrintStr # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(debugSynapses)
def _build_connections(self, traj, brian_list, network_dict): """Connects neuron groups `neurons_i` and `neurons_e`. Adds all connections to `brian_list` and adds a list of connections with the key 'connections' to the `network_dict`. """ connections = traj.connections neurons_i = network_dict['neurons_i'] neurons_e = network_dict['neurons_e'] print('Connecting ii') self.conn_ii = Synapses(neurons_i,neurons_i, on_pre='y_i += %f' % connections.J_ii) self.conn_ii.connect('i != j', p=connections.p_ii) print('Connecting ei') self.conn_ei = Synapses(neurons_i,neurons_e, on_pre='y_i += %f' % connections.J_ei) self.conn_ei.connect('i != j', p=connections.p_ei) print('Connecting ie') self.conn_ie = Synapses(neurons_e,neurons_i, on_pre='y_e += %f' % connections.J_ie) self.conn_ie.connect('i != j', p=connections.p_ie) conns_list = [self.conn_ii, self.conn_ei, self.conn_ie] if connections.R_ee > 1.0: # If we come here we want to create clusters cluster_list=[] cluster_conns_list=[] model=traj.model # Compute the number of clusters clusters = int(model.N_e/connections.clustersize_e) traj.f_add_derived_parameter('connections.clusters', clusters, comment='Number of clusters') # Compute outgoing connection probability p_out = (connections.p_ee*model.N_e) / \ (connections.R_ee*connections.clustersize_e+model.N_e- connections.clustersize_e) # Compute within cluster connection probability p_in = p_out * connections.R_ee # We keep these derived parameters traj.f_add_derived_parameter('connections.p_ee_in', p_in , comment='Connection prob within cluster') traj.f_add_derived_parameter('connections.p_ee_out', p_out , comment='Connection prob to outside of cluster') low_index = 0 high_index = connections.clustersize_e # Iterate through cluster and connect within clusters and to the rest of the neurons for irun in range(clusters): cluster = neurons_e[low_index:high_index] # Connections within cluster print('Connecting ee cluster #%d of %d' % (irun, clusters)) conn = Synapses(cluster,cluster, on_pre='y_e += %f' % (connections.J_ee*connections.strength_factor)) conn.connect('i != j', p=p_in) cluster_conns_list.append(conn) # Connections reaching out from cluster # A cluster consists of `clustersize_e` neurons with consecutive indices. # So usually the outside world consists of two groups, neurons with lower # indices than the cluster indices, and neurons with higher indices. # Only the clusters at the index boundaries project to neurons with only either # lower or higher indices if low_index > 0: rest_low = neurons_e[0:low_index] print('Connecting cluster with other neurons of lower index') low_conn = Synapses(cluster,rest_low, on_pre='y_e += %f' % connections.J_ee) low_conn.connect('i != j', p=p_out) cluster_conns_list.append(low_conn) if high_index < model.N_e: rest_high = neurons_e[high_index:model.N_e] print('Connecting cluster with other neurons of higher index') high_conn = Synapses(cluster,rest_high, on_pre='y_e += %f' % connections.J_ee) high_conn.connect('i != j', p=p_out) cluster_conns_list.append(high_conn) low_index=high_index high_index+=connections.clustersize_e self.cluster_conns=cluster_conns_list conns_list+=cluster_conns_list else: # Here we don't cluster and connection probabilities are homogeneous print('Connectiong ee') self.conn_ee = Synapses(neurons_e,neurons_e, on_pre='y_e += %f' % connections.J_ee) self.conn_ee.connect('i != j', p=connections.p_ee) conns_list.append(self.conn_ee) # Add the connections to the `brian_list` and the network dict brian_list.extend(conns_list) network_dict['connections'] = conns_list
class CNConnections(NetworkComponent): """Class to connect neuron groups. In case of no clustering `R_ee=1,0` there are 4 connection instances (i->i, i->e, e->i, e->e). Otherwise there are 3 + 3*N_c-2 connections with N_c the number of clusters (i->i, i->e, e->i, N_c conns within cluster, 2*N_c-2 connections from cluster to outside). """ @staticmethod def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) traj.v_standard_parameter = Brian2Parameter scale = traj.simulation.scale traj.f_add_parameter('connections.R_ee', 1.0, comment='Scaling factor for clustering') traj.f_add_parameter('connections.clustersize_e', 100, comment='Size of a cluster') traj.f_add_parameter('connections.strength_factor', 2.5, comment='Factor for scaling cluster weights') traj.f_add_parameter('connections.p_ii', 0.25, comment='Connection probability from inhibitory to inhibitory' ) traj.f_add_parameter('connections.p_ei', 0.25, comment='Connection probability from inhibitory to excitatory' ) traj.f_add_parameter('connections.p_ie', 0.25, comment='Connection probability from excitatory to inhibitory' ) traj.f_add_parameter('connections.p_ee', 0.1, comment='Connection probability from excitatory to excitatory' ) traj.f_add_parameter('connections.J_ii', 0.027/np.sqrt(scale), comment='Connection strength from inhibitory to inhibitory') traj.f_add_parameter('connections.J_ei', 0.032/np.sqrt(scale), comment='Connection strength from inhibitory to excitatroy') traj.f_add_parameter('connections.J_ie', 0.009/np.sqrt(scale), comment='Connection strength from excitatory to inhibitory') traj.f_add_parameter('connections.J_ee', 0.012/np.sqrt(scale), comment='Connection strength from excitatory to excitatory') def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ self._pre_build = not _explored_parameters_in_group(traj, traj.parameters.connections) self._pre_build = (self._pre_build and 'neurons_i' in network_dict and 'neurons_e' in network_dict) if self._pre_build: self._build_connections(traj, brian_list, network_dict) def build(self, traj, brian_list, network_dict): """Builds the connections. Build is only performed if connections have not been pre-build. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ if not hasattr(self, '_pre_build') or not self._pre_build: self._build_connections(traj, brian_list, network_dict) def _build_connections(self, traj, brian_list, network_dict): """Connects neuron groups `neurons_i` and `neurons_e`. Adds all connections to `brian_list` and adds a list of connections with the key 'connections' to the `network_dict`. """ connections = traj.connections neurons_i = network_dict['neurons_i'] neurons_e = network_dict['neurons_e'] print('Connecting ii') self.conn_ii = Synapses(neurons_i,neurons_i, on_pre='y_i += %f' % connections.J_ii) self.conn_ii.connect('i != j', p=connections.p_ii) print('Connecting ei') self.conn_ei = Synapses(neurons_i,neurons_e, on_pre='y_i += %f' % connections.J_ei) self.conn_ei.connect('i != j', p=connections.p_ei) print('Connecting ie') self.conn_ie = Synapses(neurons_e,neurons_i, on_pre='y_e += %f' % connections.J_ie) self.conn_ie.connect('i != j', p=connections.p_ie) conns_list = [self.conn_ii, self.conn_ei, self.conn_ie] if connections.R_ee > 1.0: # If we come here we want to create clusters cluster_list=[] cluster_conns_list=[] model=traj.model # Compute the number of clusters clusters = int(model.N_e/connections.clustersize_e) traj.f_add_derived_parameter('connections.clusters', clusters, comment='Number of clusters') # Compute outgoing connection probability p_out = (connections.p_ee*model.N_e) / \ (connections.R_ee*connections.clustersize_e+model.N_e- connections.clustersize_e) # Compute within cluster connection probability p_in = p_out * connections.R_ee # We keep these derived parameters traj.f_add_derived_parameter('connections.p_ee_in', p_in , comment='Connection prob within cluster') traj.f_add_derived_parameter('connections.p_ee_out', p_out , comment='Connection prob to outside of cluster') low_index = 0 high_index = connections.clustersize_e # Iterate through cluster and connect within clusters and to the rest of the neurons for irun in range(clusters): cluster = neurons_e[low_index:high_index] # Connections within cluster print('Connecting ee cluster #%d of %d' % (irun, clusters)) conn = Synapses(cluster,cluster, on_pre='y_e += %f' % (connections.J_ee*connections.strength_factor)) conn.connect('i != j', p=p_in) cluster_conns_list.append(conn) # Connections reaching out from cluster # A cluster consists of `clustersize_e` neurons with consecutive indices. # So usually the outside world consists of two groups, neurons with lower # indices than the cluster indices, and neurons with higher indices. # Only the clusters at the index boundaries project to neurons with only either # lower or higher indices if low_index > 0: rest_low = neurons_e[0:low_index] print('Connecting cluster with other neurons of lower index') low_conn = Synapses(cluster,rest_low, on_pre='y_e += %f' % connections.J_ee) low_conn.connect('i != j', p=p_out) cluster_conns_list.append(low_conn) if high_index < model.N_e: rest_high = neurons_e[high_index:model.N_e] print('Connecting cluster with other neurons of higher index') high_conn = Synapses(cluster,rest_high, on_pre='y_e += %f' % connections.J_ee) high_conn.connect('i != j', p=p_out) cluster_conns_list.append(high_conn) low_index=high_index high_index+=connections.clustersize_e self.cluster_conns=cluster_conns_list conns_list+=cluster_conns_list else: # Here we don't cluster and connection probabilities are homogeneous print('Connectiong ee') self.conn_ee = Synapses(neurons_e,neurons_e, on_pre='y_e += %f' % connections.J_ee) self.conn_ee.connect('i != j', p=connections.p_ee) conns_list.append(self.conn_ee) # Add the connections to the `brian_list` and the network dict brian_list.extend(conns_list) network_dict['connections'] = conns_list
def simulate_wm( N_excitatory=1024, N_inhibitory=256, N_extern_poisson=1000, poisson_firing_rate=1.4 * b2.Hz, weight_scaling_factor=2., sigma_weight_profile=20., Jpos_excit2excit=1.6, stimulus_center_deg=180, stimulus_width_deg=40, stimulus_strength=0.07 * b2.namp, t_stimulus_start=0 * b2.ms, t_stimulus_duration=0 * b2.ms, distractor_center_deg=90, distractor_width_deg=40, distractor_strength=0.0 * b2.namp, t_distractor_start=0 * b2.ms, t_distractor_duration=0 * b2.ms, G_inhib2inhib=.35 * 1.024 * b2.nS, G_inhib2excit=.35 * 1.336 * b2.nS, G_excit2excit=.35 * 0.381 * b2.nS, G_excit2inhib=.35 * 1.2 * 0.292 * b2.nS, monitored_subset_size=1024, sim_time=800. * b2.ms): """ Args: N_excitatory (int): Size of the excitatory population N_inhibitory (int): Size of the inhibitory population weight_scaling_factor (float): weight prefactor. When increasing the size of the populations, the synaptic weights have to be decreased. Using the default values, we have N_excitatory*weight_scaling_factor = 2048 and N_inhibitory*weight_scaling_factor=512 N_extern_poisson (int): Size of the external input population (Poisson input) poisson_firing_rate (Quantity): Firing rate of the external population sigma_weight_profile (float): standard deviation of the gaussian input profile in the excitatory population. Jpos_excit2excit (float): Strength of the recurrent input within the excitatory population. Jneg_excit2excit is computed from sigma_weight_profile, Jpos_excit2excit and the normalization condition. stimulus_center_deg (float): Center of the stimulus in [0, 360] stimulus_width_deg (float): width of the stimulus. All neurons in stimulus_center_deg +\- (stimulus_width_deg/2) receive the same input current stimulus_strength (Quantity): Input current to the neurons at stimulus_center_deg +\- (stimulus_width_deg/2) t_stimulus_start (Quantity): time when the input stimulus is turned on t_stimulus_duration (Quantity): duration of the stimulus. distractor_center_deg (float): Center of the distractor in [0, 360] distractor_width_deg (float): width of the distractor. All neurons in distractor_center_deg +\- (distractor_width_deg/2) receive the same input current distractor_strength (Quantity): Input current to the neurons at distractor_center_deg +\- (distractor_width_deg/2) t_distractor_start (Quantity): time when the distractor is turned on t_distractor_duration (Quantity): duration of the distractor. G_inhib2inhib (Quantity): projections from inhibitory to inhibitory population (later rescaled by weight_scaling_factor) G_inhib2excit (Quantity): projections from inhibitory to excitatory population (later rescaled by weight_scaling_factor) G_excit2excit (Quantity): projections from excitatory to excitatory population (later rescaled by weight_scaling_factor) G_excit2inhib (Quantity): projections from excitatory to inhibitory population (later rescaled by weight_scaling_factor) monitored_subset_size (int): nr of neurons for which a Spike- and Voltage monitor is registered. sim_time (Quantity): simulation time Returns: results (tuple): rate_monitor_excit (Brian2 PopulationRateMonitor for the excitatory population), spike_monitor_excit, voltage_monitor_excit, idx_monitored_neurons_excit,\ rate_monitor_inhib, spike_monitor_inhib, voltage_monitor_inhib, idx_monitored_neurons_inhib,\ weight_profile_45 (The weights profile for the neuron with preferred direction = 45deg). """ # specify the excitatory pyramidal cells: Cm_excit = 0.5 * b2.nF # membrane capacitance of excitatory neurons G_leak_excit = 25.0 * b2.nS # leak conductance E_leak_excit = -70.0 * b2.mV # reversal potential v_firing_threshold_excit = -50.0 * b2.mV # spike condition v_reset_excit = -60.0 * b2.mV # reset voltage after spike t_abs_refract_excit = 2.0 * b2.ms # absolute refractory period # specify the weight profile in the recurrent population # std-dev of the gaussian weight profile around the prefered direction # sigma_weight_profile = 12.0 # std-dev of the gaussian weight profile around the prefered direction # # Jneg_excit2excit = 0 # specify the inhibitory interneurons: Cm_inhib = 0.2 * b2.nF G_leak_inhib = 20.0 * b2.nS E_leak_inhib = -70.0 * b2.mV v_firing_threshold_inhib = -50.0 * b2.mV v_reset_inhib = -60.0 * b2.mV t_abs_refract_inhib = 1.0 * b2.ms # specify the AMPA synapses E_AMPA = 0.0 * b2.mV tau_AMPA = .9 * 2.0 * b2.ms # specify the GABA synapses E_GABA = -70.0 * b2.mV tau_GABA = 10.0 * b2.ms # specify the NMDA synapses E_NMDA = 0.0 * b2.mV tau_NMDA_s = .65 * 100.0 * b2.ms # orig: 100 tau_NMDA_x = .94 * 2.0 * b2.ms alpha_NMDA = 0.5 * b2.kHz # projections from the external population G_extern2inhib = 2.38 * b2.nS G_extern2excit = 3.1 * b2.nS # projectsions from the inhibitory populations G_inhib2inhib *= weight_scaling_factor G_inhib2excit *= weight_scaling_factor # projections from the excitatory population G_excit2excit *= weight_scaling_factor G_excit2inhib *= weight_scaling_factor # todo: verify this scaling t_stimulus_end = t_stimulus_start + t_stimulus_duration t_distractor_end = t_distractor_start + t_distractor_duration # compute the simulus index stim_center_idx = int(round(N_excitatory / 360. * stimulus_center_deg)) stim_width_idx = int(round(N_excitatory / 360. * stimulus_width_deg / 2)) stim_target_idx = [idx % N_excitatory for idx in range(stim_center_idx - stim_width_idx, stim_center_idx + stim_width_idx + 1)] # compute the distractor index distr_center_idx = int(round(N_excitatory / 360. * distractor_center_deg)) distr_width_idx = int(round(N_excitatory / 360. * distractor_width_deg / 2)) distr_target_idx = [idx % N_excitatory for idx in range(distr_center_idx - distr_width_idx, distr_center_idx + distr_width_idx + 1)] # precompute the weight profile for the recurrent population tmp = math.sqrt(2. * math.pi) * sigma_weight_profile * erf(180. / math.sqrt(2.) / sigma_weight_profile) / 360. Jneg_excit2excit = (1. - Jpos_excit2excit * tmp) / (1. - tmp) presyn_weight_kernel = \ [(Jneg_excit2excit + (Jpos_excit2excit - Jneg_excit2excit) * math.exp(-.5 * (360. * min(j, N_excitatory - j) / N_excitatory) ** 2 / sigma_weight_profile ** 2)) for j in range(N_excitatory)] # validate the normalization condition: (360./N_excitatory)*sum(presyn_weight_kernel)/360. fft_presyn_weight_kernel = rfft(presyn_weight_kernel) weight_profile_45 = deque(presyn_weight_kernel) rot_dist = int(round(len(weight_profile_45) / 8)) weight_profile_45.rotate(rot_dist) # define the inhibitory population inhib_lif_dynamics = """ s_NMDA_total : 1 # the post synaptic sum of s. compare with s_NMDA_presyn dv/dt = ( - G_leak_inhib * (v-E_leak_inhib) - G_extern2inhib * s_AMPA * (v-E_AMPA) - G_inhib2inhib * s_GABA * (v-E_GABA) - G_excit2inhib * s_NMDA_total * (v-E_NMDA)/(1.0+1.0*exp(-0.062*v/volt)/3.57) )/Cm_inhib : volt (unless refractory) ds_AMPA/dt = -s_AMPA/tau_AMPA : 1 ds_GABA/dt = -s_GABA/tau_GABA : 1 """ inhib_pop = NeuronGroup( N_inhibitory, model=inhib_lif_dynamics, threshold="v>v_firing_threshold_inhib", reset="v=v_reset_inhib", refractory=t_abs_refract_inhib, method="rk2") # initialize with random voltages: inhib_pop.v = numpy.random.uniform(v_reset_inhib / b2.mV, high=v_firing_threshold_inhib / b2.mV, size=N_inhibitory) * b2.mV # set the connections: inhib2inhib syn_inhib2inhib = Synapses(inhib_pop, target=inhib_pop, on_pre="s_GABA += 1.0", delay=0.0 * b2.ms) syn_inhib2inhib.connect(condition="i!=j", p=1.0) # set the connections: extern2inhib input_ext2inhib = PoissonInput(target=inhib_pop, target_var="s_AMPA", N=N_extern_poisson, rate=poisson_firing_rate, weight=1.0) # specify the excitatory population: excit_lif_dynamics = """ I_stim : amp s_NMDA_total : 1 # the post synaptic sum of s. compare with s_NMDA_presyn dv/dt = ( - G_leak_excit * (v-E_leak_excit) - G_extern2excit * s_AMPA * (v-E_AMPA) - G_inhib2excit * s_GABA * (v-E_GABA) - G_excit2excit * s_NMDA_total * (v-E_NMDA)/(1.0+1.0*exp(-0.062*v/volt)/3.57) + I_stim )/Cm_excit : volt (unless refractory) ds_AMPA/dt = -s_AMPA/tau_AMPA : 1 ds_GABA/dt = -s_GABA/tau_GABA : 1 ds_NMDA/dt = -s_NMDA/tau_NMDA_s + alpha_NMDA * x * (1-s_NMDA) : 1 dx/dt = -x/tau_NMDA_x : 1 """ excit_pop = NeuronGroup(N_excitatory, model=excit_lif_dynamics, threshold="v>v_firing_threshold_excit", reset="v=v_reset_excit; x+=1.0", refractory=t_abs_refract_excit, method="rk2") # initialize with random voltages: excit_pop.v = numpy.random.uniform(v_reset_excit / b2.mV, high=v_firing_threshold_excit / b2.mV, size=N_excitatory) * b2.mV excit_pop.I_stim = 0. * b2.namp # set the connections: extern2excit input_ext2excit = PoissonInput(target=excit_pop, target_var="s_AMPA", N=N_extern_poisson, rate=poisson_firing_rate, weight=1.0) # set the connections: inhibitory to excitatory syn_inhib2excit = Synapses(inhib_pop, target=excit_pop, on_pre="s_GABA += 1.0") syn_inhib2excit.connect(p=1.0) # set the connections: excitatory to inhibitory NMDA connections syn_excit2inhib = Synapses(excit_pop, inhib_pop, model="s_NMDA_total_post = s_NMDA_pre : 1 (summed)", method="rk2") syn_excit2inhib.connect(p=1.0) # # set the connections: UNSTRUCTURED excitatory to excitatory # syn_excit2excit = Synapses(excit_pop, excit_pop, # model= "s_NMDA_total_post = s_NMDA_pre : 1 (summed)", method="rk2") # syn_excit2excit.connect(condition="i!=j", p=1.) # set the STRUCTURED recurrent input. use a network_operation @network_operation() def update_nmda_sum(): fft_s_NMDA = rfft(excit_pop.s_NMDA) fft_s_NMDA_total = numpy.multiply(fft_presyn_weight_kernel, fft_s_NMDA) s_NMDA_tot = irfft(fft_s_NMDA_total) excit_pop.s_NMDA_total_ = s_NMDA_tot @network_operation(dt=1 * b2.ms) def stimulate_network(t): if t >= t_stimulus_start and t < t_stimulus_end: # excit_pop[stim_start_i - 15:stim_start_i + 15].I_stim = 0.25 * b2.namp # Todo: review indexing # print("stim on") excit_pop.I_stim[stim_target_idx] = stimulus_strength else: # print("stim off") excit_pop.I_stim = 0. * b2.namp # add distractor if t >= t_distractor_start and t < t_distractor_end: excit_pop.I_stim[distr_target_idx] = distractor_strength def get_monitors(pop, nr_monitored, N): nr_monitored = min(nr_monitored, (N)) idx_monitored_neurons = \ [int(math.ceil(k)) for k in numpy.linspace(0, N - 1, nr_monitored + 2)][1:-1] # sample(range(N), nr_monitored) rate_monitor = PopulationRateMonitor(pop) # record= some_list is not supported? :-( spike_monitor = SpikeMonitor(pop, record=idx_monitored_neurons) voltage_monitor = StateMonitor(pop, "v", record=idx_monitored_neurons) return rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons # collect data of a subset of neurons: rate_monitor_inhib, spike_monitor_inhib, voltage_monitor_inhib, idx_monitored_neurons_inhib = \ get_monitors(inhib_pop, monitored_subset_size, N_inhibitory) rate_monitor_excit, spike_monitor_excit, voltage_monitor_excit, idx_monitored_neurons_excit = \ get_monitors(excit_pop, monitored_subset_size, N_excitatory) b2.run(sim_time) return \ rate_monitor_excit, spike_monitor_excit, voltage_monitor_excit, idx_monitored_neurons_excit,\ rate_monitor_inhib, spike_monitor_inhib, voltage_monitor_inhib, idx_monitored_neurons_inhib,\ weight_profile_45
lsonGrp.m = 1. / (1 + exp(-(vu + 38.) / 7.)) lsonGrp.h = 1. / (1 + exp((vu + 65.) / 6.)) lsonGrp.n = (1 + exp(-(vu + 15) / 5.))**-0.5 lsonGrp.p = 1. / (1 + exp(-(vu + 23) / 6.)) lsonGrp.r = 1. / (1 + exp((vu + 76.) / 7.)) lsonGrp.w = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 lsonGrp.z = zss + ((1. - zss) / (1 + exp((vu + 71.) / 10.))) lsonGrp.a = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 lsonGrp.b = 1. / (1 + exp((vu + 66) / 7.))**0.5 lsonGrp.c = 1. / (1 + exp((vu + 66) / 7.))**0.5 lsonGrp.h1 = 1. / (1 + exp((vu + 66.) / 7.)) lsonGrp.h2 = 1. / (1 + exp((vu + 66.) / 7.)) lsonSynI = Synapses(gbCoSpkGenGrp, lsonGrp, model='''dg_i/dt = -g_i/tausI : siemens (clock-driven) gs_i_post = g_i : siemens (summed)''', on_pre='g_i += w_ilson*siemens', method='exact') lsonSynI.connect(i=np.arange(nGbcsCoPerLson), j=0) #lsonSynE = Synapses(sbIpSpkGenGrp, lsonGrp, # model='''dg_e/dt = -g_e/tausE : siemens (clock-driven) # gs_e_post = g_e : siemens (summed)''', # on_pre='g_e += w_elson*siemens', # method = 'exact') #lsonSynE.connect(i=np.arange(nSbcsIpPerLson), j=0) lsonSpks = SpikeMonitor(lsonGrp) lsonState = StateMonitor(lsonGrp, ['gs_e', 'Is_e', 'gs_i', 'Is_i', 'v'], record=True)
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 lson(lsoInputSpkFileTuple, temp_degC=37): defaultclock.dt = 0.02 * ms # for better precision neuron_type = 'type2' # medium-fast membrane f0 180-260Hz, CF4kHz #temp_degC=37. Vrest = -63.6 * mV # resting potential for type1c from RM2003 nLsons = 1 # number of LSO neurons nGbcsCo = 4 # nGbcsIp = 4 # nSbcsCo = 4 nSbcsIp = 4 # nSbcs = 4 # nAnfsPerSbc = 3 # nGbcs = 4 # nAnfsPerGbc=30 nAnfsPerInputFile = 40 nGbcsCoPerLson = 8 # Gjoni et al. 2018 nSbcsIpPerLson = 40 # Gjoni et al. 2018 # sbCoSpkFile = inputSpkFileTuple[0] # sbIpSpkFile = lsoInputSpkFileTuple[1] # gbCoSpkFile = lsoInputSpkFileTuple[2] # gbIpSpkFile = inputSpkFileTuple[3] anCoSpkFile = lsoInputSpkFileTuple[0] anIpSpkFile = lsoInputSpkFileTuple[1] # sbCoIdxSpktimeArray = np.loadtxt(sbCoSpkFile) # sbCoCellIndices = sbCoIdxSpktimeArray[:, 0].astype(int) # sbCoSpkTimes = sbCoIdxSpktimeArray[:, 1] * ms # sbCoSpkGenGrp = SpikeGeneratorGroup(nSbcsCo, sbCoCellIndices, sbCoSpkTimes) gbCoIdxSpktimeArray = np.loadtxt(anCoSpkFile) gbCoCellIndices = gbCoIdxSpktimeArray[:, 0].astype(int) # For now, spiketimes from Zilany AN in SECONDS, so * 1000*ms gbCoSpkTimes = gbCoIdxSpktimeArray[:, 1] * 1000. * ms gbCoSpkGenGrp = SpikeGeneratorGroup(nAnfsPerInputFile, gbCoCellIndices, gbCoSpkTimes) sbIpIdxSpktimeArray = np.loadtxt(anIpSpkFile) sbIpCellIndices = sbIpIdxSpktimeArray[:, 0].astype(int) # For now, spiketimes from Zilany AN in SECONDS, so * 1000*ms sbIpSpkTimes = sbIpIdxSpktimeArray[:, 1] * 1000. * ms sbIpSpkGenGrp = SpikeGeneratorGroup(nAnfsPerInputFile, sbIpCellIndices, sbIpSpkTimes) # gbIpIdxSpktimeArray = np.loadtxt(gbIpSpkFile) # gbIpCellIndices = gbIpIdxSpktimeArray[:, 0].astype(int) # gbIpSpkTimes = gbIpIdxSpktimeArray[:, 1] * ms # gbIpSpkGenGrp = SpikeGeneratorGroup(nGbcsIp, gbIpCellIndices, gbIpSpkTimes) # anfIdxSpktimeArray = np.loadtxt(anfSpkFile) # anfIndices = anfIdxSpktimeArray[:, 0].astype(int) # nANF = 132 # #anfSpkTimes = [i * second for i in anfIdxSpktimeArray[:, 1]] # anfSpkTimes = anfIdxSpktimeArray[:, 1] * 1000*ms # anfSpkGeneratorGrp = SpikeGeneratorGroup(nANF, anfIndices, anfSpkTimes) # Membrane and Ion-Channel parameters C = 12 * pF EH = -43 * mV EK = -70 * mV # -77*mV in mod file EL = -65 * mV ENa = 55 * mV # 55*mV in RM2003; 50*mv by Brette nf = 0.85 # proportion of n vs p kinetics zss = 0.5 # steady state inactivation of glt # default temp_degC = 37., human body temperature in degree celcius # q10 for ion-channel time-constants (RM2003, p.3106): q10 = 3.**((temp_degC - 22.) / 10.) # q10 for ion-channel gbar parameters (RM2003, p.3106): q10gbar = 2.**((temp_degC - 22.) / 10.) # hcno current (octopus cell) frac = 0.0 qt = 4.5**((temp_degC - 33.) / 10.) # Synaptic parameters: Es_e = 0. * mV tausE = 0.5 * ms Es_i = -90 * mV tausI = 1.0 * ms '''Synaptic weights are unitless according to Brian2. The effective unit is siemens, so they can work in amp, volt, siemens eqns. We multiply synaptic weight w_e by unit siemens when adding it to g_e. We use a local variable w_e for synaptic weight rather than the standard w:''' w_elson = 5e-9 w_ilson = 50e-9 # 6e-9 @ 200Hz; 12e-9 @ 600 Hz '''Here's why: The synapses sbc3SynE.w synaptic weight references the Same State Variable as as the neuron group sbc3Grp.w (klt activation w). Update sbc3Grp.w, and you set sbc3SynE.w to same value, and vice versa. This way klt activation and synaptic weight are identical and quite ridiculous. So use a local variable other than w for the synaptic weight!''' # Maximal conductances of different cell types in nS maximal_conductances = dict( type1c=(1000, 150, 0, 0, 0.5, 0, 2), type1t=(1000, 80, 0, 65, 0.5, 0, 2), type12=(1000, 150, 20, 0, 2, 0, 2), type21=(1000, 150, 35, 0, 3.5, 0, 2), type2=(1000, 150, 200, 0, 20, 0, 2), type2g1p5x=(1000, 150, 300, 0, 30, 0, 2), type2g0p5x=(1000, 150, 100, 0, 10, 0, 2), type2o=(1000, 150, 600, 0, 0, 40, 2) # octopus cell ) gnabar, gkhtbar, gkltbar, gkabar, ghbar, gbarno, gl = [ x * nS for x in maximal_conductances[neuron_type] ] # Classical Na channel eqs_na = """ ina = gnabar*m**3*h*(ENa-v) : amp dm/dt=q10*(minf-m)/mtau : 1 dh/dt=q10*(hinf-h)/htau : 1 minf = 1./(1+exp(-(vu + 38.) / 7.)) : 1 hinf = 1./(1+exp((vu + 65.) / 6.)) : 1 mtau = ((10. / (5*exp((vu+60.) / 18.) + 36.*exp(-(vu+60.) / 25.))) + 0.04)*ms : second htau = ((100. / (7*exp((vu+60.) / 11.) + 10.*exp(-(vu+60.) / 25.))) + 0.6)*ms : second """ # KHT channel (delayed-rectifier K+) eqs_kht = """ ikht = gkhtbar*(nf*n**2 + (1-nf)*p)*(EK-v) : amp dn/dt=q10*(ninf-n)/ntau : 1 dp/dt=q10*(pinf-p)/ptau : 1 ninf = (1 + exp(-(vu + 15) / 5.))**-0.5 : 1 pinf = 1. / (1 + exp(-(vu + 23) / 6.)) : 1 ntau = ((100. / (11*exp((vu+60) / 24.) + 21*exp(-(vu+60) / 23.))) + 0.7)*ms : second ptau = ((100. / (4*exp((vu+60) / 32.) + 5*exp(-(vu+60) / 22.))) + 5)*ms : second """ # Ih channel (subthreshold adaptive, non-inactivating) eqs_ih = """ ih = ghbar*r*(EH-v) : amp dr/dt=q10*(rinf-r)/rtau : 1 rinf = 1. / (1+exp((vu + 76.) / 7.)) : 1 rtau = ((100000. / (237.*exp((vu+60.) / 12.) + 17.*exp(-(vu+60.) / 14.))) + 25.)*ms : second """ # KLT channel (low threshold K+) eqs_klt = """ iklt = gkltbar*w**4*z*(EK-v) : amp dw/dt=q10*(winf-w)/wtau : 1 dz/dt=q10*(zinf-z)/ztau : 1 winf = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 : 1 zinf = zss + ((1.-zss) / (1 + exp((vu + 71.) / 10.))) : 1 wtau = ((100. / (6.*exp((vu+60.) / 6.) + 16.*exp(-(vu+60.) / 45.))) + 1.5)*ms : second ztau = ((1000. / (exp((vu+60.) / 20.) + exp(-(vu+60.) / 8.))) + 50)*ms : second """ # Ka channel (transient K+) eqs_ka = """ ika = gkabar*a**4*b*c*(EK-v): amp da/dt=q10*(ainf-a)/atau : 1 db/dt=q10*(binf-b)/btau : 1 dc/dt=q10*(cinf-c)/ctau : 1 ainf = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 : 1 binf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 cinf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 atau = ((100. / (7*exp((vu+60) / 14.) + 29*exp(-(vu+60) / 24.))) + 0.1)*ms : second btau = ((1000. / (14*exp((vu+60) / 27.) + 29*exp(-(vu+60) / 24.))) + 1)*ms : second ctau = ((90. / (1 + exp((-66-vu) / 17.))) + 10)*ms : second """ # Leak eqs_leak = """ ileak = gl*(EL-v) : amp """ # h current for octopus cells eqs_hcno = """ ihcno = gbarno*(h1*frac + h2*(1-frac))*(EH-v) : amp dh1/dt=(hinfno-h1)/tau1 : 1 dh2/dt=(hinfno-h2)/tau2 : 1 hinfno = 1./(1+exp((vu+66.)/7.)) : 1 tau1 = bet1/(qt*0.008*(1+alp1))*ms : second tau2 = bet2/(qt*0.0029*(1+alp2))*ms : second alp1 = exp(1e-3*3*(vu+50)*9.648e4/(8.315*(273.16+temp_degC))) : 1 bet1 = exp(1e-3*3*0.3*(vu+50)*9.648e4/(8.315*(273.16+temp_degC))) : 1 alp2 = exp(1e-3*3*(vu+84)*9.648e4/(8.315*(273.16+temp_degC))) : 1 bet2 = exp(1e-3*3*0.6*(vu+84)*9.648e4/(8.315*(273.16+temp_degC))) : 1 """ eqs = """ dv/dt = (ileak + ina + ikht + iklt + ika + ih + ihcno + I + Is_e + Is_i)/C : volt Is_e = gs_e * (Es_e - v) : amp gs_e : siemens Is_i = gs_i * (Es_i - v) : amp gs_i : siemens vu = v/mV : 1 # unitless v I : amp """ #Added Is_i to RM2003 eqs += eqs_leak + eqs_ka + eqs_na + eqs_ih + eqs_klt + eqs_kht + eqs_hcno lsonGrp = NeuronGroup(nLsons, eqs, method='exponential_euler', threshold='v > -30*mV', refractory='v > -45*mV') #gbcGrp.I = 2500.0*pA lsonGrp.I = 0.0 * pA # Initialize model near v_rest with no inputs lsonGrp.v = Vrest #vu = EL/mV # unitless v vu = lsonGrp.v / mV # unitless v lsonGrp.m = 1. / (1 + exp(-(vu + 38.) / 7.)) lsonGrp.h = 1. / (1 + exp((vu + 65.) / 6.)) lsonGrp.n = (1 + exp(-(vu + 15) / 5.))**-0.5 lsonGrp.p = 1. / (1 + exp(-(vu + 23) / 6.)) lsonGrp.r = 1. / (1 + exp((vu + 76.) / 7.)) lsonGrp.w = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 lsonGrp.z = zss + ((1. - zss) / (1 + exp((vu + 71.) / 10.))) lsonGrp.a = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 lsonGrp.b = 1. / (1 + exp((vu + 66) / 7.))**0.5 lsonGrp.c = 1. / (1 + exp((vu + 66) / 7.))**0.5 lsonGrp.h1 = 1. / (1 + exp((vu + 66.) / 7.)) lsonGrp.h2 = 1. / (1 + exp((vu + 66.) / 7.)) #lsonGrp.gs_e = 0.0*siemens #netGbcEq = Network(gbcGrp, report='text') #netGbcEq.run(50*ms, report='text') lsonSynI = Synapses(gbCoSpkGenGrp, lsonGrp, model='''dg_i/dt = -g_i/tausI : siemens (clock-driven) gs_i_post = g_i : siemens (summed)''', on_pre='g_i += w_ilson*siemens', method='exact') lsonSynI.connect(i=np.arange(nGbcsCoPerLson), j=0) lsonSynE = Synapses(sbIpSpkGenGrp, lsonGrp, model='''dg_e/dt = -g_e/tausE : siemens (clock-driven) gs_e_post = g_e : siemens (summed)''', on_pre='g_e += w_elson*siemens', method='exact') lsonSynE.connect(i=np.arange(nSbcsIpPerLson), j=0) lsonSpks = SpikeMonitor(lsonGrp) lsonState = StateMonitor(lsonGrp, ['v', 'gs_e'], record=True) run(300 * ms, report='text') # Console Output Won't Clear from Script # Memory issue with so many repeated simulations: # Comment out the plt commands #plt.plot(lsonState.t / ms, lsonState[0].v / mV) #plt.xlabel('t (ms)') #plt.ylabel('v (mV)') #plt.show() # Output file - EIPD in output filename. Spiketimes in file EPhsStrCo = anCoSpkFile[27:31] EPhsStrIp = anIpSpkFile[27:31] if (EPhsStrCo[0] == 'N'): EPhsIntCo = -1 * int(EPhsStrCo[1:4]) else: EPhsIntCo = int(EPhsStrCo[0:3]) if (EPhsStrIp[0] == 'N'): EPhsIntIp = -1 * int(EPhsStrIp[1:4]) else: EPhsIntIp = int(EPhsStrIp[0:3]) # EIPD = (EPhsIntCo - EPhsIntIp) % 360 EIPDint = (EPhsIntCo - EPhsIntIp) # unwrapped Envelope IPD #EIPDstr = str(EIPDint) if (EIPDint == 15): EIPDstr = 'EIPDP015' elif (EIPDint == 30): EIPDstr = 'EIPDP030' elif (EIPDint == 45): EIPDstr = 'EIPDP045' elif (EIPDint == 60): EIPDstr = 'EIPDP060' elif (EIPDint == 75): EIPDstr = 'EIPDP075' elif (EIPDint == 90): EIPDstr = 'EIPDP090' elif (EIPDint == -15): EIPDstr = 'EIPDN015' elif (EIPDint == -30): EIPDstr = 'EIPDN030' elif (EIPDint == -45): EIPDstr = 'EIPDN045' elif (EIPDint == -60): EIPDstr = 'EIPDN060' elif (EIPDint == -75): EIPDstr = 'EIPDN075' elif (EIPDint == -90): EIPDstr = 'EIPDN090' elif (EIPDint > 0): EIPDstr = 'EIPDP' + str(EIPDint) elif (EIPDint < 0): EIPDstr = 'EIPDN' + str(-EIPDint) elif (EIPDint == 0): EIPDstr = 'EIPDP000' # if (EIPDint < 0): # EIPDstr = EIPDstr.replace('-','N') # Synaptic parameters in output filename if (abs(round(tausE / ms) - (tausE / ms)) < 0.1): Te = str(round(tausE / ms)) else: Te = str(tausE / ms) Te = Te.replace('.', 'p') if (abs(round(w_elson / 1e-9) - (w_elson / 1e-9)) < 0.1): We = str(round(w_elson / 1e-9)) else: We = str(w_elson / 1e-9) We = We.replace('.', 'p') if (abs(round(tausI / ms) - (tausI / ms)) < 0.1): Ti = str(round(tausI / ms)) else: Ti = str(tausI / ms) Ti = Ti.replace('.', 'p') if (abs(round(w_ilson / 1e-9) - (w_ilson / 1e-9)) < 0.1): Wi = str(round(w_ilson / 1e-9)) else: Wi = str(w_ilson / 1e-9) Wi = Wi.replace('.', 'p') lsonSpkFile = 'Lso2SpTms' + anCoSpkFile[6:13] + anCoSpkFile[ 16: 23] + 'Te' + Te + 'We' + We + 'Ti' + Ti + 'Wi' + Wi + EIPDstr + 'Co' + anCoSpkFile[ 38:40] + anCoSpkFile[23:31] + anCoSpkFile[45:] file0 = open(lsonSpkFile, 'w') for index in range(len(lsonSpks.t)): file0.write( str(lsonSpks.i[index]) + " " + str(lsonSpks.t[index] / ms) + '\n') file0.close() return (lsonGrp, lsonSpks, lsonState) # end of mkgbcs
class BrianerClass(BaseClass): def default_init( self, _BrianingNeurongroupDict=None, _BrianingSynapsesDict=None, _BrianingConnectVariable=None, _BrianingTraceDict=None, _BrianingMoniterTuple=None, _BrianingSpikesDict=None, _BrianingPyplotDict=None, _BrianingTimeQuantityStr="ms", _BrianingPyplotBool=True, _BrianingStepTimeFloat=0.1, _BrianingDebugVariable=0, _BrianingRecordBool=True, _BrianedTimeQuantityVariable=None, _BrianedNetworkVariable=None, _BrianedNeurongroupVariable=None, _BrianedSynapsesVariable=None, _BrianedStateMonitorVariable=None, _BrianedSpikeMonitorVariable=None, _BrianedClockVariable=None, _BrianedParentSingularStr=None, _BrianedRecordKeyStrsList=None, _BrianedTraceDeriveBrianersList=None, _BrianedSynapsesDeriveBrianersList=None, _BrianedStateDeriveBrianersList=None, _BrianedSpikeDeriveBrianersList=None, _BrianedParentNetworkDeriveBrianerVariable=None, _BrianedParentPopulationDeriveBrianerVariable=None, _BrianedParentInteractomeDeriveBrianerVariable=None, _BrianedParentDeriveRecorderVariable=None, **_KwargVariablesDict ): # Call the parent __init__ method BaseClass.__init__(self, **_KwargVariablesDict) def do_brian(self): # /#################/# # Determine if it is an inside structure or the top # # debug """ self.debug( [ 'We brian here', 'First look for deeper teams in the structure', ] ) """ # Check if self.ParentedTotalSingularListDict != None and len(self.ParentedTotalSingularListDict) > 0: # debug """ self.debug( [ 'self.ParentedTotalSingularListDict.keys() is ', str(self.ParentedTotalSingularListDict.keys()) ] ) """ # get self.BrianedParentSingularStr = self.ParentedTotalSingularListDict.keys()[0] # debug """ self.debug( [ 'Ok', ('self.',self,[ 'BrianedParentSingularStr' ]) ] ) """ # /########################/# # Network level # # Check if ( self.ParentDeriveTeamerVariable == None or "Populations" in self.TeamDict or self.ParentDeriveTeamerVariable.TeamTagStr not in ["Clocks", "Traces", "Samples", "Events", "Interactomes", "Interactions"] ) and self.BrianedParentSingularStr != "Population": # debug """ self.debug( [ 'It is a Network level', 'We set the brian network' ] ) """ # set self.brianNetwork() # /########################/# # Special Network-Neurongroup level # # Check if "Populations" not in self.TeamDict: # debug """ self.debug( [ 'It is a network with a one level pop', 'So set the neurongroup' ] ) """ # brianPopulation self.brianPopulation() # debug """ self.debug( [ 'We end to set the neuron group here' ] ) """ # /########################/# # structure # # debug """ self.debug( [ 'We brian structure in all the brian children...', ] ) """ # structure self.structure( ["Clocks", "Populations", "Traces", "Events", "Samples", "Interactomes", "Interactions"], "#all", _ManagerCommandSetList=["brian"], ) # debug """ self.debug( [ 'Ok we have brian structured all the brian children...', ] ) """ else: # debug """ self.debug( [ 'Ok we check if this parentsingular has a special method ', ('self.',self,[ 'BrianedParentSingularStr' ]) ] ) """ # set BrianedMethodKeyStr = "brian" + self.BrianedParentSingularStr # Check if hasattr(self, BrianedMethodKeyStr): # /########################/# # call the special brian<BrianedParentSingularStr> method # # debug """ self.debug( [ 'It is a '+self.BrianedParentSingularStr+' level', 'We brian<BrianedParentSingularStr>' ] ) """ # call getattr(self, BrianedMethodKeyStr)() # debug """ self.debug( [ 'Ok we have setted brian'+self.BrianedParentSingularStr ] ) """ # debug """ self.debug( [ 'end of brian here' ] ) """ def brianNetwork(self): # /####################/# # init the Network # # maybe should import import brian2 # set self.BrianedNetworkVariable = brian2.Network() # get self.BrianedTimeQuantityVariable = getattr(brian2, self.BrianingTimeQuantityStr) # /####################/# # init a simulation clock # # debug """ self.debug( [ 'We set a simulation clock at least' ] ) """ # Check if "Clocks" not in self.TeamDict: ClocksDeriveManager = self.team("Clocks").TeamedValueVariable else: ClocksDeriveManager = self.TeamDict["Clocks"] # manage if "Simulation" not in ClocksDeriveManager.ManagementDict: # debug """ self.debug( [ 'We init a simulation clock here' ] ) """ # manage SimulationDeriveBrianer = ClocksDeriveManager.manage( "Simulation", {"BrianingStepTimeFloat": self.BrianingStepTimeFloat} ) def brianClock(self): # /####################/# # Determine the parents # # get self.BrianedParentNetworkDeriveBrianerVariable = self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable # /####################/# # Set the brian clock # # import from brian2 import Clock # debug """ self.debug( [ 'We set the brian clock', ('self.',self,['StructureTagStr']) ] ) """ # init self.BrianedClockVariable = Clock( dt=self.BrianingStepTimeFloat * self.BrianedParentNetworkDeriveBrianerVariable.BrianedTimeQuantityVariable, # name=self.StructureTagStr ) # debug """ self.debug( [ 'We have setted the clock', ('self.',self,[ 'BrianedClockVariable' ]) ] ) """ def brianPopulation(self): # debug """ self.debug( [ 'It is a Neurongroup level, we set the Neurongroup', 'We adapt the shape of BrianingNeurongroupDict', ('self.',self,[ 'BrianingNeurongroupDict', 'RecordingKeyVariable' ]) ] ) """ # /########################/# # Determine parents # # Check if self.ParentDeriveTeamerVariable != None: # set the parent self.BrianedParentNetworkDeriveBrianerVariable = self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable else: # set the parent self.BrianedParentNetworkDeriveBrianerVariable = self # /################/# # Adapt the arg # # Check if "N" not in self.BrianingNeurongroupDict: self.BrianingNeurongroupDict["N"] = 0 # Check if "model" not in self.BrianingNeurongroupDict: self.BrianingNeurongroupDict["model"] = "" # maybe should import from brian2 import NeuronGroup # debug """ self.debug( [ ('self.',self,[ 'BrianingNeurongroupDict' ]), 'We now set the model system Neurongroup if N>0 and model!=""' ] ) """ # /################/# # Set the brian neurongroup # # Check if self.BrianingNeurongroupDict["N"] > 0 and self.BrianingNeurongroupDict["model"] != "": # init self.BrianedNeurongroupVariable = NeuronGroup( **dict( self.BrianingNeurongroupDict, **{ #'name':self.ParentedTotalPathStr.replace('/','_')+'_'+self.ManagementTagStr, #'clock':self.BrianedParentNetworkDeriveBrianerVariable.TeamDict[ # 'Clocks' # ].ManagementDict['Simulation'].BrianedClockVariable } ) ) # debug """ self.debug( [ 'Ok we have setted the Neurongroup', ('self.',self,[ 'BrianedNeurongroupVariable' ]) ] ) """ # /##################/# # Define a debug # # Check if self.BrianingDebugVariable > 0: # import from brian2 import network_operation, ms @network_operation( dt=self.BrianingDebugVariable * self.BrianedParentNetworkDeriveBrianerVariable.BrianedTimeQuantityVariable ) def debugNeurongroup(): # init PrintStr = "At time t=" + str(self.BrianedNeurongroupVariable.clock.t) + ", \n" PrintStr += "In the NeuronGroup " + self.BrianedNeurongroupVariable.name + " : \n" # loop for __KeyStr in self.BrianedNeurongroupVariable.equations._equations.keys(): # set PrintStr += __KeyStr + " is " + str(getattr(self.BrianedNeurongroupVariable, __KeyStr)) + "\n" # add PrintStr += "\n" # print print PrintStr # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(debugNeurongroup) # Check if self.BrianingNeurongroupDict["N"] > 0: # /##################/# # team States first all the brian variables # # get self.BrianedRecordKeyStrsList = self.BrianedNeurongroupVariable.equations._equations.keys() # Check if len(self.BrianedRecordKeyStrsList) > 0: # debug """ self.debug( [ 'We simulate with neurongroup', 'adapt the initial conditions of all the brian variables', 'so first we team Traces and put Recorders inside or get it and mapSet' ] ) """ # Check if "Traces" not in self.TeamDict: BrianedDeriveTraces = self.team("Traces").TeamedValueVariable else: BrianedDeriveTraces = self.TeamDict["Traces"] # debug """ self.debug( [ 'We set the tracers', ('self.',self,['BrianedRecordKeyStrsList']) ] ) """ # map self.BrianedTraceDeriveBrianersList = map( lambda __ManagementKeyStr, __RecordKeyStr: BrianedDeriveTraces.manage( __ManagementKeyStr, { "RecordingKeyVariable": getattr(self.BrianedNeurongroupVariable, __RecordKeyStr), "RecordKeyStr": __RecordKeyStr, }, ).ManagedValueVariable if __ManagementKeyStr not in BrianedDeriveTraces.ManagementDict else BrianedDeriveTraces.ManagementDict[__ManagementKeyStr].mapSet( { "RecordingKeyVariable": getattr(self.BrianedNeurongroupVariable, __RecordKeyStr), "RecordKeyStr": __RecordKeyStr, } ), map( lambda __BrianedRecordKeyStr: Recorder.RecordPrefixStr + __BrianedRecordKeyStr, self.BrianedRecordKeyStrsList, ), self.BrianedRecordKeyStrsList, ) # /##################/# # add in the net # # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(self.BrianedNeurongroupVariable) """ #/####################/# # maybe view a draw plot # #call self.viewPopulation() """ # debug """ self.debug( [ 'End of brianPopulation' ] ) """ def brianInteraction(self): # /########################/# # Postlet level # # debug """ self.debug( [ 'It is an Interaction level', ('self.',self,[ #'BrianingSynapsesDict' ] ) ] ) """ # /####################/# # Set the parent # # Check if self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable.BrianedParentSingularStr == "Interactome": # debug """ self.debug( [ 'We are in a projectome structure' ] ) """ # set self.BrianedParentInteractomeDeriveBrianerVariable = ( self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable ) # get self.BrianedParentPopulationDeriveBrianerVariable = ( self.BrianedParentInteractomeDeriveBrianerVariable.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable ) else: # debug """ self.debug( [ 'There is no projectome structure' ] ) """ # get self.BrianedParentPopulationDeriveBrianerVariable = ( self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable ) # get self.BrianedParentNetworkDeriveBrianerVariable = ( self.BrianedParentPopulationDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable ) # /####################/# # Set the ConnectedTo Variable # # debug """ self.debug( [ 'Check if we have to get the connected to variable', ('self.',self,['ConnectedToVariable']) ] ) """ # Check if self.ConnectedToVariable == None: # debug """ self.debug( [ 'We setConnection here' ] ) """ # setConnection self.setConnection(self.ManagementTagStr, self, self.BrianedParentPopulationDeriveBrianerVariable) # /####################/# # Set the BrianedParentPopulationDeriveBrianerVariable # # debug """ self.debug( [ 'Do we have to make parent-brian the connected variable ?', 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable) ] ) """ # Check if self.ConnectedToVariable.BrianedNeurongroupVariable == None: # parent brian self.ConnectedToVariable.parent().brian() # set BrianedNameStr = ( self.BrianedParentPopulationDeriveBrianerVariable.StructureTagStr + "_To_" + self.ConnectedToVariable.StructureTagStr ) # debug """ self.debug( [ 'We set the synapses', 'self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable is ', str(self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable), 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable), 'Maybe we have to make brian the post', 'BrianedNameStr is '+BrianedNameStr ] ) """ # import from brian2 import Synapses # init self.BrianedSynapsesVariable = Synapses( source=self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable, target=self.ConnectedToVariable.BrianedNeurongroupVariable, # name=BrianedNameStr.replace('/','_'), **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) # /####################/# # add to the structure # # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(self.BrianedSynapsesVariable) # /##################/# # Define a debug # # Check if self.BrianingDebugVariable > 0: # import from brian2 import network_operation, ms @network_operation( dt=self.BrianingDebugVariable * self.BrianedParentNetworkDeriveBrianerVariable.BrianedTimeQuantityVariable ) def debugSynapses(): # init PrintStr = "At time t=" + str(self.BrianedSynapsesVariable.clock.t) + ", \n" PrintStr += "In the Synapses " + self.BrianedSynapsesVariable.name + " : \n" # loop for __KeyStr in self.BrianedSynapsesVariable.equations._equations.keys(): # set PrintStr += __KeyStr + " is " + str(getattr(self.BrianedSynapsesVariable, __KeyStr)) + "\n" # add PrintStr += "\n" # print print PrintStr # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(debugSynapses) def brianTrace(self): # debug """ self.debug( [ 'It is a Trace level, we set the Samples', ('self.',self,[ #'RecordingKeyVariable', 'RecordKeyStr' ]) ] ) """ # /####################/# # Set the parent # # get self.BrianedParentPopulationDeriveBrianerVariable = self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable # get self.BrianedParentNetworkDeriveBrianerVariable = ( self.BrianedParentPopulationDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable ) # Check if self.BrianedParentPopulationDeriveBrianerVariable.BrianingNeurongroupDict["N"] > 0: # /####################/# # we record # # Check if self.BrianingRecordBool: # debug """ self.debug( [ 'We record here' ] ) """ # record self.record() # /###################/# # Build the samples and maybe one default moniter # # debug """ self.debug( [ 'Look if we have samples here', "'Samples' not in self.TeamDict is ", str('Samples' not in self.TeamDict) ] ) """ # Check if "Samples" not in self.TeamDict: BrianedSamplesDeriveManager = self.team("Samples").TeamedValueVariable else: BrianedSamplesDeriveManager = self.TeamDict["Samples"] # debug """ self.debug( [ 'Do we have to set a default moniter ?', #'len(self.BrianedParentPopulationDeriveBrianerVariable.BrianedRecordKeyStrsList) is ', #str(len(self.BrianedParentPopulationDeriveBrianerVariable.BrianedRecordKeyStrsList)), 'self.BrianedParentPopulationDeriveBrianerVariable.BrianedRecordKeyStrsList) is ', str(self.BrianedParentPopulationDeriveBrianerVariable.BrianedRecordKeyStrsList), ] ) """ # Check if len(self.BrianedParentPopulationDeriveBrianerVariable.BrianedRecordKeyStrsList) == 1: # debug """ self.debug( [ 'BrianedSamplesDeriveManager.ManagementDict.keys() is', str(BrianedSamplesDeriveManager.ManagementDict.keys()) ] ) """ # Check if len(BrianedSamplesDeriveManager.ManagementDict) == 0 or ( len(BrianedSamplesDeriveManager.ManagementDict) == 1 and "Default" in BrianedSamplesDeriveManager.ManagementDict ): # debug """ self.debug( [ 'There is just one variable that we sample', 'we manage and make it brian' ] ) """ # manage BrianedDefaultBrianer = BrianedSamplesDeriveManager.manage("Default").ManagedValueVariable # Check if BrianedDefaultBrianer.RecordingLabelVariable == None: # Check if self.BrianedParentPopulationDeriveBrianerVariable.RecordingLabelVariable != None: # get BrianedDefaultBrianer.RecordingLabelVariable = ( self.BrianedParentPopulationDeriveBrianerVariable.RecordingLabelVariable ) else: # set the record labels BrianedDefaultBrianer.RecordingLabelVariable = ( [0] if self.BrianedParentPopulationDeriveBrianerVariable.BrianingNeurongroupDict["N"] > 0 else [] ) # brian BrianedDefaultBrianer.parent().brian() def brianSample(self): # debug """ self.debug( [ 'It is a Sample State Moniter level', ('self.',self,[ 'RecordingLabelVariable', ]) ] ) """ # /####################/# # Set the parent # # get self.BrianedParentDeriveRecorderVariable = self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable # get self.BrianedParentPopulationDeriveBrianerVariable = ( self.BrianedParentDeriveRecorderVariable.BrianedParentPopulationDeriveBrianerVariable ) # get self.BrianedParentNetworkDeriveBrianerVariable = ( self.BrianedParentPopulationDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable ) # Check if self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable != None: # /####################/# # Set the brian monitor # # debug """ self.debug( [ 'We set the state monitor', ('self.',self,[ #'BrianedParentPopulationDeriveBrianerVariable' ]), #'self.BrianedParentDeriveRecorderVariable.RecordKeyStr is ', #str(self.BrianedParentDeriveRecorderVariable.RecordKeyStr) 'self.ParentedTotalManagementOrderedDict.keys() is ', str(self.ParentedTotalManagementOrderedDict.keys()) ] ) """ # import from brian2 import StateMonitor # init self.BrianedStateMonitorVariable = StateMonitor( self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable, self.BrianedParentDeriveRecorderVariable.RecordKeyStr, self.RecordingLabelVariable, ) # debug """ self.debug( [ 'Ok we have setted the monitor', ('self.',self,['BrianedStateMonitorVariable']), 'Now we add to the structure', 'self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable is ', str(self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable) ] ) """ # /####################/# # add to the structure # # debug """ self.debug( [ 'We add to the structure' ] ) """ # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(self.BrianedStateMonitorVariable) """ #/####################/# # maybe view a draw plot # #call self.viewSample() """ def brianEvent(self): # debug """ self.debug( [ 'It is a Spike Moniter level', ('self.',self,[ ]) ] ) """ # /####################/# # Set the BrianedParentPopulationDeriveBrianerVariable # # get self.BrianedParentPopulationDeriveBrianerVariable = self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable # get self.BrianedParentNetworkDeriveBrianerVariable = ( self.BrianedParentPopulationDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable ) # Check if self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable != None: # /####################/# # Set the brian monitor # # debug """ self.debug( [ 'We set the spike monitor' ] ) """ # import from brian2 import SpikeMonitor # init self.BrianedSpikeMonitorVariable = SpikeMonitor( self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable ) # debug """ self.debug( [ 'Ok we have setted the monitor', ('self.',self,['BrianedSpikeMonitorVariable']), 'Now we add to the structure', 'self.BrianedParentPopulationDeriveBrianerVariable.BrianedNetworkVariable is ', str(self.BrianedParentPopulationDeriveBrianerVariable.BrianedNetworkVariable) ] ) """ # /####################/# # add to the structure # # add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add(self.BrianedSpikeMonitorVariable) """ #/####################/# # maybe view a draw plot # #call self.viewEvent() """ def mimic_view(self): # /########################/# # Network level # # Check if ( self.ParentDeriveTeamerVariable == None or "Populations" in self.TeamDict or self.ParentDeriveTeamerVariable.TeamTagStr not in ["Clocks", "Traces", "Samples", "Events", "Interactomes", "Interactions"] ) and self.BrianedParentSingularStr != "Population": # debug """ self.debug( [ 'It is a Network level', 'We sructure view' ] ) """ # /########################/# # structure # # debug """ self.debug( [ 'We view structure in all the brian children...', ] ) """ # structure self.structure( ["Clocks", "Populations", "Traces", "Events", "Samples", "Interactomes", "Interactions"], "#all", _ManagerCommandSetList=["view"], ) # debug """ self.debug( [ 'Ok we have view structured all the brian children...', ] ) """ else: # debug """ self.debug( [ 'Ok we check if this parentsingular has a special method ', ('self.',self,[ 'BrianedParentSingularStr' ]) ] ) """ # set BrianedMethodKeyStr = "view" + self.BrianedParentSingularStr # Check if hasattr(self, BrianedMethodKeyStr): # /########################/# # call the special view<BrianedParentSingularStr> method # # debug """ self.debug( [ 'It is a '+self.BrianedParentSingularStr+' level', 'We view<BrianedParentSingularStr>' ] ) """ # call getattr(self, BrianedMethodKeyStr)() # debug """ self.debug( [ 'Ok we have setted view'+self.BrianedParentSingularStr ] ) """ def viewPopulation(self): # debug """ self.debug( [ 'We complete a view so first fill the draw' ] ) """ # Check if "Charts" not in self.TeamDict: BrianedChartsDeriveTeamer = self.team("Charts").TeamedValueVariable else: BrianedChartsDeriveTeamer = self.TeamDict["Charts"] def viewSample(self): # debug self.debug( [ "We complete a view so first fill the draw", ("self.", self, ["RecordingLabelVariable", "ViewedLegendLabelStr"]), ] ) # /##################/# # Determine the way of labeling the variable names # # set if self.ViewedLegendLabelStr == "": # set self.ViewedLegendLabelStr = "$" + self.BrianedParentDeriveRecorderVariable.RecordKeyStr """ self.ViewedLegendLabelStr+='_{'+str( #self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable.name #self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable. ).replace('_','/')+'}' """ # debug self.debug(["We have specified the legend label", ("self.", self, ["ViewedLegendLabelStr"])]) # set self.PyplotingDrawVariable = map( lambda __IndexInt: ( "plot", { "#liarg:#map@get": [ "#IdGetStr.BrianedStateMonitorVariable.t", ">>SYS.IdDict[#IdStr].BrianedStateMonitorVariable." + self.BrianedParentDeriveRecorderVariable.RecordKeyStr + "[" + str(__IndexInt) + ",:]", ], "#kwarg": dict( { "label": self.ViewedLegendLabelStr + "^{" + str(__IndexInt) + "}$", "linestyle": "-", "color": "b", }, **self.BrianingPyplotDict ), }, ), self.RecordingLabelVariable, ) # /####################/# # maybe set for the Chart # # init self.PyplotingChartVariable = [] # /####################/# # maybe set the X Chart also # # get BrianedTimeUnit = self.BrianedStateMonitorVariable.t.unit # scale # self.ViewingXVariable=self.BrianedStateMonitorVariable.t[:] self.ViewingXVariable = self.BrianedStateMonitorVariable.t / ( # (1./self.ViewingXScaleFloat)*BrianedTimeUnit BrianedTimeUnit ) # set self.ViewingXLabelStr = "$t\ (" + str((1.0 / self.ViewingXScaleFloat) * BrianedTimeUnit).split(".")[-1] + ")$" # /####################/# # maybe set the Y Chart also # # debug self.debug( [ "We set the y axis", "self.BrianedParentDeriveRecorderVariable.RecordedTraceFloatsArray is ", str(self.BrianedParentDeriveRecorderVariable.RecordedTraceFloatsArray), ] ) # import import brian2 # get ViewingYVariable = getattr( self.BrianedStateMonitorVariable, self.BrianedParentDeriveRecorderVariable.RecordKeyStr ) # split # BrianedDimensionStr=str(ViewingYVariable).split(' ')[-1] BrianedActivityUnit = getattr( self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable, self.BrianedParentDeriveRecorderVariable.RecordKeyStr, ).unit # divide # self.ViewingYVariable=ViewingYVariable/getattr( # brian2,BrianedDimensionStr # ) self.ViewingYVariable = ViewingYVariable / (BrianedActivityUnit) # self.ViewingYVariable=ViewingYVariable self.ViewingYVariable = self.ViewingYVariable[:] print (self.ViewingYVariable) # set self.ViewingYLabelStr = "$" + self.BrianedParentDeriveRecorderVariable.RecordKeyStr """ self.ViewingYLabelStr+='_{'+str( self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable.name ).replace('_','/')+'}(t)\ ('+str( self.BrianedParentDeriveRecorderVariable.RecordedTraceFloatsArray.unit )+')' """ # self.ViewingYLabelStr+='\ ('+BrianedDimensionStr+')' self.ViewingYLabelStr += "\ (" + str((1.0 / self.ViewingYScaleFloat) * BrianedActivityUnit).split(".")[-1] + ")" self.ViewingYLabelStr += "$" # /################/# # call the base view method # # debug self.debug([("self.", self, ["ViewingXVariable", "ViewingYVariable"]), "Now we call the view"]) # call BaseClass.view(self) # /####################/# # maybe set global Chart also # self.PyplotingChartVariable += [ ("tick_params", {"#kwarg": {"length": 10, "width": 5, "which": "major"}}), ("tick_params", {"#kwarg": {"length": 5, "width": 2, "which": "minor"}}), ("xaxis.set_ticks_position", {"#liarg": ["bottom"]}), ("yaxis.set_ticks_position", {"#liarg": ["left"]}), ( "legend", { "#liarg": [], "#kwarg": { "fontsize": 10, "shadow": True, "fancybox": True, "ncol": max( 1, len( getattr( self.BrianedStateMonitorVariable, self.BrianedParentDeriveRecorderVariable.RecordKeyStr, ) ) / 2, ), "loc": 2, "bbox_to_anchor": (1.05, 1), }, }, ), ] # /####################/# # maybe replace Chart also # # debug """ self.debug( [ 'Before replace', ('self.',self,[ 'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) """ # mapReplace [self.PyplotingDrawVariable, self.PyplotingChartVariable] = map( lambda __Variable: SYS.replace( __Variable, {"#IdStr": str(self.PrintIdInt), "#IdGetStr": "#id:" + str(self.PrintIdInt)}, self ) if __Variable != None else None, map(lambda __KeyStr: getattr(self, __KeyStr), ["PyplotingDrawVariable", "PyplotingChartVariable"]), ) # debug """ self.debug( [ 'After replace', ('self.',self,[ #'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) """ # /####################/# # Update maybe the # parent neuron group # debug self.debug(["Maybe we also update the view in the parent population"]) # Check if "Charts" in self.BrianedParentPopulationDeriveBrianerVariable.TeamDict: # get BrianedChartsDeriveManager = self.BrianedParentPopulationDeriveBrianerVariable.TeamDict["Charts"] # manage BrianedChartDerivePyploter = BrianedChartsDeriveManager.manage( self.BrianedParentDeriveRecorderVariable.ManagementTagStr ).ManagedValueVariable # debug """ self.debug( [ 'We update in the parent neurongroup chart', 'BrianedChartDerivePyploter is ', SYS._str(BrianedChartDerivePyploter), ('self.',self,[]) ] ) """ # team BrianedDrawDeriveManager = BrianedChartDerivePyploter.team("Draws").TeamedValueVariable # manage BrianedDrawDeriveManager.manage( str(self.ManagementIndexInt), {"PyplotingDrawVariable": self.PyplotingDrawVariable} ) def viewEvent(self): # debug """ self.debug( [ 'We complete a view so first fill the draw' ] ) """ # set self.ViewedLabelStr = ( "$" + self.ManagementTagStr + "_{" + str(self.BrianedParentPopulationDeriveBrianerVariable.BrianedNeurongroupVariable.name).replace("_", "/") + "}" ) # set self.PyplotingDrawVariable = [ ( "plot", { "#liarg:#map@get": [ "#IdGetStr.BrianedSpikeMonitorVariable.t", ">>SYS.IdDict[#IdStr].BrianedSpikeMonitorVariable.i", ], "#kwarg": dict( {"label": self.ViewedLabelStr, "linestyle": "", "marker": ".", "color": "b"}, **self.BrianingPyplotDict ), }, ) ] # /####################/# # maybe replace Chart also # # debug """ self.debug( [ 'Before replace', ('self.',self,[ 'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) """ # mapReplace [self.PyplotingDrawVariable, self.PyplotingChartVariable] = map( lambda __Variable: SYS.replace( __Variable, {"#IdStr": str(self.PrintIdInt), "#IdGetStr": "#id:" + str(self.PrintIdInt)}, self ) if __Variable != None else None, map(lambda __KeyStr: getattr(self, __KeyStr), ["PyplotingDrawVariable", "PyplotingChartVariable"]), ) # debug """ self.debug( [ 'After replace', ('self.',self,[ #'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) """ # /####################/# # Update maybe the # parent neuron group # get BrianedChartDeriveManager = self.BrianedParentPopulationDeriveBrianerVariable.TeamDict["Charts"] # manage BrianedChartDerivePyploter = BrianedChartDeriveManager.manage(self.ManagementTagStr).ManagedValueVariable # debug """ self.debug( [ 'We update in the parent neurongroup chart', 'BrianedChartDerivePyploter is ', SYS._str(BrianedChartDerivePyploter), ('self.',self,[]) ] ) """ # team BrianedDrawDeriveManager = BrianedChartDerivePyploter.team("Draws").TeamedValueVariable # manage BrianedDrawDeriveManager.manage( str(self.ManagementIndexInt), {"PyplotingDrawVariable": self.PyplotingDrawVariable} ) 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.BrianedTimeQuantityVariable) # debug """ self.debug('We stop running in brian') """ def mimic_record(self): # base method BaseClass.record(self) # debug """ self.debug( [ 'We have traced, alias the init in the brian object', ('self.',self,[ 'RecordedTraceFloatsArray', 'RecordedInitFloatsArray' ]) ] ) """ # alias self.RecordedTraceFloatsArray[:] = self.RecordedInitFloatsArray * self.RecordedTraceFloatsArray.unit # debug """ self.debug( [ ('self.',self,['RecordedTraceFloatsArray']) ] ) """ def mimic__print(self, **_KwargVariablesDict): # /##################/# # Modify the printing Variable # # Check if self.PrintingSelfBool: # /##################/# # Remove the brian objects that are non setted # # map map( lambda __KeyStr: self.forcePrint([__KeyStr], "BrianerClass") if getattr(self.PrintingCopyVariable, __KeyStr) != None else None, [ "BrianedNetworkVariable", "BrianedNeurongroupVariable", "BrianedSynapsesVariable", "BrianedStateMonitorVariable", "BrianedSpikeMonitorVariable", "BrianedClockVariable", ], ) # /##################/# # Call the base method # # call BaseClass._print(self, **_KwargVariablesDict)
def sim_decision_making_network( N_Excit=384, N_Inhib=96, weight_scaling_factor=5.33, t_stimulus_start=100 * b2.ms, t_stimulus_duration=9999 * b2.ms, coherence_level=0., stimulus_update_interval=30 * b2.ms, mu0_mean_stimulus_Hz=160., stimulus_std_Hz=20., N_extern=1000, firing_rate_extern=9.8 * b2.Hz, w_pos=1.90, f_Subpop_size=0.25, # .15 in publication [1] max_sim_time=1000. * b2.ms, stop_condition_rate=None, monitored_subset_size=512): """ Args: N_Excit (int): total number of neurons in the excitatory population N_Inhib (int): nr of neurons in the inhibitory populations weight_scaling_factor: When increasing the number of neurons by 2, the weights should be scaled down by 1/2 t_stimulus_start (Quantity): time when the stimulation starts t_stimulus_duration (Quantity): duration of the stimulation coherence_level (int): coherence of the stimulus. Difference in mean between the PoissonGroups "left" stimulus and "right" stimulus stimulus_update_interval (Quantity): the mean of the stimulating PoissonGroups is re-sampled at this interval mu0_mean_stimulus_Hz (float): maximum mean firing rate of the stimulus if c=+1 or c=-1. Each neuron in the populations "Left" and "Right" receives an independent poisson input. stimulus_std_Hz (float): std deviation of the stimulating PoissonGroups. N_extern (int): nr of neurons in the stimulus independent poisson background population firing_rate_extern (int): firing rate of the stimulus independent poisson background population w_pos (float): Scaling (strengthening) of the recurrent weights within the subpopulations "Left" and "Right" f_Subpop_size (float): fraction of the neurons in the subpopulations "Left" and "Right". #left = #right = int(f_Subpop_size*N_Excit). max_sim_time (Quantity): simulated time. stop_condition_rate (Quantity): An optional stopping criteria: If not None, the simulation stops if the firing rate of either subpopulation "Left" or "Right" is above stop_condition_rate. monitored_subset_size (int): max nr of neurons for which a state monitor is registered. Returns: A dictionary with the following keys (strings): "rate_monitor_A", "spike_monitor_A", "voltage_monitor_A", "idx_monitored_neurons_A", "rate_monitor_B", "spike_monitor_B", "voltage_monitor_B", "idx_monitored_neurons_B", "rate_monitor_Z", "spike_monitor_Z", "voltage_monitor_Z", "idx_monitored_neurons_Z", "rate_monitor_inhib", "spike_monitor_inhib", "voltage_monitor_inhib", "idx_monitored_neurons_inhib" """ print("simulating {} neurons. Start: {}".format(N_Excit + N_Inhib, time.ctime())) t_stimulus_end = t_stimulus_start + t_stimulus_duration N_Group_A = int( N_Excit * f_Subpop_size ) # size of the excitatory subpopulation sensitive to stimulus A N_Group_B = N_Group_A # size of the excitatory subpopulation sensitive to stimulus B N_Group_Z = N_Excit - N_Group_A - N_Group_B # (1-2f)Ne excitatory neurons do not respond to either stimulus. Cm_excit = 0.5 * b2.nF # membrane capacitance of excitatory neurons G_leak_excit = 25.0 * b2.nS # leak conductance E_leak_excit = -70.0 * b2.mV # reversal potential v_spike_thr_excit = -50.0 * b2.mV # spike condition v_reset_excit = -60.0 * b2.mV # reset voltage after spike t_abs_refract_excit = 2. * b2.ms # absolute refractory period # specify the inhibitory interneurons: # N_Inhib = 200 Cm_inhib = 0.2 * b2.nF G_leak_inhib = 20.0 * b2.nS E_leak_inhib = -70.0 * b2.mV v_spike_thr_inhib = -50.0 * b2.mV v_reset_inhib = -60.0 * b2.mV t_abs_refract_inhib = 1.0 * b2.ms # specify the AMPA synapses E_AMPA = 0.0 * b2.mV tau_AMPA = 2.5 * b2.ms # specify the GABA synapses E_GABA = -70.0 * b2.mV tau_GABA = 5.0 * b2.ms # specify the NMDA synapses E_NMDA = 0.0 * b2.mV tau_NMDA_s = 100.0 * b2.ms tau_NMDA_x = 2. * b2.ms alpha_NMDA = 0.5 * b2.kHz # projections from the external population g_AMPA_extern2inhib = 1.62 * b2.nS g_AMPA_extern2excit = 2.1 * b2.nS # projectsions from the inhibitory populations g_GABA_inhib2inhib = weight_scaling_factor * 1.25 * b2.nS g_GABA_inhib2excit = weight_scaling_factor * 1.60 * b2.nS # projections from the excitatory population g_AMPA_excit2excit = weight_scaling_factor * 0.012 * b2.nS g_AMPA_excit2inhib = weight_scaling_factor * 0.015 * b2.nS g_NMDA_excit2excit = weight_scaling_factor * 0.040 * b2.nS g_NMDA_excit2inhib = weight_scaling_factor * 0.045 * b2.nS # stronger projection to inhib. # weights and "adjusted" weights. w_neg = 1. - f_Subpop_size * (w_pos - 1.) / (1. - f_Subpop_size) # We use the same postsyn AMPA and NMDA conductances. Adjust the weights coming from different sources: w_ext2inhib = g_AMPA_extern2inhib / g_AMPA_excit2inhib w_ext2excit = g_AMPA_extern2excit / g_AMPA_excit2excit # other weights are 1 # print("w_neg={}, w_ext2inhib={}, w_ext2excit={}".format(w_neg, w_ext2inhib, w_ext2excit)) # Define the inhibitory population # dynamics: inhib_lif_dynamics = """ s_NMDA_total : 1 # the post synaptic sum of s. compare with s_NMDA_presyn dv/dt = ( - G_leak_inhib * (v-E_leak_inhib) - g_AMPA_excit2inhib * s_AMPA * (v-E_AMPA) - g_GABA_inhib2inhib * s_GABA * (v-E_GABA) - g_NMDA_excit2inhib * s_NMDA_total * (v-E_NMDA)/(1.0+1.0*exp(-0.062*v/volt)/3.57) )/Cm_inhib : volt (unless refractory) ds_AMPA/dt = -s_AMPA/tau_AMPA : 1 ds_GABA/dt = -s_GABA/tau_GABA : 1 """ inhib_pop = NeuronGroup(N_Inhib, model=inhib_lif_dynamics, threshold="v>v_spike_thr_inhib", reset="v=v_reset_inhib", refractory=t_abs_refract_inhib, method="rk2") # initialize with random voltages: inhib_pop.v = rnd.uniform(v_spike_thr_inhib / b2.mV - 4., high=v_spike_thr_inhib / b2.mV - 1., size=N_Inhib) * b2.mV # Specify the excitatory population: # dynamics: excit_lif_dynamics = """ s_NMDA_total : 1 # the post synaptic sum of s. compare with s_NMDA_presyn dv/dt = ( - G_leak_excit * (v-E_leak_excit) - g_AMPA_excit2excit * s_AMPA * (v-E_AMPA) - g_GABA_inhib2excit * s_GABA * (v-E_GABA) - g_NMDA_excit2excit * s_NMDA_total * (v-E_NMDA)/(1.0+1.0*exp(-0.062*v/volt)/3.57) )/Cm_excit : volt (unless refractory) ds_AMPA/dt = -s_AMPA/tau_AMPA : 1 ds_GABA/dt = -s_GABA/tau_GABA : 1 ds_NMDA/dt = -s_NMDA/tau_NMDA_s + alpha_NMDA * x * (1-s_NMDA) : 1 dx/dt = -x/tau_NMDA_x : 1 """ # define the three excitatory subpopulations. # A: subpop receiving stimulus A excit_pop_A = NeuronGroup(N_Group_A, model=excit_lif_dynamics, threshold="v>v_spike_thr_excit", reset="v=v_reset_excit", refractory=t_abs_refract_excit, method="rk2") excit_pop_A.v = rnd.uniform(E_leak_excit / b2.mV, high=E_leak_excit / b2.mV + 5., size=excit_pop_A.N) * b2.mV # B: subpop receiving stimulus B excit_pop_B = NeuronGroup(N_Group_B, model=excit_lif_dynamics, threshold="v>v_spike_thr_excit", reset="v=v_reset_excit", refractory=t_abs_refract_excit, method="rk2") excit_pop_B.v = rnd.uniform(E_leak_excit / b2.mV, high=E_leak_excit / b2.mV + 5., size=excit_pop_B.N) * b2.mV # Z: non-sensitive excit_pop_Z = NeuronGroup(N_Group_Z, model=excit_lif_dynamics, threshold="v>v_spike_thr_excit", reset="v=v_reset_excit", refractory=t_abs_refract_excit, method="rk2") excit_pop_Z.v = rnd.uniform(v_reset_excit / b2.mV, high=v_spike_thr_excit / b2.mV - 1., size=excit_pop_Z.N) * b2.mV # now define the connections: # projections FROM EXTERNAL POISSON GROUP: #################################################### poisson2Inhib = PoissonInput(target=inhib_pop, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2inhib) poisson2A = PoissonInput(target=excit_pop_A, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2excit) poisson2B = PoissonInput(target=excit_pop_B, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2excit) poisson2Z = PoissonInput(target=excit_pop_Z, target_var="s_AMPA", N=N_extern, rate=firing_rate_extern, weight=w_ext2excit) ############################################################################################### # GABA projections FROM INHIBITORY population: ################################################ syn_inhib2inhib = Synapses(inhib_pop, target=inhib_pop, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2inhib.connect(p=1.) syn_inhib2A = Synapses(inhib_pop, target=excit_pop_A, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2A.connect(p=1.) syn_inhib2B = Synapses(inhib_pop, target=excit_pop_B, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2B.connect(p=1.) syn_inhib2Z = Synapses(inhib_pop, target=excit_pop_Z, on_pre="s_GABA += 1.0", delay=0.5 * b2.ms) syn_inhib2Z.connect(p=1.) ############################################################################################### # AMPA projections FROM EXCITATORY A: ######################################################### syn_AMPA_A2A = Synapses(excit_pop_A, target=excit_pop_A, on_pre="s_AMPA += w_pos", delay=0.5 * b2.ms) syn_AMPA_A2A.connect(p=1.) syn_AMPA_A2B = Synapses(excit_pop_A, target=excit_pop_B, on_pre="s_AMPA += w_neg", delay=0.5 * b2.ms) syn_AMPA_A2B.connect(p=1.) syn_AMPA_A2Z = Synapses(excit_pop_A, target=excit_pop_Z, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_A2Z.connect(p=1.) syn_AMPA_A2inhib = Synapses(excit_pop_A, target=inhib_pop, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_A2inhib.connect(p=1.) ############################################################################################### # AMPA projections FROM EXCITATORY B: ######################################################### syn_AMPA_B2A = Synapses(excit_pop_B, target=excit_pop_A, on_pre="s_AMPA += w_neg", delay=0.5 * b2.ms) syn_AMPA_B2A.connect(p=1.) syn_AMPA_B2B = Synapses(excit_pop_B, target=excit_pop_B, on_pre="s_AMPA += w_pos", delay=0.5 * b2.ms) syn_AMPA_B2B.connect(p=1.) syn_AMPA_B2Z = Synapses(excit_pop_B, target=excit_pop_Z, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_B2Z.connect(p=1.) syn_AMPA_B2inhib = Synapses(excit_pop_B, target=inhib_pop, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_B2inhib.connect(p=1.) ############################################################################################### # AMPA projections FROM EXCITATORY Z: ######################################################### syn_AMPA_Z2A = Synapses(excit_pop_Z, target=excit_pop_A, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2A.connect(p=1.) syn_AMPA_Z2B = Synapses(excit_pop_Z, target=excit_pop_B, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2B.connect(p=1.) syn_AMPA_Z2Z = Synapses(excit_pop_Z, target=excit_pop_Z, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2Z.connect(p=1.) syn_AMPA_Z2inhib = Synapses(excit_pop_Z, target=inhib_pop, on_pre="s_AMPA += 1.0", delay=0.5 * b2.ms) syn_AMPA_Z2inhib.connect(p=1.) ############################################################################################### # NMDA projections FROM EXCITATORY to INHIB, A,B,Z @network_operation() def update_nmda_sum(): sum_sNMDA_A = sum(excit_pop_A.s_NMDA) sum_sNMDA_B = sum(excit_pop_B.s_NMDA) sum_sNMDA_Z = sum(excit_pop_Z.s_NMDA) # note the _ at the end of s_NMDA_total_ disables unit checking inhib_pop.s_NMDA_total_ = (1.0 * sum_sNMDA_A + 1.0 * sum_sNMDA_B + 1.0 * sum_sNMDA_Z) excit_pop_A.s_NMDA_total_ = (w_pos * sum_sNMDA_A + w_neg * sum_sNMDA_B + w_neg * sum_sNMDA_Z) excit_pop_B.s_NMDA_total_ = (w_neg * sum_sNMDA_A + w_pos * sum_sNMDA_B + w_neg * sum_sNMDA_Z) excit_pop_Z.s_NMDA_total_ = (1.0 * sum_sNMDA_A + 1.0 * sum_sNMDA_B + 1.0 * sum_sNMDA_Z) # set a self-recurrent synapse to introduce a delay when updating the intermediate # gating variable x syn_x_A2A = Synapses(excit_pop_A, excit_pop_A, on_pre="x += 1.", delay=0.5 * b2.ms) syn_x_A2A.connect(j="i") syn_x_B2B = Synapses(excit_pop_B, excit_pop_B, on_pre="x += 1.", delay=0.5 * b2.ms) syn_x_B2B.connect(j="i") syn_x_Z2Z = Synapses(excit_pop_Z, excit_pop_Z, on_pre="x += 1.", delay=0.5 * b2.ms) syn_x_Z2Z.connect(j="i") ############################################################################################### # Define the stimulus: two PoissonInput with time time-dependent mean. poissonStimulus2A = PoissonGroup(N_Group_A, 0. * b2.Hz) syn_Stim2A = Synapses(poissonStimulus2A, excit_pop_A, on_pre="s_AMPA+=w_ext2excit") syn_Stim2A.connect(j="i") poissonStimulus2B = PoissonGroup(N_Group_B, 0. * b2.Hz) syn_Stim2B = Synapses(poissonStimulus2B, excit_pop_B, on_pre="s_AMPA+=w_ext2excit") syn_Stim2B.connect(j="i") @network_operation(dt=stimulus_update_interval) def update_poisson_stimulus(t): if t >= t_stimulus_start and t < t_stimulus_end: offset_A = mu0_mean_stimulus_Hz * (0.5 + 0.5 * coherence_level) offset_B = mu0_mean_stimulus_Hz * (0.5 - 0.5 * coherence_level) rate_A = numpy.random.normal(offset_A, stimulus_std_Hz) rate_A = (max(0, rate_A)) * b2.Hz # avoid negative rate rate_B = numpy.random.normal(offset_B, stimulus_std_Hz) rate_B = (max(0, rate_B)) * b2.Hz poissonStimulus2A.rates = rate_A poissonStimulus2B.rates = rate_B # print("stim on. rate_A= {}, rate_B = {}".format(rate_A, rate_B)) else: # print("stim off") poissonStimulus2A.rates = 0. poissonStimulus2B.rates = 0. ############################################################################################### def get_monitors(pop, monitored_subset_size): """ Internal helper. Args: pop: monitored_subset_size: Returns: """ monitored_subset_size = min(monitored_subset_size, pop.N) idx_monitored_neurons = sample(range(pop.N), monitored_subset_size) rate_monitor = PopulationRateMonitor(pop) # record parameter: record=idx_monitored_neurons is not supported??? spike_monitor = SpikeMonitor(pop, record=idx_monitored_neurons) voltage_monitor = StateMonitor(pop, "v", record=idx_monitored_neurons) return rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons # collect data of a subset of neurons: rate_monitor_inhib, spike_monitor_inhib, voltage_monitor_inhib, idx_monitored_neurons_inhib = \ get_monitors(inhib_pop, monitored_subset_size) rate_monitor_A, spike_monitor_A, voltage_monitor_A, idx_monitored_neurons_A = \ get_monitors(excit_pop_A, monitored_subset_size) rate_monitor_B, spike_monitor_B, voltage_monitor_B, idx_monitored_neurons_B = \ get_monitors(excit_pop_B, monitored_subset_size) rate_monitor_Z, spike_monitor_Z, voltage_monitor_Z, idx_monitored_neurons_Z = \ get_monitors(excit_pop_Z, monitored_subset_size) if stop_condition_rate is None: b2.run(max_sim_time) else: sim_sum = 0. * b2.ms sim_batch = 100. * b2.ms samples_in_batch = int(floor(sim_batch / b2.defaultclock.dt)) avg_rate_in_batch = 0 while (sim_sum < max_sim_time) and (avg_rate_in_batch < stop_condition_rate): b2.run(sim_batch) avg_A = numpy.mean(rate_monitor_A.rate[-samples_in_batch:]) avg_B = numpy.mean(rate_monitor_B.rate[-samples_in_batch:]) avg_rate_in_batch = max(avg_A, avg_B) sim_sum += sim_batch print("sim end: {}".format(time.ctime())) ret_vals = dict() ret_vals["rate_monitor_A"] = rate_monitor_A ret_vals["spike_monitor_A"] = spike_monitor_A ret_vals["voltage_monitor_A"] = voltage_monitor_A ret_vals["idx_monitored_neurons_A"] = idx_monitored_neurons_A ret_vals["rate_monitor_B"] = rate_monitor_B ret_vals["spike_monitor_B"] = spike_monitor_B ret_vals["voltage_monitor_B"] = voltage_monitor_B ret_vals["idx_monitored_neurons_B"] = idx_monitored_neurons_B ret_vals["rate_monitor_Z"] = rate_monitor_Z ret_vals["spike_monitor_Z"] = spike_monitor_Z ret_vals["voltage_monitor_Z"] = voltage_monitor_Z ret_vals["idx_monitored_neurons_Z"] = idx_monitored_neurons_Z ret_vals["rate_monitor_inhib"] = rate_monitor_inhib ret_vals["spike_monitor_inhib"] = spike_monitor_inhib ret_vals["voltage_monitor_inhib"] = voltage_monitor_inhib ret_vals["idx_monitored_neurons_inhib"] = idx_monitored_neurons_inhib return ret_vals
class BrianerClass(BaseClass): def default_init(self, _BrianingNeurongroupDict=None, _BrianingSynapsesDict=None, _BrianingConnectVariable=None, _BrianingTraceDict=None, _BrianingMoniterTuple=None, _BrianingSpikesDict=None, _BrianingPyplotDict=None, _BrianingTimeDimensionVariable=None, _BrianingPyplotBool=True, _BrianingStepTimeFloat=0.1, _BrianedNetworkVariable=None, _BrianedNeurongroupVariable=None, _BrianedSynapsesVariable=None, _BrianedStateMonitorVariable=None, _BrianedSpikeMonitorVariable=None, _BrianedClockVariable=None, _BrianedParentSingularStr=None, _BrianedRecordKeyStrsList=None, _BrianedTraceDeriveBrianersList=None, _BrianedSynapsesDeriveBrianersList=None, _BrianedStateDeriveBrianersList=None, _BrianedSpikeDeriveBrianersList=None, _BrianedParentNetworkDeriveBrianerVariable=None, _BrianedParentNeurongroupDeriveBrianerVariable=None, _BrianedParentInteractomeDeriveBrianerVariable=None, _BrianedParentDeriveRecorderVariable=None, **_KwargVariablesDict ): #Call the parent __init__ method BaseClass.__init__(self,**_KwargVariablesDict) def do_brian(self): #/#################/# # Determine if it is an inside structure or the top # #debug ''' self.debug( [ 'We brian here', 'First look for deeper teams in the structure', ] ) ''' #Check if self.ParentedTotalSingularListDict!=None and len(self.ParentedTotalSingularListDict)>0: #debug ''' self.debug( [ 'self.ParentedTotalSingularListDict.keys() is ', str(self.ParentedTotalSingularListDict.keys()) ] ) ''' #get self.BrianedParentSingularStr=self.ParentedTotalSingularListDict.keys()[0] #debug self.debug( [ 'Ok', ('self.',self,[ 'BrianedParentSingularStr' ]) ] ) #/########################/# # Network level # #Check if (self.ParentDeriveTeamerVariable==None or 'Populations' in self.TeamDict or self.ParentDeriveTeamerVariable.TeamTagStr not in [ 'Clocks', 'Traces', 'Samples', 'Events', 'Interactomes', 'Interactions' ]) and self.BrianedParentSingularStr!='Population': #debug ''' self.debug( [ 'It is a Network level', 'We set the brian network' ] ) ''' #set self.brianNetwork() #/########################/# # Special Network-Neurongroup level # #Check if 'Populations' not in self.TeamDict: #debug ''' self.debug( [ 'It is a network with a one level pop', 'So set the neurongroup' ] ) ''' #brianPopulation self.brianPopulation() #debug ''' self.debug( [ 'We end to set the neuron group here' ] ) ''' #/########################/# # structure # #debug ''' self.debug( [ 'We brian structure in all the brian children...', ] ) ''' #structure self.structure( [ 'Clocks', 'Populations', 'Traces', 'Events', 'Samples', 'Interactomes', 'Interactions' ], '#all', _ManagerCommandSetList=['brian'] ) #debug ''' self.debug( [ 'Ok we have brian structured all the brian children...', ] ) ''' else: #debug self.debug( [ 'Ok we check if this parentsingular has a special method ', ('self.',self,[ 'BrianedParentSingularStr' ]) ] ) #set BrianedMethodKeyStr='brian'+self.BrianedParentSingularStr #Check if hasattr(self,BrianedMethodKeyStr): #/########################/# # call the special brian<BrianedParentSingularStr> method # #debug ''' self.debug( [ 'It is a '+self.BrianedParentSingularStr+' level', 'We brian<BrianedParentSingularStr>' ] ) ''' #call getattr( self, BrianedMethodKeyStr )() #debug ''' self.debug( [ 'Ok we have setted brian'+self.BrianedParentSingularStr ] ) ''' #debug ''' self.debug( [ 'end of brian here' ] ) ''' def brianNetwork(self): #/####################/# # init the Network # #maybe should import from brian2 import Network #set self.BrianedNetworkVariable=Network() #/####################/# # adapt dimension time # #Check if self.BrianingTimeDimensionVariable==None: from brian2 import ms self.BrianingTimeDimensionVariable=ms #/####################/# # init a simulation clock # #debug self.debug( [ 'We set a simulation clock at least' ] ) #Check if 'Clocks' not in self.TeamDict: ClocksDeriveManager=self.team('Clocks').TeamedValueVariable else: ClocksDeriveManager=self.TeamDict['Clocks'] #manage if 'Simulation' not in ClocksDeriveManager.ManagementDict: #debug self.debug( [ 'We init a simulation clock here' ] ) #manage SimulationDeriveBrianer=ClocksDeriveManager.manage( 'Simulation', { 'BrianingStepTimeFloat':self.BrianingStepTimeFloat } ) def brianClock(self): #/####################/# # Determine the parents # #get self.BrianedParentNetworkDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #/####################/# # Set the brian clock # #import from brian2 import Clock #debug self.debug( [ 'We set the brian clock', ('self.',self,['StructureTagStr']) ] ) #init self.BrianedClockVariable=Clock( dt=self.BrianingStepTimeFloat*self.BrianedParentNetworkDeriveBrianerVariable.BrianingTimeDimensionVariable, name=self.StructureTagStr ) #debug ''' self.debug( [ 'We have setted the clock', ('self.',self,[ 'BrianedClockVariable' ]) ] ) ''' def brianPopulation(self): #debug ''' self.debug( [ 'It is a Neurongroup level, we set the Neurongroup', 'We adapt the shape of BrianingNeurongroupDict', ('self.',self,[ 'BrianingNeurongroupDict', 'RecordingKeyVariable' ]) ] ) ''' #/########################/# # Determine parents # #Check if self.ParentDeriveTeamerVariable!=None: #set the parent self.BrianedParentNetworkDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable else: #set the parent self.BrianedParentNetworkDeriveBrianerVariable=self #/################/# # Adapt the arg # #Check if 'N' not in self.BrianingNeurongroupDict: self.BrianingNeurongroupDict['N']=0 #Check if 'model' not in self.BrianingNeurongroupDict: self.BrianingNeurongroupDict['model']='' #maybe should import from brian2 import NeuronGroup #debug self.debug( [ ('self.',self,[ 'BrianingNeurongroupDict' ]), 'We now set the model system Neurongroup if N>0 and model!=""' ] ) #/################/# # Set the brian neurongroup # #Check if self.BrianingNeurongroupDict['N']>0 and self.BrianingNeurongroupDict['model']!="": #init self.BrianedNeurongroupVariable=NeuronGroup( **dict( self.BrianingNeurongroupDict, **{ 'name':self.ParentedTotalPathStr.replace('/','_')+'_'+self.ManagementTagStr, #'clock':self.BrianedParentNetworkDeriveBrianerVariable.TeamDict[ # 'Clocks' #].ManagementDict['Simulation'].BrianedClockVariable } ) ) #debug self.debug( [ 'Ok we have setted the Neurongroup', ('self.',self,[ 'BrianedNeurongroupVariable' ]) ] ) #/##################/# # team States first all the brian variables # #get self.BrianedRecordKeyStrsList=self.BrianedNeurongroupVariable.equations._equations.keys() #Check if len(self.BrianedRecordKeyStrsList)>0: #debug ''' self.debug( [ 'We simulate with neurongroup', 'adapt the initial conditions of all the brian variables', 'so first we team Traces and put Recorders inside or get it and mapSet' ] ) ''' #Check if 'Traces' not in self.TeamDict: BrianedDeriveTraces=self.team( 'Traces' ).TeamedValueVariable else: BrianedDeriveTraces=self.TeamDict[ 'Traces' ] #debug self.debug( [ 'We set the tracers', ('self.',self,['BrianedRecordKeyStrsList']) ] ) #map self.BrianedTraceDeriveBrianersList=map( lambda __ManagementKeyStr,__RecordKeyStr: BrianedDeriveTraces.manage( __ManagementKeyStr, { 'RecordingKeyVariable':getattr( self.BrianedNeurongroupVariable, __RecordKeyStr ), 'RecordKeyStr':__RecordKeyStr } ).ManagedValueVariable if __ManagementKeyStr not in BrianedDeriveTraces.ManagementDict else BrianedDeriveTraces.ManagementDict[__ManagementKeyStr].mapSet( { 'RecordingKeyVariable':getattr( self.BrianedNeurongroupVariable, __RecordKeyStr ), 'RecordKeyStr':__RecordKeyStr } ), map( lambda __BrianedRecordKeyStr: Recorder.RecordPrefixStr+__BrianedRecordKeyStr, self.BrianedRecordKeyStrsList ), self.BrianedRecordKeyStrsList ) #/##################/# # add in the net # #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedNeurongroupVariable ) #/####################/# # maybe pyplot a draw plot # #debug ''' self.debug( [ 'We complete a view so first fill the draw' ] ) ''' #Check if 'Charts' not in self.TeamDict: BrianedChartsDeriveTeamer=self.team( 'Charts' ).TeamedValueVariable else: BrianedChartsDeriveTeamer=self.TeamDict['Charts'] """ #Check if 'Traces' in self.TeamDict: #debug ''' self.debug( [ 'First we add the traces' ] ) ''' #set map( lambda __KeyStr: BrianedChartsDeriveTeamer.manage( __KeyStr, { '-Draws': { } } ), self.TeamDict['Traces'].ManagementDict.keys() ) #debug ''' self.debug( [ 'self.TeamDict["Traces"] is ', str(self.TeamDict["Traces"]) ] ) ''' #Check if 'Events' in self.TeamDict: #debug ''' self.debug( [ 'Then we add the events' ] ) ''' #set BrianedChartsDeriveTeamer.mapSet( map( lambda __KeyStr: ( '|'+__KeyStr, { '-Draws': { } } ), self.TeamDict['Events'].ManagementDict.keys() ) ) #debug ''' self.debug( [ 'self.TeamDict["Events"] is ', str(self.TeamDict["Events"]) ] ) ''' """ #/################/# # Make maybe brian the new traces # #debug self.debug( [ 'We make parent brian the new tracers' ] ) #map map( lambda __BrianedTraceDeriveBrianer: __BrianedTraceDeriveBrianer.parent( ).brian( ), self.BrianedTraceDeriveBrianersList ) #debug ''' self.debug( [ 'Ok we know the structure ', ('self.',self,['BrianedNetworkVariable']) ] ) ''' #debug ''' self.debug( [ 'End of brianPopulation' ] ) ''' def brianInteraction(self): #/########################/# # Postlet level # #debug self.debug( [ 'It is a Synapser level, we set the Synapser', ('self.',self,[ #'BrianingSynapsesDict' ] ) ] ) #/####################/# # Set the parent # #Check if self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable.BrianedParentSingularStr=='Interactome': #debug ''' self.debug( [ 'We are in a projectome structure' ] ) ''' #set self.BrianedParentInteractomeDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.BrianedParentInteractomeDeriveBrianerVariable.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable else: #debug ''' self.debug( [ 'There is no projectome structure' ] ) ''' #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/####################/# # Set the ConnectedTo Variable # #debug self.debug( [ 'Check if we have to get the connected to variable', ('self.',self,['ConnectedToVariable']) ] ) #Check if self.ConnectedToVariable==None: #debug self.debug( [ 'We setConnection here' ] ) #setConnection self.setConnection( self.ManagementTagStr, self, self.BrianedParentNeurongroupDeriveBrianerVariable ) #/####################/# # Set the BrianedParentNeurongroupDeriveBrianerVariable # #debug self.debug( [ 'Do we have to make parent-brian the connected variable ?', 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable) ] ) #Check if self.ConnectedToVariable.BrianedNeurongroupVariable==None: #parent brian self.ConnectedToVariable.parent( ).brian( ) #set BrianedNameStr=self.BrianedParentNeurongroupDeriveBrianerVariable.StructureTagStr+'_To_'+self.ConnectedToVariable.StructureTagStr #debug self.debug( [ 'We set the synapses', 'self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable is ', str(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable), 'self.ConnectedToVariable.BrianedNeurongroupVariable is ', str(self.ConnectedToVariable.BrianedNeurongroupVariable), 'Maybe we have to make brian the post', 'BrianedNameStr is '+BrianedNameStr ] ) #import from brian2 import Synapses #init self.BrianedSynapsesVariable=Synapses( source=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable, target=self.ConnectedToVariable.BrianedNeurongroupVariable, name=BrianedNameStr.replace('/','_'), **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 ) #/####################/# # add to the structure # #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedSynapsesVariable ) def brianTrace(self): #debug ''' self.debug( [ 'It is a Trace level, we set the Samples', ('self.',self,[ #'RecordingKeyVariable', 'RecordKeyStr' ]) ] ) ''' #/####################/# # we record # #record self.record() #/####################/# # Set the parent # #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/###################/# # Build the samples and maybe one default moniter # #debug self.debug( [ 'Look if we have samples here', "'Samples' not in self.TeamDict is ", str('Samples' not in self.TeamDict) ] ) #Check if 'Samples' not in self.TeamDict: BrianedSamplesDeriveManager=self.team( 'Samples' ).TeamedValueVariable else: BrianedSamplesDeriveManager=self.TeamDict[ 'Samples' ] #debug self.debug( [ 'Do we have to set a default moniter ?', #'len(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedRecordKeyStrsList) is ', #str(len(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedRecordKeyStrsList)), 'self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedRecordKeyStrsList) is ', str(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedRecordKeyStrsList), ] ) #Check if len(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedRecordKeyStrsList)==1: #debug self.debug( [ 'BrianedSamplesDeriveManager.ManagementDict.keys() is', str(BrianedSamplesDeriveManager.ManagementDict.keys()) ] ) #Check if len(BrianedSamplesDeriveManager.ManagementDict)==0: #debug self.debug( [ 'There is just one variable that we sample', 'we manage and make it brian' ] ) #manage BrianedDefaultMoniter=BrianedSamplesDeriveManager.manage( 'Default', ).ManagedValueVariable #set the monitor BrianedDefaultMoniter.MoniteringLabelIndexIntsArray=[0] if self.BrianedParentNeurongroupDeriveBrianerVariable.BrianingNeurongroupDict[ 'N']>0 else [] #brian BrianedDefaultMoniter.parent( ).brian( ) else: #debug self.debug( [ 'Just be sure to parent brian everybody' ] ) #map map( lambda __DeriveBrianer: __DeriveBrianer.parent( ).brian( ), BrianedSamplesDeriveManager.ManagementDict.values() ) def brianSample(self): #debug self.debug( [ 'It is a Sample State Moniter level', ('self.',self,[ 'MoniteringLabelIndexIntsArray', ]) ] ) #/####################/# # Set the parent # #get self.BrianedParentDeriveRecorderVariable=self.ParentDeriveTeamerVariable.ParentDeriveTeamerVariable #get self.BrianedParentNeurongroupDeriveBrianerVariable=self.BrianedParentDeriveRecorderVariable.BrianedParentNeurongroupDeriveBrianerVariable #get self.BrianedParentNetworkDeriveBrianerVariable=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedParentNetworkDeriveBrianerVariable #/####################/# # Set the brian monitor # #debug ''' self.debug( [ 'We set the state monitor', ('self.',self,[ #'BrianedParentNeurongroupDeriveBrianerVariable' ]), #'self.BrianedParentDeriveRecorderVariable.RecordKeyStr is ', #str(self.BrianedParentDeriveRecorderVariable.RecordKeyStr) 'self.ParentedTotalManagementOrderedDict.keys() is ', str(self.ParentedTotalManagementOrderedDict.keys()) ] ) ''' #import from brian2 import StateMonitor #init self.BrianedStateMonitorVariable=StateMonitor( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable, self.BrianedParentDeriveRecorderVariable.RecordKeyStr, self.MoniteringLabelIndexIntsArray, ) #debug ''' self.debug( [ 'Ok we have setted the monitor', ('self.',self,['BrianedStateMonitorVariable']), 'Now we add to the structure', 'self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable is ', str(self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable) ] ) ''' #/####################/# # add to the structure # #debug ''' self.debug( [ 'We add to the structure' ] ) ''' #add self.BrianedParentNetworkDeriveBrianerVariable.BrianedNetworkVariable.add( self.BrianedStateMonitorVariable ) #/####################/# # maybe pyplot a draw plot # #debug self.debug( [ 'Maybe we pyplot' ] ) #Check if self.BrianingPyplotBool: #debug ''' self.debug( [ 'We complete a view so first fill the draw' ] ) ''' #set LabelStr='$'+self.BrianedParentDeriveRecorderVariable.RecordKeyStr+'_{'+str( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable.name ).replace('_','/')+'}' #set self.PyplotingDrawVariable=map( lambda __IndexInt: ( 'plot', { '#liarg:#map@get':[ '#IdGetStr.BrianedStateMonitorVariable.t', '>>SYS.IdDict[#IdStr].BrianedStateMonitorVariable.'+self.BrianedParentDeriveRecorderVariable.RecordKeyStr+'['+str( __IndexInt)+',:]' ], '#kwarg':dict( { 'label':LabelStr+'^{'+str(__IndexInt)+'}$', 'linestyle':'-', 'color':'b' }, **self.BrianingPyplotDict ) } ), self.MoniteringLabelIndexIntsArray ) #/####################/# # maybe set for the Chart # #init self.PyplotingChartVariable=[] #/####################/# # maybe set the X Chart also # #Check if self.BrianedParentNeurongroupDeriveBrianerVariable.BrianingTimeDimensionVariable==None: from brian2 import ms self.BrianedParentNeurongroupDeriveBrianerVariable.BrianingTimeDimensionVariable=ms #set XLabelStr='$t\ ('+str( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianingTimeDimensionVariable )+')$' #set SampleTagStr=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable.name+'t' #join XlimLiargStr="".join([ ">>SYS.set(SYS,'"+SampleTagStr+"LimFloatsArray',", "[SYS.IdDict[#IdStr].BrianedStateMonitorVariable.t[:].min(),", "SYS.IdDict[#IdStr].BrianedStateMonitorVariable.t[:].max()]", ').'+SampleTagStr+"LimFloatsArray" ]) #join XticksLiargStr="".join([ ">>SYS.set(SYS,'"+SampleTagStr+"TickFloatsArray',", "map(lambda __Float:float('%.2f'%__Float),", "SYS.getTickFloatsArray(", 'SYS.'+SampleTagStr+"LimFloatsArray,3", ")))."+SampleTagStr+"TickFloatsArray" ]) XtickLabelLiargStr="".join([ ">>SYS.set(SYS,'"+SampleTagStr+"TickStrsArray',", "map(lambda __Float:'$'+str(__Float)+'$',", "SYS."+SampleTagStr+"TickFloatsArray))."+SampleTagStr+"TickStrsArray" ]) #debug ''' self.debug( [ 'XLabelStr is ', XLabelStr, 'XlimLiargStr is', XlimLiargStr, 'XticksLiargStr is ', XticksLiargStr, 'XtickLabelLiargStr is ', XtickLabelLiargStr ] ) ''' #set self.PyplotingChartVariable+=[ ( 'set_xlabel',XLabelStr ), ( 'set_xlim',{ '#liarg:#map@get':[XlimLiargStr] } ), ( 'set_xticks',{ '#liarg:#map@get':[XticksLiargStr] } ), ( 'set_xticklabels',{ '#liarg:#map@get':[XtickLabelLiargStr] } ) ] #/####################/# # maybe set the Y Chart also # #set YLabelStr='$'+self.BrianedParentDeriveRecorderVariable.RecordKeyStr+'_{'+str( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable.name ).replace('_','/')+'}(t)\ ('+str( self.BrianedParentDeriveRecorderVariable.RecordedTraceFloatsArray.unit )+')$' #set SampleTagStr=self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable.name+self.BrianedParentDeriveRecorderVariable.RecordKeyStr #join YlimLiargStr="".join([ ">>SYS.set(SYS,'"+SampleTagStr+"LimFloatsArray',", "[SYS.IdDict[#IdStr].BrianedStateMonitorVariable."+self.BrianedParentDeriveRecorderVariable.RecordKeyStr+".min(),", "SYS.IdDict[#IdStr].BrianedStateMonitorVariable."+self.BrianedParentDeriveRecorderVariable.RecordKeyStr+".max()]", ').'+SampleTagStr+"LimFloatsArray" ]) #join YticksLiargStr="".join([ ">>SYS.set(SYS,'"+SampleTagStr+"TickFloatsArray',", "map(lambda __Float:float('%.2f'%__Float),", "SYS.getTickFloatsArray(", 'SYS.'+SampleTagStr+"LimFloatsArray,3", ")))."+SampleTagStr+"TickFloatsArray" ]) YtickLabelLiargStr="".join([ ">>SYS.set(SYS,'"+SampleTagStr+"TickStrsArray',", "map(lambda __Float:'$'+str(__Float)+'$',", "SYS."+SampleTagStr+"TickFloatsArray))."+SampleTagStr+"TickStrsArray" ]) #debug ''' self.debug( [ 'YLabelStr is ', YLabelStr, 'YlimLiargStr is', YlimLiargStr, 'YticksLiargStr is ', YticksLiargStr, 'YtickLabelLiargStr is ', YtickLabelLiargStr ] ) ''' #set self.PyplotingChartVariable+=[ ( 'set_ylabel',YLabelStr ), ( 'set_ylim',{ '#liarg:#map@get':[YlimLiargStr] } ), ( 'set_yticks',{ '#liarg:#map@get':[YticksLiargStr] } ), ( 'set_yticklabels',{ '#liarg:#map@get':[YtickLabelLiargStr] } ) ] #/####################/# # maybe set global Chart also # self.PyplotingChartVariable+=[ ( 'tick_params',{ '#kwarg':{ 'length':10, 'width':5, 'which':'major' } } ), ( 'tick_params',{ '#kwarg':{ 'length':5, 'width':2, 'which':'minor' } } ), ('xaxis.set_ticks_position', { '#liarg':['bottom'] } ), ('yaxis.set_ticks_position', { '#liarg':['left'] } ), ('legend',{ '#liarg':[], '#kwarg':{ 'fontsize':10, 'shadow':True, 'fancybox':True, 'ncol':max(1,len( getattr( self.BrianedStateMonitorVariable, self.BrianedParentDeriveRecorderVariable.RecordKeyStr ) )/2), 'loc':2, 'bbox_to_anchor':(1.05, 1) } }) ] #/####################/# # maybe replace Chart also # #debug ''' self.debug( [ 'Before replace', ('self.',self,[ 'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) ''' #mapReplace [ self.PyplotingDrawVariable, self.PyplotingChartVariable ]=map( lambda __Variable: SYS.replace( __Variable, { '#IdStr':str(self.PrintIdInt), '#IdGetStr':"#id:"+str(self.PrintIdInt) }, self ) if __Variable!=None else None, map( lambda __KeyStr: getattr( self, __KeyStr ), [ 'PyplotingDrawVariable', 'PyplotingChartVariable' ] ) ) #debug ''' self.debug( [ 'After replace', ('self.',self,[ #'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) ''' #/####################/# # Update maybe the # parent neuron group """ #Check if 'Charts' not in self.BrianedParentNeurongroupDeriveBrianerVariable.TeamDict: BrianedChartsDeriveManager=self.BrianedParentNeurongroupDeriveBrianerVariable.team( 'Charts').TeamedValueVariable else: BrianedChartsDeriveManager=self.BrianedParentNeurongroupDeriveBrianerVariable.TeamDict['Charts'] """ #get BrianedChartsDeriveManager=self.BrianedParentNeurongroupDeriveBrianerVariable.TeamDict[ 'Charts' ] #get #BrianedChartDerivePyploter=BrianedChartsDeriveManager.ManagementDict[ # self.BrianedParentDeriveRecorderVariable.ManagementTagStr #] BrianedChartDerivePyploter=BrianedChartsDeriveManager.manage( self.BrianedParentDeriveRecorderVariable.ManagementTagStr ).ManagedValueVariable #debug ''' self.debug( [ 'We update in the parent neurongroup chart', 'BrianedChartDerivePyploter is ', SYS._str(BrianedChartDerivePyploter), ('self.',self,[]) ] ) ''' #team BrianedDrawDeriveManager=BrianedChartDerivePyploter.team( 'Draws' ).TeamedValueVariable #manage BrianedDrawDeriveManager.manage( str(self.ManagementIndexInt), { 'PyplotingDrawVariable':self.PyplotingDrawVariable } ) def brianEvent(self): #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 ) #/####################/# # maybe pyplot a draw plot # #Check if self.BrianingPyplotBool: #debug ''' self.debug( [ 'We complete a view so first fill the draw' ] ) ''' #set LabelStr='$'+self.ManagementTagStr+'_{'+str( self.BrianedParentNeurongroupDeriveBrianerVariable.BrianedNeurongroupVariable.name ).replace('_','/')+'}' #set self.PyplotingDrawVariable=[ ( 'plot', { '#liarg:#map@get':[ '#IdGetStr.BrianedSpikeMonitorVariable.t', '>>SYS.IdDict[#IdStr].BrianedSpikeMonitorVariable.i' ], '#kwarg':dict( { 'label':LabelStr, 'linestyle':'', 'marker':'.', 'color':'b' }, **self.BrianingPyplotDict ) } ) ] #/####################/# # maybe replace Chart also # #debug ''' self.debug( [ 'Before replace', ('self.',self,[ 'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) ''' #mapReplace [ self.PyplotingDrawVariable, self.PyplotingChartVariable ]=map( lambda __Variable: SYS.replace( __Variable, { '#IdStr':str(self.PrintIdInt), '#IdGetStr':"#id:"+str(self.PrintIdInt) }, self ) if __Variable!=None else None, map( lambda __KeyStr: getattr( self, __KeyStr ), [ 'PyplotingDrawVariable', 'PyplotingChartVariable' ] ) ) #debug ''' self.debug( [ 'After replace', ('self.',self,[ #'PyplotingDrawVariable', 'PyplotingChartVariable' ]) ] ) ''' #/####################/# # Update maybe the # parent neuron group #get BrianedChartDeriveManager=self.BrianedParentNeurongroupDeriveBrianerVariable.TeamDict[ 'Charts' ] #manage BrianedChartDerivePyploter=BrianedChartDeriveManager.manage( self.ManagementTagStr ).ManagedValueVariable #debug ''' self.debug( [ 'We update in the parent neurongroup chart', 'BrianedChartDerivePyploter is ', SYS._str(BrianedChartDerivePyploter), ('self.',self,[]) ] ) ''' #team BrianedDrawDeriveManager=BrianedChartDerivePyploter.team( 'Draws' ).TeamedValueVariable #manage BrianedDrawDeriveManager.manage( str(self.ManagementIndexInt), { 'PyplotingDrawVariable':self.PyplotingDrawVariable } ) 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 mimic_record(self): #base method BaseClass.record(self) #debug ''' self.debug( [ 'We have traced, alias the init in the brian object', ('self.',self,[ 'RecordedTraceFloatsArray', 'RecordedInitFloatsArray' ]) ] ) ''' #alias self.RecordedTraceFloatsArray[:]=self.RecordedInitFloatsArray*self.RecordedTraceFloatsArray.unit #debug ''' self.debug( [ ('self.',self,['RecordedTraceFloatsArray']) ] ) ''' def mimic__print(self,**_KwargVariablesDict): #/##################/# # Modify the printing Variable # #Check if self.PrintingSelfBool: #/##################/# # Remove the brian objects that are non setted # #map map( lambda __KeyStr: self.forcePrint( [__KeyStr], 'BrianerClass' ) if getattr(self.PrintingCopyVariable,__KeyStr)!=None else None, [ 'BrianedNetworkVariable', 'BrianedNeurongroupVariable', 'BrianedSynapsesVariable', 'BrianedStateMonitorVariable', 'BrianedSpikeMonitorVariable', 'BrianedClockVariable' ] ) #/##################/# # Call the base method # #call BaseClass._print(self,**_KwargVariablesDict)