def generatefISimulationLEMS(population, units): # Create LEMS file sim_id = 'LEMS_fISim_%s.xml' % population ls = LEMSSimulation(sim_id, 200, 0.1, 'net_%s' % population) # Add additional LEMS file # Add Rate Base Components ls.include_lems_file('../RateBased.xml', include_included=True) ls.include_lems_file('../CellDefinition.xml', include_included=True) # Add specifications for these Rate Based Components ls.include_lems_file('../RateBasedSpecifications_high_baseline.xml', include_included=True) # Add the network definition ls.include_lems_file('fI_%s.nml' % population, include_included=True) # Display outputs and check the results plot the lowest, middle and highest values middle = math.ceil(units / 2) disp0 = 'Rate' ls.create_display(disp0, 'Rates', '-2', '45') ls.add_line_to_display(disp0, '%s0' % population, '%sPop[0]/r' % population, color='#0000ff') ls.add_line_to_display(disp0, '%s%d' % (population, middle), '%sPop[%d]/r' % (population, middle), color='#DDA0DD') ls.add_line_to_display(disp0, '%s19' % population, '%sPop[19]/r' % population, color='#00ff00') disp1 = 'Voltage' ls.create_display(disp1, 'Voltages', '-.072', '-.035') ls.add_line_to_display(disp1, '%s0' % population, '%sPop[0]/V' % population, color='#0000ff') ls.add_line_to_display(disp1, '%s%d' % (population, middle), '%sPop[%d]/V' % (population, middle), color='#DDA0DD') ls.add_line_to_display(disp1, '%s19' % population, '%sPop[19]/V' % population, color='#00ff00') # Create output file of1 = 'of1' ls.create_output_file(of1, 'fI_%s.dat' % population) for unit in range(units): ls.add_column_to_output_file(of1, 'r%d' % unit, '%sPop[%d]/r' % (population, unit)) ls.add_column_to_output_file(of1, 'V%d' % unit, '%sPop[%d]/V' % (population, unit)) save_path = os.path.join(sim_id) ls.save_to_file(file_name=save_path)
def generatePopulationSimulationLEMS(n_pops, baseline, pops, duration, dt, dl): # Create simulation # Create LEMS file dl_str = 'DL' if dl else '' sim_file = 'LEMS_WC_%s%s.xml' % (baseline, dl_str) sim_id = 'WC_%s%s' % (baseline, dl_str) ls = LEMSSimulation(sim_id, duration, dt, 'net1') colours = ['#ff0000', '#0000ff'] colours2 = ['#ff7777', '#7777ff'] # Add additional LEMS files # Add Wilson and Cowan Components ls.include_lems_file('WC_Parameters%s.xml' % dl_str, include_included=True) # Add the network definition ls.include_lems_file('WC_%s%s.net.nml' % (baseline, dl_str), include_included=True) ls.set_report_file('report.txt') disp2 = 'd2' ls.create_display(disp2, 'Rates', -.1, 1.2) for pop_idx, pop in enumerate(pops): for n_pop in range(n_pops[pop_idx]): ls.add_line_to_display(disp2, 'r_%s' % pop, '%sPop/%d/%s/%s' % (pop, n_pop, pop, 'R' if dl else 'r'), color=colours[pop_idx]) disp1 = 'd1' ls.create_display(disp1, 'iSyn', -2, 8) for pop_idx, pop in enumerate(pops): for n_pop in range(n_pops[pop_idx]): ls.add_line_to_display(disp1, 'iSyn_%s' % pop, '%sPop/%d/%s/iSyn' % (pop, n_pop, pop), color=colours[pop_idx], scale=1 if dl else '1nA') ls.add_line_to_display(disp1, 'f_%s' % pop, '%sPop/%d/%s/f' % (pop, n_pop, pop), color=colours2[pop_idx]) of1 = 'of_%s' % pop ls.create_output_file(of1, 'WC_%s%s.dat' % (baseline, dl_str)) for pop_idx, pop in enumerate(pops): # save rates in output file for n_pop in range(n_pops[pop_idx]): ls.add_column_to_output_file( of1, 'r_%s' % pop, '%sPop/%d/%s/%s' % (pop, n_pop, pop, 'R' if dl else 'r')) save_path = os.path.join(sim_file) ls.save_to_file(file_name=save_path)
def generatePopulationSimulationLEMS(n_pops, baseline, pops, sim_length): # Create LEMS file sim_id = 'LEMS_PopulationSim%sBaseline.xml' % baseline dt = 0.1 ls = LEMSSimulation(sim_id, sim_length, dt, 'net2') colours = ['#0000ff', '#ff0000', '#DDA0DD', '#00ff00'] # Add additional LEMS files # Add Rate Base Components ls.include_lems_file('../RateBased.xml', include_included=True) ls.include_lems_file('../CellDefinition.xml', include_included=True) # Add specifications for the Rate Base Components ls.include_lems_file('../RateBasedSpecifications_%s_baseline.xml' % baseline, include_included=True) # Add the network definition ls.include_lems_file('RandomPopulationRate_%s_baseline.nml' % baseline, include_included=True) for pop_idx, pop in enumerate(pops): disp1 = '%s' % pop ls.create_display(disp1, '%s' % pop, -1, 12) for n_pop in range(n_pops[pop_idx]): ls.add_line_to_display(disp1, '%s%d' % (pop, n_pop), '%sPop/%d/%s/r' % (pop, n_pop, pop.upper()), color=colours[pop_idx]) for pop_idx, pop in enumerate(pops): # Create output file of1 = 'of_%s' % pop ls.create_output_file( of1, 'Population_%s_%s_baseline.dat' % (pop, baseline)) for n_pop in range(n_pops[pop_idx]): ls.add_column_to_output_file( of1, 'r_%s_%d' % (pop, n_pop), '%sPop/%d/%s/r' % (pop, n_pop, pop.upper())) save_path = os.path.join(sim_id) ls.save_to_file(file_name=save_path)
def generate_granule_cell_layer(network_id, x_size = 0, # um y_size = 0, # um z_size = 0, # um numCells_grc = 0, numCells_gol = 0, connections = True, connections_method = 'random', connection_probability_grc_gol = 0.2, connection_probability_gol_grc = 0.1, inputs = False, input_firing_rate = 50, # Hz num_inputs_per_grc = 4, validate = True, random_seed = 1234, generate_lems_simulation = False, max_plotted_cells_per_pop = 10, duration = 500, # ms dt = 0.025, temperature="32.0 degC"): seed(random_seed) nml_doc = NeuroMLDocument(id=network_id) net = Network(id = network_id, type = "networkWithTemperature", temperature = temperature) net.notes = "Network generated using libNeuroML v%s"%__version__ nml_doc.networks.append(net) # The names of the cell type/component used in the populations (Cell Type in neuroConstruct) grc_group_component = "Granule_98" gol_group_component = "Golgi_98" nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component)) nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component)) # The names of the Exc & Inh groups/populations (Cell Group in neuroConstruct) grc_group = "Grans" gol_group = "Golgis" # The names of the network connections net_conn_grc_gol = "NetConn_Grans_Golgis" net_conn_gol_grc = "NetConn_Golgis_Grans" # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct) grc_gol_syn = "AMPA_GranGol" gol_grc_syn = "GABAA" for syn in [grc_gol_syn, gol_grc_syn]: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn)) if network_id == 'Solinas2010': # Set size and cell numbers for Solinas 2010 network import sys,os NEURON_sim_path = '../NEURON' sys.path.append(NEURON_sim_path) local_path = os.getcwd() os.chdir(NEURON_sim_path) print os.getcwd() import GenerateSolinas2010 as GS2010 structure = GS2010.GenerateSolinas2010(generate=True) os.chdir(local_path) goc_data = structure['Golgis'] grc_data = structure['Granules'] grc_pos = grc_data['positions']['data'] goc_pos = goc_data['positions']['data'] numCells_grc = grc_pos.shape[0] numCells_gol = goc_pos.shape[0] # Generate excitatory cells grc_pop = Population(id=grc_group, component=grc_group_component, type="populationList", size=numCells_grc) net.populations.append(grc_pop) for i in range(0, numCells_grc) : index = i inst = Instance(id=index) grc_pop.instances.append(inst) inst.location = Location(x=str(grc_pos[i,0]), y=str(grc_pos[i,1]), z=str(grc_pos[i,2])) # Generate inhibitory cells gol_pop = Population(id=gol_group, component=gol_group_component, type="populationList", size=numCells_gol) net.populations.append(gol_pop) for i in range(0, numCells_gol) : index = i inst = Instance(id=index) gol_pop.instances.append(inst) inst.location = Location(x=str(goc_pos[i,0]), y=str(goc_pos[i,1]), z=str(goc_pos[i,2])) if connections: proj_grc_gol = Projection(id=net_conn_grc_gol, presynaptic_population=grc_group, postsynaptic_population=gol_group, synapse=grc_gol_syn) net.projections.append(proj_grc_gol) proj_gol_grc = Projection(id=net_conn_gol_grc, presynaptic_population=gol_group, postsynaptic_population=grc_group, synapse=gol_grc_syn) net.projections.append(proj_gol_grc) count_grc_gol = 0 count_gol_grc = 0 # Generate exc -> * connections def add_connection(projection, id, pre_pop, pre_component, pre_cell_id, pre_seg_id, post_pop, post_component, post_cell_id, post_seg_id): connection = Connection(id=id, \ pre_cell_id="../%s/%i/%s"%(pre_pop, pre_cell_id, pre_component), \ pre_segment_id=pre_seg_id, \ pre_fraction_along=0.5, post_cell_id="../%s/%i/%s"%(post_pop, post_cell_id, post_component), \ post_segment_id=post_seg_id, post_fraction_along=0.5) projection.connections.append(connection) # Connect Granule cells to Golgi cells for i in range(0, numCells_grc): # get targets for grc[i] from the structure dict # print 'Granule ', i , structure['Granules']['divergence_to_goc']['data'][i][1:] for j in structure['Granules']['divergence_to_goc']['data'][i][1:]: add_connection(proj_grc_gol, count_grc_gol, grc_group, grc_group_component, i, 0, gol_group, gol_group_component, j, 0) count_grc_gol+=1 # Connect Golgi cells to Granule cells for i in range(0, numCells_gol): # get targets glomeruli for goc[i] from the lol in structure dict # print 'Golgi ', i # print structure['Golgis']['divergence_to_glom']['data'][i][1:] for k in structure['Golgis']['divergence_to_glom']['data'][i][1:]: # get target granule cells for glom[k] from the lol in structure dict # print 'Glom ', k # print structure['Glomeruli']['divergence_to_grc']['data'][k] for j in structure['Glomeruli']['divergence_to_grc']['data'][k][1:]: # print 'Granule ', j add_connection(proj_gol_grc, count_gol_grc, gol_group, gol_group_component, i, 0, grc_group, grc_group_component, j, 0) count_gol_grc+=1 if inputs: mf_input_syn = "MF_AMPA" nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn)) rand_spiker_id = "input50Hz" #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/> pfs = PoissonFiringSynapse(id="input50Hz", average_rate="%s per_s"%input_firing_rate, synapse=mf_input_syn, spike_target="./%s"%mf_input_syn) nml_doc.poisson_firing_synapses.append(pfs) input_list = InputList(id="Input_0", component=rand_spiker_id, populations=grc_group) count = 0 for i in range(0, numCells_grc): for j in range(num_inputs_per_grc): input = Input(id=count, target="../%s/%i/%s"%(grc_group, i, grc_group_component), destination="synapses") input_list.input.append(input) count += 1 net.input_lists.append(input_list) ####### Write to file ###### print("Saving to file...") nml_file = network_id+'.net.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: "+nml_file) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_lems_simulation: # Create a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation("Sim_%s"%network_id, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Include generated/existing NeuroML2 files ls.include_neuroml2_file('%s.cell.nml'%grc_group_component) ls.include_neuroml2_file('%s.cell.nml'%gol_group_component) ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files disp_grc = "display_grc" ls.create_display(disp_grc, "Voltages Granule cells", "-95", "-38") of_grc = 'Volts_file_grc' ls.create_output_file(of_grc, "v_grc.dat") disp_gol = "display_gol" ls.create_display(disp_gol, "Voltages Golgi cells", "-95", "-38") of_gol = 'Volts_file_gol' ls.create_output_file(of_gol, "v_gol.dat") for i in range(min(numCells_grc,max_plotted_cells_per_pop)): quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component) ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity) for i in range(min(numCells_gol,max_plotted_cells_per_pop)): quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component) ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() print "-----------------------------------"
def generate_lems_file_for_neuroml(sim_id, neuroml_file, target, duration, dt, lems_file_name, target_dir, nml_doc = None, # Use this if the nml doc has already been loaded (to avoid delay in reload) include_extra_files = [], gen_plots_for_all_v = True, plot_all_segments = False, gen_plots_for_quantities = {}, # Dict with displays vs lists of quantity paths gen_plots_for_only_populations = [], # List of populations, all pops if = [] gen_saves_for_all_v = True, save_all_segments = False, gen_saves_for_only_populations = [], # List of populations, all pops if = [] gen_saves_for_quantities = {}, # Dict with file names vs lists of quantity paths gen_spike_saves_for_all_somas = False, gen_spike_saves_for_only_populations = [], # List of populations, all pops if = [] gen_spike_saves_for_cells = {}, # Dict with file names vs lists of quantity paths spike_time_format='ID_TIME', copy_neuroml = True, report_file_name = None, lems_file_generate_seed=None, verbose=False, simulation_seed=12345): my_random = random.Random() if lems_file_generate_seed: my_random.seed(lems_file_generate_seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input else: my_random.seed(12345) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input file_name_full = '%s/%s'%(target_dir,lems_file_name) print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s (copy: %s)'%(file_name_full,neuroml_file,copy_neuroml)) ls = LEMSSimulation(sim_id, duration, dt, target,simulation_seed=simulation_seed) if nml_doc == None: nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=verbose) nml_doc_inc_not_included = read_neuroml2_file(neuroml_file, include_includes=False, verbose=False) else: nml_doc_inc_not_included = nml_doc ls.set_report_file(report_file_name) quantities_saved = [] for f in include_extra_files: ls.include_neuroml2_file(f, include_included=False) if not copy_neuroml: rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir)) print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file)) ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir)) else: print_comment_v("Copying a NeuroML file (%s) to: %s (abs path: %s)"%(neuroml_file, target_dir, os.path.abspath(target_dir))) if not os.path.isdir(target_dir): raise Exception("Target directory %s does not exist!"%target_dir) if os.path.realpath(os.path.dirname(neuroml_file))!=os.path.realpath(target_dir): shutil.copy(neuroml_file, target_dir) else: print_comment_v("No need, same file...") neuroml_file_name = os.path.basename(neuroml_file) ls.include_neuroml2_file(neuroml_file_name, include_included=False) nml_dir = os.path.dirname(neuroml_file) if len(os.path.dirname(neuroml_file))>0 else '.' for include in nml_doc_inc_not_included.includes: if nml_dir=='.' and os.path.isfile(include.href): incl_curr = include.href else: incl_curr = '%s/%s'%(nml_dir,include.href) if os.path.isfile(include.href): incl_curr = include.href print_comment_v(' - Including %s (located at %s; nml dir: %s), copying to %s'%(include.href, incl_curr, nml_dir, target_dir)) ''' if not os.path.isfile("%s/%s"%(target_dir, os.path.basename(incl_curr))) and \ not os.path.isfile("%s/%s"%(target_dir, incl_curr)) and \ not os.path.isfile(incl_curr): shutil.copy(incl_curr, target_dir) else: print_comment_v("No need to copy...")''' f1 = "%s/%s"%(target_dir, os.path.basename(incl_curr)) f2 = "%s/%s"%(target_dir, incl_curr) if os.path.isfile(f1): print_comment_v("No need to copy, file exists: %s..."%f1) elif os.path.isfile(f2): print_comment_v("No need to copy, file exists: %s..."%f2) else: shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) sub_doc = read_neuroml2_file(incl_curr) sub_dir = os.path.dirname(incl_curr) if len(os.path.dirname(incl_curr))>0 else '.' for include in sub_doc.includes: incl_curr = '%s/%s'%(sub_dir,include.href) print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr)) if not os.path.isfile("%s/%s"%(target_dir, os.path.basename(incl_curr))) and \ not os.path.isfile("%s/%s"%(target_dir, incl_curr)): shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) if gen_plots_for_all_v \ or gen_saves_for_all_v \ or len(gen_plots_for_only_populations)>0 \ or len(gen_saves_for_only_populations)>0 \ or gen_spike_saves_for_all_somas \ or len(gen_spike_saves_for_only_populations)>0 : for network in nml_doc.networks: for population in network.populations: variable = "v" # quantity_template_e = "%s[%i]" component = population.component size = population.size cell = None segment_ids = [] for c in nml_doc.spike_generator_poissons: if c.id == component: variable = "tsince" for c in nml_doc.SpikeSourcePoisson: if c.id == component: variable = "tsince" quantity_template = "%s[%i]/"+variable if plot_all_segments or gen_spike_saves_for_all_somas: for c in nml_doc.cells: if c.id == component: cell = c for segment in cell.morphology.segments: segment_ids.append(segment.id) segment_ids.sort() if population.type and population.type == 'populationList': quantity_template = "%s/%i/"+component+"/"+variable quantity_template_e = "%s/%i/"+component+"" # Multicompartmental cell ### Needs to be supported in NeuronWriter ###if len(segment_ids)>1: ### quantity_template_e = "%s/%i/"+component+"/0" size = len(population.instances) if gen_plots_for_all_v or population.id in gen_plots_for_only_populations: print_comment('Generating %i plots for %s in population %s'%(size, component, population.id)) disp0 = 'DispPop__%s'%population.id ls.create_display(disp0, "Membrane potentials of cells in %s"%population.id, "-90", "50") for i in range(size): if cell!=None and plot_all_segments: quantity_template_seg = "%s/%i/"+component+"/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg%(population.id, i, segment_id) ls.add_line_to_display(disp0, "%s[%i] seg %i: v"%(population.id, i, segment_id), quantity, "1mV", get_next_hex_color(my_random)) else: quantity = quantity_template%(population.id, i) ls.add_line_to_display(disp0, "%s[%i]: v"%(population.id, i), quantity, "1mV", get_next_hex_color(my_random)) if gen_saves_for_all_v or population.id in gen_saves_for_only_populations: print_comment('Saving %i values of %s for %s in population %s'%(size, variable, component, population.id)) of0 = 'Volts_file__%s'%population.id ls.create_output_file(of0, "%s.%s.%s.dat"%(sim_id,population.id,variable)) for i in range(size): if cell!=None and save_all_segments: quantity_template_seg = "%s/%i/"+component+"/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg%(population.id, i, segment_id) ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity) quantities_saved.append(quantity) else: quantity = quantity_template%(population.id, i) ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity) quantities_saved.append(quantity) if gen_spike_saves_for_all_somas or population.id in gen_spike_saves_for_only_populations: print_comment('Saving spikes in %i somas for %s in population %s'%(size, component, population.id)) eof0 = 'Spikes_file__%s'%population.id ls.create_event_output_file(eof0, "%s.%s.spikes"%(sim_id,population.id), format=spike_time_format) for i in range(size): quantity = quantity_template_e%(population.id, i) ls.add_selection_to_event_output_file(eof0, i, quantity, "spike") quantities_saved.append(quantity) for display in gen_plots_for_quantities.keys(): quantities = gen_plots_for_quantities[display] max_ = "1" min_ = "-1" scale = "1" # Check for v ... if quantities and len(quantities)>0 and quantities[0].endswith('/v'): max_ = "40" min_ = "-80" scale = "1mV" ls.create_display(display, "Plots of %s"%display, min_, max_) for q in quantities: ls.add_line_to_display(display, safe_variable(q), q, scale, get_next_hex_color(my_random)) for file_name in gen_saves_for_quantities.keys(): quantities = gen_saves_for_quantities[file_name] of_id = safe_variable(file_name) ls.create_output_file(of_id, file_name) for q in quantities: ls.add_column_to_output_file(of_id, safe_variable(q), q) quantities_saved.append(q) for file_name in gen_spike_saves_for_cells.keys(): cells = gen_spike_saves_for_cells[file_name] of_id = safe_variable(file_name) ls.create_event_output_file(of_id, file_name) for i, c in enumerate(cells): ls.add_selection_to_event_output_file(of_id, i, c, "spike") quantities_saved.append(c) ls.save_to_file(file_name=file_name_full) return quantities_saved, ls
def generate_Vm_vs_time_plot(nml2_file, cell_id, inj_amp_nA = 80, delay_ms = 20, inj_dur_ms = 60, sim_dur_ms = 100, dt = 0.05, temperature = "32degC", spike_threshold_mV=0., plot_voltage_traces=False, show_plot_already=True, simulator="jNeuroML", include_included=True): # simulation parameters nogui = '-nogui' in sys.argv # Used to supress GUI in tests for Travis-CI ref = "Test" print_comment_v("Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"% (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms)) sim_id = 'Vm_%s'%ref duration = sim_dur_ms ls = LEMSSimulation(sim_id, sim_dur_ms, dt) ls.include_neuroml2_file(nml2_file, include_included=include_included) ls.assign_simulation_target('network') nml_doc = nml.NeuroMLDocument(id=cell_id) nml_doc.includes.append(nml.IncludeType(href=nml2_file)) net = nml.Network(id="network") nml_doc.networks.append(net) input_id = ("input_%s"%str(inj_amp_nA).replace('.','_')) pg = nml.PulseGenerator(id=input_id, delay="%sms"%delay_ms, duration='%sms'%inj_dur_ms, amplitude='%spA'%inj_amp_nA) nml_doc.pulse_generators.append(pg) pop_id = 'hhpop' pop = nml.Population(id=pop_id, component='hhcell', size=1, type="populationList") inst = nml.Instance(id=0) pop.instances.append(inst) inst.location = nml.Location(x=0, y=0, z=0) net.populations.append(pop) # Add these to cells input_list = nml.InputList(id='il_%s'%input_id, component=pg.id, populations=pop_id) input = nml.Input(id='0', target='../hhpop/0/hhcell', destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) sim_file_name = '%s.sim.nml'%sim_id pynml.write_neuroml2_file(nml_doc, sim_file_name) ls.include_neuroml2_file(sim_file_name) disp0 = 'Voltage_display' ls.create_display(disp0,"Voltages", "-90", "50") ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV') of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat"%sim_id) ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v") lems_file_name = ls.save_to_file() if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) if show_plot_already: from matplotlib import pyplot as plt plt.show() return of0
def generate_current_vs_frequency_curve(nml2_file, cell_id, start_amp_nA=-0.1, end_amp_nA=0.1, step_nA=0.01, custom_amps_nA=[], analysis_duration=1000, analysis_delay=0, pre_zero_pulse=0, post_zero_pulse=0, dt=0.05, temperature="32degC", spike_threshold_mV=0., plot_voltage_traces=False, plot_if=True, plot_iv=False, xlim_if=None, ylim_if=None, xlim_iv=None, ylim_iv=None, label_xaxis=True, label_yaxis=True, show_volts_label=True, grid=True, font_size=12, if_iv_color='k', linewidth=1, bottom_left_spines_only=False, show_plot_already=True, save_voltage_traces_to=None, save_if_figure_to=None, save_iv_figure_to=None, save_if_data_to=None, save_iv_data_to=None, simulator="jNeuroML", num_processors=1, include_included=True, title_above_plot=False, return_axes=False, verbose=False): print_comment( "Running generate_current_vs_frequency_curve() on %s (%s)" % (nml2_file, os.path.abspath(nml2_file)), verbose) from pyelectro.analysis import max_min from pyelectro.analysis import mean_spike_frequency import numpy as np traces_ax = None if_ax = None iv_ax = None sim_id = 'iv_%s' % cell_id total_duration = pre_zero_pulse + analysis_duration + analysis_delay + post_zero_pulse pulse_duration = analysis_duration + analysis_delay end_stim = pre_zero_pulse + analysis_duration + analysis_delay ls = LEMSSimulation(sim_id, total_duration, dt) ls.include_neuroml2_file(nml2_file, include_included=include_included) stims = [] if len(custom_amps_nA) > 0: stims = [float(a) for a in custom_amps_nA] stim_info = ['%snA' % float(a) for a in custom_amps_nA] else: amp = start_amp_nA while amp <= end_amp_nA: stims.append(amp) amp += step_nA stim_info = '(%snA->%snA; %s steps of %snA; %sms)' % ( start_amp_nA, end_amp_nA, len(stims), step_nA, total_duration) print_comment_v("Generating an IF curve for cell %s in %s using %s %s" % (cell_id, nml2_file, simulator, stim_info)) number_cells = len(stims) pop = nml.Population(id="population_of_%s" % cell_id, component=cell_id, size=number_cells) # create network and add populations net_id = "network_of_%s" % cell_id net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature) ls.assign_simulation_target(net_id) net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(nml.IncludeType(nml2_file)) net.populations.append(pop) for i in range(number_cells): stim_amp = "%snA" % stims[i] input_id = ("input_%s" % stim_amp).replace('.', '_').replace('-', 'min') pg = nml.PulseGenerator(id=input_id, delay="%sms" % pre_zero_pulse, duration="%sms" % pulse_duration, amplitude=stim_amp) net_doc.pulse_generators.append(pg) # Add these to cells input_list = nml.InputList(id=input_id, component=pg.id, populations=pop.id) input = nml.Input(id='0', target="../%s[%i]" % (pop.id, i), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) net_file_name = '%s.net.nml' % sim_id pynml.write_neuroml2_file(net_doc, net_file_name) ls.include_neuroml2_file(net_file_name) disp0 = 'Voltage_display' ls.create_display(disp0, "Voltages", "-90", "50") of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat" % sim_id) for i in range(number_cells): ref = "v_cell%i" % i quantity = "%s[%i]/v" % (pop.id, i) ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of0, ref, quantity) lems_file_name = ls.save_to_file() print_comment( "Written LEMS file %s (%s)" % (lems_file_name, os.path.abspath(lems_file_name)), verbose) if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=False, show_plot_already=False, verbose=verbose) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=False, show_plot_already=False, verbose=verbose) elif simulator == "jNeuroML_NetPyNE": results = pynml.run_lems_with_jneuroml_netpyne( lems_file_name, nogui=True, load_saved_data=True, plot=False, show_plot_already=False, num_processors=num_processors, verbose=verbose) else: raise Exception( "Sorry, cannot yet run current vs frequency analysis using simulator %s" % simulator) print_comment( "Completed run in simulator %s (results: %s)" % (simulator, results.keys()), verbose) #print(results.keys()) times_results = [] volts_results = [] volts_labels = [] if_results = {} iv_results = {} for i in range(number_cells): t = np.array(results['t']) * 1000 v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000 if plot_voltage_traces: times_results.append(t) volts_results.append(v) volts_labels.append("%s nA" % stims[i]) mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV) spike_times = mm['maxima_times'] freq = 0 if len(spike_times) > 2: count = 0 for s in spike_times: if s >= pre_zero_pulse + analysis_delay and s < ( pre_zero_pulse + analysis_duration + analysis_delay): count += 1 freq = 1000 * count / float(analysis_duration) mean_freq = mean_spike_frequency(spike_times) #print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq)) if_results[stims[i]] = freq if freq == 0: if post_zero_pulse == 0: iv_results[stims[i]] = v[-1] else: v_end = None for j in range(len(t)): if v_end == None and t[j] >= end_stim: v_end = v[j] iv_results[stims[i]] = v_end if plot_voltage_traces: traces_ax = pynml.generate_plot( times_results, volts_results, "Membrane potential traces for: %s" % nml2_file, xaxis='Time (ms)' if label_xaxis else ' ', yaxis='Membrane potential (mV)' if label_yaxis else '', xlim=[total_duration * -0.05, total_duration * 1.05], show_xticklabels=label_xaxis, font_size=font_size, bottom_left_spines_only=bottom_left_spines_only, grid=False, labels=volts_labels if show_volts_label else [], show_plot_already=False, save_figure_to=save_voltage_traces_to, title_above_plot=title_above_plot, verbose=verbose) if plot_if: stims = sorted(if_results.keys()) stims_pA = [ii * 1000 for ii in stims] freqs = [if_results[s] for s in stims] if_ax = pynml.generate_plot( [stims_pA], [freqs], "Firing frequency versus injected current for: %s" % nml2_file, colors=[if_iv_color], linestyles=['-'], markers=['o'], linewidths=[linewidth], xaxis='Input current (pA)' if label_xaxis else ' ', yaxis='Firing frequency (Hz)' if label_yaxis else '', xlim=xlim_if, ylim=ylim_if, show_xticklabels=label_xaxis, show_yticklabels=label_yaxis, font_size=font_size, bottom_left_spines_only=bottom_left_spines_only, grid=grid, show_plot_already=False, save_figure_to=save_if_figure_to, title_above_plot=title_above_plot, verbose=verbose) if save_if_data_to: with open(save_if_data_to, 'w') as if_file: for i in range(len(stims_pA)): if_file.write("%s\t%s\n" % (stims_pA[i], freqs[i])) if plot_iv: stims = sorted(iv_results.keys()) stims_pA = [ii * 1000 for ii in sorted(iv_results.keys())] vs = [iv_results[s] for s in stims] xs = [] ys = [] xs.append([]) ys.append([]) for si in range(len(stims)): stim = stims[si] if len(custom_amps_nA) == 0 and si > 1 and ( stims[si] - stims[si - 1]) > step_nA * 1.01: xs.append([]) ys.append([]) xs[-1].append(stim * 1000) ys[-1].append(iv_results[stim]) iv_ax = pynml.generate_plot( xs, ys, "V at %sms versus I below threshold for: %s" % (end_stim, nml2_file), colors=[if_iv_color for s in xs], linestyles=['-' for s in xs], markers=['o' for s in xs], xaxis='Input current (pA)' if label_xaxis else '', yaxis='Membrane potential (mV)' if label_yaxis else '', xlim=xlim_iv, ylim=ylim_iv, show_xticklabels=label_xaxis, show_yticklabels=label_yaxis, font_size=font_size, linewidths=[linewidth for s in xs], bottom_left_spines_only=bottom_left_spines_only, grid=grid, show_plot_already=False, save_figure_to=save_iv_figure_to, title_above_plot=title_above_plot, verbose=verbose) if save_iv_data_to: with open(save_iv_data_to, 'w') as iv_file: for i in range(len(stims_pA)): iv_file.write("%s\t%s\n" % (stims_pA[i], vs[i])) if show_plot_already: from matplotlib import pyplot as plt plt.show() if return_axes: return traces_ax, if_ax, iv_ax return if_results
def generate_current_vs_frequency_curve(nml2_file, cell_id, start_amp_nA, end_amp_nA, step_nA, analysis_duration, analysis_delay, dt=0.05, temperature="32degC", spike_threshold_mV=0., plot_voltage_traces=False, plot_if=True, plot_iv=False, xlim_if=None, ylim_if=None, xlim_iv=None, ylim_iv=None, show_plot_already=True, save_if_figure_to=None, save_iv_figure_to=None, simulator="jNeuroML", include_included=True): from pyelectro.analysis import max_min from pyelectro.analysis import mean_spike_frequency import numpy as np print_comment_v( "Generating FI curve for cell %s in %s using %s (%snA->%snA; %snA steps)" % (cell_id, nml2_file, simulator, start_amp_nA, end_amp_nA, step_nA)) sim_id = 'iv_%s' % cell_id duration = analysis_duration + analysis_delay ls = LEMSSimulation(sim_id, duration, dt) ls.include_neuroml2_file(nml2_file, include_included=include_included) stims = [] amp = start_amp_nA while amp <= end_amp_nA: stims.append(amp) amp += step_nA number_cells = len(stims) pop = nml.Population(id="population_of_%s" % cell_id, component=cell_id, size=number_cells) # create network and add populations net_id = "network_of_%s" % cell_id net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature) ls.assign_simulation_target(net_id) net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(nml.IncludeType(nml2_file)) net.populations.append(pop) for i in range(number_cells): stim_amp = "%snA" % stims[i] input_id = ("input_%s" % stim_amp).replace('.', '_').replace('-', 'min') pg = nml.PulseGenerator(id=input_id, delay="0ms", duration="%sms" % duration, amplitude=stim_amp) net_doc.pulse_generators.append(pg) # Add these to cells input_list = nml.InputList(id=input_id, component=pg.id, populations=pop.id) input = nml.Input(id='0', target="../%s[%i]" % (pop.id, i), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) net_file_name = '%s.net.nml' % sim_id pynml.write_neuroml2_file(net_doc, net_file_name) ls.include_neuroml2_file(net_file_name) disp0 = 'Voltage_display' ls.create_display(disp0, "Voltages", "-90", "50") of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat" % sim_id) for i in range(number_cells): ref = "v_cell%i" % i quantity = "%s[%i]/v" % (pop.id, i) ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of0, ref, quantity) lems_file_name = ls.save_to_file() if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) #print(results.keys()) if_results = {} iv_results = {} for i in range(number_cells): t = np.array(results['t']) * 1000 v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000 mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV) spike_times = mm['maxima_times'] freq = 0 if len(spike_times) > 2: count = 0 for s in spike_times: if s >= analysis_delay and s < (analysis_duration + analysis_delay): count += 1 freq = 1000 * count / float(analysis_duration) mean_freq = mean_spike_frequency(spike_times) # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq)) if_results[stims[i]] = freq if freq == 0: iv_results[stims[i]] = v[-1] if plot_if: stims = sorted(if_results.keys()) stims_pA = [ii * 1000 for ii in stims] freqs = [if_results[s] for s in stims] pynml.generate_plot([stims_pA], [freqs], "Frequency versus injected current for: %s" % nml2_file, colors=['k'], linestyles=['-'], markers=['o'], xaxis='Input current (pA)', yaxis='Firing frequency (Hz)', xlim=xlim_if, ylim=ylim_if, grid=True, show_plot_already=False, save_figure_to=save_if_figure_to) if plot_iv: stims = sorted(iv_results.keys()) stims_pA = [ii * 1000 for ii in sorted(iv_results.keys())] vs = [iv_results[s] for s in stims] pynml.generate_plot( [stims_pA], [vs], "Final membrane potential versus injected current for: %s" % nml2_file, colors=['k'], linestyles=['-'], markers=['o'], xaxis='Input current (pA)', yaxis='Membrane potential (mV)', xlim=xlim_iv, ylim=ylim_iv, grid=True, show_plot_already=False, save_figure_to=save_iv_figure_to) if show_plot_already: from matplotlib import pyplot as plt plt.show() return if_results
def generate_granule_cell_layer(network_id, x_size, # um y_size, # um z_size, # um numCells_mf, numCells_grc, numCells_gol, mf_group_component = "MossyFiber", grc_group_component = "Granule_98", gol_group_component = "Golgi_98", connections = True, connection_probability_grc_gol = 0.2, connection_probability_gol_grc = 0.1, inputs = False, input_firing_rate = 50, # Hz num_inputs_per_mf = 4, validate = True, random_seed = 1234, generate_lems_simulation = False, duration = 500, # ms dt = 0.005, temperature="32.0 degC"): seed(random_seed) nml_doc = NeuroMLDocument(id=network_id) net = Network(id = network_id, type = "networkWithTemperature", temperature = temperature) net.notes = "Network generated using libNeuroML v%s"%__version__ nml_doc.networks.append(net) if numCells_mf>0: nml_doc.includes.append(IncludeType(href='%s.cell.nml'%mf_group_component)) if numCells_grc>0: nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component)) if numCells_gol>0: nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component)) # The names of the groups/populations mf_group = "MossyFibers" grc_group = "Grans" gol_group = "Golgis" # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)= mf_grc_syn = "MF_AMPA" grc_gol_syn = "AMPA_GranGol" gol_grc_syn = "GABAA" for syn in [mf_grc_syn, grc_gol_syn, gol_grc_syn]: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn)) # Generate Gran cells if numCells_mf>0: add_population_in_rectangular_region(net, mf_group, mf_group_component, numCells_mf, 0, 0, 0, x_size, y_size, z_size, color="0 0 1") # Generate Gran cells if numCells_grc>0: add_population_in_rectangular_region(net, grc_group, grc_group_component, numCells_grc, 0, 0, 0, x_size, y_size, z_size, color="1 0 0") # Generate Golgi cells if numCells_gol>0: add_population_in_rectangular_region(net, gol_group, gol_group_component, numCells_gol, 0, 0, 0, x_size, y_size, z_size, color="0 1 0") if connections: add_probabilistic_projection(net, mf_group, mf_group_component, grc_group, grc_group_component, 'NetConn', mf_grc_syn, numCells_mf, numCells_grc, 0.01) add_probabilistic_projection(net, grc_group, grc_group_component, gol_group, gol_group_component, 'NetConn', grc_gol_syn, numCells_grc, numCells_gol, connection_probability_grc_gol) add_probabilistic_projection(net, gol_group, gol_group_component, grc_group, grc_group_component, 'NetConn', gol_grc_syn, numCells_gol, numCells_grc, connection_probability_gol_grc) if inputs: mf_input_syn = "MFSpikeSyn" nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn)) rand_spiker_id = "input%sHz"%input_firing_rate #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/> pfs = PoissonFiringSynapse(id=rand_spiker_id, average_rate="%s per_s"%input_firing_rate, synapse=mf_input_syn, spike_target="./%s"%mf_input_syn) nml_doc.poisson_firing_synapses.append(pfs) input_list = InputList(id="Input_0", component=rand_spiker_id, populations=mf_group) count = 0 for i in range(0, numCells_mf): for j in range(num_inputs_per_mf): input = Input(id=count, target="../%s/%i/%s"%(mf_group, i, mf_group_component), destination="synapses") input_list.input.append(input) count += 1 net.input_lists.append(input_list) ####### Write to file ###### print("Saving to file...") nml_file = network_id+'.net.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: "+nml_file) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_lems_simulation: # Create a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation("Sim_%s"%network_id, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Include generated/existing NeuroML2 files ls.include_neuroml2_file('%s.cell.nml'%grc_group_component) ls.include_neuroml2_file('%s.cell.nml'%gol_group_component) ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files if numCells_mf>0: disp_mf = "display_mf" ls.create_display(disp_mf, "Voltages Mossy fibers", "-70", "10") of_mf = 'Volts_file_mf' ls.create_output_file(of_mf, "v_mf.dat") for i in range(numCells_mf): quantity = "%s/%i/%s/v"%(mf_group, i, mf_group_component) ls.add_line_to_display(disp_mf, "MF %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_mf, "v_%i"%i, quantity) # Specify Displays and Output Files if numCells_grc>0: disp_grc = "display_grc" ls.create_display(disp_grc, "Voltages Granule cells", "-75", "30") of_grc = 'Volts_file_grc' ls.create_output_file(of_grc, "v_grc.dat") for i in range(numCells_grc): quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component) ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity) if numCells_gol>0: disp_gol = "display_gol" ls.create_display(disp_gol, "Voltages Golgi cells", "-75", "30") of_gol = 'Volts_file_gol' ls.create_output_file(of_gol, "v_gol.dat") for i in range(numCells_gol): quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component) ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() else: ls = None print "-----------------------------------" return nml_doc, ls
def generate_lems_file_for_neuroml(sim_id, neuroml_file, target, duration, dt, lems_file_name, target_dir, include_extra_files = [], gen_plots_for_all_v = True, plot_all_segments = False, gen_plots_for_quantities = {}, # Dict with displays vs lists of quantity paths gen_plots_for_only_populations = [], # List of populations, all pops if = [] gen_saves_for_all_v = True, save_all_segments = False, gen_saves_for_only_populations = [], # List of populations, all pops if = [] gen_saves_for_quantities = {}, # Dict with file names vs lists of quantity paths copy_neuroml = True, seed=None): if seed: random.seed(seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input file_name_full = '%s/%s'%(target_dir,lems_file_name) print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s'%(file_name_full,neuroml_file)) ls = LEMSSimulation(sim_id, duration, dt, target) nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=True) quantities_saved = [] for f in include_extra_files: ls.include_neuroml2_file(f, include_included=False) if not copy_neuroml: rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir)) print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file)) ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir)) else: print_comment_v("Copying NeuroML file (%s) to: %s (%s)"%(neuroml_file, target_dir, os.path.abspath(target_dir))) if os.path.abspath(os.path.dirname(neuroml_file))!=os.path.abspath(target_dir): shutil.copy(neuroml_file, target_dir) neuroml_file_name = os.path.basename(neuroml_file) ls.include_neuroml2_file(neuroml_file_name, include_included=False) for include in nml_doc.includes: incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href) print_comment_v(' - Including %s located at %s'%(include.href, incl_curr)) shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) sub_doc = read_neuroml2_file(incl_curr) for include in sub_doc.includes: incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href) print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr)) shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) if gen_plots_for_all_v or gen_saves_for_all_v or len(gen_plots_for_only_populations)>0 or len(gen_saves_for_only_populations)>0 : for network in nml_doc.networks: for population in network.populations: quantity_template = "%s[%i]/v" component = population.component size = population.size cell = None segment_ids = [] if plot_all_segments: for c in nml_doc.cells: if c.id == component: cell = c for segment in cell.morphology.segments: segment_ids.append(segment.id) segment_ids.sort() if population.type and population.type == 'populationList': quantity_template = "%s/%i/"+component+"/v" size = len(population.instances) if gen_plots_for_all_v or population.id in gen_plots_for_only_populations: print_comment('Generating %i plots for %s in population %s'%(size, component, population.id)) disp0 = 'DispPop__%s'%population.id ls.create_display(disp0, "Membrane potentials of cells in %s"%population.id, "-90", "50") for i in range(size): if cell!=None and plot_all_segments: quantity_template_seg = "%s/%i/"+component+"/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg%(population.id, i, segment_id) ls.add_line_to_display(disp0, "%s[%i] seg %i: v"%(population.id, i, segment_id), quantity, "1mV", get_next_hex_color()) else: quantity = quantity_template%(population.id, i) ls.add_line_to_display(disp0, "%s[%i]: v"%(population.id, i), quantity, "1mV", get_next_hex_color()) if gen_saves_for_all_v or population.id in gen_saves_for_only_populations: print_comment('Saving %i values of v for %s in population %s'%(size, component, population.id)) of0 = 'Volts_file__%s'%population.id ls.create_output_file(of0, "%s.%s.v.dat"%(sim_id,population.id)) for i in range(size): if cell!=None and save_all_segments: quantity_template_seg = "%s/%i/"+component+"/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg%(population.id, i, segment_id) ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity) quantities_saved.append(quantity) else: quantity = quantity_template%(population.id, i) ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity) quantities_saved.append(quantity) for display in gen_plots_for_quantities.keys(): quantities = gen_plots_for_quantities[display] ls.create_display(display, "Plots of %s"%display, "-90", "50") for q in quantities: ls.add_line_to_display(display, safe_variable(q), q, "1", get_next_hex_color()) for file_name in gen_saves_for_quantities.keys(): quantities = gen_saves_for_quantities[file_name] ls.create_output_file(file_name, file_name) for q in quantities: ls.add_column_to_output_file(file_name, safe_variable(q), q) ls.save_to_file(file_name=file_name_full) return quantities_saved
def generate_lems_file_for_neuroml(sim_id, neuroml_file, target, duration, dt, lems_file_name, target_dir, gen_plots_for_all_v = True, gen_saves_for_all_v = True, copy_neuroml = True, seed=None): if seed: random.seed(seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input file_name_full = '%s/%s'%(target_dir,lems_file_name) print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s'%(file_name_full,neuroml_file)) ls = LEMSSimulation(sim_id, duration, dt, target) nml_doc = read_neuroml2_file(neuroml_file) quantities_saved = [] if not copy_neuroml: rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir)) print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file)) ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir)) else: if os.path.abspath(os.path.dirname(neuroml_file))!=os.path.abspath(target_dir): shutil.copy(neuroml_file, target_dir) neuroml_file_name = os.path.basename(neuroml_file) ls.include_neuroml2_file(neuroml_file_name, include_included=False) for include in nml_doc.includes: incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href) print_comment_v(' - Including %s located at %s'%(include.href, incl_curr)) shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) sub_doc = read_neuroml2_file(incl_curr) for include in sub_doc.includes: incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href) print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr)) shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) if gen_plots_for_all_v or gen_saves_for_all_v: for network in nml_doc.networks: for population in network.populations: size = population.size component = population.component quantity_template = "%s[%i]/v" if population.type and population.type == 'populationList': quantity_template = "%s/%i/"+component+"/v" if gen_plots_for_all_v: print_comment('Generating %i plots for %s in population %s'%(size, component, population.id)) disp0 = 'DispPop__%s'%population.id ls.create_display(disp0, "Voltages of %s"%disp0, "-90", "50") for i in range(size): quantity = quantity_template%(population.id, i) ls.add_line_to_display(disp0, "v %s"%safe_variable(quantity), quantity, "1mV", get_next_hex_color()) if gen_saves_for_all_v: print_comment('Saving %i values of v for %s in population %s'%(size, component, population.id)) of0 = 'Volts_file__%s'%population.id ls.create_output_file(of0, "%s.%s.v.dat"%(sim_id,population.id)) for i in range(size): quantity = quantity_template%(population.id, i) ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity) quantities_saved.append(quantity) ls.save_to_file(file_name=file_name_full) return quantities_saved
validate_neuroml2(nml_file) # Create a LEMSSimulation to manage creation of LEMS file duration = 1000 # ms dt = 0.05 # ms ls = LEMSSimulation(ref, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Include generated/existing NeuroML2 files ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files disp0 = "display_voltages" ls.create_display(disp0, "Voltages", "-68", "-47") of0 = 'Volts_file' ls.create_output_file(of0, "v.dat") for i in range(size0): quantity = "%s[%i]/v"%(pop0.id, i) ls.add_line_to_display(disp0, "%s[%i]: Vm"%(pop0.id,i), quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of0, 'v%i'%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() # Run with jNeuroML results1 = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=True)
def generate_current_vs_frequency_curve(nml2_file, cell_id, start_amp_nA = -0.1, end_amp_nA = 0.1, step_nA = 0.01, custom_amps_nA = [], analysis_duration = 1000, analysis_delay = 0, pre_zero_pulse = 0, post_zero_pulse = 0, dt = 0.05, temperature = "32degC", spike_threshold_mV = 0., plot_voltage_traces = False, plot_if = True, plot_iv = False, xlim_if = None, ylim_if = None, xlim_iv = None, ylim_iv = None, label_xaxis = True, label_yaxis = True, show_volts_label = True, grid = True, font_size = 12, if_iv_color = 'k', linewidth = 1, bottom_left_spines_only = False, show_plot_already = True, save_voltage_traces_to = None, save_if_figure_to = None, save_iv_figure_to = None, save_if_data_to = None, save_iv_data_to = None, simulator = "jNeuroML", num_processors = 1, include_included = True, title_above_plot = False, return_axes = False, verbose = False): print_comment("Running generate_current_vs_frequency_curve() on %s (%s)"%(nml2_file,os.path.abspath(nml2_file)), verbose) from pyelectro.analysis import max_min from pyelectro.analysis import mean_spike_frequency import numpy as np traces_ax = None if_ax = None iv_ax = None sim_id = 'iv_%s'%cell_id total_duration = pre_zero_pulse+analysis_duration+analysis_delay+post_zero_pulse pulse_duration = analysis_duration+analysis_delay end_stim = pre_zero_pulse+analysis_duration+analysis_delay ls = LEMSSimulation(sim_id, total_duration, dt) ls.include_neuroml2_file(nml2_file, include_included=include_included) stims = [] if len(custom_amps_nA)>0: stims = [float(a) for a in custom_amps_nA] stim_info = ['%snA'%float(a) for a in custom_amps_nA] else: amp = start_amp_nA while amp<=end_amp_nA : stims.append(amp) amp+=step_nA stim_info = '(%snA->%snA; %s steps of %snA; %sms)'%(start_amp_nA, end_amp_nA, len(stims), step_nA, total_duration) print_comment_v("Generating an IF curve for cell %s in %s using %s %s"% (cell_id, nml2_file, simulator, stim_info)) number_cells = len(stims) pop = nml.Population(id="population_of_%s"%cell_id, component=cell_id, size=number_cells) # create network and add populations net_id = "network_of_%s"%cell_id net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature) ls.assign_simulation_target(net_id) net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(nml.IncludeType(nml2_file)) net.populations.append(pop) for i in range(number_cells): stim_amp = "%snA"%stims[i] input_id = ("input_%s"%stim_amp).replace('.','_').replace('-','min') pg = nml.PulseGenerator(id=input_id, delay="%sms"%pre_zero_pulse, duration="%sms"%pulse_duration, amplitude=stim_amp) net_doc.pulse_generators.append(pg) # Add these to cells input_list = nml.InputList(id=input_id, component=pg.id, populations=pop.id) input = nml.Input(id='0', target="../%s[%i]"%(pop.id, i), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) net_file_name = '%s.net.nml'%sim_id pynml.write_neuroml2_file(net_doc, net_file_name) ls.include_neuroml2_file(net_file_name) disp0 = 'Voltage_display' ls.create_display(disp0,"Voltages", "-90", "50") of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat"%sim_id) for i in range(number_cells): ref = "v_cell%i"%i quantity = "%s[%i]/v"%(pop.id, i) ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of0, ref, quantity) lems_file_name = ls.save_to_file() print_comment("Written LEMS file %s (%s)"%(lems_file_name,os.path.abspath(lems_file_name)), verbose) if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=False, show_plot_already=False, verbose=verbose) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=False, show_plot_already=False, verbose=verbose) elif simulator == "jNeuroML_NetPyNE": results = pynml.run_lems_with_jneuroml_netpyne(lems_file_name, nogui=True, load_saved_data=True, plot=False, show_plot_already=False, num_processors = num_processors, verbose=verbose) else: raise Exception("Sorry, cannot yet run current vs frequency analysis using simulator %s"%simulator) print_comment("Completed run in simulator %s (results: %s)"%(simulator,results.keys()), verbose) #print(results.keys()) times_results = [] volts_results = [] volts_labels = [] if_results = {} iv_results = {} for i in range(number_cells): t = np.array(results['t'])*1000 v = np.array(results["%s[%i]/v"%(pop.id, i)])*1000 if plot_voltage_traces: times_results.append(t) volts_results.append(v) volts_labels.append("%s nA"%stims[i]) mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV) spike_times = mm['maxima_times'] freq = 0 if len(spike_times) > 2: count = 0 for s in spike_times: if s >= pre_zero_pulse + analysis_delay and s < (pre_zero_pulse + analysis_duration+analysis_delay): count+=1 freq = 1000 * count/float(analysis_duration) mean_freq = mean_spike_frequency(spike_times) #print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq)) if_results[stims[i]] = freq if freq == 0: if post_zero_pulse==0: iv_results[stims[i]] = v[-1] else: v_end = None for j in range(len(t)): if v_end==None and t[j]>=end_stim: v_end = v[j] iv_results[stims[i]] = v_end if plot_voltage_traces: traces_ax = pynml.generate_plot(times_results, volts_results, "Membrane potential traces for: %s"%nml2_file, xaxis = 'Time (ms)' if label_xaxis else ' ', yaxis = 'Membrane potential (mV)' if label_yaxis else '', xlim = [total_duration*-0.05,total_duration*1.05], show_xticklabels = label_xaxis, font_size = font_size, bottom_left_spines_only = bottom_left_spines_only, grid = False, labels = volts_labels if show_volts_label else [], show_plot_already=False, save_figure_to = save_voltage_traces_to, title_above_plot = title_above_plot, verbose=verbose) if plot_if: stims = sorted(if_results.keys()) stims_pA = [ii*1000 for ii in stims] freqs = [if_results[s] for s in stims] if_ax = pynml.generate_plot([stims_pA], [freqs], "Firing frequency versus injected current for: %s"%nml2_file, colors = [if_iv_color], linestyles=['-'], markers=['o'], linewidths = [linewidth], xaxis = 'Input current (pA)' if label_xaxis else ' ', yaxis = 'Firing frequency (Hz)' if label_yaxis else '', xlim = xlim_if, ylim = ylim_if, show_xticklabels = label_xaxis, show_yticklabels = label_yaxis, font_size = font_size, bottom_left_spines_only = bottom_left_spines_only, grid = grid, show_plot_already=False, save_figure_to = save_if_figure_to, title_above_plot = title_above_plot, verbose=verbose) if save_if_data_to: with open(save_if_data_to,'w') as if_file: for i in range(len(stims_pA)): if_file.write("%s\t%s\n"%(stims_pA[i],freqs[i])) if plot_iv: stims = sorted(iv_results.keys()) stims_pA = [ii*1000 for ii in sorted(iv_results.keys())] vs = [iv_results[s] for s in stims] xs = [] ys = [] xs.append([]) ys.append([]) for si in range(len(stims)): stim = stims[si] if len(custom_amps_nA)==0 and si>1 and (stims[si]-stims[si-1])>step_nA*1.01: xs.append([]) ys.append([]) xs[-1].append(stim*1000) ys[-1].append(iv_results[stim]) iv_ax = pynml.generate_plot(xs, ys, "V at %sms versus I below threshold for: %s"%(end_stim,nml2_file), colors = [if_iv_color for s in xs], linestyles=['-' for s in xs], markers=['o' for s in xs], xaxis = 'Input current (pA)' if label_xaxis else '', yaxis = 'Membrane potential (mV)' if label_yaxis else '', xlim = xlim_iv, ylim = ylim_iv, show_xticklabels = label_xaxis, show_yticklabels = label_yaxis, font_size = font_size, linewidths = [linewidth for s in xs], bottom_left_spines_only = bottom_left_spines_only, grid = grid, show_plot_already=False, save_figure_to = save_iv_figure_to, title_above_plot = title_above_plot, verbose=verbose) if save_iv_data_to: with open(save_iv_data_to,'w') as iv_file: for i in range(len(stims_pA)): iv_file.write("%s\t%s\n"%(stims_pA[i],vs[i])) if show_plot_already: from matplotlib import pyplot as plt plt.show() if return_axes: return traces_ax, if_ax, iv_ax return if_results
def generate_Vm_vs_time_plot(nml2_file, cell_id, inj_amp_nA=80, delay_ms=20, inj_dur_ms=60, sim_dur_ms=100, dt=0.05, plot_voltage_traces=False, show_plot_already=True, simulator="jNeuroML", include_included=True): ref = "Test" print_comment_v( "Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)" % (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms)) sim_id = 'Vm_%s' % ref duration = sim_dur_ms ls = LEMSSimulation(sim_id, sim_dur_ms, dt) ls.include_neuroml2_file(nml2_file, include_included=include_included) ls.assign_simulation_target('network') nml_doc = nml.NeuroMLDocument(id=cell_id) nml_doc.includes.append(nml.IncludeType(href=nml2_file)) net = nml.Network(id="network") nml_doc.networks.append(net) input_id = ("input_%s" % str(inj_amp_nA).replace('.', '_')) pg = nml.PulseGenerator(id=input_id, delay="%sms" % delay_ms, duration='%sms' % inj_dur_ms, amplitude='%spA' % inj_amp_nA) nml_doc.pulse_generators.append(pg) pop_id = 'hhpop' pop = nml.Population(id=pop_id, component='hhcell', size=1, type="populationList") inst = nml.Instance(id=0) pop.instances.append(inst) inst.location = nml.Location(x=0, y=0, z=0) net.populations.append(pop) # Add these to cells input_list = nml.InputList(id='il_%s' % input_id, component=pg.id, populations=pop_id) input = nml.Input(id='0', target='../hhpop/0/hhcell', destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) sim_file_name = '%s.sim.nml' % sim_id pynml.write_neuroml2_file(nml_doc, sim_file_name) ls.include_neuroml2_file(sim_file_name) disp0 = 'Voltage_display' ls.create_display(disp0, "Voltages", "-90", "50") ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV') of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat" % sim_id) ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v") lems_file_name = ls.save_to_file() if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) if show_plot_already: from matplotlib import pyplot as plt plt.show() return of0
def generate_current_vs_frequency_curve(nml2_file, cell_id, start_amp_nA, end_amp_nA, step_nA, analysis_duration, analysis_delay, dt = 0.05, temperature = "32degC", spike_threshold_mV=0., plot_voltage_traces=False, plot_if=True, plot_iv=False, xlim_if = None, ylim_if = None, xlim_iv = None, ylim_iv = None, show_plot_already=True, save_if_figure_to=None, save_iv_figure_to=None, simulator="jNeuroML", include_included=True): from pyelectro.analysis import max_min from pyelectro.analysis import mean_spike_frequency import numpy as np print_comment_v("Generating FI curve for cell %s in %s using %s (%snA->%snA; %snA steps)"% (cell_id, nml2_file, simulator, start_amp_nA, end_amp_nA, step_nA)) sim_id = 'iv_%s'%cell_id duration = analysis_duration+analysis_delay ls = LEMSSimulation(sim_id, duration, dt) ls.include_neuroml2_file(nml2_file, include_included=include_included) stims = [] amp = start_amp_nA while amp<=end_amp_nA : stims.append(amp) amp+=step_nA number_cells = len(stims) pop = nml.Population(id="population_of_%s"%cell_id, component=cell_id, size=number_cells) # create network and add populations net_id = "network_of_%s"%cell_id net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature) ls.assign_simulation_target(net_id) net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(nml.IncludeType(nml2_file)) net.populations.append(pop) for i in range(number_cells): stim_amp = "%snA"%stims[i] input_id = ("input_%s"%stim_amp).replace('.','_').replace('-','min') pg = nml.PulseGenerator(id=input_id, delay="0ms", duration="%sms"%duration, amplitude=stim_amp) net_doc.pulse_generators.append(pg) # Add these to cells input_list = nml.InputList(id=input_id, component=pg.id, populations=pop.id) input = nml.Input(id='0', target="../%s[%i]"%(pop.id, i), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) net_file_name = '%s.net.nml'%sim_id pynml.write_neuroml2_file(net_doc, net_file_name) ls.include_neuroml2_file(net_file_name) disp0 = 'Voltage_display' ls.create_display(disp0,"Voltages", "-90", "50") of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat"%sim_id) for i in range(number_cells): ref = "v_cell%i"%i quantity = "%s[%i]/v"%(pop.id, i) ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of0, ref, quantity) lems_file_name = ls.save_to_file() if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) #print(results.keys()) if_results = {} iv_results = {} for i in range(number_cells): t = np.array(results['t'])*1000 v = np.array(results["%s[%i]/v"%(pop.id, i)])*1000 mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV) spike_times = mm['maxima_times'] freq = 0 if len(spike_times) > 2: count = 0 for s in spike_times: if s >= analysis_delay and s < (analysis_duration+analysis_delay): count+=1 freq = 1000 * count/float(analysis_duration) mean_freq = mean_spike_frequency(spike_times) # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq)) if_results[stims[i]] = freq if freq == 0: iv_results[stims[i]] = v[-1] if plot_if: stims = sorted(if_results.keys()) stims_pA = [ii*1000 for ii in stims] freqs = [if_results[s] for s in stims] pynml.generate_plot([stims_pA], [freqs], "Frequency versus injected current for: %s"%nml2_file, colors = ['k'], linestyles=['-'], markers=['o'], xaxis = 'Input current (pA)', yaxis = 'Firing frequency (Hz)', xlim = xlim_if, ylim = ylim_if, grid = True, show_plot_already=False, save_figure_to = save_if_figure_to) if plot_iv: stims = sorted(iv_results.keys()) stims_pA = [ii*1000 for ii in sorted(iv_results.keys())] vs = [iv_results[s] for s in stims] pynml.generate_plot([stims_pA], [vs], "Final membrane potential versus injected current for: %s"%nml2_file, colors = ['k'], linestyles=['-'], markers=['o'], xaxis = 'Input current (pA)', yaxis = 'Membrane potential (mV)', xlim = xlim_iv, ylim = ylim_iv, grid = True, show_plot_already=False, save_figure_to = save_iv_figure_to) if show_plot_already: from matplotlib import pyplot as plt plt.show() return if_results
def generate_example_network(network_id, numCells_exc, numCells_inh, x_size = 1000, y_size = 100, z_size = 1000, exc_group_component = "SimpleIaF", inh_group_component = "SimpleIaF_inh", validate = True, random_seed = 1234, generate_lems_simulation = False, connections = True, connection_probability_exc_exc = 0.4, connection_probability_inh_exc = 0.4, connection_probability_exc_inh = 0.4, connection_probability_inh_inh = 0.4, inputs = False, input_firing_rate = 50, # Hz input_offset_min = 0, # nA input_offset_max = 0, # nA num_inputs_per_exc = 4, duration = 500, # ms dt = 0.05, temperature="32.0 degC"): seed(random_seed) nml_doc = NeuroMLDocument(id=network_id) net = Network(id = network_id, type = "networkWithTemperature", temperature = temperature) net.notes = "Network generated using libNeuroML v%s"%__version__ nml_doc.networks.append(net) for cell_comp in set([exc_group_component, inh_group_component]): # removes duplicates nml_doc.includes.append(IncludeType(href='%s.cell.nml'%cell_comp)) # The names of the Exc & Inh groups/populations exc_group = "Exc" inh_group = "Inh" # The names of the network connections net_conn_exc_inh = "NetConn_Exc_Inh" net_conn_inh_exc = "NetConn_Inh_Exc" net_conn_exc_exc = "NetConn_Exc_Exc" net_conn_inh_inh = "NetConn_Inh_Inh" # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct) exc_inh_syn = "AMPAR" inh_exc_syn = "GABAA" exc_exc_syn = "AMPAR" inh_inh_syn = "GABAA" for syn in [exc_inh_syn, inh_exc_syn]: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn)) # Generate excitatory cells exc_pop = Population(id=exc_group, component=exc_group_component, type="populationList", size=numCells_exc) net.populations.append(exc_pop) for i in range(0, numCells_exc) : index = i inst = Instance(id=index) exc_pop.instances.append(inst) inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random())) # Generate inhibitory cells inh_pop = Population(id=inh_group, component=inh_group_component, type="populationList", size=numCells_inh) net.populations.append(inh_pop) for i in range(0, numCells_inh) : index = i inst = Instance(id=index) inh_pop.instances.append(inst) inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random())) if connections: proj_exc_exc = Projection(id=net_conn_exc_exc, presynaptic_population=exc_group, postsynaptic_population=exc_group, synapse=exc_exc_syn) net.projections.append(proj_exc_exc) proj_exc_inh = Projection(id=net_conn_exc_inh, presynaptic_population=exc_group, postsynaptic_population=inh_group, synapse=exc_inh_syn) net.projections.append(proj_exc_inh) proj_inh_exc = Projection(id=net_conn_inh_exc, presynaptic_population=inh_group, postsynaptic_population=exc_group, synapse=inh_exc_syn) net.projections.append(proj_inh_exc) proj_inh_inh = Projection(id=net_conn_inh_inh, presynaptic_population=inh_group, postsynaptic_population=inh_group, synapse=inh_inh_syn) net.projections.append(proj_inh_inh) count_exc_inh = 0 count_inh_exc = 0 count_exc_exc = 0 count_inh_inh = 0 for i in range(0, numCells_exc): for j in range(0, numCells_inh): if i != j: if random()<connection_probability_exc_inh: add_connection(proj_exc_inh, count_exc_inh, exc_group, exc_group_component, i, 0, inh_group, inh_group_component, j, 0) count_exc_inh+=1 if random()<connection_probability_inh_exc: add_connection(proj_inh_exc, count_inh_exc, inh_group, inh_group_component, j, 0, exc_group, exc_group_component, i, 0) count_inh_exc+=1 for i in range(0, numCells_exc): for j in range(0, numCells_exc): if i != j: if random()<connection_probability_exc_exc: add_connection(proj_exc_exc, count_exc_exc, exc_group, exc_group_component, i, 0, exc_group, exc_group_component, j, 0) count_exc_exc+=1 for i in range(0, numCells_inh): for j in range(0, numCells_inh): if i != j: if random()<connection_probability_inh_inh: add_connection(proj_inh_inh, count_inh_inh, inh_group, inh_group_component, j, 0, inh_group, inh_group_component, i, 0) count_inh_inh+=1 if inputs: if input_firing_rate>0: mf_input_syn = "AMPAR" if mf_input_syn!=exc_inh_syn and mf_input_syn!=inh_exc_syn: nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn)) rand_spiker_id = "input_%sHz"%input_firing_rate pfs = PoissonFiringSynapse(id=rand_spiker_id, average_rate="%s per_s"%input_firing_rate, synapse=mf_input_syn, spike_target="./%s"%mf_input_syn) nml_doc.poisson_firing_synapses.append(pfs) input_list = InputList(id="Input_0", component=rand_spiker_id, populations=exc_group) count = 0 for i in range(0, numCells_exc): for j in range(num_inputs_per_exc): input = Input(id=count, target="../%s/%i/%s"%(exc_group, i, exc_group_component), destination="synapses") input_list.input.append(input) count += 1 net.input_lists.append(input_list) if input_offset_max != 0 or input_offset_min != 0: for i in range(0, numCells_exc): pg = PulseGenerator(id="PulseGenerator_%i"%i, delay="0ms", duration="%sms"%duration, amplitude="%fnA"%(input_offset_min+(input_offset_max-input_offset_min)*random())) nml_doc.pulse_generators.append(pg) input_list = InputList(id="Input_Pulse_List_%i"%i, component=pg.id, populations=exc_group) input = Input(id=0, target="../%s/%i/%s"%(exc_group, i, exc_group_component), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) ####### Write to file ###### print("Saving to file...") nml_file = network_id+'.net.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: "+nml_file) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_lems_simulation: # Create a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation("Sim_%s"%network_id, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Include generated/existing NeuroML2 files ls.include_neuroml2_file('%s.cell.nml'%exc_group_component) ls.include_neuroml2_file('%s.cell.nml'%inh_group_component) ls.include_neuroml2_file(nml_file) # Specify Displays and Output Files disp_exc = "display_exc" ls.create_display(disp_exc, "Voltages Exc cells", "-80", "50") of_exc = 'Volts_file_exc' ls.create_output_file(of_exc, "v_exc.dat") disp_inh = "display_inh" ls.create_display(disp_inh, "Voltages Inh cells", "-80", "50") of_inh = 'Volts_file_inh' ls.create_output_file(of_inh, "v_inh.dat") for i in range(numCells_exc): quantity = "%s/%i/%s/v"%(exc_group, i, exc_group_component) ls.add_line_to_display(disp_exc, "Exc %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_exc, "v_%i"%i, quantity) for i in range(numCells_inh): quantity = "%s/%i/%s/v"%(inh_group, i, inh_group_component) ls.add_line_to_display(disp_inh, "Inh %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of_inh, "v_%i"%i, quantity) # Save to LEMS XML file lems_file_name = ls.save_to_file() print "-----------------------------------"
def generate_lems_file_for_neuroml( sim_id, neuroml_file, target, duration, dt, lems_file_name, target_dir, nml_doc=None, # Use this if the nml doc has already been loaded (to avoid delay in reload) include_extra_files=[], gen_plots_for_all_v=True, plot_all_segments=False, gen_plots_for_quantities={}, # Dict with displays vs lists of quantity paths gen_plots_for_only_populations=[], # List of populations, all pops if=[] gen_saves_for_all_v=True, save_all_segments=False, gen_saves_for_only_populations=[], # List of populations, all pops if=[] gen_saves_for_quantities={}, # Dict with file names vs lists of quantity paths gen_spike_saves_for_all_somas=False, gen_spike_saves_for_only_populations=[], # List of populations, all pops if=[] gen_spike_saves_for_cells={}, # Dict with file names vs lists of quantity paths spike_time_format='ID_TIME', copy_neuroml=True, report_file_name=None, lems_file_generate_seed=None, verbose=False, simulation_seed=12345): my_random = random.Random() if lems_file_generate_seed: my_random.seed( lems_file_generate_seed ) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input else: my_random.seed( 12345 ) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input file_name_full = '%s/%s' % (target_dir, lems_file_name) print_comment_v( 'Creating LEMS file at: %s for NeuroML 2 file: %s (copy: %s)' % (file_name_full, neuroml_file, copy_neuroml)) ls = LEMSSimulation(sim_id, duration, dt, target, simulation_seed=simulation_seed) if nml_doc is None: nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=verbose) nml_doc_inc_not_included = read_neuroml2_file(neuroml_file, include_includes=False, verbose=False) else: nml_doc_inc_not_included = nml_doc ls.set_report_file(report_file_name) quantities_saved = [] for f in include_extra_files: ls.include_neuroml2_file(f, include_included=False) if not copy_neuroml: rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir)) print_comment_v("Including existing NeuroML file (%s) as: %s" % (neuroml_file, rel_nml_file)) ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir)) else: print_comment_v( "Copying a NeuroML file (%s) to: %s (abs path: %s)" % (neuroml_file, target_dir, os.path.abspath(target_dir))) if not os.path.isdir(target_dir): raise Exception("Target directory %s does not exist!" % target_dir) if os.path.realpath( os.path.dirname(neuroml_file)) != os.path.realpath(target_dir): shutil.copy(neuroml_file, target_dir) else: print_comment_v("No need, same file...") neuroml_file_name = os.path.basename(neuroml_file) ls.include_neuroml2_file(neuroml_file_name, include_included=False) nml_dir = os.path.dirname(neuroml_file) if len( os.path.dirname(neuroml_file)) > 0 else '.' for include in nml_doc_inc_not_included.includes: if nml_dir == '.' and os.path.isfile(include.href): incl_curr = include.href else: incl_curr = '%s/%s' % (nml_dir, include.href) if os.path.isfile(include.href): incl_curr = include.href print_comment_v( ' - Including %s (located at %s; nml dir: %s), copying to %s' % (include.href, incl_curr, nml_dir, target_dir)) ''' if not os.path.isfile("%s/%s" % (target_dir, os.path.basename(incl_curr))) and \ not os.path.isfile("%s/%s" % (target_dir, incl_curr)) and \ not os.path.isfile(incl_curr): shutil.copy(incl_curr, target_dir) else: print_comment_v("No need to copy...")''' f1 = "%s/%s" % (target_dir, os.path.basename(incl_curr)) f2 = "%s/%s" % (target_dir, incl_curr) if os.path.isfile(f1): print_comment_v("No need to copy, file exists: %s..." % f1) elif os.path.isfile(f2): print_comment_v("No need to copy, file exists: %s..." % f2) else: shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) sub_doc = read_neuroml2_file(incl_curr) sub_dir = os.path.dirname(incl_curr) if len( os.path.dirname(incl_curr)) > 0 else '.' if sub_doc.__class__ == neuroml.nml.nml.NeuroMLDocument: for include in sub_doc.includes: incl_curr = '%s/%s' % (sub_dir, include.href) print_comment_v(' -- Including %s located at %s' % (include.href, incl_curr)) if not os.path.isfile("%s/%s" % (target_dir, os.path.basename(incl_curr))) and \ not os.path.isfile("%s/%s" % (target_dir, incl_curr)): shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) if gen_plots_for_all_v \ or gen_saves_for_all_v \ or len(gen_plots_for_only_populations) > 0 \ or len(gen_saves_for_only_populations) > 0 \ or gen_spike_saves_for_all_somas \ or len(gen_spike_saves_for_only_populations) > 0: for network in nml_doc.networks: for population in network.populations: variable = "v" quantity_template_e = "%s[%i]" component = population.component size = population.size cell = None segment_ids = [] for c in nml_doc.spike_generator_poissons: if c.id == component: variable = "tsince" for c in nml_doc.SpikeSourcePoisson: if c.id == component: variable = "tsince" quantity_template = "%s[%i]/" + variable if plot_all_segments or gen_spike_saves_for_all_somas: for c in nml_doc.cells: if c.id == component: cell = c for segment in cell.morphology.segments: segment_ids.append(segment.id) segment_ids.sort() if population.type and population.type == 'populationList': quantity_template = "%s/%i/" + component + "/" + variable quantity_template_e = "%s/%i/" + component + "" # Multicompartmental cell # Needs to be supported in NeuronWriter # if len(segment_ids)>1: # quantity_template_e = "%s/%i/"+component+"/0" size = len(population.instances) if gen_plots_for_all_v or population.id in gen_plots_for_only_populations: print_comment( 'Generating %i plots for %s in population %s' % (size, component, population.id)) disp0 = 'DispPop__%s' % population.id ls.create_display( disp0, "Membrane potentials of cells in %s" % population.id, "-90", "50") for i in range(size): if cell is not None and plot_all_segments: quantity_template_seg = "%s/%i/" + component + "/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg % ( population.id, i, segment_id) ls.add_line_to_display( disp0, "%s[%i] seg %i: v" % (population.id, i, segment_id), quantity, "1mV", get_next_hex_color(my_random)) else: quantity = quantity_template % (population.id, i) ls.add_line_to_display( disp0, "%s[%i]: v" % (population.id, i), quantity, "1mV", get_next_hex_color(my_random)) if gen_saves_for_all_v or population.id in gen_saves_for_only_populations: print_comment( 'Saving %i values of %s for %s in population %s' % (size, variable, component, population.id)) of0 = 'Volts_file__%s' % population.id ls.create_output_file( of0, "%s.%s.%s.dat" % (sim_id, population.id, variable)) for i in range(size): if cell is not None and save_all_segments: quantity_template_seg = "%s/%i/" + component + "/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg % ( population.id, i, segment_id) ls.add_column_to_output_file( of0, 'v_%s' % safe_variable(quantity), quantity) quantities_saved.append(quantity) else: quantity = quantity_template % (population.id, i) ls.add_column_to_output_file( of0, 'v_%s' % safe_variable(quantity), quantity) quantities_saved.append(quantity) if gen_spike_saves_for_all_somas or population.id in gen_spike_saves_for_only_populations: print_comment( 'Saving spikes in %i somas for %s in population %s' % (size, component, population.id)) eof0 = 'Spikes_file__%s' % population.id ls.create_event_output_file(eof0, "%s.%s.spikes" % (sim_id, population.id), format=spike_time_format) for i in range(size): quantity = quantity_template_e % (population.id, i) ls.add_selection_to_event_output_file( eof0, i, quantity, "spike") quantities_saved.append(quantity) for display in sorted(gen_plots_for_quantities.keys()): quantities = gen_plots_for_quantities[display] max_ = "1" min_ = "-1" scale = "1" # Check for v ... if quantities and len(quantities) > 0 and quantities[0].endswith('/v'): max_ = "40" min_ = "-80" scale = "1mV" ls.create_display(display, "Plots of %s" % display, min_, max_) for q in quantities: ls.add_line_to_display(display, safe_variable(q), q, scale, get_next_hex_color(my_random)) for file_name in sorted(gen_saves_for_quantities.keys()): quantities = gen_saves_for_quantities[file_name] of_id = safe_variable(file_name) ls.create_output_file(of_id, file_name) for q in quantities: ls.add_column_to_output_file(of_id, safe_variable(q), q) quantities_saved.append(q) for file_name in sorted(gen_spike_saves_for_cells.keys()): quantities = gen_spike_saves_for_cells[file_name] of_id = safe_variable(file_name) ls.create_event_output_file(of_id, file_name) pop_here = None for i, quantity in enumerate(quantities): pop, index = get_pop_index(quantity) if pop_here: if pop_here != pop: raise Exception('Problem with generating LEMS for saving spikes for file %s.\n' % file_name + \ 'Multiple cells from different populations in one file will cause issues with index/spike id.') pop_here = pop # print('===== Adding to %s (%s) event %i for %s, pop: %s, i: %s' % (file_name, of_id, i, quantity, pop, index)) ls.add_selection_to_event_output_file(of_id, index, quantity, "spike") quantities_saved.append(quantity) ls.save_to_file(file_name=file_name_full) return quantities_saved, ls
def generate_hippocampal_net(network_id, conndata="430", nrn_runname="TestRun", validate=True, randomSeed=12345, generate_LEMS_simulation=False, duration=100, dt=0.01, temperature="34.0 degC"): seed(randomSeed) cell_types = [ 'axoaxonic', 'bistratified', 'cck', 'cutsuridis', 'ivy', 'ngf', 'olm', 'poolosyn', 'pvbasket', 'sca' ] synapse_types = ['exp2Synapses', 'customGABASynapses'] ###### Create network doc ##### nml_doc = neuroml.NeuroMLDocument(id=network_id) for cell in cell_types: nml_doc.includes.append( neuroml.IncludeType(href="../cells/%s.cell.nml" % cell)) for synapse in synapse_types: nml_doc.includes.append( neuroml.IncludeType(href="../synapses/%s.synapse.nml" % synapse)) nml_doc.includes.append(neuroml.IncludeType(href="stimulations.nml")) # Create network net = neuroml.Network(id=network_id, type="networkWithTemperature", temperature=temperature) from neuroml import __version__ net.notes = "Network generated using libNeuroML v%s" % __version__ nml_doc.networks.append(net) # Create populations print("Creating populations...") dCellIDs, dNumCells = create_populations(net, cell_types, nrn_runname, randomSeed) # Create synapses print("Connecting cells...") add_synapses(net, conndata, nrn_runname, dCellIDs, dNumCells, write_synapse_file=False) # initialise voltage print("Initialising cell voltage..") # TODO: this shouldn't be hard coded ... dClamps = {} dClamps["axoaxonic"] = -65.0127 dClamps["bistratified"] = -67.0184 dClamps["cck"] = -70.6306 dClamps["ivy"] = -59.9512 dClamps["ngf"] = -59.9512 dClamps["olm"] = -71.1411 dClamps["poolosyn"] = -62.9601 dClamps["pvbasket"] = -65.0246 dClamps["sca"] = -70.5652 init_voltage(nml_doc, net, dClamps, dNumCells) ####### Write to file ###### print("Saving to file...") nml_file = network_id + '.net.nml' writers.NeuroMLWriter.write(nml_doc, nml_file) print("Written network file to: " + nml_file) if validate: ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_LEMS_simulation: # Create a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation('Sim_' + network_id, duration, dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Incude generated/existing NeuroML2 files channel_types = [ 'CavL', 'CavN', 'HCN', 'HCNolm', 'HCNp', 'KCaS', 'Kdrfast', 'Kdrfastngf', 'Kdrp', 'Kdrslow', 'KvA', 'KvAdistp', 'KvAngf', 'KvAolm', 'KvAproxp', 'KvCaB', 'KvGroup', 'Nav', 'Navaxonp', 'Navbis', 'Navcck', 'Navngf', 'Navp', 'leak_chan' ] for channel in channel_types: ls.include_neuroml2_file("../channels/%s.channel.nml" % channel, include_included=False) ls.include_neuroml2_file("../channels/Capool.nml", include_included=False) for cell in cell_types: ls.include_neuroml2_file("../cells/%s.cell.nml" % cell, include_included=False) for synapse in synapse_types: ls.include_neuroml2_file("../synapses/%s.synapse.nml" % synapse, include_included=False) ls.include_neuroml2_file("stimulations.nml", include_included=False) ls.include_neuroml2_file(nml_file, include_included=False) ###### Specify Display and output files ##### max_traces = 9 # the 10th color in NEURON is white ... for cell_type, numCells in dNumCells.iteritems(): PC = False if numCells > 0: of = "of_%s" % cell_type ls.create_output_file(of, "%s.v.dat" % cell_type) if cell_type == 'poolosyn' or cell_type == 'cutsuridis': # TODO: ensure that only one of them is used for modelling pyramidal cells (in a given simulation) PC = True ls.create_event_output_file("spikes_PC", "PC.spikes.dat") ls.create_display("disp_PC", "Voltages Pyramidal cells", "-80", "50") cell_id = "%scell" % cell_type pop_id = "pop_%s" % cell_type for i in range(numCells): quantity = "%s/%i/%s/v" % (pop_id, i, cell_id) ls.add_column_to_output_file(of, "v_%i" % i, quantity) if PC: ls.add_selection_to_event_output_file( "spikes_PC", i, select='%s/%i/%s' % (pop_id, i, cell_id), event_port='spike') if i < max_traces: ls.add_line_to_display("disp_PC", "PC %i: V[mV]" % i, quantity, "1mV", pynml.get_next_hex_color()) # Save to LEMS file print("Writing LEMS file...") lems_file_name = ls.save_to_file() else: ls = None lems_file_name = '' print("-----------------------------------") return ls, lems_file_name
def generate_current_vs_frequency_curve( nml2_file, cell_id, start_amp_nA, end_amp_nA, step_nA, analysis_duration, analysis_delay, dt=0.05, temperature="32degC", spike_threshold_mV=0.0, plot_voltage_traces=False, plot_if=True, simulator="jNeuroML", ): from pyelectro.analysis import max_min from pyelectro.analysis import mean_spike_frequency import numpy as np sim_id = "iv_%s" % cell_id duration = analysis_duration + analysis_delay ls = LEMSSimulation(sim_id, duration, dt) ls.include_neuroml2_file(nml2_file) stims = [] amp = start_amp_nA while amp <= end_amp_nA: stims.append(amp) amp += step_nA number_cells = len(stims) pop = nml.Population(id="population_of_%s" % cell_id, component=cell_id, size=number_cells) # create network and add populations net_id = "network_of_%s" % cell_id net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature) ls.assign_simulation_target(net_id) net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net.populations.append(pop) for i in range(number_cells): stim_amp = "%snA" % stims[i] input_id = ("input_%s" % stim_amp).replace(".", "_") pg = nml.PulseGenerator(id=input_id, delay="0ms", duration="%sms" % duration, amplitude=stim_amp) net_doc.pulse_generators.append(pg) # Add these to cells input_list = nml.InputList(id=input_id, component=pg.id, populations=pop.id) input = nml.Input(id="0", target="../%s[%i]" % (pop.id, i), destination="synapses") input_list.input.append(input) net.input_lists.append(input_list) net_file_name = "%s.net.nml" % sim_id pynml.write_neuroml2_file(net_doc, net_file_name) ls.include_neuroml2_file(net_file_name) disp0 = "Voltage_display" ls.create_display(disp0, "Voltages", "-90", "50") of0 = "Volts_file" ls.create_output_file(of0, "%s.v.dat" % sim_id) for i in range(number_cells): ref = "v_cell%i" % i quantity = "%s[%i]/v" % (pop.id, i) ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color()) ls.add_column_to_output_file(of0, ref, quantity) lems_file_name = ls.save_to_file() if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml( lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces ) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron( lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces ) # print(results.keys()) if_results = {} for i in range(number_cells): t = np.array(results["t"]) * 1000 v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000 mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV) spike_times = mm["maxima_times"] freq = 0 if len(spike_times) > 2: count = 0 for s in spike_times: if s >= analysis_delay and s < (analysis_duration + analysis_delay): count += 1 freq = 1000 * count / float(analysis_duration) mean_freq = mean_spike_frequency(spike_times) # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq)) if_results[stims[i]] = freq if plot_if: from matplotlib import pyplot as plt plt.xlabel("Input current (nA)") plt.ylabel("Firing frequency (Hz)") plt.grid("on") stims = sorted(if_results.keys()) freqs = [] for s in stims: freqs.append(if_results[s]) plt.plot(stims, freqs, "o") plt.show() return if_results
def generate_Vm_vs_time_plot(NML2_file, cell_id, # inj_amp_nA = 80, # delay_ms = 20, # inj_dur_ms = 0.5, sim_dur_ms = 1000, dt = 0.05, temperature = "35", spike_threshold_mV=0., plot_voltage_traces=False, show_plot_already=True, simulator="jNeuroML_NEURON", include_included=True): # simulation parameters nogui = '-nogui' in sys.argv # Used to supress GUI in tests for Travis-CI ref = "iMC1_cell_1_origin" print_comment_v("Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s"% # (Inj %snA / %sms dur after %sms delay)"% (cell_id, NML2_file, simulator))#, inj_amp_nA, inj_dur_ms, delay_ms)) sim_id = 'Vm_%s'%ref duration = sim_dur_ms ls = LEMSSimulation(sim_id, sim_dur_ms, dt) ls.include_neuroml2_file(NML2_file, include_included=include_included) ls.assign_simulation_target('network') nml_doc = nml.NeuroMLDocument(id=cell_id) nml_doc.includes.append(nml.IncludeType(href=NML2_file)) net = nml.Network(id="network", type='networkWithTemperature', temperature='%sdegC'%temperature) nml_doc.networks.append(net) #input_id = ("input_%s"%str(inj_amp_nA).replace('.','_')) #pg = nml.PulseGenerator(id=input_id, # delay="%sms"%delay_ms, # duration='%sms'%inj_dur_ms, # amplitude='%spA'%inj_amp_nA) #nml_doc.pulse_generators.append(pg) pop_id = 'single_cell' pop = nml.Population(id=pop_id, component='iMC1_cell_1_origin', size=1, type="populationList") inst = nml.Instance(id=0) pop.instances.append(inst) inst.location = nml.Location(x=0, y=0, z=0) net.populations.append(pop) # Add these to cells #input_list = nml.InputList(id='il_%s'%input_id, # component=pg.id, # populations=pop_id) #input = nml.Input(id='0', target='../hhpop/0/hhcell', # destination="synapses") #input_list.input.append(input) #net.input_lists.append(input_list) sim_file_name = '%s.sim.nml'%sim_id pynml.write_neuroml2_file(nml_doc, sim_file_name) ls.include_neuroml2_file(sim_file_name) disp0 = 'Voltage_display' ls.create_display(disp0,"Voltages", "-90", "50") ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV') of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat"%sim_id) ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v") lems_file_name = ls.save_to_file() if simulator == "jNeuroML": results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) elif simulator == "jNeuroML_NEURON": results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces, show_plot_already=False) if show_plot_already: from matplotlib import pyplot as plt plt.show() #plt.plot("t","V") #plt.title("Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"% # (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms)) #plt.xlabel('Time (ms)') #plt.ylabel('Vmemb (mV)') #plt.legend(['Test'], loc='upper right') return of0
def generate_WB_network(cell_id, synapse_id, numCells_bc, connection_probability, I_mean, I_sigma, generate_LEMS_simulation, duration, x_size=100, y_size=100, z_size=100, network_id=ref + 'Network', color='0 0 1', connection=True, temperature='37 degC', validate=True, dt=0.01): nml_doc = neuroml.NeuroMLDocument(id=network_id) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsaki.cell.nml')) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiSynapse.xml')) # Create network net = neuroml.Network(id=network_id, type='networkWithTemperature', temperature=temperature) net.notes = 'Network generated using libNeuroML v%s' % __version__ nml_doc.networks.append(net) # Create population pop = neuroml.Population(id=ref + 'pop', component=cell_id, type='populationList', size=numCells_bc) if color is not None: pop.properties.append(neuroml.Property('color', color)) net.populations.append(pop) for i in range(0, numCells_bc): inst = neuroml.Instance(id=i) pop.instances.append(inst) inst.location = neuroml.Location(x=str(x_size * rnd.random()), y=str(y_size * rnd.random()), z=str(z_size * rnd.random())) # Add connections proj = neuroml.ContinuousProjection(id=ref + 'proj', presynaptic_population=pop.id, postsynaptic_population=pop.id) conn_count = 0 for i in range(0, numCells_bc): for j in range(0, numCells_bc): if i != j and rnd.random() < connection_probability: connection = neuroml.ContinuousConnectionInstance( id=conn_count, pre_cell='../%s/%i/%s' % (pop.id, i, cell_id), pre_component='silent', post_cell='../%s/%i/%s' % (pop.id, j, cell_id), post_component=synapse_id) proj.continuous_connection_instances.append(connection) conn_count += 1 net.continuous_projections.append(proj) # make cell pop inhomogenouos (different V_init-s with voltage-clamp) vc_dur = 2 # ms for i in range(0, numCells_bc): tmp = -75 + (rnd.random() * 15) vc = neuroml.VoltageClamp(id='VClamp%i' % i, delay='0ms', duration='%ims' % vc_dur, simple_series_resistance='1e6ohm', target_voltage='%imV' % tmp) nml_doc.voltage_clamps.append(vc) input_list = neuroml.InputList(id='input_%i' % i, component='VClamp%i' % i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s' % (pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Add outer input (IClamp) tmp = rnd.normal(I_mean, I_sigma**2, numCells_bc) # random numbers from Gaussian distribution for i in range(0, numCells_bc): pg = neuroml.PulseGenerator(id='IClamp%i' % i, delay='%ims' % vc_dur, duration='%ims' % (duration - vc_dur), amplitude='%fpA' % (tmp[i])) nml_doc.pulse_generators.append(pg) input_list = neuroml.InputList(id='input%i' % i, component='IClamp%i' % i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s' % (pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Write to file nml_file = '%s100Cells.net.nml' % ref print 'Writing network file to:', nml_file, '...' neuroml.writers.NeuroMLWriter.write(nml_doc, nml_file) if validate: # Validate the NeuroML from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_LEMS_simulation: # Vreate a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation(sim_id='%sNetSim' % ref, duration=duration, dt=dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Incude generated/existing NeuroML2 files ls.include_neuroml2_file('WangBuzsaki.cell.nml', include_included=False) ls.include_neuroml2_file('WangBuzsakiSynapse.xml', include_included=False) ls.include_neuroml2_file(nml_file, include_included=False) # Specify Display and output files disp_bc = 'display_bc' ls.create_display(disp_bc, 'Basket Cell Voltage trace', '-80', '40') of_bc = 'volts_file_bc' ls.create_output_file(of_bc, 'wangbuzsaki_network.dat') of_spikes_bc = 'spikes_bc' ls.create_event_output_file(of_spikes_bc, 'wangbuzsaki_network_spikes.dat') max_traces = 9 # the 10th color in NEURON is white ... for i in range(numCells_bc): quantity = '%s/%i/%s/v' % (pop.id, i, cell_id) if i < max_traces: ls.add_line_to_display(disp_bc, 'BC %i: Vm' % i, quantity, '1mV', pynml.get_next_hex_color()) ls.add_column_to_output_file(of_bc, 'v_%i' % i, quantity) ls.add_selection_to_event_output_file(of_spikes_bc, i, select='%s/%i/%s' % (pop.id, i, cell_id), event_port='spike') # Save to LEMS file print 'Writing LEMS file...' lems_file_name = ls.save_to_file() else: ls = None lems_file_name = '' return ls, lems_file_name
def generate_WB_network(cell_id, synapse_id, numCells_bc, connection_probability, I_mean, I_sigma, generate_LEMS_simulation, duration, x_size = 100, y_size = 100, z_size = 100, network_id = ref+'Network', color = '0 0 1', connection = True, temperature = '37 degC', validate = True, dt = 0.001): nml_doc = neuroml.NeuroMLDocument(id=network_id) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiCell.xml')) nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiSynapse.xml')) # Create network net = neuroml.Network(id=network_id, type='networkWithTemperature', temperature=temperature) net.notes = 'Network generated using libNeuroML v%s'%__version__ nml_doc.networks.append(net) # Create population pop = neuroml.Population(id=ref+'pop', component=cell_id, type='populationList', size=numCells_bc) if color is not None: pop.properties.append(neuroml.Property('color', color)) net.populations.append(pop) for i in range(0, numCells_bc): inst = neuroml.Instance(id=i) pop.instances.append(inst) inst.location = neuroml.Location(x=str(x_size*rnd.random()), y=str(y_size*rnd.random()), z=str(z_size*rnd.random())) # Add connections proj = neuroml.ContinuousProjection(id=ref+'proj', presynaptic_population=pop.id, postsynaptic_population=pop.id) conn_count = 0 for i in range(0, numCells_bc): for j in range(0, numCells_bc): if i != j and rnd.random() < connection_probability: connection = neuroml.ContinuousConnectionInstance(id=conn_count, pre_cell='../%s/%i/%s'%(pop.id, i, cell_id), pre_component='silent', post_cell='../%s/%i/%s'%(pop.id, j, cell_id), post_component=synapse_id) proj.continuous_connection_instances.append(connection) conn_count += 1 net.continuous_projections.append(proj) # make cell pop inhomogenouos (different V_init-s with voltage-clamp) vc_dur = 2 # ms for i in range(0, numCells_bc): tmp = -75 + (rnd.random()*15) vc = neuroml.VoltageClamp(id='VClamp%i'%i, delay='0ms', duration='%ims'%vc_dur, simple_series_resistance='1e6ohm', target_voltage='%imV'%tmp) nml_doc.voltage_clamps.append(vc) input_list = neuroml.InputList(id='input_%i'%i, component='VClamp%i'%i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s'%(pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Add outer input (IClamp) tmp = rnd.normal(I_mean, I_sigma**2, numCells_bc) # random numbers from Gaussian distribution for i in range(0, numCells_bc): pg = neuroml.PulseGenerator(id='IClamp%i'%i, delay='%ims'%vc_dur, duration='%ims'%(duration-vc_dur), amplitude='%fpA'%(tmp[i])) nml_doc.pulse_generators.append(pg) input_list = neuroml.InputList(id='input%i'%i, component='IClamp%i'%i, populations=pop.id) input = neuroml.Input(id=i, target='../%s/%i/%s'%(pop.id, i, cell_id), destination='synapses') input_list.input.append(input) net.input_lists.append(input_list) # Write to file nml_file = '%sNet.nml'%ref print 'Writing network file to:', nml_file, '...' neuroml.writers.NeuroMLWriter.write(nml_doc, nml_file) if validate: # Validate the NeuroML from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file) if generate_LEMS_simulation: # Vreate a LEMSSimulation to manage creation of LEMS file ls = LEMSSimulation(sim_id='%sNetSim'%ref, duration=duration, dt=dt) # Point to network as target of simulation ls.assign_simulation_target(net.id) # Incude generated/existing NeuroML2 files ls.include_neuroml2_file('WangBuzsakiCell.xml', include_included=False) ls.include_neuroml2_file('WangBuzsakiSynapse.xml', include_included=False) ls.include_neuroml2_file(nml_file, include_included=False) # Specify Display and output files disp_bc = 'display_bc' ls.create_display(disp_bc, 'Basket Cell Voltage trace', '-80', '40') of_bc = 'volts_file_bc' ls.create_output_file(of_bc, 'wangbuzsaki_network.dat') of_spikes_bc = 'spikes_bc' ls.create_event_output_file(of_spikes_bc, 'wangbuzsaki_network_spikes.dat') max_traces = 9 # the 10th color in NEURON is white ... for i in range(numCells_bc): quantity = '%s/%i/%s/v'%(pop.id, i, cell_id) if i < max_traces: ls.add_line_to_display(disp_bc, 'BC %i: Vm'%i, quantity, '1mV', pynml.get_next_hex_color()) ls.add_column_to_output_file(of_bc, 'v_%i'%i, quantity) ls.add_selection_to_event_output_file(of_spikes_bc, i, select='%s/%i/%s'%(pop.id, i, cell_id), event_port='spike') # Save to LEMS file print 'Writing LEMS file...' lems_file_name = ls.save_to_file() else: ls = None lems_file_name = '' return ls, lems_file_name
def generate_lems_file_for_neuroml( sim_id, neuroml_file, target, duration, dt, lems_file_name, target_dir, gen_plots_for_all_v=True, plot_all_segments=False, gen_plots_for_only=[], # List of populations gen_plots_for_quantities={}, # Dict with displays vs lists of quantity paths gen_saves_for_all_v=True, save_all_segments=False, gen_saves_for_only=[], # List of populations gen_saves_for_quantities={}, # Dict with file names vs lists of quantity paths copy_neuroml=True, seed=None): if seed: random.seed( seed ) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input file_name_full = '%s/%s' % (target_dir, lems_file_name) print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s' % (file_name_full, neuroml_file)) ls = LEMSSimulation(sim_id, duration, dt, target) nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=True) quantities_saved = [] if not copy_neuroml: rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir)) print_comment_v("Including existing NeuroML file (%s) as: %s" % (neuroml_file, rel_nml_file)) ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir)) else: print_comment_v( "Copying NeuroML file (%s) to: %s (%s)" % (neuroml_file, target_dir, os.path.abspath(target_dir))) if os.path.abspath( os.path.dirname(neuroml_file)) != os.path.abspath(target_dir): shutil.copy(neuroml_file, target_dir) neuroml_file_name = os.path.basename(neuroml_file) ls.include_neuroml2_file(neuroml_file_name, include_included=False) for include in nml_doc.includes: incl_curr = '%s/%s' % (os.path.dirname(neuroml_file), include.href) print_comment_v(' - Including %s located at %s' % (include.href, incl_curr)) shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) sub_doc = read_neuroml2_file(incl_curr) for include in sub_doc.includes: incl_curr = '%s/%s' % (os.path.dirname(neuroml_file), include.href) print_comment_v(' -- Including %s located at %s' % (include.href, incl_curr)) shutil.copy(incl_curr, target_dir) ls.include_neuroml2_file(include.href, include_included=False) if gen_plots_for_all_v or gen_saves_for_all_v or len( gen_plots_for_only) > 0 or len(gen_saves_for_only) > 0: for network in nml_doc.networks: for population in network.populations: quantity_template = "%s[%i]/v" component = population.component size = population.size cell = None segment_ids = [] if plot_all_segments: for c in nml_doc.cells: if c.id == component: cell = c for segment in cell.morphology.segments: segment_ids.append(segment.id) segment_ids.sort() if population.type and population.type == 'populationList': quantity_template = "%s/%i/" + component + "/v" size = len(population.instances) if gen_plots_for_all_v or population.id in gen_plots_for_only: print_comment( 'Generating %i plots for %s in population %s' % (size, component, population.id)) disp0 = 'DispPop__%s' % population.id ls.create_display(disp0, "Voltages of %s" % disp0, "-90", "50") for i in range(size): if plot_all_segments: quantity_template_seg = "%s/%i/" + component + "/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg % ( population.id, i, segment_id) ls.add_line_to_display( disp0, "v in seg %i %s" % (segment_id, safe_variable(quantity)), quantity, "1mV", get_next_hex_color()) else: quantity = quantity_template % (population.id, i) ls.add_line_to_display( disp0, "v %s" % safe_variable(quantity), quantity, "1mV", get_next_hex_color()) if gen_saves_for_all_v or population.id in gen_saves_for_only: print_comment( 'Saving %i values of v for %s in population %s' % (size, component, population.id)) of0 = 'Volts_file__%s' % population.id ls.create_output_file( of0, "%s.%s.v.dat" % (sim_id, population.id)) for i in range(size): if save_all_segments: quantity_template_seg = "%s/%i/" + component + "/%i/v" for segment_id in segment_ids: quantity = quantity_template_seg % ( population.id, i, segment_id) ls.add_column_to_output_file( of0, 'v_%s' % safe_variable(quantity), quantity) quantities_saved.append(quantity) else: quantity = quantity_template % (population.id, i) ls.add_column_to_output_file( of0, 'v_%s' % safe_variable(quantity), quantity) quantities_saved.append(quantity) for display in gen_plots_for_quantities.keys(): quantities = gen_plots_for_quantities[display] ls.create_display(display, "Plots of %s" % display, "-90", "50") for q in quantities: ls.add_line_to_display(display, safe_variable(q), q, "1", get_next_hex_color()) for file_name in gen_saves_for_quantities.keys(): quantities = gen_saves_for_quantities[file_name] ls.create_output_file(file_name, file_name) for q in quantities: ls.add_column_to_output_file(file_name, safe_variable(q), q) ls.save_to_file(file_name=file_name_full) return quantities_saved