def generate(scalePops = 1, percentage_exc_detailed=0, exc2_cell = 'SmithEtAl2013/L23_Retuned_477127614', percentage_inh_detailed=0, scalex=1, scaley=1, scalez=1, ratio_inh_exc=2, connections=True, exc_target_dendrites=False, inh_target_dendrites=False, duration = 1000, dt = 0.025, input_rate = 150, global_delay = 2, max_in_pop_to_plot_and_save = 5, format='xml', suffix='', run_in_simulator = None, num_processors = 1, target_dir='./temp/', exc_clamp=None): # exc_clamp is work in progress... reference = ("Multiscale__g%s__i%s%s"%(ratio_inh_exc,input_rate,suffix)).replace('.','_') num_exc = scale_pop_size(80,scalePops) num_exc2 = int(math.ceil(num_exc*percentage_exc_detailed/100.0)) num_exc -= num_exc2 num_inh = scale_pop_size(40,scalePops) num_inh2 = int(math.ceil(num_inh*percentage_inh_detailed/100.0)) num_inh -= num_inh2 nml_doc, network = oc.generate_network(reference, network_seed=1234) #exc_cell_id = 'AllenHH_480351780' exc_cell_id = 'AllenHH_477127614' #exc_cell_id = 'HH_477127614' exc_type = exc_cell_id.split('_')[0] oc.include_neuroml2_cell_and_channels(nml_doc, 'cells/%s/%s.cell.nml'%(exc_type,exc_cell_id), exc_cell_id) #inh_cell_id = 'AllenHH_485058595' inh_cell_id = 'AllenHH_476686112' #inh_cell_id = 'HH_476686112' inh_type = exc_cell_id.split('_')[0] oc.include_neuroml2_cell_and_channels(nml_doc, 'cells/%s/%s.cell.nml'%(inh_type,inh_cell_id), inh_cell_id) if percentage_exc_detailed>0: exc2_cell_id = exc2_cell.split('/')[1] exc2_cell_dir = exc2_cell.split('/')[0] oc.include_neuroml2_cell_and_channels(nml_doc, 'cells/%s/%s.cell.nml'%(exc2_cell_dir,exc2_cell_id), exc2_cell_id) if percentage_inh_detailed>0: inh2_cell_id = 'cNAC187_L23_NBC_9d37c4b1f8_0_0' oc.include_neuroml2_cell_and_channels(nml_doc, 'cells/BBP/%s.cell.nml'%inh2_cell_id, inh2_cell_id) xDim = 700*scalex yDim = 200*scaley zDim = 700*scalez xs = -1*xDim/2 ys = -1*yDim/2 zs = -1*zDim/2 ##### Synapses exc_syn_nS = 1. synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="%snS"%exc_syn_nS, erev="0mV", tau_rise="0.5ms", tau_decay="5ms") synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="%snS"%(exc_syn_nS*ratio_inh_exc), erev="-80mV", tau_rise="1ms", tau_decay="20ms") ##### Input types pfs1 = oc.add_poisson_firing_synapse(nml_doc, id="psf1", average_rate="%s Hz"%input_rate, synapse_id=synAmpa1.id) ##### Populations popExc = oc.add_population_in_rectangular_region(network, 'popExc', exc_cell_id, num_exc, xs,ys,zs, xDim,yDim,zDim, color=exc_color) allExc = [popExc] if num_exc2>0: popExc2 = oc.add_population_in_rectangular_region(network, 'popExc2', exc2_cell_id, num_exc2, xs,ys,zs, xDim,yDim,zDim, color=exc2_color) allExc.append(popExc2) popInh = oc.add_population_in_rectangular_region(network, 'popInh', inh_cell_id, num_inh, xs,ys,zs, xDim,yDim,zDim, color=inh_color) allInh = [popInh] if num_inh2>0: popInh2 = oc.add_population_in_rectangular_region(network, 'popInh2', inh2_cell_id, num_inh2, xs,ys,zs, xDim,yDim,zDim, color=inh2_color) allInh.append(popInh2) ##### Projections if connections: exc_exc_conn_prob = 0.5 exc_inh_conn_prob = 0.7 inh_exc_conn_prob = 0.7 inh_inh_conn_prob = 0.5 for popEpr in allExc: for popEpo in allExc: proj = add_projection(network, "projEE", popEpr, popEpo, synAmpa1.id, exc_exc_conn_prob, global_delay, exc_target_dendrites) for popIpo in allInh: proj = add_projection(network, "projEI", popEpr, popIpo, synAmpa1.id, exc_inh_conn_prob, global_delay, exc_target_dendrites) for popIpr in allInh: for popEpo in allExc: proj = add_projection(network, "projIE", popIpr, popEpo, synGaba1.id, inh_exc_conn_prob, global_delay, inh_target_dendrites) for popIpo in allInh: proj = add_projection(network, "projII", popIpr, popIpo, synGaba1.id, inh_inh_conn_prob, global_delay, inh_target_dendrites) ##### Inputs for pop in allExc: oc.add_inputs_to_population(network, "Stim_%s"%pop.id, pop, pfs1.id, all_cells=True) # Work in progress... # General idea: clamp one (or more) exc cell at rev pot of inh syn and see only exc inputs # if exc_clamp: vc = oc.add_voltage_clamp_triple(nml_doc, id="exc_clamp", delay='0ms', duration='%sms'%duration, conditioning_voltage=synGaba1.erev, testing_voltage=synGaba1.erev, return_voltage=synGaba1.erev, simple_series_resistance="1e5ohm", active = "1") for pop in exc_clamp: oc.add_inputs_to_population(network, "exc_clamp_%s"%pop, network.get_by_id(pop), vc.id, all_cells=False, only_cells=exc_clamp[pop]) ##### Save NeuroML and LEMS Simulation files nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') oc.save_network(nml_doc, nml_file_name, validate=(format=='xml'), format = format, target_dir=target_dir) if format=='xml': save_v = {} plot_v = {} if num_exc>0: exc_traces = '%s_%s_v.dat'%(network.id,popExc.id) save_v[exc_traces] = [] plot_v[popExc.id] = [] if num_inh>0: inh_traces = '%s_%s_v.dat'%(network.id,popInh.id) save_v[inh_traces] = [] plot_v[popInh.id] = [] if num_exc2>0: exc2_traces = '%s_%s_v.dat'%(network.id,popExc2.id) save_v[exc2_traces] = [] plot_v[popExc2.id] = [] if num_inh2>0: inh2_traces = '%s_%s_v.dat'%(network.id,popInh2.id) save_v[inh2_traces] = [] plot_v[popInh2.id] = [] for i in range(min(max_in_pop_to_plot_and_save,num_exc)): plot_v[popExc.id].append("%s/%i/%s/v"%(popExc.id,i,popExc.component)) save_v[exc_traces].append("%s/%i/%s/v"%(popExc.id,i,popExc.component)) for i in range(min(max_in_pop_to_plot_and_save,num_exc2)): plot_v[popExc2.id].append("%s/%i/%s/v"%(popExc2.id,i,popExc2.component)) save_v[exc2_traces].append("%s/%i/%s/v"%(popExc2.id,i,popExc2.component)) for i in range(min(max_in_pop_to_plot_and_save,num_inh)): plot_v[popInh.id].append("%s/%i/%s/v"%(popInh.id,i,popInh.component)) save_v[inh_traces].append("%s/%i/%s/v"%(popInh.id,i,popInh.component)) for i in range(min(max_in_pop_to_plot_and_save,num_inh2)): plot_v[popInh2.id].append("%s/%i/%s/v"%(popInh2.id,i,popInh2.component)) save_v[inh2_traces].append("%s/%i/%s/v"%(popInh2.id,i,popInh2.component)) gen_spike_saves_for_all_somas = run_in_simulator!='jNeuroML_NetPyNE' lems_file_name = oc.generate_lems_simulation(nml_doc, network, target_dir+nml_file_name, duration = duration, dt = dt, gen_plots_for_all_v = False, gen_plots_for_quantities = plot_v, gen_saves_for_all_v = False, gen_saves_for_quantities = save_v, gen_spike_saves_for_all_somas = gen_spike_saves_for_all_somas, target_dir=target_dir) if run_in_simulator: print ("Running %s for %sms in %s"%(lems_file_name, duration, run_in_simulator)) traces, events = oc.simulate_network(lems_file_name, run_in_simulator, max_memory='4000M', nogui=True, load_saved_data=True, reload_events=True, plot=False, verbose=False, num_processors=num_processors) print("Reloaded traces: %s"%traces.keys()) #print("Reloaded events: %s"%events.keys()) use_events_for_rates = False exc_rate = 0 inh_rate = 0 if use_events_for_rates: if (run_in_simulator=='jNeuroML_NetPyNE'): raise('Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE') for ek in events.keys(): rate = 1000 * len(events[ek])/float(duration) print("Cell %s has rate %s Hz"%(ek,rate)) if 'popExc' in ek: exc_rate += rate/num_exc if 'popInh' in ek: inh_rate += rate/num_inh else: tot_exc_rate = 0 exc_cells = 0 tot_inh_rate = 0 inh_cells = 0 tt = [t*1000 for t in traces['t']] for tk in traces.keys(): if tk!='t': rate = get_rate_from_trace(tt,[v*1000 for v in traces[tk]]) print("Cell %s has rate %s Hz"%(tk,rate)) if 'popExc' in tk: tot_exc_rate += rate exc_cells+=1 if 'popInh' in tk: tot_inh_rate += rate inh_cells+=1 exc_rate = tot_exc_rate/exc_cells inh_rate = tot_inh_rate/inh_cells print("Run %s: Exc rate: %s Hz; Inh rate %s Hz"%(reference,exc_rate, inh_rate)) return exc_rate, inh_rate, traces else: lems_file_name = None return nml_doc, nml_file_name, lems_file_name
def generate(cell_id, duration, reference, Bee=1, Ensyn = 10, Erates = [50,100], st_onset = 0, st_duration = 1e9, format='hdf5', simulator=None, num_processors=1, target_group='soma_group', temperature='35degC'): #Insyn = int(Ensyn * 0.2) #bInsyn = int(bEnsyn * 0.2) cell_file = '../%s.cell.nml'%cell_id if '/' in cell_id: cell_id=cell_id.split('/')[-1] nml_doc, network = oc.generate_network(reference, temperature=temperature) oc.include_neuroml2_cell_and_channels(nml_doc,cell_file,cell_id) synAmpaEE = oc.add_exp_one_syn(nml_doc, id="synAmpaEE", gbase="%snS"%Bee, erev="0mV", tau_decay="1ms") pop = oc.add_population_in_rectangular_region(network, 'L23_pop', cell_id, len(Erates), 0,0,0, 100,100,100) to_plot = {'Some_voltages':[]} to_save = {'%s_voltages.dat'%cell_id:[]} interesting_seg_ids = [0,200,1000,2000,2500,2949] # [soma, .. some dends .. , axon] interesting_seg_ids = [0] # [soma, .. some dends .. , axon] for i,r in enumerate(Erates): syn0 = oc.add_transient_poisson_firing_synapse(nml_doc, id="%s_stim_%s"%(synAmpaEE.id,r), average_rate="%s Hz"%r, synapse_id=synAmpaEE.id, delay='%s ms'%st_onset, duration='%s ms'%st_duration) oc.add_targeted_inputs_to_population(network, "Esyn_%s"%r, pop, syn0.id, segment_group=target_group, number_per_cell = Ensyn, all_cells=False, only_cells=[i]) for seg_id in interesting_seg_ids: to_plot.values()[0].append('%s/%s/%s/%s/v'%(pop.id, i, pop.component,seg_id)) to_save.values()[0].append('%s/%s/%s/%s/v'%(pop.id, i, pop.component,seg_id)) nml_file_name = '%s.net.nml'%network.id + ('.h5' if format=='hdf5' else '') target_dir='./' oc.save_network(nml_doc, nml_file_name, validate=False, use_subfolder=True, target_dir=target_dir, format=format) lems_file_name, lems_sim = oc.generate_lems_simulation(nml_doc, network, nml_file_name, duration, dt = 0.025, target_dir=target_dir, gen_plots_for_all_v = False, plot_all_segments = False, gen_plots_for_quantities = to_plot, # Dict with displays vs lists of quantity paths gen_saves_for_all_v = False, save_all_segments = False, gen_saves_for_quantities = to_save, # Dict with file names vs lists of quantity paths verbose = True) if simulator: print ("Running %s for %sms in %s"%(lems_file_name, duration, simulator)) traces, events = oc.simulate_network(lems_file_name, simulator, max_memory='4000M', nogui=True, load_saved_data=True, reload_events=True, plot=False, verbose=True, num_processors=num_processors) rates = {} tt = [t*1000 for t in traces['t']] for tk in traces.keys(): if tk!='t': rate = get_rate_from_trace(tt,[v*1000 for v in traces[tk]]) print("Cell %s has rate %s Hz"%(tk,rate)) i = int(tk.split('/')[1]) rates[Erates[i]]=rate print Erates print rates ax = pynml.generate_plot([Erates], [ [rates[r] for r in Erates] ], "FF plots", xaxis = 'Input frequency (Hz)', yaxis = 'Firing frequency (Hz)', markers=['o'], show_plot_already=True) # Save figure file_name = '%s.%s.%ssyns.%s.rates'%(cell_id,target_group,Ensyn,temperature) f = open(file_name,'w') for r in Erates: f.write('%s\t%s\n'%(r,rates[r])) f.close() print("Finished! Saved rates data to %s"%file_name)
def RunColumnSimulation(net_id="TestRunColumn", nml2_source_dir="../../../neuroConstruct/generatedNeuroML2/", sim_config="TempSimConfig", scale_cortex=0.1, scale_thalamus=0.1, cell_bodies_overlap=True, cylindrical=True, default_synaptic_delay=0.05, gaba_scaling=1.0, l4ss_ampa_scaling=1.0, l5pyr_gap_scaling =1.0, in_nrt_tcr_nmda_scaling =1.0, pyr_ss_nmda_scaling=1.0, deep_bias_current=-1, include_gap_junctions=True, which_cell_types_to_include='all', dir_nml2="../../", backgroundL5Rate=30, # Hz backgroundL23Rate=30, # Hz duration=300, dt=0.025, max_memory='1000M', seed=1234, simulator=None, num_of_cylinder_sides=None): popDictFull = {} ############## Full model ################################## popDictFull['CG3D_L23PyrRS'] = (1000, 'L23','L23PyrRS','multi', occ.L23_PRINCIPAL_CELL) popDictFull['CG3D_L23PyrFRB']= (50,'L23','L23PyrFRB_varInit','multi', occ.L23_PRINCIPAL_CELL_2) popDictFull['CG3D_SupBask'] = (90, 'L23','SupBasket','multi', occ.L23_INTERNEURON) # over both l23 & l4 popDictFull['CG3D_SupAxAx'] = (90, 'L23','SupAxAx','multi', occ.L23_INTERNEURON_2) # over both l23 & l4 popDictFull['CG3D_SupLTS']= (90,'L23','SupLTSInter','multi', occ.L4_INTERNEURON) # over both l23 & l4 popDictFull['CG3D_L4SpinStell']= (240,'L4','L4SpinyStellate','multi', occ.L4_PRINCIPAL_CELL) popDictFull['CG3D_L5TuftIB'] = (800, 'L5','L5TuftedPyrIB','multi', occ.L5_PRINCIPAL_CELL) popDictFull['CG3D_L5TuftRS']= (200,'L5','L5TuftedPyrRS','multi', occ.L5_PRINCIPAL_CELL_2) popDictFull['CG3D_L6NonTuftRS']= (500,'L6','L6NonTuftedPyrRS','multi', occ.L6_PRINCIPAL_CELL) popDictFull['CG3D_DeepAxAx']= (100,'L6','DeepAxAx','multi', occ.L5_INTERNEURON) # over both l5 & l6 popDictFull['CG3D_DeepBask']= (100,'L6','DeepBasket','multi', occ.L5_INTERNEURON_2) # over both l5 & l6 popDictFull['CG3D_DeepLTS']= (100,'L6','DeepLTSInter','multi', occ.L6_INTERNEURON) # over both l5 & l6 popDictFull['CG3D_nRT']= (100,'Thalamus','nRT','multi', occ.THALAMUS_1) popDictFull['CG3D_TCR']= (100,'Thalamus','TCR','multi', occ.THALAMUS_2) ############################################################### dir_to_cells=os.path.join(dir_nml2,"cells") dir_to_synapses=os.path.join(dir_nml2,"synapses") dir_to_gap_junctions=os.path.join(dir_nml2,"gapJunctions") popDict={} cell_model_list=[] cell_diameter_dict={} nml_doc, network = oc.generate_network(net_id,seed) for cell_population in popDictFull.keys(): include_cell_population=False cell_model=popDictFull[cell_population][2] if which_cell_types_to_include=='all' or cell_model in which_cell_types_to_include: popDict[cell_population]=() if popDictFull[cell_population][1] !='Thalamus': popDict[cell_population]=(int(round(scale_cortex*popDictFull[cell_population][0])), popDictFull[cell_population][1], popDictFull[cell_population][2], popDictFull[cell_population][3], popDictFull[cell_population][4]) cell_count=int(round(scale_cortex*popDictFull[cell_population][0])) else: popDict[cell_population]=(int(round(scale_thalamus*popDictFull[cell_population][0])), popDictFull[cell_population][1], popDictFull[cell_population][2], popDictFull[cell_population][3], popDictFull[cell_population][4]) cell_count=int(round(scale_thalamus*popDictFull[cell_population][0])) if cell_count !=0: include_cell_population=True if include_cell_population: cell_model_list.append(popDictFull[cell_population][2]) cell_diameter=oc_build.get_soma_diameter(popDictFull[cell_population][2],dir_to_cell=dir_to_cells) if popDictFull[cell_population][2] not in cell_diameter_dict.keys(): cell_diameter_dict[popDictFull[cell_population][2]]=cell_diameter cell_model_list_final=list(set(cell_model_list)) opencortex.print_comment_v("This is a final list of cell model ids: %s"%cell_model_list_final) copy_nml2_from_source=False for cell_model in cell_model_list_final: if not os.path.exists(os.path.join(dir_to_cells,"%s.cell.nml"%cell_model)): copy_nml2_from_source=True break if copy_nml2_from_source: oc_build.copy_nml2_source(dir_to_project_nml2=dir_nml2, primary_nml2_dir=nml2_source_dir, electrical_synapse_tags=['Elect'], chemical_synapse_tags=['.synapse.'], extra_channel_tags=['cad']) passed_includes_in_cells=oc_utils.check_includes_in_cells(dir_to_cells,cell_model_list_final,extra_channel_tags=['cad']) if not passed_includes_in_cells: opencortex.print_comment_v("Execution of RunColumn.py will terminate.") quit() for cell_model in cell_model_list_final: oc_build._add_cell_and_channels(nml_doc, os.path.join(dir_to_cells,"%s.cell.nml"%cell_model), cell_model, use_prototypes=False) t1=-0 t2=-250 t3=-250 t4=-200.0 t5=-300.0 t6=-300.0 t7=-200.0 t8=-200.0 boundaries={} boundaries['L1']=[0,t1] boundaries['L23']=[t1,t1+t2+t3] boundaries['L4']=[t1+t2+t3,t1+t2+t3+t4] boundaries['L5']=[t1+t2+t3+t4,t1+t2+t3+t4+t5] boundaries['L6']=[t1+t2+t3+t4+t5,t1+t2+t3+t4+t5+t6] boundaries['Thalamus']=[t1+t2+t3+t4+t5+t6+t7,t1+t2+t3+t4+t5+t6+t7+t8] xs = [0,500] zs = [0,500] passed_pops=oc_utils.check_pop_dict_and_layers(pop_dict=popDict,boundary_dict=boundaries) if passed_pops: opencortex.print_comment_v("Population parameters were specified correctly.") if cylindrical: pop_params=oc_utils.add_populations_in_cylindrical_layers(network,boundaries,popDict,radiusOfCylinder=250,cellBodiesOverlap=cell_bodies_overlap, cellDiameterArray=cell_diameter_dict,numOfSides=num_of_cylinder_sides) else: pop_params=oc_utils.add_populations_in_rectangular_layers(network,boundaries,popDict,xs,zs,cellBodiesOverlap=False,cellDiameterArray=cell_diameter_dict) else: opencortex.print_comment_v("Population parameters were specified incorrectly; execution of RunColumn.py will terminate.") quit() src_files = os.listdir("./") if 'netConnList' in src_files: full_path_to_connectivity='netConnList' else: full_path_to_connectivity="../../../neuroConstruct/pythonScripts/netbuild/netConnList" weight_params=[{'weight':gaba_scaling,'synComp':'GABAA','synEndsWith':[],'targetCellGroup':[]}, {'weight':l4ss_ampa_scaling,'synComp':'Syn_AMPA_L4SS_L4SS','synEndsWith':[],'targetCellGroup':[]}, {'weight':l5pyr_gap_scaling,'synComp':'Syn_Elect_DeepPyr_DeepPyr','synEndsWith':[],'targetCellGroup':['CG3D_L5']}, {'weight':in_nrt_tcr_nmda_scaling,'synComp':'NMDA','synEndsWith':["_IN","_DeepIN","_SupIN","_SupFS","_DeepFS","_SupLTS","_DeepLTS","_nRT","_TCR"], 'targetCellGroup':[]}, {'weight':pyr_ss_nmda_scaling,'synComp':'NMDA','synEndsWith':["_IN","_DeepIN","_SupIN","_SupFS","_DeepFS","_SupLTS","_DeepLTS","_nRT","_TCR"], 'targetCellGroup':[]}] delay_params=[{'delay':default_synaptic_delay,'synComp':'all'}] passed_weight_params=oc_utils.check_weight_params(weight_params) passed_delay_params=oc_utils.check_delay_params(delay_params) if passed_weight_params and passed_delay_params: opencortex.print_comment_v("Synaptic weight and delay parameters were specified correctly.") ignore_synapses = [] if not include_gap_junctions: ignore_synapses = ['Syn_Elect_SupPyr_SupPyr','Syn_Elect_CortIN_CortIN','Syn_Elect_L4SS_L4SS','Syn_Elect_DeepPyr_DeepPyr','Syn_Elect_nRT_nRT'] all_synapse_components,projArray,cached_segment_dicts=oc_utils.build_connectivity(net=network, pop_objects=pop_params, path_to_cells=dir_to_cells, full_path_to_conn_summary=full_path_to_connectivity, pre_segment_group_info=[{'PreSegGroup':"distal_axon",'ProjType':'Chem'}], synaptic_scaling_params=weight_params, synaptic_delay_params=delay_params, ignore_synapses=ignore_synapses) else: if not passed_weight_params: opencortex.print_comment_v("Synaptic weight parameters were specified incorrectly; execution of RunColumn.py will terminate.") if not passed_delay_params: opencortex.print_comment_v("Synaptic delay parameters were specified incorrectly; execution of RunColumn.py will terminate.") quit() ############ for testing only; will add original specifications later ############################################################## if sim_config=="Testing1": input_params={'CG3D_L23PyrRS':[{'InputType':'GeneratePoissonTrains', 'InputName':'Poi_CG3D_L23PyrRS', 'TrainType':'transient', 'Synapse':'Syn_AMPA_SupPyr_SupPyr', 'AverageRateList':[200.0,150.0], 'RateUnits':'Hz', 'TimeUnits':'ms', 'DurationList':[100.0,50.0], 'DelayList':[50.0,200.0], 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'soma_group':1 } }] } ################################################################################################################################### if sim_config=="Testing2": input_params_final={'CG3D_L23PyrRS':[{'InputType':'PulseGenerators', 'InputName':"DepCurr_L23RS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5,1.0E-5], 'LargestAmplitudeList':[1.0E-4,2.0E-5], 'DurationList':[20000.0,20000.0], 'DelayList':[0.0,20000.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':1} }] } if sim_config=="TempSimConfig": input_params ={'CG3D_L23PyrRS':[{'InputType':'PulseGenerators', 'InputName':"DepCurr_L23RS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5}, {'InputType':'GeneratePoissonTrains', 'InputName':"BackgroundL23RS", 'TrainType':'persistent', 'Synapse':'Syn_AMPA_SupPyr_SupPyr', 'AverageRateList':[float(backgroundL23Rate)], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':100} }, {'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL23RS", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[0.1], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':143, 'UniversalFractionAlong':0.5} ], 'CG3D_TCR':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimTCR", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':269, 'UniversalFractionAlong':0.5}, {'InputType':'GeneratePoissonTrains', 'InputName':"Input_20", 'TrainType':'persistent', 'Synapse':'Syn_AMPA_L6NT_TCR', 'AverageRateList':[50.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':100} }], 'CG3D_L23PyrFRB':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL23FRB", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[0.1], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':143, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L23FRB", 'Noise':True, 'SmallestAmplitudeList':[2.5E-4], 'LargestAmplitudeList':[3.5E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ], 'CG3D_L6NonTuftRS':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL6NT", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':95, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L6NT", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ], 'CG3D_L4SpinStell':[{'InputType':'PulseGenerators', 'InputName':"DepCurr_L4SS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5}], 'CG3D_L5TuftIB':[{'InputType':'GeneratePoissonTrains', 'InputName':"BackgroundL5", 'TrainType':'persistent', 'Synapse':'Syn_AMPA_L5RS_L5Pyr', 'AverageRateList':[float(backgroundL5Rate)], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':100} }, {'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL5IB", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':119, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L5IB", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ], 'CG3D_L5TuftRS':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL5RS", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':119, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L5RS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ] } input_params_final={} for pop_id in pop_params.keys(): if pop_id in input_params.keys(): input_params_final[pop_id]=input_params[pop_id] if deep_bias_current >= 0: for cell_group in input_params_final.keys(): for input_group in range(0,len(input_params_final[cell_group])): check_type=input_params_final[cell_group][input_group]['InputType']=="PulseGenerators" check_group_1= cell_group=="CG3D_L5TuftIB" check_group_2=cell_group =="CG3D_L5TuftRS" check_group_3= cell_group =="CG3D_L6NonTuftRS" if check_type and (check_group_1 or check_group_2 or check_group_3): opencortex.print_comment_v("Changing offset current in 'PulseGenerators' for %s to %f"%(cell_group, deep_bias_current)) input_params_final[cell_group][input_group]['SmallestAmplitudeList']=[ (deep_bias_current-0.05)/1000 ] input_params_final[cell_group][input_group]['LargestAmplitudeList']=[ (deep_bias_current+0.05)/1000 ] input_list_array_final, input_synapse_list=oc_utils.build_inputs(nml_doc=nml_doc, net=network, population_params=pop_params, input_params=input_params_final, cached_dicts=cached_segment_dicts, path_to_cells=dir_to_cells, path_to_synapses=dir_to_synapses) #################################################################################################################################### for input_synapse in input_synapse_list: if input_synapse not in all_synapse_components: all_synapse_components.append(input_synapse) synapse_list=[] gap_junction_list=[] for syn_ind in range(0,len(all_synapse_components)): if 'Elect' not in all_synapse_components[syn_ind]: synapse_list.append(all_synapse_components[syn_ind]) all_synapse_components[syn_ind]=os.path.join(net_id,all_synapse_components[syn_ind]+".synapse.nml") else: gap_junction_list.append(all_synapse_components[syn_ind]) all_synapse_components[syn_ind]=os.path.join(net_id,all_synapse_components[syn_ind]+".nml") oc_build.add_synapses(nml_doc,dir_to_synapses,synapse_list,synapse_tag=True) oc_build.add_synapses(nml_doc,dir_to_gap_junctions,gap_junction_list,synapse_tag=False) nml_file_name = '%s.net.nml'%network.id oc.save_network(nml_doc, nml_file_name, validate=True,max_memory=max_memory) oc_build.remove_component_dirs(dir_to_project_nml2="%s"%network.id,list_of_cell_ids=cell_model_list_final,extra_channel_tags=['cad']) lems_file_name=oc.generate_lems_simulation(nml_doc, network, nml_file_name, duration =duration, dt =dt, include_extra_lems_files=all_synapse_components) if simulator != None: opencortex.print_comment_v("Starting simulation of %s.net.nml"%net_id) oc.simulate_network(lems_file_name=lems_file_name, simulator=simulator, max_memory=max_memory)
def generate(scale_populations=1, percentage_exc_detailed=0, exc2_cell='SmithEtAl2013/L23_Retuned_477127614', percentage_inh_detailed=0, scalex=1, scaley=1, scalez=1, Bee=.1, Bei=.1, Bie=-.2, Bii=-.2, Be_bkg=.1, Be_stim=.1, r_bkg=0, r_stim=0, fraction_inh_pert=0.75, connections=True, exc_target_dendrites=False, inh_target_dendrites=False, duration=1000, dt=0.025, global_delay=.1, max_in_pop_to_plot_and_save=10, format='xml', suffix='', run_in_simulator=None, num_processors=1, target_dir='./temp/', exc_clamp=None): # exc_clamp is work in progress... reference = ("ISN_net%s" % (suffix)).replace('.', '_') print('-------------------------------------------------') print(' Generating ISN network: %s' % reference) print(' Duration: %s; dt: %s; scale: %s; simulator: %s (num proc. %s)' % (duration, dt, scale_populations, run_in_simulator, num_processors)) print(' Bee: %s; Bei: %s; Bie: %s; Bii: %s' % (Bee, Bei, Bie, Bii)) print(' Be_bkg: %s at %sHz' % (Be_bkg, r_bkg)) print(' Be_stim: %s at %sHz (i.e. %sHz for %s perturbed I cells)' % (Be_stim, r_stim, r_bkg + r_stim, fraction_inh_pert)) print(' Exc detailed: %s%% - Inh detailed %s%%' % (percentage_exc_detailed, percentage_inh_detailed)) print('-------------------------------------------------') num_exc = scale_pop_size(80, scale_populations) num_exc2 = int(math.ceil(num_exc * percentage_exc_detailed / 100.0)) num_exc -= num_exc2 num_inh = scale_pop_size(20, scale_populations) num_inh2 = int(math.ceil(num_inh * percentage_inh_detailed / 100.0)) num_inh -= num_inh2 nml_doc, network = oc.generate_network(reference, network_seed=1234) #exc_cell_id = 'AllenHH_480351780' exc_cell_id = 'AllenHH_477127614' #exc_cell_id = 'HH_477127614' exc_cell_id = 'HH2_477127614' exc_type = exc_cell_id.split('_')[0] oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/%s/%s.cell.nml' % (exc_type, exc_cell_id), exc_cell_id) #inh_cell_id = 'AllenHH_485058595' inh_cell_id = 'AllenHH_476686112' #inh_cell_id = 'AllenHH_477127614' #inh_cell_id = 'HH_476686112' inh_cell_id = 'HH2_476686112' inh_type = exc_cell_id.split('_')[0] oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/%s/%s.cell.nml' % (inh_type, inh_cell_id), inh_cell_id) if percentage_exc_detailed > 0: exc2_cell_id = exc2_cell.split('/')[1] exc2_cell_dir = exc2_cell.split('/')[0] oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/%s/%s.cell.nml' % (exc2_cell_dir, exc2_cell_id), exc2_cell_id) if percentage_inh_detailed > 0: inh2_cell_id = 'cNAC187_L23_NBC_9d37c4b1f8_0_0' oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/BBP/%s.cell.nml' % inh2_cell_id, inh2_cell_id) xDim = 700 * scalex yDim = 200 * scaley zDim = 700 * scalez xs = -1 * xDim / 2 ys = -1 * yDim / 2 zs = -1 * zDim / 2 ##### Synapses synAmpaEE = oc.add_exp_one_syn(nml_doc, id="synAmpaEE", gbase="%snS" % Bee, erev="0mV", tau_decay="1ms") synAmpaEI = oc.add_exp_one_syn(nml_doc, id="synAmpaEI", gbase="%snS" % Bei, erev="0mV", tau_decay="1ms") synGabaIE = oc.add_exp_one_syn(nml_doc, id="synGabaIE", gbase="%snS" % abs(Bie), erev="-80mV", tau_decay="1ms") synGabaII = oc.add_exp_one_syn(nml_doc, id="synGabaII", gbase="%snS" % abs(Bii), erev="-80mV", tau_decay="1ms") synAmpaBkg = oc.add_exp_one_syn(nml_doc, id="synAmpaBkg", gbase="%snS" % Be_bkg, erev="0mV", tau_decay="1ms") synAmpaStim = oc.add_exp_one_syn(nml_doc, id="synAmpaStim", gbase="%snS" % Be_stim, erev="0mV", tau_decay="1ms") ##### Input types tpfsA = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpsfA", average_rate="%s Hz" % r_bkg, delay='0ms', duration='%sms' % (Ttrans + Tblank), synapse_id=synAmpaBkg.id) tpfsB = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpsfB", average_rate="%s Hz" % r_bkg, delay='%sms' % (Ttrans + Tblank), duration='%sms' % (Tstim), synapse_id=synAmpaBkg.id) tpfsC = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpsfC", average_rate="%s Hz" % (r_bkg + r_stim), delay='%sms' % (Ttrans + Tblank), duration='%sms' % (Tstim), synapse_id=synAmpaStim.id) ##### Populations popExc = oc.add_population_in_rectangular_region(network, 'popExc', exc_cell_id, num_exc, xs, ys, zs, xDim, yDim, zDim, color=exc_color) allExc = [popExc] if num_exc2 > 0: popExc2 = oc.add_population_in_rectangular_region(network, 'popExc2', exc2_cell_id, num_exc2, xs, ys, zs, xDim, yDim, zDim, color=exc2_color) allExc.append(popExc2) popInh = oc.add_population_in_rectangular_region(network, 'popInh', inh_cell_id, num_inh, xs, ys, zs, xDim, yDim, zDim, color=inh_color) allInh = [popInh] if num_inh2 > 0: popInh2 = oc.add_population_in_rectangular_region(network, 'popInh2', inh2_cell_id, num_inh2, xs, ys, zs, xDim, yDim, zDim, color=inh2_color) allInh.append(popInh2) ##### Projections if connections: exc_exc_conn_prob = 0.15 exc_inh_conn_prob = 0.15 inh_exc_conn_prob = 1 inh_inh_conn_prob = 1 weight_expr = 'abs(normal(1,0.5))' for popEpr in allExc: for popEpo in allExc: proj = add_projection(network, "projEE", popEpr, popEpo, synAmpaEE.id, exc_exc_conn_prob, global_delay, exc_target_dendrites, weight_expr) for popIpo in allInh: proj = add_projection(network, "projEI", popEpr, popIpo, synAmpaEI.id, exc_inh_conn_prob, global_delay, exc_target_dendrites, weight_expr) for popIpr in allInh: for popEpo in allExc: proj = add_projection(network, "projIE", popIpr, popEpo, synGabaIE.id, inh_exc_conn_prob, global_delay, inh_target_dendrites, weight_expr) for popIpo in allInh: proj = add_projection(network, "projII", popIpr, popIpo, synGabaII.id, inh_inh_conn_prob, global_delay, inh_target_dendrites, weight_expr) ##### Inputs for pop in allExc: oc.add_inputs_to_population(network, "Stim_pre_%s" % pop.id, pop, tpfsA.id, all_cells=True) for pop in allInh: oc.add_inputs_to_population(network, "Stim_pre_%s" % pop.id, pop, tpfsA.id, all_cells=True) for pop in allExc: oc.add_inputs_to_population(network, "Stim_E_%s" % pop.id, pop, tpfsB.id, all_cells=True) for pop in allInh: num_inh_pert = int(pop.get_size() * fraction_inh_pert) oc.add_inputs_to_population(network, "Stim_I_pert_%s" % pop.id, pop, tpfsC.id, all_cells=False, only_cells=range(0, num_inh_pert)) oc.add_inputs_to_population(network, "Stim_I_nonpert_%s" % pop.id, pop, tpfsB.id, all_cells=False, only_cells=range(num_inh_pert, pop.get_size())) # Work in progress... # General idea: clamp one (or more) exc cell at rev pot of inh syn and see only exc inputs # if exc_clamp: vc = oc.add_voltage_clamp_triple(nml_doc, id="exc_clamp", delay='0ms', duration='%sms' % duration, conditioning_voltage=synGaba1.erev, testing_voltage=synGaba1.erev, return_voltage=synGaba1.erev, simple_series_resistance="1e5ohm", active="1") for pop in exc_clamp: oc.add_inputs_to_population(network, "exc_clamp_%s" % pop, network.get_by_id(pop), vc.id, all_cells=False, only_cells=exc_clamp[pop]) ##### Save NeuroML and LEMS Simulation files nml_file_name = '%s.net.%s' % (network.id, 'nml.h5' if format == 'hdf5' else 'nml') oc.save_network(nml_doc, nml_file_name, validate=(format == 'xml'), format=format, target_dir=target_dir) print("Saved to: %s" % nml_file_name) save_v = {} plot_v = {} if num_exc > 0: exc_traces = '%s_%s_v.dat' % (network.id, popExc.id) save_v[exc_traces] = [] plot_v[popExc.id] = [] if num_inh > 0: inh_traces = '%s_%s_v.dat' % (network.id, popInh.id) save_v[inh_traces] = [] plot_v[popInh.id] = [] if num_exc2 > 0: exc2_traces = '%s_%s_v.dat' % (network.id, popExc2.id) save_v[exc2_traces] = [] plot_v[popExc2.id] = [] if num_inh2 > 0: inh2_traces = '%s_%s_v.dat' % (network.id, popInh2.id) save_v[inh2_traces] = [] plot_v[popInh2.id] = [] for i in range(min(max_in_pop_to_plot_and_save, num_exc)): plot_v[popExc.id].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) save_v[exc_traces].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) for i in range(min(max_in_pop_to_plot_and_save, num_exc2)): plot_v[popExc2.id].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) save_v[exc2_traces].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) for i in range(min(max_in_pop_to_plot_and_save, num_inh)): plot_v[popInh.id].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) save_v[inh_traces].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) for i in range(min(max_in_pop_to_plot_and_save, num_inh2)): plot_v[popInh2.id].append("%s/%i/%s/v" % (popInh2.id, i, popInh2.component)) save_v[inh2_traces].append("%s/%i/%s/v" % (popInh2.id, i, popInh2.component)) gen_spike_saves_for_all_somas = True lems_file_name, lems_sim = oc.generate_lems_simulation( nml_doc, network, target_dir + nml_file_name, duration=duration, dt=dt, gen_plots_for_all_v=False, gen_plots_for_quantities=plot_v, gen_saves_for_all_v=False, gen_saves_for_quantities=save_v, gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, target_dir=target_dir, report_file_name='report.txt') if run_in_simulator: print("Running %s for %sms in %s" % (lems_file_name, duration, run_in_simulator)) traces, events = oc.simulate_network(lems_file_name, run_in_simulator, max_memory='4000M', nogui=True, load_saved_data=True, reload_events=True, plot=False, verbose=True, num_processors=num_processors) print("Reloaded traces: %s" % traces.keys()) #print("Reloaded events: %s"%events.keys()) use_events_for_rates = False exc_rate = 0 inh_rate = 0 if use_events_for_rates: if (run_in_simulator == 'jNeuroML_NetPyNE'): raise ( 'Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE' ) for ek in events.keys(): rate = 1000 * len(events[ek]) / float(duration) print("Cell %s has a rate %s Hz" % (ek, rate)) if 'popExc' in ek: exc_rate += rate / num_exc if 'popInh' in ek: inh_rate += rate / num_inh else: tot_exc_rate = 0 exc_cells = 0 tot_inh_rate = 0 inh_cells = 0 tt = [t * 1000 for t in traces['t']] for tk in traces.keys(): if tk != 't': rate = get_rate_from_trace(tt, [v * 1000 for v in traces[tk]]) print("Cell %s has rate %s Hz" % (tk, rate)) if 'popExc' in tk: tot_exc_rate += rate exc_cells += 1 if 'popInh' in tk: tot_inh_rate += rate inh_cells += 1 exc_rate = tot_exc_rate / exc_cells inh_rate = tot_inh_rate / inh_cells print("Run %s: Exc rate: %s Hz; Inh rate %s Hz" % (reference, exc_rate, inh_rate)) return exc_rate, inh_rate, traces return nml_doc, nml_file_name, lems_file_name
def generate(scalePops=1, percentage_exc_detailed=0, scalex=1, scaley=1, scalez=1, ratio_inh_exc=2, connections=True, duration=1000, input_rate=150, global_delay=2, max_in_pop_to_plot_and_save=5, format='xml', run_in_simulator=None): reference = ("Multiscale__g%s__i%s" % (ratio_inh_exc, input_rate)).replace( '.', '_') num_exc = scale_pop_size(80, scalePops) num_exc2 = int(0.5 + num_exc * percentage_exc_detailed / 100.0) num_exc -= num_exc2 num_inh = scale_pop_size(40, scalePops) nml_doc, network = oc.generate_network(reference) oc.include_opencortex_cell( nml_doc, 'AllenInstituteCellTypesDB_HH/HH_477127614.cell.nml') oc.include_opencortex_cell( nml_doc, 'AllenInstituteCellTypesDB_HH/HH_476686112.cell.nml') oc.include_opencortex_cell(nml_doc, 'L23Pyr_SmithEtAl2013/L23_NoHotSpot.cell.nml') xDim = 1000 * scalex yDim = 300 * scaley zDim = 1000 * scalez xs = -200 ys = -150 zs = 100 ##### Synapses exc_syn_nS = 1. synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="%snS" % exc_syn_nS, erev="0mV", tau_rise="0.5ms", tau_decay="5ms") synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="%snS" % (exc_syn_nS * ratio_inh_exc), erev="-80mV", tau_rise="1ms", tau_decay="20ms") ##### Input types pfs1 = oc.add_poisson_firing_synapse(nml_doc, id="psf1", average_rate="%s Hz" % input_rate, synapse_id=synAmpa1.id) ##### Populations popExc = oc.add_population_in_rectangular_region(network, 'popExc', 'HH_477127614', num_exc, xs, ys, zs, xDim, yDim, zDim, color='0 0 1') popExc2 = oc.add_population_in_rectangular_region(network, 'popExc2', 'L23_NoHotSpot', num_exc2, xs, ys, zs, xDim, yDim, zDim, color='0 1 0') allExc = [popExc, popExc2] popInh = oc.add_population_in_rectangular_region(network, 'popInh', 'HH_476686112', num_inh, xs, ys, zs, xDim, yDim, zDim, color='1 0 0') ##### Projections if connections: for pop1 in allExc: for pop2 in allExc: proj = oc.add_probabilistic_projection(network, "proj0", pop1, pop2, synAmpa1.id, 0.5, delay=global_delay) proj = oc.add_probabilistic_projection(network, "proj1", pop1, popInh, synAmpa1.id, 0.7, delay=global_delay) proj = oc.add_probabilistic_projection(network, "proj2", popInh, pop1, synGaba1.id, 0.7, delay=global_delay) proj = oc.add_probabilistic_projection(network, "proj3", popInh, popInh, synGaba1.id, 0.5, delay=global_delay) ##### Inputs for pop in allExc: oc.add_inputs_to_population(network, "Stim_%s" % pop.id, pop, pfs1.id, all_cells=True) ##### Save NeuroML and LEMS Simulation files target_dir = './temp/' nml_file_name = '%s.net.%s' % (network.id, 'nml.h5' if format == 'hdf5' else 'nml') oc.save_network(nml_doc, nml_file_name, validate=(format == 'xml'), format=format, target_dir=target_dir) if format == 'xml': plot_v = {popExc.id: [], popExc2.id: [], popInh.id: []} exc_traces = '%s_%s_v.dat' % (network.id, popExc.id) exc2_traces = '%s_%s_v.dat' % (network.id, popExc2.id) inh_traces = '%s_%s_v.dat' % (network.id, popInh.id) save_v = {exc_traces: [], inh_traces: [], exc2_traces: []} for i in range(min(max_in_pop_to_plot_and_save, num_exc)): plot_v[popExc.id].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) save_v[exc_traces].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) for i in range(min(max_in_pop_to_plot_and_save, num_exc2)): plot_v[popExc2.id].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) save_v[exc2_traces].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) for i in range(min(max_in_pop_to_plot_and_save, num_inh)): plot_v[popInh.id].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) save_v[inh_traces].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) gen_spike_saves_for_all_somas = run_in_simulator != 'jNeuroML_NetPyNE' lems_file_name = oc.generate_lems_simulation( nml_doc, network, target_dir + nml_file_name, duration=duration, dt=0.025, gen_plots_for_all_v=False, gen_plots_for_quantities=plot_v, gen_saves_for_all_v=False, gen_saves_for_quantities=save_v, gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, target_dir=target_dir) if run_in_simulator: print("Running %s in %s" % (lems_file_name, run_in_simulator)) traces, events = oc.simulate_network(lems_file_name, run_in_simulator, max_memory='4000M', nogui=True, load_saved_data=True, reload_events=True, plot=False, verbose=False) print("Reloaded traces: %s" % traces.keys()) #print("Reloaded events: %s"%events.keys()) use_events_for_rates = False exc_rate = 0 inh_rate = 0 if use_events_for_rates: if (run_in_simulator == 'jNeuroML_NetPyNE'): raise ( 'Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE' ) for ek in events.keys(): rate = 1000 * len(events[ek]) / float(duration) print("Cell %s has rate %s Hz" % (ek, rate)) if 'popExc' in ek: exc_rate += rate / num_exc if 'popInh' in ek: inh_rate += rate / num_inh else: tot_exc_rate = 0 exc_cells = 0 tot_inh_rate = 0 inh_cells = 0 tt = [t * 1000 for t in traces['t']] for tk in traces.keys(): if tk != 't': rate = get_rate_from_trace( tt, [v * 1000 for v in traces[tk]]) print("Cell %s has rate %s Hz" % (tk, rate)) if 'popExc' in tk: tot_exc_rate += rate exc_cells += 1 if 'popInh' in tk: tot_inh_rate += rate inh_cells += 1 exc_rate = tot_exc_rate / exc_cells inh_rate = tot_inh_rate / inh_cells print("Run %s: Exc rate: %s Hz; Inh rate %s Hz" % (reference, exc_rate, inh_rate)) return exc_rate, inh_rate, traces else: lems_file_name = None return nml_doc, nml_file_name, lems_file_name
def RunColumnSimulation(net_id="TestRunColumn", nml2_source_dir="../../../neuroConstruct/generatedNeuroML2/", sim_config="TempSimConfig", scale_cortex=0.1, scale_thalamus=0.1, cell_bodies_overlap=True, cylindrical=True, default_synaptic_delay=0.05, gaba_scaling=1.0, l4ss_ampa_scaling=1.0, l5pyr_gap_scaling =1.0, in_nrt_tcr_nmda_scaling =1.0, pyr_ss_nmda_scaling=1.0, deep_bias_current=-1, include_gap_junctions=True, which_cell_types_to_include='all', dir_nml2="../../", backgroundL5Rate=30, # Hz backgroundL23Rate=30, # Hz duration=300, dt=0.025, max_memory='1000M', seed=1234, simulator=None, save_format='xml', num_of_cylinder_sides=None): popDictFull = {} ############## Full model ################################## popDictFull['CG3D_L23PyrRS'] = (1000, 'L23','L23PyrRS','multi', occ.L23_PRINCIPAL_CELL) popDictFull['CG3D_L23PyrFRB']= (50,'L23','L23PyrFRB_varInit','multi', occ.L23_PRINCIPAL_CELL_2) popDictFull['CG3D_SupBask'] = (90, 'L23','SupBasket','multi', occ.L23_INTERNEURON) # over both l23 & l4 popDictFull['CG3D_SupAxAx'] = (90, 'L23','SupAxAx','multi', occ.L23_INTERNEURON_2) # over both l23 & l4 popDictFull['CG3D_SupLTS']= (90,'L23','SupLTSInter','multi', occ.L4_INTERNEURON) # over both l23 & l4 popDictFull['CG3D_L4SpinStell']= (240,'L4','L4SpinyStellate','multi', occ.L4_PRINCIPAL_CELL) popDictFull['CG3D_L5TuftIB'] = (800, 'L5','L5TuftedPyrIB','multi', occ.L5_PRINCIPAL_CELL) popDictFull['CG3D_L5TuftRS']= (200,'L5','L5TuftedPyrRS','multi', occ.L5_PRINCIPAL_CELL_2) popDictFull['CG3D_L6NonTuftRS']= (500,'L6','L6NonTuftedPyrRS','multi', occ.L6_PRINCIPAL_CELL) popDictFull['CG3D_DeepAxAx']= (100,'L6','DeepAxAx','multi', occ.L5_INTERNEURON) # over both l5 & l6 popDictFull['CG3D_DeepBask']= (100,'L6','DeepBasket','multi', occ.L5_INTERNEURON_2) # over both l5 & l6 popDictFull['CG3D_DeepLTS']= (100,'L6','DeepLTSInter','multi', occ.L6_INTERNEURON) # over both l5 & l6 popDictFull['CG3D_nRT']= (100,'Thalamus','nRT','multi', occ.THALAMUS_1) popDictFull['CG3D_TCR']= (100,'Thalamus','TCR','multi', occ.THALAMUS_2) ############################################################### dir_to_cells=os.path.join(dir_nml2,"cells") dir_to_synapses=os.path.join(dir_nml2,"synapses") dir_to_gap_junctions=os.path.join(dir_nml2,"gapJunctions") popDict={} cell_model_list=[] cell_diameter_dict={} nml_doc, network = oc.generate_network(net_id,seed) for cell_population in popDictFull.keys(): include_cell_population=False cell_model=popDictFull[cell_population][2] if which_cell_types_to_include=='all' or cell_model in which_cell_types_to_include: popDict[cell_population]=() if popDictFull[cell_population][1] !='Thalamus': popDict[cell_population]=(int(round(scale_cortex*popDictFull[cell_population][0])), popDictFull[cell_population][1], popDictFull[cell_population][2], popDictFull[cell_population][3], popDictFull[cell_population][4]) cell_count=int(round(scale_cortex*popDictFull[cell_population][0])) else: popDict[cell_population]=(int(round(scale_thalamus*popDictFull[cell_population][0])), popDictFull[cell_population][1], popDictFull[cell_population][2], popDictFull[cell_population][3], popDictFull[cell_population][4]) cell_count=int(round(scale_thalamus*popDictFull[cell_population][0])) if cell_count !=0: include_cell_population=True if include_cell_population: cell_model_list.append(popDictFull[cell_population][2]) cell_diameter=oc_build.get_soma_diameter(popDictFull[cell_population][2],dir_to_cell=dir_to_cells) if popDictFull[cell_population][2] not in cell_diameter_dict.keys(): cell_diameter_dict[popDictFull[cell_population][2]]=cell_diameter cell_model_list_final=list(set(cell_model_list)) opencortex.print_comment_v("This is a final list of cell model ids: %s"%cell_model_list_final) copy_nml2_from_source=False for cell_model in cell_model_list_final: if not os.path.exists(os.path.join(dir_to_cells,"%s.cell.nml"%cell_model)): copy_nml2_from_source=True break if copy_nml2_from_source: oc_build.copy_nml2_source(dir_to_project_nml2=dir_nml2, primary_nml2_dir=nml2_source_dir, electrical_synapse_tags=['Elect'], chemical_synapse_tags=['.synapse.'], extra_channel_tags=['cad']) passed_includes_in_cells=oc_utils.check_includes_in_cells(dir_to_cells,cell_model_list_final,extra_channel_tags=['cad']) if not passed_includes_in_cells: opencortex.print_comment_v("Execution of RunColumn.py will terminate.") quit() for cell_model in cell_model_list_final: oc_build._add_cell_and_channels(nml_doc, os.path.join(dir_to_cells,"%s.cell.nml"%cell_model), cell_model, use_prototypes=False) t1=-0 t2=-250 t3=-250 t4=-200.0 t5=-300.0 t6=-300.0 t7=-200.0 t8=-200.0 boundaries={} boundaries['L1']=[0,t1] boundaries['L23']=[t1,t1+t2+t3] boundaries['L4']=[t1+t2+t3,t1+t2+t3+t4] boundaries['L5']=[t1+t2+t3+t4,t1+t2+t3+t4+t5] boundaries['L6']=[t1+t2+t3+t4+t5,t1+t2+t3+t4+t5+t6] boundaries['Thalamus']=[t1+t2+t3+t4+t5+t6+t7,t1+t2+t3+t4+t5+t6+t7+t8] xs = [0,500] zs = [0,500] passed_pops=oc_utils.check_pop_dict_and_layers(pop_dict=popDict,boundary_dict=boundaries) if passed_pops: opencortex.print_comment_v("Population parameters were specified correctly.") if cylindrical: pop_params=oc_utils.add_populations_in_cylindrical_layers(network,boundaries,popDict,radiusOfCylinder=250,cellBodiesOverlap=cell_bodies_overlap, cellDiameterArray=cell_diameter_dict,numOfSides=num_of_cylinder_sides) else: pop_params=oc_utils.add_populations_in_rectangular_layers(network,boundaries,popDict,xs,zs,cellBodiesOverlap=False,cellDiameterArray=cell_diameter_dict) else: opencortex.print_comment_v("Population parameters were specified incorrectly; execution of RunColumn.py will terminate.") quit() src_files = os.listdir("./") if 'netConnList' in src_files: full_path_to_connectivity='netConnList' else: full_path_to_connectivity="../../../neuroConstruct/pythonScripts/netbuild/netConnList" weight_params=[{'weight':gaba_scaling,'synComp':'GABAA','synEndsWith':[],'targetCellGroup':[]}, {'weight':l4ss_ampa_scaling,'synComp':'Syn_AMPA_L4SS_L4SS','synEndsWith':[],'targetCellGroup':[]}, {'weight':l5pyr_gap_scaling,'synComp':'Syn_Elect_DeepPyr_DeepPyr','synEndsWith':[],'targetCellGroup':['CG3D_L5']}, {'weight':in_nrt_tcr_nmda_scaling,'synComp':'NMDA','synEndsWith':["_IN","_DeepIN","_SupIN","_SupFS","_DeepFS","_SupLTS","_DeepLTS","_nRT","_TCR"], 'targetCellGroup':[]}, {'weight':pyr_ss_nmda_scaling,'synComp':'NMDA','synEndsWith':["_IN","_DeepIN","_SupIN","_SupFS","_DeepFS","_SupLTS","_DeepLTS","_nRT","_TCR"], 'targetCellGroup':[]}] delay_params=[{'delay':default_synaptic_delay,'synComp':'all'}] passed_weight_params=oc_utils.check_weight_params(weight_params) passed_delay_params=oc_utils.check_delay_params(delay_params) if passed_weight_params and passed_delay_params: opencortex.print_comment_v("Synaptic weight and delay parameters were specified correctly.") ignore_synapses = [] if not include_gap_junctions: ignore_synapses = ['Syn_Elect_SupPyr_SupPyr','Syn_Elect_CortIN_CortIN','Syn_Elect_L4SS_L4SS','Syn_Elect_DeepPyr_DeepPyr','Syn_Elect_nRT_nRT'] all_synapse_components,projArray,cached_segment_dicts=oc_utils.build_connectivity(net=network, pop_objects=pop_params, path_to_cells=dir_to_cells, full_path_to_conn_summary=full_path_to_connectivity, pre_segment_group_info=[{'PreSegGroup':"distal_axon",'ProjType':'Chem'}], synaptic_scaling_params=weight_params, synaptic_delay_params=delay_params, ignore_synapses=ignore_synapses) else: if not passed_weight_params: opencortex.print_comment_v("Synaptic weight parameters were specified incorrectly; execution of RunColumn.py will terminate.") if not passed_delay_params: opencortex.print_comment_v("Synaptic delay parameters were specified incorrectly; execution of RunColumn.py will terminate.") quit() ############ for testing only; will add original specifications later ############################################################## if sim_config=="Testing1": input_params={'CG3D_L23PyrRS':[{'InputType':'GeneratePoissonTrains', 'InputName':'Poi_CG3D_L23PyrRS', 'TrainType':'transient', 'Synapse':'Syn_AMPA_SupPyr_SupPyr', 'AverageRateList':[200.0,150.0], 'RateUnits':'Hz', 'TimeUnits':'ms', 'DurationList':[100.0,50.0], 'DelayList':[50.0,200.0], 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'soma_group':1 } }] } ################################################################################################################################### if sim_config=="Testing2": input_params_final={'CG3D_L23PyrRS':[{'InputType':'PulseGenerators', 'InputName':"DepCurr_L23RS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5,1.0E-5], 'LargestAmplitudeList':[1.0E-4,2.0E-5], 'DurationList':[20000.0,20000.0], 'DelayList':[0.0,20000.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':1} }] } if sim_config=="TempSimConfig": input_params ={'CG3D_L23PyrRS':[{'InputType':'PulseGenerators', 'InputName':"DepCurr_L23RS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5}, {'InputType':'GeneratePoissonTrains', 'InputName':"BackgroundL23RS", 'TrainType':'persistent', 'Synapse':'Syn_AMPA_SupPyr_SupPyr', 'AverageRateList':[float(backgroundL23Rate)], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':100} }, {'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL23RS", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[0.1], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':143, 'UniversalFractionAlong':0.5} ], 'CG3D_TCR':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimTCR", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':269, 'UniversalFractionAlong':0.5}, {'InputType':'GeneratePoissonTrains', 'InputName':"Input_20", 'TrainType':'persistent', 'Synapse':'Syn_AMPA_L6NT_TCR', 'AverageRateList':[50.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':100} }], 'CG3D_L23PyrFRB':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL23FRB", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[0.1], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':143, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L23FRB", 'Noise':True, 'SmallestAmplitudeList':[2.5E-4], 'LargestAmplitudeList':[3.5E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ], 'CG3D_L6NonTuftRS':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL6NT", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':95, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L6NT", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ], 'CG3D_L4SpinStell':[{'InputType':'PulseGenerators', 'InputName':"DepCurr_L4SS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5}], 'CG3D_L5TuftIB':[{'InputType':'GeneratePoissonTrains', 'InputName':"BackgroundL5", 'TrainType':'persistent', 'Synapse':'Syn_AMPA_L5RS_L5Pyr', 'AverageRateList':[float(backgroundL5Rate)], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetDict':{'dendrite_group':100} }, {'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL5IB", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':119, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L5IB", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ], 'CG3D_L5TuftRS':[{'InputType':'GeneratePoissonTrains', 'InputName':"EctopicStimL5RS", 'TrainType':'persistent', 'Synapse':'SynForEctStim', 'AverageRateList':[1.0], 'RateUnits':'Hz', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':119, 'UniversalFractionAlong':0.5}, {'InputType':'PulseGenerators', 'InputName':"DepCurr_L5RS", 'Noise':True, 'SmallestAmplitudeList':[5.0E-5], 'LargestAmplitudeList':[1.0E-4], 'DurationList':[20000.0], 'DelayList':[0.0], 'TimeUnits':'ms', 'AmplitudeUnits':'uA', 'FractionToTarget':1.0, 'LocationSpecific':False, 'UniversalTargetSegmentID':0, 'UniversalFractionAlong':0.5} ] } input_params_final={} for pop_id in pop_params.keys(): if pop_id in input_params.keys(): input_params_final[pop_id]=input_params[pop_id] if deep_bias_current >= 0: for cell_group in input_params_final.keys(): for input_group in range(0,len(input_params_final[cell_group])): check_type=input_params_final[cell_group][input_group]['InputType']=="PulseGenerators" check_group_1= cell_group=="CG3D_L5TuftIB" check_group_2=cell_group =="CG3D_L5TuftRS" check_group_3= cell_group =="CG3D_L6NonTuftRS" if check_type and (check_group_1 or check_group_2 or check_group_3): opencortex.print_comment_v("Changing offset current in 'PulseGenerators' for %s to %f"%(cell_group, deep_bias_current)) input_params_final[cell_group][input_group]['SmallestAmplitudeList']=[ (deep_bias_current-0.05)/1000 ] input_params_final[cell_group][input_group]['LargestAmplitudeList']=[ (deep_bias_current+0.05)/1000 ] input_list_array_final, input_synapse_list=oc_utils.build_inputs(nml_doc=nml_doc, net=network, population_params=pop_params, input_params=input_params_final, cached_dicts=cached_segment_dicts, path_to_cells=dir_to_cells, path_to_synapses=dir_to_synapses) #################################################################################################################################### for input_synapse in input_synapse_list: if input_synapse not in all_synapse_components: all_synapse_components.append(input_synapse) synapse_list=[] gap_junction_list=[] for syn_ind in range(0,len(all_synapse_components)): if 'Elect' not in all_synapse_components[syn_ind]: synapse_list.append(all_synapse_components[syn_ind]) all_synapse_components[syn_ind]=os.path.join(net_id,all_synapse_components[syn_ind]+".synapse.nml") else: gap_junction_list.append(all_synapse_components[syn_ind]) all_synapse_components[syn_ind]=os.path.join(net_id,all_synapse_components[syn_ind]+".nml") oc_build.add_synapses(nml_doc,dir_to_synapses,synapse_list,synapse_tag=True) oc_build.add_synapses(nml_doc,dir_to_gap_junctions,gap_junction_list,synapse_tag=False) nml_file_name = '%s.net.nml'%network.id validate=True if save_format=='hdf5': nml_file_name += '.h5' validate=False oc.save_network(nml_doc, nml_file_name, validate=validate,max_memory=max_memory, format=save_format) oc_build.remove_component_dirs(dir_to_project_nml2="%s"%network.id,list_of_cell_ids=cell_model_list_final,extra_channel_tags=['cad']) lems_file_name=oc.generate_lems_simulation(nml_doc, network, nml_file_name, duration =duration, dt =dt, include_extra_lems_files=all_synapse_components) if simulator != None: opencortex.print_comment_v("Starting simulation of %s.net.nml"%net_id) oc.simulate_network(lems_file_name=lems_file_name, simulator=simulator, max_memory=max_memory)
def generate( scale_populations=1, percentage_exc_detailed=0, #exc2_cell = 'SmithEtAl2013/L23_Retuned_477127614', exc2_cell='SmithEtAl2013/L23_NoHotSpot', #exc2_cell = 'BBP/cADpyr229_L23_PC_5ecbf9b163_0_0', #exc2_cell = 'BBP/cNAC187_L23_NBC_9d37c4b1f8_0_0', #exc2_cell = 'Thalamocortical/L23PyrRS', percentage_inh_detailed=0, scalex=1, scaley=1, scalez=1, exc_exc_conn_prob=0.25, exc_inh_conn_prob=0.25, inh_exc_conn_prob=0.75, inh_inh_conn_prob=0.75, ee2_conn_prob=0, ie2_conn_prob=0, Bee=.1, Bei=.1, Bie=-.2, Bii=-.2, Bee2=1, Bie2=-2, Be_bkg=.1, Be_stim=.1, r_bkg=0, r_bkg_ExtExc=0, r_bkg_ExtInh=0, r_bkg_ExtExc2=0, r_stim=0, fraction_inh_pert=0.75, Ttrans=500, # transitent time to discard the data (ms) Tblank=1500, # simulation time before perturbation (ms) Tstim=1500, # simulation time of perturbation (ms) Tpost=500, # simulation time after perturbation (ms) connections=True, connections2=False, exc_target_dendrites=False, inh_target_dendrites=False, duration=1000, dt=0.025, global_delay=.1, max_in_pop_to_plot_and_save=10, format='xml', suffix='', run_in_simulator=None, num_processors=1, target_dir='./temp/', v_clamp=False, simulation_seed=11111): reference = ("ISN_net%s" % (suffix)).replace('.', '_') ks = open('kernelseed', 'w') ks.write('%i' % simulation_seed) ks.close() info = (' Generating ISN network: %s\n' % reference) info += ( ' Duration: %s; dt: %s; scale: %s; simulator: %s (num proc. %s)\n' % (duration, dt, scale_populations, run_in_simulator, num_processors)) info += (' Bee: %s; Bei: %s; Bie: %s; Bii: %s\n' % (Bee, Bei, Bie, Bii)) info += (' Bkg exc at %sHz\n' % (r_bkg_ExtExc)) info += (' Bkg inh at %sHz\n' % (r_bkg_ExtInh)) info += (' Be_stim: %s at %sHz (i.e. %sHz for %s perturbed I cells)\n' % (Be_stim, r_stim, r_bkg_ExtInh + r_stim, fraction_inh_pert)) info += (' Exc detailed: %s%% - Inh detailed %s%%\n' % (percentage_exc_detailed, percentage_inh_detailed)) info += (' Seed: %s' % (simulation_seed)) print('-------------------------------------------------') print(info) print('-------------------------------------------------') num_exc = scale_pop_size(np.round(100 * exc_inh_fraction), scale_populations) num_exc2 = int(math.ceil(num_exc * percentage_exc_detailed / 100.0)) num_exc -= num_exc2 num_inh = scale_pop_size(np.round(100 * (1 - exc_inh_fraction)), scale_populations) num_inh2 = int(math.ceil(num_inh * percentage_inh_detailed / 100.0)) num_inh -= num_inh2 nml_doc, network = oc.generate_network(reference, network_seed=simulation_seed) nml_doc.notes = info network.notes = info #exc_cell_id = 'AllenHH_480351780' #exc_cell_id = 'AllenHH_477127614' #exc_cell_id = 'HH_477127614' exc_cell_id = 'HH2_477127614' exc_type = exc_cell_id.split('_')[0] oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/%s/%s.cell.nml' % (exc_type, exc_cell_id), exc_cell_id) #inh_cell_id = 'AllenHH_485058595' #inh_cell_id = 'AllenHH_476686112' #inh_cell_id = 'AllenHH_477127614' #inh_cell_id = 'HH_476686112' inh_cell_id = 'HH2_476686112' inh_type = exc_cell_id.split('_')[0] oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/%s/%s.cell.nml' % (inh_type, inh_cell_id), inh_cell_id) if percentage_exc_detailed > 0: exc2_cell_id = exc2_cell.split('/')[1] exc2_cell_dir = exc2_cell.split('/')[0] oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/%s/%s.cell.nml' % (exc2_cell_dir, exc2_cell_id), exc2_cell_id) if percentage_inh_detailed > 0: inh2_cell_id = 'cNAC187_L23_NBC_9d37c4b1f8_0_0' oc.include_neuroml2_cell_and_channels( nml_doc, 'cells/BBP/%s.cell.nml' % inh2_cell_id, inh2_cell_id) xDim = 700 * scalex yDim = 100 * scaley yDimExc2 = 50 * scaley zDim = 700 * scalez xs = -1 * xDim / 2 ys = -1 * yDim / 2 zs = -1 * zDim / 2 ##### Synapses synAmpaEE = oc.add_exp_one_syn(nml_doc, id="ampaEE", gbase="%snS" % Bee, erev="0mV", tau_decay="1ms") synAmpaEI = oc.add_exp_one_syn(nml_doc, id="ampaEI", gbase="%snS" % Bei, erev="0mV", tau_decay="1ms") synGabaIE = oc.add_exp_one_syn(nml_doc, id="gabaIE", gbase="%snS" % abs(Bie), erev="-80mV", tau_decay="2ms") synGabaII = oc.add_exp_one_syn(nml_doc, id="gabaII", gbase="%snS" % abs(Bii), erev="-80mV", tau_decay="2ms") synAmpaBkg = oc.add_exp_one_syn(nml_doc, id="ampaBkg", gbase="%snS" % Be_bkg, erev="0mV", tau_decay="1ms") #synAmpaStim = oc.add_exp_one_syn(nml_doc, id="ampaStim", gbase="%snS"%Be_stim, # erev="0mV", tau_decay="1ms") synAmpaEE2 = oc.add_exp_one_syn(nml_doc, id="ampaEE2", gbase="%snS" % Bee2, erev="0mV", tau_decay="10ms") synGabaIE2 = oc.add_exp_one_syn(nml_doc, id="gabaIE2", gbase="%snS" % abs(Bie2), erev="-80mV", tau_decay="10ms") ##### Input types '''tpfsA = oc.add_transient_poisson_firing_synapse(nml_doc, id="tpsfA", average_rate="%s Hz"%r_bkg, delay = '0ms', duration = '%sms'%(Ttrans+Tblank), synapse_id=synAmpaBkg.id) tpfsB = oc.add_transient_poisson_firing_synapse(nml_doc, id="tpsfB", average_rate="%s Hz"%r_bkg, delay = '%sms'%(Ttrans+Tblank), duration = '%sms'%(Tstim), synapse_id=synAmpaBkg.id) tpfsC = oc.add_transient_poisson_firing_synapse(nml_doc, id="tpsfC", average_rate="%s Hz"%(r_bkg+r_stim), delay = '%sms'%(Ttrans+Tblank), duration = '%sms'%(Tstim), synapse_id=synAmpaStim.id)''' tpfsExtExc = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpfsExtExc", average_rate="%s Hz" % r_bkg_ExtExc, delay='0ms', duration='%sms' % (Ttrans + Tblank + Tstim + Tpost), synapse_id=synAmpaBkg.id) tpfsExtExc2 = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpfsExtExc2", average_rate="%s Hz" % r_bkg_ExtExc2, delay='0ms', duration='%sms' % (Ttrans + Tblank + Tstim + Tpost), synapse_id=synAmpaBkg.id) tpfsExtInh = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpfsExtInh", average_rate="%s Hz" % r_bkg_ExtInh, delay='0ms', duration='%sms' % (Ttrans + Tblank + Tstim + Tpost), synapse_id=synAmpaBkg.id) tpfsPertInh_before = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpfsPertInh_before", average_rate="%s Hz" % r_bkg_ExtInh, delay='0ms', duration='%sms' % (Ttrans + Tblank), synapse_id=synAmpaBkg.id) tpfsPertInh_during = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpfsPertInh_during", average_rate="%s Hz" % (r_bkg_ExtInh + r_stim), delay='%sms' % (Ttrans + Tblank), duration='%sms' % (Tstim), synapse_id=synAmpaBkg.id) tpfsPertInh_after = oc.add_transient_poisson_firing_synapse( nml_doc, id="tpfsPertInh_after", average_rate="%s Hz" % r_bkg_ExtInh, delay='%sms' % (Ttrans + Tblank + Tstim), duration='%sms' % (Tpost), synapse_id=synAmpaBkg.id) ##### Populations popExc = oc.add_population_in_rectangular_region(network, 'popExc', exc_cell_id, num_exc, xs, ys, zs, xDim, yDim, zDim, color=exc_color) from neuroml import Property popExc.properties.append(Property('type', 'E')) allExc = [popExc] if num_exc2 > 0: popExc2 = oc.add_population_in_rectangular_region(network, 'popExc2', exc2_cell_id, num_exc2, xs, yDim / 2, zs, xDim, yDimExc2, zDim, color=exc2_color) popExc2.properties.append(Property('type', 'E')) allExc.append(popExc2) popInh = oc.add_population_in_rectangular_region(network, 'popInh', inh_cell_id, num_inh, xs, ys, zs, xDim, yDim, zDim, color=inh_color) popInh.properties.append(Property('type', 'I')) allInh = [popInh] if num_inh2 > 0: popInh2 = oc.add_population_in_rectangular_region(network, 'popInh2', inh2_cell_id, num_inh2, xs, ys, zs, xDim, yDim, zDim, color=inh2_color) allInh.append(popInh2) ##### Projections if connections: weight_expr = 'abs(normal(1,0.5))' for popEpr in allExc: for popEpo in allExc: proj = add_projection(network, "projEE", popEpr, popEpo, synAmpaEE.id, exc_exc_conn_prob, global_delay, exc_target_dendrites, weight_expr) for popIpo in allInh: proj = add_projection(network, "projEI", popEpr, popIpo, synAmpaEI.id, exc_inh_conn_prob, global_delay, exc_target_dendrites, weight_expr) for popIpr in allInh: for popEpo in allExc: proj = add_projection(network, "projIE", popIpr, popEpo, synGabaIE.id, inh_exc_conn_prob, global_delay, inh_target_dendrites, weight_expr) for popIpo in allInh: proj = add_projection(network, "projII", popIpr, popIpo, synGabaII.id, inh_inh_conn_prob, global_delay, inh_target_dendrites, weight_expr) elif connections2: weight_expr = 'abs(normal(1,0.5))' proj = add_projection(network, "projEE", popExc, popExc, synAmpaEE.id, exc_exc_conn_prob, global_delay, exc_target_dendrites, weight_expr) proj = add_projection(network, "projEI", popExc, popInh, synAmpaEI.id, exc_inh_conn_prob, global_delay, exc_target_dendrites, weight_expr) proj = add_projection(network, "projIE", popInh, popExc, synGabaIE.id, inh_exc_conn_prob, global_delay, inh_target_dendrites, weight_expr) proj = add_projection(network, "projII", popInh, popInh, synGabaII.id, inh_inh_conn_prob, global_delay, inh_target_dendrites, weight_expr) proj = add_projection(network, "projEE2", popExc, popExc2, synAmpaEE2.id, ee2_conn_prob, global_delay, exc_target_dendrites, weight_expr) proj = add_projection(network, "projIE2", popInh, popExc2, synGabaIE2.id, ie2_conn_prob, global_delay, inh_target_dendrites, weight_expr) ##### Inputs oc.add_inputs_to_population(network, "Stim_E", popExc, tpfsExtExc.id, all_cells=True) if num_exc2 > 0: oc.add_inputs_to_population(network, "Stim_E2", popExc2, tpfsExtExc2.id, all_cells=True) num_inh_pert = int(popInh.get_size() * fraction_inh_pert) oc.add_inputs_to_population(network, "Stim_I_nonpert", popInh, tpfsExtInh.id, all_cells=False, only_cells=range(num_inh_pert, popInh.get_size())) oc.add_inputs_to_population(network, "Stim_I_pert_before", popInh, tpfsPertInh_before.id, all_cells=False, only_cells=range(0, num_inh_pert)) oc.add_inputs_to_population(network, "Stim_I_pert_during", popInh, tpfsPertInh_during.id, all_cells=False, only_cells=range(0, num_inh_pert)) oc.add_inputs_to_population(network, "Stim_I_pert_after", popInh, tpfsPertInh_after.id, all_cells=False, only_cells=range(0, num_inh_pert)) # injecting noise in the soma of detailed neurons to insert some variability '''oc.add_targeted_inputs_to_population(network, "PG_noise", popExc2, 'noisyCurrentSource1', # from ../../../NoisyCurrentSource.xml segment_group='soma_group', number_per_cell = 1, all_cells=True) oc.add_inputs_to_population(network, "Stim_pre_ExtExc_%s"%popExc.id, popExc, tpfsExtExc.id, all_cells=True) for pop in allExc: #oc.add_inputs_to_population(network, "Stim_pre_ExtExc_%s"%pop.id, # pop, tpfsExtExc.id, # all_cells=True) oc.add_inputs_to_population(network, "Stim_pre_%s"%pop.id, pop, tpfsA.id, all_cells=True) oc.add_inputs_to_population(network, "Stim_E_%s"%pop.id, pop, tpfsB.id, all_cells=True) for pop in allInh: num_inh_pert = int(pop.get_size()*fraction_inh_pert) oc.add_inputs_to_population(network, "Stim_pre_ExtInh_%s"%pop.id, pop, tpfsExtInh.id, all_cells=True) oc.add_inputs_to_population(network, "Stim_pre_%s"%pop.id, pop, tpfsA.id, all_cells=True) oc.add_inputs_to_population(network, "Stim_I_pert_%s"%pop.id, pop, tpfsC.id, all_cells=False, only_cells=range(0,num_inh_pert)) oc.add_inputs_to_population(network, "Stim_I_nonpert_%s"%pop.id, pop, tpfsB.id, all_cells=False, only_cells=range(num_inh_pert,pop.get_size())) ''' save_v = {} plot_v = {} # Work in progress... # General idea: clamp one (or more) exc cell at rev pot of inh syn and see only exc inputs # if v_clamp: levels = {'IPSC': synAmpaEE.erev, 'EPSC': synGabaIE.erev} for l in levels: cell_index = levels.keys().index(l) pop = 'popExc2' plot = 'IClamp_i_%s' % (l) for seg_id in [0, 2953, 1406]: # 2953: end of axon; 1406 on dendrite clamp_id = "vclamp_cell%s_seg%s_%s" % (cell_index, seg_id, l) v_clamped = levels[l] vc = oc.add_voltage_clamp_triple( nml_doc, id=clamp_id, delay='0ms', duration='%sms' % duration, conditioning_voltage=v_clamped, testing_voltage=v_clamped, return_voltage=v_clamped, simple_series_resistance="1e2ohm", active="1") vc_dat_file = 'v_clamps_i_seg%s_%s.%s.dat' % (seg_id, l, simulation_seed) seg_file = '%s_seg%s_%s_v.dat' % (pop, seg_id, l) save_v[vc_dat_file] = [] plot_v[plot] = [] oc.add_inputs_to_population(network, "vclamp_seg%s_%s" % (seg_id, l), network.get_by_id(pop), vc.id, all_cells=False, only_cells=[cell_index], segment_ids=[seg_id]) # record at seg q = '%s/%s/%s/%s/%s/i' % (pop, cell_index, network.get_by_id(pop).component, seg_id, clamp_id) save_v[vc_dat_file].append(q) plot_v[plot].append(q) if seg_id != 0: save_v[seg_file] = [] q = '%s/%s/%s/%s/v' % (pop, cell_index, network.get_by_id(pop).component, seg_id) save_v[seg_file].append(q) ##### Save NeuroML and LEMS Simulation files nml_file_name = '%s.net.%s' % (network.id, 'nml.h5' if format == 'hdf5' else 'nml') oc.save_network(nml_doc, nml_file_name, validate=(format == 'xml'), format=format, target_dir=target_dir) print("Saved to: %s" % nml_file_name) if num_exc > 0: exc_traces = '%s_%s_v.dat' % (network.id, popExc.id) save_v[exc_traces] = [] plot_v[popExc.id] = [] if num_inh > 0: inh_traces = '%s_%s_v.dat' % (network.id, popInh.id) save_v[inh_traces] = [] plot_v[popInh.id] = [] if num_exc2 > 0: exc2_traces = '%s_%s_v.dat' % (network.id, popExc2.id) save_v[exc2_traces] = [] plot_v[popExc2.id] = [] if num_inh2 > 0: inh2_traces = '%s_%s_v.dat' % (network.id, popInh2.id) save_v[inh2_traces] = [] plot_v[popInh2.id] = [] for i in range(min(max_in_pop_to_plot_and_save, num_exc)): plot_v[popExc.id].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) save_v[exc_traces].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) for i in range(min(max_in_pop_to_plot_and_save, num_exc2)): plot_v[popExc2.id].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) save_v[exc2_traces].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) for i in range(min(max_in_pop_to_plot_and_save, num_inh)): plot_v[popInh.id].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) save_v[inh_traces].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) for i in range(min(max_in_pop_to_plot_and_save, num_inh2)): plot_v[popInh2.id].append("%s/%i/%s/v" % (popInh2.id, i, popInh2.component)) save_v[inh2_traces].append("%s/%i/%s/v" % (popInh2.id, i, popInh2.component)) gen_spike_saves_for_all_somas = True lems_file_name, lems_sim = oc.generate_lems_simulation( nml_doc, network, target_dir + nml_file_name, duration=duration, dt=dt, gen_plots_for_all_v=False, gen_plots_for_quantities=plot_v, gen_saves_for_all_v=False, gen_saves_for_quantities=save_v, gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, target_dir=target_dir, include_extra_lems_files=['./NoisyCurrentSource.xml'], report_file_name='report.txt', simulation_seed=simulation_seed) if run_in_simulator: print("Running %s for %sms in %s" % (lems_file_name, duration, run_in_simulator)) traces, events = oc.simulate_network(lems_file_name, run_in_simulator, max_memory='4000M', nogui=True, load_saved_data=True, reload_events=True, plot=False, verbose=True, num_processors=num_processors) print("Reloaded traces: %s" % traces.keys()) #print("Reloaded events: %s"%events.keys()) use_events_for_rates = False exc_rate = 0 inh_rate = 0 if use_events_for_rates: if (run_in_simulator == 'jNeuroML_NetPyNE'): raise ( 'Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE' ) for ek in events.keys(): rate = 1000 * len(events[ek]) / float(duration) print("Cell %s has a rate %s Hz" % (ek, rate)) if 'popExc' in ek: exc_rate += rate / num_exc if 'popInh' in ek: inh_rate += rate / num_inh else: tot_exc_rate = 0 exc_cells = 0 tot_inh_rate = 0 inh_cells = 0 tt = [t * 1000 for t in traces['t']] for tk in traces.keys(): if tk != 't': rate = get_rate_from_trace(tt, [v * 1000 for v in traces[tk]]) print("Cell %s has rate %s Hz" % (tk, rate)) if 'popExc' in tk: tot_exc_rate += rate exc_cells += 1 if 'popInh' in tk: tot_inh_rate += rate inh_cells += 1 exc_rate = tot_exc_rate / exc_cells inh_rate = tot_inh_rate / inh_cells print("Run %s: Exc rate: %s Hz; Inh rate %s Hz" % (reference, exc_rate, inh_rate)) return exc_rate, inh_rate, traces return nml_doc, nml_file_name, lems_file_name
def generate(cell_id, duration, reference, format='hdf5', num_cells=10, simulator=None): #Insyn = int(Ensyn * 0.2) #bInsyn = int(bEnsyn * 0.2) cell_file = '../%s.cell.nml' % cell_id if '/' in cell_id: cell_id = cell_id.split('/')[-1] nml_doc, network = oc.generate_network(reference, temperature='35degC') oc.include_neuroml2_cell_and_channels(nml_doc, cell_file, cell_id) pop = oc.add_population_in_rectangular_region(network, 'L23_pop', cell_id, num_cells, 0, 0, 0, 100, 100, 100) to_plot = {'Some_voltages': []} to_save = {'%s_%s_voltages.dat' % (reference, cell_id): []} interesting_seg_ids = [0, 200, 1000, 2000, 2500, 2949] # [soma, .. some dends .. , axon] interesting_seg_ids = [0] # [soma, .. some dends .. , axon] pg0 = oc.add_pulse_generator(nml_doc, id="pg0", delay="200ms", duration="600ms", amplitude="0.4nA") pg1 = oc.add_pulse_generator(nml_doc, id="pg1", delay="100ms", duration="400ms", amplitude="0.02nA") oc.add_targeted_inputs_to_population(network, "PG_fixed", pop, pg0.id, segment_group='soma_group', number_per_cell=1, all_cells=True) oc.add_targeted_inputs_to_population( network, "PG_variable", pop, 'cond0', # from ../../../ConductanceClamp.xml segment_group='soma_group', number_per_cell=1, all_cells=True, weights='random()') for i in range(num_cells): for seg_id in interesting_seg_ids: to_plot.values()[0].append('%s/%s/%s/%s/v' % (pop.id, i, pop.component, seg_id)) to_save.values()[0].append('%s/%s/%s/%s/v' % (pop.id, i, pop.component, seg_id)) nml_file_name = '%s.net.nml' % network.id + ('.h5' if format == 'hdf5' else '') target_dir = './' oc.save_network(nml_doc, nml_file_name, validate=False, use_subfolder=True, target_dir=target_dir, format=format) lems_file_name, lems_sim = oc.generate_lems_simulation( nml_doc, network, nml_file_name, duration, dt=0.025, target_dir=target_dir, include_extra_lems_files=['../../../ConductanceClamp.xml'], gen_plots_for_all_v=False, plot_all_segments=False, gen_plots_for_quantities= to_plot, # Dict with displays vs lists of quantity paths gen_saves_for_all_v=False, save_all_segments=False, gen_saves_for_quantities= to_save, # Dict with file names vs lists of quantity paths verbose=True) if simulator: print("Running %s for %sms in %s" % (lems_file_name, duration, simulator)) traces, events = oc.simulate_network(lems_file_name, simulator, max_memory='4000M', nogui=True, load_saved_data=True, reload_events=True, plot=False, verbose=True, num_processors=min(num_cells, 16))