def setUp(self): """ Testing a complex hand-built morphology (from neuroml objects rather than arrays) """ p = neuroml.Point3DWithDiam(x=0,y=0,z=0,diameter=50) d = neuroml.Point3DWithDiam(x=50,y=0,z=0,diameter=50) soma = neuroml.Segment(proximal=p, distal=d) soma.name = 'Soma' soma.id = 0 #now make an axon with 100 compartments: parent = neuroml.SegmentParent(segments=soma.id) parent_segment = soma axon_segments = [] seg_id = 1 for i in range(100): p = neuroml.Point3DWithDiam(x=parent_segment.distal.x, y=parent_segment.distal.y, z=parent_segment.distal.z, diameter=0.1) d = neuroml.Point3DWithDiam(x=parent_segment.distal.x+10, y=parent_segment.distal.y, z=parent_segment.distal.z, diameter=0.1) axon_segment = neuroml.Segment(proximal = p, distal = d, parent = parent) axon_segment.id = seg_id axon_segment.name = 'axon_segment_' + str(axon_segment.id) #now reset everything: parent = neuroml.SegmentParent(segments=axon_segment.id) parent_segment = axon_segment seg_id += 1 axon_segments.append(axon_segment) test_morphology = am.ArrayMorphology() test_morphology.segments.append(soma) test_morphology.segments += axon_segments test_morphology.id = "TestMorphology" self.test_morphology = test_morphology
def segment_from_vertex_index(self, index): print "index:" print index parent_index = self.connectivity[index] node_x = self.vertices[index][0] node_y = self.vertices[index][1] node_z = self.vertices[index][2] node_d = self.vertices[index][3] parent_x = self.vertices[parent_index][0] parent_y = self.vertices[parent_index][1] parent_z = self.vertices[parent_index][2] parent_d = self.vertices[parent_index][3] p = neuroml.Point3DWithDiam(x=node_x, y=node_y, z=node_z, diameter=node_d) d = neuroml.Point3DWithDiam(x=parent_x, y=parent_y, z=parent_z, diameter=parent_d) seg = neuroml.Segment(proximal=p, distal=d, id=index) if index > 1: parent = neuroml.SegmentParent(segments=parent_index) seg.parent = parent return seg
def _morphology(self): """Return the morphology of the cell. Currently this is restricted to `Neuron <#neuron>`_ objects. """ morph_name = "morphology_" + str(next(self.name())) # Query for segments query = segment_query.substitute(morph_name=morph_name) qres = self.rdf.query(query, initNs=ns) morph = neuroml.Morphology(id=morph_name) for r in qres: par = False if r['par_id']: par = neuroml.SegmentParent(segments=str(r['par_id'])) s = neuroml.Segment(name=str(r['seg_name']), id=str(r['seg_id']), parent=par) else: s = neuroml.Segment(name=str(r['seg_name']), id=str(r['seg_id'])) if r['x_prox']: loop_prox = neuroml.Point3DWithDiam( *(r[x] for x in ['x_prox', 'y_prox', 'z_prox', 'd_prox'])) s.proximal = loop_prox loop = neuroml.Point3DWithDiam(*(r[x] for x in ['x', 'y', 'z', 'd'])) s.distal = loop morph.segments.append(s) # Query for segment groups query = segment_group_query.substitute(morph_name=morph_name) qres = self.rdf.query(query, initNs=ns) for r in qres: s = neuroml.SegmentGroup(id=r['gid']) if r['member']: m = neuroml.Member() m.segments = str(r['member']) s.members.append(m) elif r['include']: i = neuroml.Include() i.segment_groups = str(r['include']) s.includes.append(i) morph.segment_groups.append(s) return morph
def morphology(self): morph_name = "morphology_" + str(self.name()) # Query for segments query = segment_query.substitute(morph_name=morph_name) qres = self['semantic_net'].query(query, initNs=ns) morph = neuroml.Morphology(id=morph_name) for r in qres: par = False if r['par_id']: par = neuroml.SegmentParent(segments=str(r['par_id'])) s = neuroml.Segment(name=str(r['seg_name']), id=str(r['seg_id']), parent=par) else: s = neuroml.Segment(name=str(r['seg_name']), id=str(r['seg_id'])) if r['x_prox']: loop_prox = neuroml.Point3DWithDiam( *(r[x] for x in ['x_prox', 'y_prox', 'z_prox', 'd_prox'])) s.proximal = loop_prox loop = neuroml.Point3DWithDiam(*(r[x] for x in ['x', 'y', 'z', 'd'])) s.distal = loop morph.segments.append(s) # Query for segment groups query = segment_group_query.substitute(morph_name=morph_name) qres = self['semantic_net'].query(query, initNs=ns) for r in qres: s = neuroml.SegmentGroup(id=r['gid']) if r['member']: m = neuroml.Member() m.segments = str(r['member']) s.members.append(m) elif r['include']: i = neuroml.Include() i.segment_groups = str(r['include']) s.includes.append(i) morph.segment_groups.append(s) return morph
def convert_morphology(root, positions='auto'): """Convert moose neuron morphology contained under `root` into a NeuroML object. The id of the return object is {root.name}_morphology. Each segment object gets the numeric value of the moose id of the object. The name of the segments are same as the corresponding moose compartment. Parameters ---------- root : a moose element containing a single cell model. positions : string flag to indicate if the positions of the end points of the compartments are explicitly available in the compartments or should be automatically generated. Possible values: `auto` - automatically generate z coordinates using length of the compartments. `explicit` - model has explicit coordinates for all compartments. Return ------ a neuroml.Morphology instance. """ if positions == 'auto': queue = deque([autoposition(root)]) elif positions == 'explicit': compartments = moose.wildcardFind('%s/##[TYPE=Compartment]' % (root.path)) queue = deque([compartment for compartment in map(moose.element, compartments) if len(compartment.neighbours['axial']) == 0]) if len(queue) != 1: raise Exception('There must be one and only one top level compartment. Found %d' % (len(topcomp_list))) else: raise Exception('allowed values for keyword argument positions=`auto` or `explicit`') comp_seg = {} parent = None while len(queue) > 0: compartment = queue.popleft() proximal = neuroml.Point3DWithDiam(x=compartment.x0, y=compartment.y0, z=compartment.z0, diameter=compartment.diameter) distal = neuroml.Point3DWithDiam(x=compartment.x, y=compartment.y, z=compartment.z, diameter=compartment.diameter) plist = list(map(moose.element, compartment.neighbours['axial'])) try: parent = neuroml.SegmentParent(segments=comp_seg[moose.element(plist[0])].id) except (KeyError, IndexError) as e: parent = None segment = neuroml.Segment(id=compartment.id_.value, proximal=proximal, distal=distal, parent=parent) # TODO: For the time being using numerical value of the moose # id for neuroml id.This needs to be updated for handling # array elements segment.name = compartment.name comp_seg[compartment] = segment queue.extend([comp for comp in map(moose.element, compartment.neighbours['raxial'])]) morph = neuroml.Morphology(id='%s_morphology' % (root.name)) morph.segments.extend(comp_seg.values()) return morph
In this example an axon is built, a morphology is loaded, the axon is then connected to the loadeed morphology. """ import neuroml import neuroml.loaders as loaders import neuroml.writers as writers fn = './test_files/Purk2M9s.nml' doc = loaders.NeuroMLLoader.load(fn) print("Loaded morphology file from: " + fn) #get the parent segment: parent_segment = doc.cells[0].morphology.segments[0] parent = neuroml.SegmentParent(segments=parent_segment.id) #make an axon: seg_id = 5000 # need a way to get a unique id from a morphology axon_segments = [] for i in range(10): p = neuroml.Point3DWithDiam(x=parent_segment.distal.x, y=parent_segment.distal.y, z=parent_segment.distal.z, diameter=0.1) d = neuroml.Point3DWithDiam(x=parent_segment.distal.x + 10, y=parent_segment.distal.y, z=parent_segment.distal.z, diameter=0.1)
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
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()