def network_to_neuroml(network, output_file_name, **kwargs): # Unpack neuroml extras from kwargs: doc_id = kwargs.get('doc_id', 'default_dipde_network') # Create neuroml doc: nml_doc = nml.NeuroMLDocument(id=doc_id) # Append types: # nml_doc.iaf_cells.append(nml.IafCell0) population_type_list = {} for p in network.population_list: curr_population_name = p.__class__.__name__ if curr_population_name == 'InternalPopulation': print neuroml_internal_population_parameter_dict_adapter(p) elif curr_population_name == 'ExternalPopulation': pass # print neuroml_external_population_parameter_dict_adapter(p) else: raise Exception( 'Population Type (%s) not recognize when converting to NeuroML' % curr_population_name)
def pointset_to_objects(pointset): """ This function is just for visualization of intermediate data (i.e. debugging). """ doc = neuroml.NeuroMLDocument() for i in range(len(pointset)): point = pointset[i] p = neuroml.Point3DWithDiam(x=point[0], y=point[1], z=point[2], diameter=1) soma = neuroml.Segment(proximal=p, distal=p) soma.name = "Soma" soma.id = 0 sg = neuroml.SegmentGroup() sg.id = "Soma" sgm = neuroml.Member(segments=0) sg.members.append(sgm) morphology = neuroml.Morphology() morphology.segments.append(soma) morphology.segment_groups.append(sg) cell = neuroml.Cell() cell.id = "pseudocell for bbpt " + str(i) cell.morphology = morphology doc.cells.append(cell) writers.NeuroMLWriter.write(doc, "backbone.nml")
def generate_network(reference, network_seed=1234, temperature='32degC'): """ Generate a network which will contain populations, projections, etc. Arguments: `reference` the reference to use as the id for the network `network_seed` optional, will be used for random elements of the network, e.g. placement of cells in 3D `temperature` optional, will be specified in network and used in temperature dependent elements, e.g. ion channels with Q10. Default: 32degC """ del oc_build.all_included_files[:] oc_build.all_cells.clear() nml_doc = neuroml.NeuroMLDocument(id='%s' % reference) random.seed(network_seed) nml_doc.properties.append(neuroml.Property("Network seed", network_seed)) # Create network network = neuroml.Network(id='%s' % reference, type='networkWithTemperature', temperature=temperature) nml_doc.networks.append(network) opencortex.print_comment_v( "Created NeuroMLDocument containing a network with id: %s" % reference) return nml_doc, network
def __init__(self, num_segments=1e6): num_segments = int(num_segments) num_vertices = int(num_segments) + 1 x = np.linspace(0, 10, num_vertices) y = np.zeros(num_vertices) z = np.zeros(num_vertices) d = np.linspace(1, 0.01, num_vertices) vertices = np.array([x, y, z, d]).T connectivity = range(-1, num_segments) big_arraymorph = am.ArrayMorphology(vertices=vertices, connectivity=connectivity) self.big_arraymorph = big_arraymorph self.cell = neuroml.Cell(id='test_cell') self.cell.morphology = big_arraymorph self.test_doc = neuroml.NeuroMLDocument(id='TestDocument') self.test_doc.cells.append(self.cell) self.__write_time = None self.num_segments = num_segments
def save_to_neuroml(filename, gid=None, resolution=10): ''' Save the morphology of each neuron to a single NeuroML file. Parameters ---------- filename : str Name of the file. If not present, the .nml suffix will be automatically added. gid : int or list, optional (default: all neurons) Ids of the neurons to save. resolution : int, optional (default: 10) Subsampling coefficient for points on a neurite (sample on point every `resolution`). ''' import neuroml import neuroml.writers as writers if not filename.endswith(".nml"): filename += ".nml" if gid is None: gid = _pg.get_neurons() if not is_iterable(gid): gid = [gid] doc = neuroml.NeuroMLDocument(id=filename) for n in gid: neuron = n if isinstance(n, Neuron) else _pg.get_neurons(n) cell = neuron.to_neuroml(filename, resolution, write=False) doc.cells.append(cell) writers.NeuroMLWriter.write(doc, filename)
def _get_nml_doc(reference="PyNN_NeuroML2_Export", reset=False): """Return the main NeuroMLDocument object being created""" global nml_doc global comment if nml_doc == None or reset: nml_doc = neuroml.NeuroMLDocument(id=reference) nml_doc.notes = comment % 'NeuroML 2' return nml_doc
def test_convert_morphology(self): morph = converter.convert_morphology(self.neuron, positions='auto') cell = neuroml.Cell() cell.name = self.neuron.name cell.id = cell.name cell.morphology = morph doc = neuroml.NeuroMLDocument() doc.cells.append(cell) doc.id = 'TestNeuroMLDocument' fname = os.path.join(outdir, 'test_morphology_conversion.nml') NeuroMLWriter.write(doc, fname) print('Wrote', fname)
def __init__(self): self.DUMMY_CELL_ID = 'dummy_cell' self.current_population = None self.nml_doc = neuroml.NeuroMLDocument(id="BlueBrainConnectome") iafCell0 = neuroml.IafCell(id=self.DUMMY_CELL_ID, C="1.0 nF", thresh="-50mV", reset="-65mV", leak_conductance="10 nS", leak_reversal="-65mV") self.nml_doc.iaf_cells.append(iafCell0)
def setUp(self): num_segments = int(1e4) #Per cell num_vertices = num_segments + 1 x = np.linspace(0, 10, num_vertices) y = np.zeros(num_vertices) z = np.zeros(num_vertices) d = np.linspace(1, 0.01, num_vertices) vertices = np.array([x, y, z, d]).T connectivity = range(-1, num_segments) big_arraymorph = am.ArrayMorphology(vertices=vertices, connectivity=connectivity) transposed_x = x + 10 transposed_vertices = np.array([transposed_x, y, z, d]).T transposed_arraymorph = am.ArrayMorphology( vertices=transposed_vertices, connectivity=connectivity) bigger_d = d + 0.5 fatter_vertices = np.array([x, y, z, bigger_d]).T fatter_arraymorph = am.ArrayMorphology(vertices=fatter_vertices, connectivity=connectivity) neuroml_cell = neuroml.Cell(id='cell_4') neuroml_morphology = neuroml.Morphology(id='my_morph') neuroml_cell.morphology = neuroml_morphology self.transposed_arraymorph = transposed_arraymorph self.fatter_arraymorph = fatter_arraymorph self.big_arraymorph = big_arraymorph self.cell_1 = neuroml.Cell(id='cell_1') self.cell_2 = neuroml.Cell(id='cell_2') self.cell_3 = neuroml.Cell(id='cell_3') self.cell_1.morphology = transposed_arraymorph self.cell_2.morphology = fatter_arraymorph self.cell_3.morphology = big_arraymorph self.test_doc = neuroml.NeuroMLDocument(id='TestDocument') self.test_doc.cells.append(self.cell_1) self.test_doc.cells.append(self.cell_2) self.test_doc.cells.append(self.cell_3) self.test_doc.cells.append(neuroml_cell)
def get_nml_doc(self): if not self.optimized: nml2_doc = nmlHandler.get_nml_doc() if self.nml_doc_extra_elements: add_all_to_document(self.nml_doc_extra_elements, nml2_doc) return nml2_doc else: nml_doc = neuroml.NeuroMLDocument(id=self.doc_id, notes=self.doc_notes) if self.nml_doc_extra_elements: add_all_to_document(self.nml_doc_extra_elements, nml_doc) nml_doc.networks.append(self.optimizedNetwork) return nml_doc
def main(): """Main""" nml2_cell_dir = '../NeuroML2/' net_ref = "ManyCells" net_doc = neuroml.NeuroMLDocument(id=net_ref) net = neuroml.Network(id=net_ref) net_doc.networks.append(net) cell_dirs = [ f for f in os.listdir('.') if (os.path.isdir(f) and os.path.isfile(f + '/.provenance.json')) ] clear_neuron() inputs_list = [] for index, cell_dir in enumerate(cell_dirs): inputs_list.append((index, cell_dir, nml2_cell_dir, len(cell_dirs))) # Parallelise the generation of the files using multiprocessing if the # -parallel option is specified if parallel: import multiprocessing pool = multiprocessing.Pool(maxtasksperchild=1) # pylint: disable=E1123 nml_cell_files = pool.map(process_celldir, inputs_list, chunksize=1) else: nml_cell_files = map(process_celldir, inputs_list) for nml_cell_file, pop in nml_cell_files: net.populations.append(pop) net_doc.includes.append(neuroml.IncludeType(nml_cell_file)) count = len(cell_dirs) if not make_zips: net_file = '%s/%s.net.nml' % (nml2_cell_dir, net_ref) neuroml.writers.NeuroMLWriter.write(net_doc, net_file) print("Written network with %i cells in network to: %s" % (count, net_file)) pynml.nml2_to_svg(net_file)
def load(cls, filepath): """ Right now this load method isn't done in a very nice way. TODO: Complete refactoring. """ import tables file = tables.open_file(filepath,mode='r') document = neuroml.NeuroMLDocument() for node in file.root: if hasattr(node,'vertices'): loaded_morphology = cls.__extract_morphology(node) document.morphology.append(loaded_morphology) else: for morphology in node: loaded_morphology = cls.__extract_morphology(morphology) document.morphology.append(loaded_morphology) return document
def setUp(self): """ Make an optimized morphology, add a couple of segments, save it and then load it back """ vertices = [[0, 0, 0, 0.1], [1, 0, 0, 0.2], [2, 0, 0, 0.3], [3, 0, 0, 0.4]] connectivity = [-1, 0, 1, 2] self.optimized_morphology = am.ArrayMorphology( vertices=vertices, connectivity=connectivity, id="arraymorph_test") seg = neuroml.Segment() #TODO: #self.optimized_morphology.segments.append(seg) doc = neuroml.NeuroMLDocument() cell = neuroml.Cell()
def generate(cls, o, t=2): """ Get a NeuroML object that represents the given object. The ``type`` determines what content is included in the NeuroML object: :param o: The object to generate neuroml from :param t: The what kind of content should be included in the document - 0=full morphology+biophysics - 1=cell body only+biophysics - 2=full morphology only :returns: A NeuroML object that represents the given object. :rtype: NeuroMLDocument """ if isinstance(o, Neuron): # read in the morphology data d = N.NeuroMLDocument(id=o.name()) c = N.Cell(id=o.name()) c.morphology = o.morphology() d.cells.append(c) return d else: raise "Not a valid object for conversion to neuroml"
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_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 create_GoC(runid): ### ---------- Load Params noPar = True pfile = Path('cellparams_file.pkl') keepFile = open('useParams_FI_14_25.pkl', 'rb') runid = pkl.load(keepFile)[runid] keepFile.close() print('Running morphology for parameter set = ', runid) if pfile.exists(): print('Reading parameters from file:') file = open('cellparams_file.pkl', 'rb') params_list = pkl.load(file) if len(params_list) > runid: p = params_list[runid] file.close() if noPar: p = icp.get_channel_params(runid) # Creating document for cell gocID = 'Golgi_040408_C1_' + format(runid, '05d') goc = nml.Cell(id=gocID) #--------simid cell_doc = nml.NeuroMLDocument(id=gocID) cell_doc.cells.append(goc) ### Load morphology morpho_fname = 'Golgi_040408_C1.cell.nml' morpho_file = pynml.read_neuroml2_file(morpho_fname) morpho = morpho_file.cells[0].morphology cell_doc.includes.append(nml.IncludeType(href=morpho_fname)) goc.morphology = morpho ### ---------- Channels na_fname = 'Golgi_Na.channel.nml' cell_doc.includes.append(nml.IncludeType(href=na_fname)) nar_fname = 'Golgi_NaR.channel.nml' cell_doc.includes.append(nml.IncludeType(href=nar_fname)) nap_fname = 'Golgi_NaP.channel.nml' cell_doc.includes.append(nml.IncludeType(href=nap_fname)) ka_fname = 'Golgi_KA.channel.nml' cell_doc.includes.append(nml.IncludeType(href=ka_fname)) sk2_fname = 'Golgi_SK2.channel.nml' cell_doc.includes.append(nml.IncludeType(href=sk2_fname)) km_fname = 'Golgi_KM.channel.nml' cell_doc.includes.append(nml.IncludeType(href=km_fname)) kv_fname = 'Golgi_KV.channel.nml' cell_doc.includes.append(nml.IncludeType(href=kv_fname)) bk_fname = 'Golgi_BK.channel.nml' cell_doc.includes.append(nml.IncludeType(href=bk_fname)) cahva_fname = 'Golgi_CaHVA.channel.nml' cell_doc.includes.append(nml.IncludeType(href=cahva_fname)) calva_fname = 'Golgi_CaLVA.channel.nml' cell_doc.includes.append(nml.IncludeType(href=calva_fname)) hcn1f_fname = 'Golgi_HCN1f.channel.nml' cell_doc.includes.append(nml.IncludeType(href=hcn1f_fname)) hcn1s_fname = 'Golgi_HCN1s.channel.nml' cell_doc.includes.append(nml.IncludeType(href=hcn1s_fname)) hcn2f_fname = 'Golgi_HCN2f.channel.nml' cell_doc.includes.append(nml.IncludeType(href=hcn2f_fname)) hcn2s_fname = 'Golgi_HCN2s.channel.nml' cell_doc.includes.append(nml.IncludeType(href=hcn2s_fname)) leak_fname = 'Golgi_lkg.channel.nml' #leak_ref = nml.IncludeType( href=leak_fname) cell_doc.includes.append(nml.IncludeType(href=leak_fname)) calc_fname = 'Golgi_CALC.nml' cell_doc.includes.append(nml.IncludeType(href=calc_fname)) calc = pynml.read_neuroml2_file( calc_fname).decaying_pool_concentration_models[0] calc2_fname = 'Golgi_CALC2.nml' cell_doc.includes.append(nml.IncludeType(href=calc2_fname)) goc_2pools_fname = 'GoC_2Pools.cell.nml' ### ------Biophysical Properties biophys = nml.BiophysicalProperties(id='biophys_' + gocID) goc.biophysical_properties = biophys # Inproperties ''' res = nml.Resistivity( p["ra"] ) # --------- "0.1 kohm_cm" ca_species = nml.Species( id="ca", ion="ca", concentration_model=calc.id, initial_concentration ="5e-5 mM", initial_ext_concentration="2 mM" ) ca2_species = nml.Species( id="ca2", ion="ca2", concentration_model="Golgi_CALC2", initial_concentration ="5e-5 mM", initial_ext_concentration="2 mM" ) intracellular = nml.IntracellularProperties( ) intracellular.resistivities.append( res ) intracellular.species.append( ca_species ) ''' intracellular = pynml.read_neuroml2_file(goc_2pools_fname).cells[ 0].biophysical_properties.intracellular_properties biophys.intracellular_properties = intracellular # Membrane properties ------- cond memb = nml.MembraneProperties() biophys.membrane_properties = memb #pynml.read_neuroml2_file(leak_fname).ion_channel[0].id -> can't read ion channel passive chan_leak = nml.ChannelDensity(ion_channel="LeakConductance", cond_density=p["leak_cond"], erev="-55 mV", ion="non_specific", id="Leak") memb.channel_densities.append(chan_leak) chan_na = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(na_fname).ion_channel[0].id, cond_density=p["na_cond"], erev="87.39 mV", ion="na", id="Golgi_Na_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_na) chan_nap = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(nap_fname).ion_channel[0].id, cond_density=p["nap_cond"], erev="87.39 mV", ion="na", id="Golgi_NaP_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_nap) chan_nar = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(nar_fname).ion_channel[0].id, cond_density=p["nar_cond"], erev="87.39 mV", ion="na", id="Golgi_NaR_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_nar) chan_ka = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(ka_fname).ion_channel[0].id, cond_density=p["ka_cond"], erev="-84.69 mV", ion="k", id="Golgi_KA_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_ka) chan_sk = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(sk2_fname).ion_channel_kses[0].id, cond_density=p["sk2_cond"], erev="-84.69 mV", ion="k", id="Golgi_KAHP_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_sk) chan_kv = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(kv_fname).ion_channel[0].id, cond_density=p["kv_cond"], erev="-84.69 mV", ion="k", id="Golgi_KV_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_kv) chan_km = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(km_fname).ion_channel[0].id, cond_density=p["km_cond"], erev="-84.69 mV", ion="k", id="Golgi_KM_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_km) chan_bk = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(bk_fname).ion_channel[0].id, cond_density=p["bk_cond"], erev="-84.69 mV", ion="k", id="Golgi_BK_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_bk) chan_h1f = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(hcn1f_fname).ion_channel[0].id, cond_density=p["hcn1f_cond"], erev="-20 mV", ion="h", id="Golgi_hcn1f_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_h1f) chan_h1s = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(hcn1s_fname).ion_channel[0].id, cond_density=p["hcn1s_cond"], erev="-20 mV", ion="h", id="Golgi_hcn1s_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_h1s) chan_h2f = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(hcn2f_fname).ion_channel[0].id, cond_density=p["hcn2f_cond"], erev="-20 mV", ion="h", id="Golgi_hcn2f_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_h2f) chan_h2s = nml.ChannelDensity( ion_channel=pynml.read_neuroml2_file(hcn2s_fname).ion_channel[0].id, cond_density=p["hcn2s_cond"], erev="-20 mV", ion="h", id="Golgi_hcn2s_soma_group", segment_groups="soma_group") memb.channel_densities.append(chan_h2s) chan_hva = nml.ChannelDensityNernst( ion_channel=pynml.read_neuroml2_file(cahva_fname).ion_channel[0].id, cond_density=p["cahva_cond"], ion="ca", id="Golgi_Ca_HVA_soma_group", segment_groups="soma_group") memb.channel_density_nernsts.append(chan_hva) chan_lva = nml.ChannelDensityNernst( ion_channel=pynml.read_neuroml2_file(calva_fname).ion_channel[0].id, cond_density=p["calva_cond"], ion="ca2", id="Golgi_Ca_LVA_soma_group", segment_groups="soma_group") memb.channel_density_nernsts.append(chan_lva) memb.spike_threshes.append(nml.SpikeThresh("0 mV")) memb.specific_capacitances.append( nml.SpecificCapacitance("1.0 uF_per_cm2")) memb.init_memb_potentials.append(nml.InitMembPotential("-60 mV")) goc_filename = '{}.cell.nml'.format(gocID) pynml.write_neuroml2_file(cell_doc, goc_filename) return True
def handleDocumentStart(self, id, notes): self.nml_doc = neuroml.NeuroMLDocument(id=id) if notes and len(notes) > 0: self.nml_doc.notes = notes
def create_GoC_network( duration, dt, seed, runid, run=False): ### ---------- Load Params noPar = True pfile = Path('params_file.pkl') if pfile.exists(): print('Reading parameters from file:') file = open('params_file.pkl','rb') params_list = pkl.load(file) if len(params_list)>runid: p = params_list[runid] file.close() if noPar: p = inp.get_simulation_params( runid ) ### ---------- Component types goc_filename = 'GoC.cell.nml' # Golgi cell with channels goc_file = pynml.read_neuroml2_file( goc_filename ) goc_type = goc_file.cells[0] goc_ref = nml.IncludeType( href=goc_filename ) MFSyn_filename = 'MF_GoC_Syn.nml' # small conductance synapse for background inputs mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename ) MFSyn_type = mfsyn_file.exp_three_synapses[0] mfsyn_ref = nml.IncludeType( href=MFSyn_filename ) MF20Syn_filename = 'MF_GoC_SynMult.nml' # multi-syn conductance for strong/coincident transient input mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename ) MF20Syn_type = mf20syn_file.exp_three_synapses[0] mf20syn_ref = nml.IncludeType( href=MF20Syn_filename ) mf_type2 = 'spikeGeneratorPoisson' # Spike source for background inputs mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" ) # Not tuned to any data - qqq ! mf_bursttype = 'transientPoissonFiringSynapse' # Burst of MF input (as explicit input) mf_burst = nml.TransientPoissonFiringSynapse( id="MF_Burst", average_rate="100 Hz", delay="2000 ms", duration="500 ms", synapse=MF20Syn_type.id, spike_target='./{}'.format(MF20Syn_type.id) ) gj = nml.GapJunction( id="GJ_0", conductance="426pS" ) # GoC synapse ### --------- Populations # Build network to specify cells and connectivity net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" ) # Create GoC population goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=p["nGoC"] ) for goc in range( p["nGoC"] ): inst = nml.Instance( id=goc ) goc_pop.instances.append( inst ) inst.location = nml.Location( x=p["GoC_pos"][goc,0], y=p["GoC_pos"][goc,1], z=p["GoC_pos"][goc,2] ) net.populations.append( goc_pop ) ### MF population MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=p["nMF"]) for mf in range( p["nMF"] ): inst = nml.Instance(id=mf) MF_Poisson_pop.instances.append( inst ) inst.location = nml.Location( x=p["MF_pos"][mf,0], y=p["MF_pos"][mf,1], z=p["MF_pos"][mf,2] ) net.populations.append( MF_Poisson_pop ) # Create NML document for network specification net_doc = nml.NeuroMLDocument( id=net.id ) net_doc.networks.append( net ) net_doc.includes.append( goc_ref ) net_doc.includes.append( mfsyn_ref ) net_doc.includes.append( mf20syn_ref ) net_doc.spike_generator_poissons.append( mf_poisson ) net_doc.transient_poisson_firing_synapses.append( mf_burst ) net_doc.gap_junctions.append(gj) ### ------------ Connectivity ### 1. Background excitatory inputs: MF to GoC populations MFProjection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id) net.projections.append(MFProjection) # MF_> GoC synapses (with syn_count equivalent to integer scaling of Mf synapse strength) nMFSyn = p["MF_GoC_pairs"].shape[1] ctr=0 for syn in range( nMFSyn ): mf, goc = p["MF_GoC_pairs"][:, syn] for syn_count in range(p["MF_GoC_wt"][ctr]): conn2 = nml.Connection(id=ctr, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5") #on soma MFProjection.connections.append(conn2) ctr+=1 ### 2. Perturbation as High Freq MF Inputs ctr=0 for goc in p["Burst_GoC"]: for jj in range( p["nBurst"] ): # Each Perturbed GoC gets nBurst random Burst sources inst = nml.ExplicitInput( id=ctr, target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), input=mf_burst.id, synapse=MF20Syn_type.id, spikeTarget='./{}'.format(MF20Syn_type.id)) net.explicit_inputs.append( inst ) ctr += 1 ### 3. Electrical coupling between GoCs GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id ) net.electrical_projections.append( GoCCoupling ) dend_id = [1,2,5] for jj in range( p["GJ_pairs"].shape[0] ): conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,0], goc_type.id), pre_segment=dend_id[p["GJ_loc"][jj,0]], pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,1], goc_type.id), post_segment=dend_id[p["GJ_loc"][jj,1]], post_fraction_along='0.5', synapse=gj.id, weight=p["GJ_wt"][jj] ) GoCCoupling.electrical_connection_instance_ws.append( conn ) ### -------------- Write files net_filename = 'gocNetwork.nml' pynml.write_neuroml2_file( net_doc, net_filename ) simid = 'sim_gocnet_'+goc_type.id+'_run_{}'.format(runid) ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed ) ls.assign_simulation_target( net.id ) ls.include_neuroml2_file( net_filename) ls.include_neuroml2_file( goc_filename) ls.include_neuroml2_file( MFSyn_filename) ls.include_neuroml2_file( MF20Syn_filename) # Specify outputs eof0 = 'Events_file' ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME') for jj in range( goc_pop.size): ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format( goc_pop.id, jj, goc_type.id), 'spike' ) of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat"%simid) for jj in range( goc_pop.size ): ls.add_column_to_output_file(of0, jj, '{}/{}/{}/v'.format( goc_pop.id, jj, goc_type.id)) #Create Lems file to run lems_simfile = ls.save_to_file() if run: res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", nogui=True, plot=False) else: res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False) return res
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_network_for_sweeps(cell_type, dataset_id, cell_file_name, cell_id, target_dir, data_dir="../../data"): target_sweep_numbers = DH.DATASET_TARGET_SWEEPS[dataset_id] net_id = "network_%s_%s"%(dataset_id, cell_type) net = neuroml.Network(id=net_id, type="networkWithTemperature", temperature=DH.SIMULATION_TEMPERATURE) net_doc = neuroml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(neuroml.IncludeType(cell_file_name)) number_cells = len(target_sweep_numbers) pop = neuroml.Population(id="Pop0", component=cell_id, size=number_cells, type="populationList") net.populations.append(pop) for i in range(number_cells): location = neuroml.Location(x=100*i,y=0,z=0) pop.instances.append(neuroml.Instance(id=i,location=location)) print target_sweep_numbers f = "%s/%s_analysis.json"%(data_dir,dataset_id) with open(f, "r") as json_file: data = json.load(json_file) id = data['data_set_id'] sweeps = data['sweeps'] print("Looking at data analysis in %s (dataset: %s)"%(f,id)) index = 0 for s in target_sweep_numbers: current = float(sweeps['%i'%s]["sweep_metadata"]["aibs_stimulus_amplitude_pa"]) print("Sweep %s (%s pA)"%(s, current)) stim_amp = "%s pA"%current input_id = ("input_%i"%s) pg = neuroml.PulseGenerator(id=input_id, delay="270ms", duration="1000ms", amplitude=stim_amp) net_doc.pulse_generators.append(pg) input_list = neuroml.InputList(id=input_id, component=pg.id, populations=pop.id) input = neuroml.Input(id='0', target="../%s/%i/%s"%(pop.id, index, cell_id), destination="synapses") index+=1 input_list.input.append(input) net.input_lists.append(input_list) net_file_name = '%s/%s.net.nml'%(target_dir,net_id) print("Saving generated network to: %s"%net_file_name) pynml.write_neuroml2_file(net_doc, net_file_name) return net_file_name
""" Example to build a network using libNeuroML, save it as XML and validate it """ ######################################################### import neuroml nml_doc = neuroml.NeuroMLDocument(id="simplenet") net = neuroml.Network(id="simplenet") nml_doc.networks.append(net) # Create 2 populations size0 = 5 size1 = 5 pop0 = neuroml.Population(id="Pop0", size = size0, component="myComponent") net.populations.append(pop0) p = neuroml.Property(tag="axes_to_plot_tuple", value="(1,1)") pop0.properties.append(p) pop1 = neuroml.Population(id="Pop1", size = size1, component="myComponent") net.populations.append(pop1)
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 create_GoC_network(duration, dt, seed, runid, run=False): ### ---------- Load Params noPar = True pfile = Path('params_file.pkl') if pfile.exists(): print('Reading parameters from file:') file = open('params_file.pkl', 'rb') params_list = pkl.load(file) if len(params_list) > runid: p = params_list[runid] file.close() if noPar: p = inp.get_simulation_params(runid) ### ---------- Component types goc_filename = 'GoC.cell.nml' # Golgi cell with channels goc_file = pynml.read_neuroml2_file(goc_filename) goc_type = goc_file.cells[0] goc_ref = nml.IncludeType(href=goc_filename) gj = nml.GapJunction(id="GJ_0", conductance="426pS") # GoC synapse ### --------- Populations # Build network to specify cells and connectivity net = nml.Network(id="gocNetwork", type="networkWithTemperature", temperature="23 degC") # Create GoC population goc_pop = nml.Population(id=goc_type.id + "Pop", component=goc_type.id, type="populationList", size=p["nGoC"]) for goc in range(p["nGoC"]): inst = nml.Instance(id=goc) goc_pop.instances.append(inst) inst.location = nml.Location(x=p["GoC_pos"][goc, 0], y=p["GoC_pos"][goc, 1], z=p["GoC_pos"][goc, 2]) net.populations.append(goc_pop) # Create NML document for network specification net_doc = nml.NeuroMLDocument(id=net.id) net_doc.networks.append(net) net_doc.includes.append(goc_ref) net_doc.gap_junctions.append(gj) ### ------------ Connectivity ### 1. Input Current to one cell ctr = 0 for goc in p["Test_GoC"]: for jj in range(p["nSteps"]): input_id = 'stim_{}'.format(ctr) istep = nml.PulseGenerator( id=input_id, delay='{} ms'.format(p["iDuration"] * jj + p["iRest"] * (jj + 1)), duration='{} ms'.format(p["iDuration"]), amplitude='{} pA'.format(p["iAmp"][jj])) net_doc.pulse_generators.append(istep) input_list = nml.InputList(id='ilist_{}'.format(ctr), component=istep.id, populations=goc_pop.id) curr_inj = nml.Input('0', target="../%s[%i]" % (goc_pop.id, goc), destination="synapses") input_list.input.append(curr_inj) net.input_lists.append(input_list) ctr += 1 ### 2. Electrical coupling between GoCs GoCCoupling = nml.ElectricalProjection(id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id) net.electrical_projections.append(GoCCoupling) dend_id = [1, 2, 5] for jj in range(p["GJ_pairs"].shape[0]): conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj, 0], goc_type.id), pre_segment=dend_id[p["GJ_loc"][jj, 0]], pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj, 1], goc_type.id), post_segment=dend_id[p["GJ_loc"][jj, 1]], post_fraction_along='0.5', synapse=gj.id, weight=p["GJ_wt"][jj]) GoCCoupling.electrical_connection_instance_ws.append(conn) ### -------------- Write files net_filename = 'gocNetwork.nml' pynml.write_neuroml2_file(net_doc, net_filename) simid = 'sim_gocnet_' + goc_type.id + '_run_{}'.format(runid) ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed) ls.assign_simulation_target(net.id) ls.include_neuroml2_file(net_filename) ls.include_neuroml2_file(goc_filename) # Specify outputs eof0 = 'Events_file' ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME') for jj in range(goc_pop.size): ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike') of0 = 'Volts_file' ls.create_output_file(of0, "%s.v.dat" % simid) ctr = 0 for jj in p["Test_GoC"]: ls.add_column_to_output_file( of0, jj, '{}/{}/{}/v'.format(goc_pop.id, ctr, goc_type.id)) ctr += 1 #Create Lems file to run lems_simfile = ls.save_to_file() if run: res = pynml.run_lems_with_jneuroml_neuron(lems_simfile, max_memory="2G", nogui=True, plot=False) else: res = pynml.run_lems_with_jneuroml_neuron(lems_simfile, max_memory="2G", only_generate_scripts=True, compile_mods=False, nogui=True, plot=False) return res
def channelpedia_xml_to_neuroml2(cpd_xml, nml2_file_name, unknowns=""): info = 'Automatic conversion of Channelpedia XML file to NeuroML2\n'+\ 'Uses: https://github.com/OpenSourceBrain/BlueBrainProjectShowcase/blob/master/Channelpedia/ChannelpediaToNeuroML2.py' print(info) root = ET.fromstring(cpd_xml) channel_id = 'Channelpedia_%s_%s' % (root.attrib['ModelName'].replace( "/", "_").replace(" ", "_").replace(".", "_"), root.attrib['ModelID']) doc = neuroml.NeuroMLDocument() metadata = osb.metadata.RDF(info) ion = root.findall('Ion')[0] chan = neuroml.IonChannelHH( id=channel_id, conductance='10pS', species=ion.attrib['Name'], notes= "This is an automated conversion to NeuroML 2 of an ion channel model from Channelpedia. " + "\nThe original channel model file can be found at: http://channelpedia.epfl.ch/ionchannels/%s" % root.attrib['ID'] + "\n\nConversion scripts at https://github.com/OpenSourceBrain/BlueBrainProjectShowcase" ) chan.annotation = neuroml.Annotation() model_url_template = 'http://channelpedia.epfl.ch/ionchannels/%s/hhmodels/%s.xml' desc = osb.metadata.Description(channel_id) metadata.descriptions.append(desc) osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDerivedFrom', \ model_url_template%(root.attrib['ID'], root.attrib['ModelID']), \ "Channelpedia channel ID: %s, ModelID: %s; direct link to original XML model" % (root.attrib['ID'], root.attrib['ModelID'])) channel_url_template = 'http://channelpedia.epfl.ch/ionchannels/%s' osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDescribedBy', \ channel_url_template%(root.attrib['ID']), \ "Channelpedia channel ID: %s; link to main page for channel" % (root.attrib['ID'])) for reference in root.findall('Reference'): pmid = reference.attrib['PubmedID'] #metadata = update_metadata(chan, metadata, channel_id, "http://identifiers.org/pubmed/%s"%pmid) ref_info = reference.text osb.metadata.add_simple_qualifier(desc, \ 'bqmodel', \ 'isDescribedBy', \ osb.resources.PUBMED_URL_TEMPLATE % (pmid), \ ("PubMed ID: %s is referenced in original XML\n"+\ " %s") % (pmid, ref_info)) for environment in root.findall('Environment'): for animal in environment.findall('Animal'): species = animal.attrib['Name'].lower() if species: if species in osb.resources.KNOWN_SPECIES: known_id = osb.resources.KNOWN_SPECIES[species] osb.metadata.add_simple_qualifier(desc, \ 'bqbiol', \ 'hasTaxon', \ osb.resources.NCBI_TAXONOMY_URL_TEMPLATE % known_id, \ "Known species: %s; taxonomy id: %s" % (species, known_id)) else: print("Unknown species: %s" % species) unknowns += "Unknown species: %s\n" % species for cell_type_el in environment.findall('CellType'): cell_type = cell_type_el.text.strip().lower() if cell_type: if cell_type in osb.resources.KNOWN_CELL_TYPES: known_id = osb.resources.KNOWN_CELL_TYPES[cell_type] osb.metadata.add_simple_qualifier(desc, \ 'bqbiol', \ 'isPartOf', \ osb.resources.NEUROLEX_URL_TEMPLATE % known_id, \ "Known cell type: %s; taxonomy id: %s" % (cell_type, known_id)) else: print("Unknown cell_type: %s" % cell_type) unknowns += "Unknown cell_type: %s\n" % cell_type print("Currently unknown: <<<%s>>>" % unknowns) comp_types = {} for gate in root.findall('Gates'): eq_type = gate.attrib['EqType'] gate_name = gate.attrib['Name'] target = chan.gates if eq_type == '1': g = neuroml.GateHHUndetermined(id=gate_name, type='gateHHtauInf', instances=int( float(gate.attrib['Power']))) elif eq_type == '2': g = neuroml.GateHHUndetermined(id=gate_name, type='gateHHrates', instances=int( float(gate.attrib['Power']))) for inf in gate.findall('Inf_Alpha'): equation = check_equation(inf.findall('Equation')[0].text) if eq_type == '1': new_comp_type = "%s_%s_%s" % (channel_id, gate_name, 'inf') g.steady_state = neuroml.HHVariable(type=new_comp_type) comp_type = lems.ComponentType( new_comp_type, extends="baseVoltageDepVariable") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='x', dimension="none", value="%s" % equation, exposure="x")) comp_types[new_comp_type] = comp_type elif eq_type == '2': new_comp_type = "%s_%s_%s" % (channel_id, gate_name, 'alpha') g.forward_rate = neuroml.HHRate(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepRate") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='r', dimension="per_time", value="%s / TIME_SCALE" % equation, exposure="r")) comp_types[new_comp_type] = comp_type for tau in gate.findall('Tau_Beta'): equation = check_equation(tau.findall('Equation')[0].text) if eq_type == '1': new_comp_type = "%s_%s_tau" % (channel_id, gate_name) g.time_course = neuroml.HHTime(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepTime") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='t', dimension="time", value="(%s) * TIME_SCALE" % equation, exposure="t")) comp_types[new_comp_type] = comp_type elif eq_type == '2': new_comp_type = "%s_%s_%s" % (channel_id, gate_name, 'beta') g.reverse_rate = neuroml.HHRate(type=new_comp_type) comp_type = lems.ComponentType(new_comp_type, extends="baseVoltageDepRate") comp_type.add(lems.Constant('TIME_SCALE', '1 ms', 'time')) comp_type.add(lems.Constant('VOLT_SCALE', '1 mV', 'voltage')) comp_type.dynamics.add( lems.DerivedVariable(name='V', dimension="none", value="v / VOLT_SCALE")) comp_type.dynamics.add( lems.DerivedVariable(name='r', dimension="per_time", value="%s / TIME_SCALE" % equation, exposure="r")) comp_types[new_comp_type] = comp_type target.append(g) doc.ion_channel_hhs.append(chan) doc.id = channel_id writers.NeuroMLWriter.write(doc, nml2_file_name) print("Written NeuroML 2 channel file to: " + nml2_file_name) for comp_type_name in comp_types.keys(): comp_type = comp_types[comp_type_name] ct_xml = comp_type.toxml() # Quick & dirty pretty printing.. ct_xml = ct_xml.replace('<Const', '\n <Const') ct_xml = ct_xml.replace('<Dyna', '\n <Dyna') ct_xml = ct_xml.replace('</Dyna', '\n </Dyna') ct_xml = ct_xml.replace('<Deriv', '\n <Deriv') ct_xml = ct_xml.replace('</Compone', '\n </Compone') # print("Adding definition for %s:\n%s\n"%(comp_type_name, ct_xml)) nml2_file = open(nml2_file_name, 'r') orig = nml2_file.read() new_contents = orig.replace("</neuroml>", "\n %s\n\n</neuroml>" % ct_xml) nml2_file.close() nml2_file = open(nml2_file_name, 'w') nml2_file.write(new_contents) nml2_file.close() print("Inserting metadata...") nml2_file = open(nml2_file_name, 'r') orig = nml2_file.read() new_contents = orig.replace( "<annotation/>", "\n <annotation>\n%s </annotation>\n" % metadata.to_xml(" ")) nml2_file.close() nml2_file = open(nml2_file_name, 'w') nml2_file.write(new_contents) nml2_file.close() ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml2_file_name) return unknowns
def parse_templates_json(templates_json="templates.json", ignore_chans = [], save_example_files=False, verbose=False): with open(templates_json, "r") as templates_json_file: json_cells = json.load(templates_json_file) concentrationModels = '' for firing_type_u in json_cells: if verbose: print("\n --------------- %s "%(firing_type_u)) firing_type = str(firing_type_u) cell_dict = json_cells[firing_type] nml_doc = neuroml.NeuroMLDocument(id=firing_type) # Membrane properties # included_channels[firing_type] = [] channel_densities = [] channel_density_nernsts = [] channel_density_non_uniform_nernsts = [] channel_density_non_uniforms = [] species = [] for section_list in cell_dict['forsecs']: for parameter_name in cell_dict['forsecs'][section_list]: value = cell_dict['forsecs'][section_list][parameter_name] if verbose: print(" --- %s, %s: %s "%(section_list,parameter_name,value)) if parameter_name == 'g_pas': channel = 'pas' arguments = {} cond_density = "%s S_per_cm2" % value if verbose: print(' - Adding %s with %s'%(channel, cond_density)) channel_nml2_file = "%s.channel.nml"%channel if channel_nml2_file not in included_channels[firing_type]: nml_doc.includes.append( neuroml.IncludeType( href="../../NeuroML2/%s" % channel_nml2_file)) included_channels[firing_type].append(channel_nml2_file) erev = cell_dict['forsecs'][section_list]['e_pas'] erev = "%s mV" % erev arguments["cond_density"] = cond_density arguments['ion_channel'] = channel arguments["ion"] = "non_specific" arguments["erev"] = erev arguments["id"] = "%s_%s" % (section_list, parameter_name) channel_class = 'ChannelDensity' density = getattr(neuroml, channel_class)(**arguments) channel_densities.append(density) for section_list in cell_dict['parameters']: for parameter_name in cell_dict['parameters'][section_list]: if parameter_name != 'e_pas' and 'CaDynamics_E2' not in parameter_name: parameter_dict = cell_dict['parameters'][section_list][parameter_name] if verbose: print(" --- %s, %s: %s "%(section_list,parameter_name,parameter_dict)) channel = parameter_dict['channel'] if channel not in ignore_chans: arguments = {} cond_density = None variable_parameters = None if parameter_dict['distribution']['disttype'] == "uniform": value = float(parameter_dict['distribution']['value']) if channel in density_scales: value = value * density_scales[channel] cond_density = "%s S_per_cm2" % value else: new_expr = '1e4 * (%s)'%parameter_dict['distribution']['value'].replace('x','p').replace('epp','exp') iv = neuroml.InhomogeneousValue(inhomogeneous_parameters="PathLengthOver_%s"%section_list, value=new_expr) variable_parameters = [ neuroml.VariableParameter( segment_groups=section_list, parameter='condDensity', inhomogeneous_value=iv)] channel_name = channel if channel_substitutes.has_key(channel): channel_name = channel_substitutes[channel] channel_nml2_file = "%s.channel.nml"%channel_name if channel_nml2_file not in included_channels[firing_type]: nml_doc.includes.append( neuroml.IncludeType( href="../../NeuroML2/%s" % channel_nml2_file)) included_channels[firing_type].append(channel_nml2_file) arguments['ion'] = channel_ions[channel] erev = ion_erevs[arguments["ion"]] channel_class = 'ChannelDensity' if erev == "nernst": erev = None channel_class = 'ChannelDensityNernst' elif erev == "pas": erev = cell_dict['parameters'] \ [section_list]['e_pas']['distribution']\ ['value'] erev = "%s mV" % erev arguments["ion"] = "non_specific" if variable_parameters is not None: channel_class += 'NonUniform' else: arguments["segment_groups"] = section_list if erev is not None: arguments["erev"] = erev arguments["id"] = "%s_%s" % (section_list, parameter_name) if cond_density is not None: arguments["cond_density"] = cond_density arguments['ion_channel'] = channel_name if variable_parameters is not None: arguments['variable_parameters'] = variable_parameters density = getattr(neuroml, channel_class)(**arguments) if channel_class == "ChannelDensityNernst": channel_density_nernsts.append(density) elif channel_class == "ChannelDensityNernstNonUniform": channel_density_non_uniform_nernsts.append(density) elif channel_class == "ChannelDensityNonUniform": channel_density_non_uniforms.append(density) else: channel_densities.append(density) elif 'gamma_CaDynamics_E2' in parameter_name: parameter_dict = cell_dict['parameters'][section_list][parameter_name] model = 'CaDynamics_E2_NML2__%s_%s'%(firing_type,section_list) value = parameter_dict['distribution']['value'] concentrationModels+='<concentrationModel id="%s" ion="ca" '%model +\ 'type="concentrationModelHayEtAl" minCai="1e-4 mM" ' +\ 'gamma="%s" '%value elif 'decay_CaDynamics_E2' in parameter_name: # calcium_model = \ # neuroml.DecayingPoolConcentrationModel(ion='ca') model = 'CaDynamics_E2_NML2__%s_%s'%(firing_type,section_list) species.append(neuroml.Species( id='ca', ion='ca', initial_concentration='5.0E-11 mol_per_cm3', initial_ext_concentration='2.0E-6 mol_per_cm3', concentration_model=model, segment_groups=section_list)) channel_nml2_file = 'CaDynamics_E2_NML2.nml' if channel_nml2_file not in included_channels[firing_type]: included_channels[firing_type].append(channel_nml2_file) parameter_dict = cell_dict['parameters'][section_list][parameter_name] value = parameter_dict['distribution']['value'] concentrationModels+='decay="%s ms" depth="0.1 um"/> <!-- For group %s in %s-->\n\n'%(value,section_list,firing_type) capacitance_overwrites = {} for section_list in cell_dict['forsecs']: for parameter_name in cell_dict['forsecs'][section_list]: if parameter_name == "cm" and section_list != 'all': value = cell_dict['forsecs'][section_list][parameter_name] capacitance_overwrites[ section_list] = "%s uF_per_cm2" % value specific_capacitances = [] for section_list in default_capacitances: if section_list in capacitance_overwrites: capacitance = capacitance_overwrites[section_list] else: capacitance = default_capacitances[section_list] specific_capacitances.append( neuroml.SpecificCapacitance(value=capacitance, segment_groups=section_list)) init_memb_potentials = [neuroml.InitMembPotential( value="-80 mV", segment_groups='all')] membrane_properties = neuroml.MembraneProperties( channel_densities=channel_densities, channel_density_nernsts=channel_density_nernsts, channel_density_non_uniform_nernsts=channel_density_non_uniform_nernsts, channel_density_non_uniforms=channel_density_non_uniforms, specific_capacitances=specific_capacitances, init_memb_potentials=init_memb_potentials) # Intracellular Properties # resistivities = [] resistivities.append(neuroml.Resistivity( value="100 ohm_cm", segment_groups='all')) intracellular_properties = neuroml.IntracellularProperties( resistivities=resistivities, species=species) # Cell construction # biophysical_properties = \ neuroml.BiophysicalProperties(id="biophys", intracellular_properties= intracellular_properties, membrane_properties= membrane_properties) biophysical_properties_vs_types[firing_type] = biophysical_properties if save_example_files: cell = neuroml.Cell(id=firing_type, notes="\n*************************\nThis is not a physiologically constrained cell model!!\n"+\ "It is only for testing formatting of the biophysicalProperties extracted from templates.json\n*************************\n", biophysical_properties=biophysical_properties) nml_doc.cells.append(cell) cell.morphology = neuroml.Morphology(id="morph") cell.morphology.segments.append(neuroml.Segment(id='0', name='soma', proximal=neuroml.Point3DWithDiam(x=0,y=0,z=0,diameter=10), distal=neuroml.Point3DWithDiam(x=0,y=20,z=0,diameter=10))) cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="soma", neuro_lex_id="sao864921383", members=[neuroml.Member("0")])) cell.morphology.segments.append(neuroml.Segment(id='1', name='axon', parent=neuroml.SegmentParent(segments='0',fraction_along="0"), proximal=neuroml.Point3DWithDiam(x=0,y=0,z=0,diameter=2), distal=neuroml.Point3DWithDiam(x=0,y=-50,z=0,diameter=2))) cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="axon", neuro_lex_id="sao864921383", members=[neuroml.Member("1")])) cell.morphology.segments.append(neuroml.Segment(id='2', name='basal_dend', parent=neuroml.SegmentParent(segments='0'), proximal=neuroml.Point3DWithDiam(x=0,y=20,z=0,diameter=3), distal=neuroml.Point3DWithDiam(x=50,y=20,z=0,diameter=3))) cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="basal_dend", neuro_lex_id="sao864921383", members=[neuroml.Member("2")])) cell.morphology.segments.append(neuroml.Segment(id='3', name='apical_dend1', parent=neuroml.SegmentParent(segments='0'), proximal=neuroml.Point3DWithDiam(x=0,y=20,z=0,diameter=3), distal=neuroml.Point3DWithDiam(x=0,y=120,z=0,diameter=3))) cell.morphology.segments.append(neuroml.Segment(id='4', name='apical_dend2', parent=neuroml.SegmentParent(segments='0'), proximal=neuroml.Point3DWithDiam(x=0,y=120,z=0,diameter=3), distal=neuroml.Point3DWithDiam(x=0,y=220,z=0,diameter=3))) cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="apical_dend", neuro_lex_id="sao864921383", members=[neuroml.Member("3"),neuroml.Member("4")])) cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="somatic",includes=[neuroml.Include("soma")])) cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="axonal", includes=[neuroml.Include("axon")])) sg = neuroml.SegmentGroup(id="basal", includes=[neuroml.Include("basal_dend")]) sg.inhomogeneous_parameters.append(neuroml.InhomogeneousParameter(id="PathLengthOver_"+"basal", variable="x", metric="Path Length from root", proximal=neuroml.ProximalDetails(translation_start="0"))) cell.morphology.segment_groups.append(sg) sg = neuroml.SegmentGroup(id="apical", includes=[neuroml.Include("apical_dend")]) sg.inhomogeneous_parameters.append(neuroml.InhomogeneousParameter(id="PathLengthOver_"+"apical", variable="x", metric="Path Length from root", proximal=neuroml.ProximalDetails(translation_start="0"))) cell.morphology.segment_groups.append(sg) nml_filename = 'test/%s.cell.nml' % firing_type neuroml.writers.NeuroMLWriter.write(nml_doc, nml_filename) logging.debug("Written cell file to: %s", nml_filename) neuroml.utils.validate_neuroml2(nml_filename) conc_mod_file = open('test/concentrationModel.txt','w') conc_mod_file.write(concentrationModels) conc_mod_file.close()
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
scale="10mV") h_gate.forward_rate = neuroml.HHRate(type="HHExpLinearRate", rate="0.1per_ms", midpoint="-55mV", scale="10mV") h_gate.reverse_rate = neuroml.HHRate(type="HHExpRate", rate="0.125per_ms", midpoint="-65mV", scale="-80mV") chan.gate_hh_rates.append(m_gate) chan.gate_hh_rates.append(h_gate) doc = neuroml.NeuroMLDocument() doc.ion_channel_hhs.append(chan) doc.id = "ChannelMLDemo" nml_file = './tmp/ionChannelTest.xml' writers.NeuroMLWriter.write(doc,nml_file) print("Written channel file to: "+nml_file) ###### Validate the NeuroML ###### from neuroml.utils import validate_neuroml2 validate_neuroml2(nml_file)
import neuroml import neuroml.loaders as loaders import neuroml.writers as writers from pyneuroml.lems import generate_lems_file_for_neuroml net_ref = "BC_StimNet" net_doc = neuroml.NeuroMLDocument(id=net_ref) net = neuroml.Network(id=net_ref) net_doc.networks.append(net) cell_id = 'BC2_na_k' net_doc.includes.append(neuroml.IncludeType(cell_id + '.cell.nml')) pop = neuroml.Population(id="BC", component=cell_id, type="populationList") inst = neuroml.Instance(id="0") pop.instances.append(inst) inst.location = neuroml.Location(x=0, y=0, z=0) net.populations.append(pop) stim = neuroml.PulseGenerator(id='stim0', delay='50ms', duration='200ms', amplitude='0.5nA') net_doc.pulse_generators.append(stim)
def to_neuroml(self, filename, resolution=10, write=True): ''' Save the neuron as a NeuroML (.nml) object. Parameters ---------- filename : str Name of the MNL file to write. resolution : int, optional (default: 10) Coarse-graining factor of the structure: only one point every `resolution` will be kept. write : bool, optional (default: True) Write the file. Returns ------- neuroml.Cell object. ''' import neuroml import neuroml.writers as writers x = self.position[0].to('micrometer').m y = self.position[1].to('micrometer').m z = 0. p = neuroml.Point3DWithDiam(x=x, y=y, z=z, diameter=2. * self.soma_radius.m) soma = neuroml.Segment(proximal=p, distal=p) soma.name = 'Soma' soma.id = 0 seg_id = 0 morpho = neuroml.Morphology() morpho.id = "Morphology neuron {}".format(int(self)) morpho.segments.append(soma) neurites_segments = [] neurites = list(self.dendrites.values()) if self.axon is not None: neurites.append(self.axon) # set dendrites for neurite in neurites: p_segment = soma parent = neuroml.SegmentParent(segments=soma.id) branch_seen = {} todo = _deque([branch for branch in neurite.branches]) indices = _deque([i for i in range(len(todo))]) while todo: branch = todo.popleft() idx = indices.popleft() if branch.parent in (-1, 0, None): p_segment = soma parent = neuroml.SegmentParent(segments=soma.id) elif branch.parent in branch_seen: p_segment = branch_seen[branch.parent] parent = neuroml.SegmentParent(segments=p_segment.id) else: parent = None if parent is not None: diameter = branch.diameter if neurite.taper_rate is not None: dist_to_tip = _np.cumsum(branch.r[::-1])[::-1] diameter = diameter + neurite.taper_rate * dist_to_tip else: diameter = (diameter for _ in range(len(branch.xy))) # subsample positions and diameters subnodes = branch.xy[::resolution].m subdiam = diameter[::resolution].m for pos, diam in zip(subnodes, subdiam): p = neuroml.Point3DWithDiam( x=p_segment.distal.x, y=p_segment.distal.y, z=p_segment.distal.z, diameter=p_segment.distal.diameter) d = neuroml.Point3DWithDiam(x=pos[0], y=pos[1], z=p_segment.distal.z, diameter=diam) n_segment = neuroml.Segment(proximal=p, distal=d, parent=parent) n_segment.id = seg_id n_segment.name = '{}_segment_{}'.format( neurite, seg_id) # set as next parent p_segment = n_segment parent = neuroml.SegmentParent(segments=p_segment.id) seg_id += 1 neurites_segments.append(n_segment) # store the last point as future parent for child branches branch_seen[branch.node_id] = p_segment else: todo.append(branch) indices.append(idx) morpho.segments += neurites_segments # make the neuroml cell cell = neuroml.Cell() cell.name = "Neuron {}".format(int(self)) cell.id = int(self) cell.morphology = morpho # write if write: doc = neuroml.NeuroMLDocument(id=filename) doc.cells.append(cell) writers.NeuroMLWriter.write(doc, filename) return cell