예제 #1
0
    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
예제 #3
0
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")
예제 #4
0
    def test_add_segment_vertices_added(self):
        proximal_point = neuroml.Point3DWithDiam(
            x=0.1,
            y=0.2,
            z=0.3,
            diameter=0.1,
        )

        distal_point = neuroml.Point3DWithDiam(x=0.0,
                                               y=0.0,
                                               z=0.0,
                                               diameter=0.1)

        seg = neuroml.Segment(proximal=proximal_point, distal=distal_point)

        num_segments = len(self.complex_morphology.segments)

        self.optimized_morphology.segments.append(seg)

        true_vertices = self.optimized_morphology.vertices
        expected_vertices = np.array([
            [0, 0, 0, 0.1],
            [1, 0, 0, 0.2],
            [2, 0, 0, 0.3],
            [3, 0, 0, 0.4],
            [0, 0, 0, 0.1],
            [0.1, 0.2, 0.3, 0.1],
        ])

        arrays_equal = np.array_equal(true_vertices, expected_vertices)

        self.assertTrue(arrays_equal)
        self.setUp()
예제 #5
0
    def test_add_segment_len(self):
        """
        Add a neuroml.Segment() object, the segments proximal
        and distal vertices should be used. The internal connectivity
        should be passed.
        """

        proximal_point = neuroml.Point3DWithDiam(
            x=0.1,
            y=0.2,
            z=0.3,
            diameter=1.1,
        )

        distal_point = neuroml.Point3DWithDiam(
            x=0.0,
            y=0.0,
            z=0.0,
            diameter=1.1,
        )

        seg = neuroml.Segment(proximal=proximal_point, distal=distal_point)

        num_segments = len(self.complex_morphology.segments)

        self.complex_morphology.segments.append(seg)

        len_segment_list = len(self.complex_morphology.segments)

        self.assertEqual(num_segments + 1, len_segment_list)
        self.setUp()
예제 #6
0
파일: cell.py 프로젝트: hytsang/PyOpenWorm
    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
예제 #7
0
    def setUp(self):

        num_segments = int(100)
        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)

        connectivity = range(-1, num_segments)

        vertices = np.array([x, y, z, d]).T

        self.complex_vertices = vertices

        physical_mask = np.zeros(num_vertices)

        #third segment is non-physical:
        physical_mask[2] = 1
        physical_mask[20] = 1

        self.complex_morphology = am.ArrayMorphology(
            vertices=vertices,
            connectivity=connectivity,
            physical_mask=physical_mask,
            id='test_arraymorph')

        self.valid_vertices = [[0, 0, 0, 0.1], [1, 0, 0, 0.2], [2, 0, 0, 0.3],
                               [3, 0, 0, 0.4]]

        self.valid_connectivity = [-1, 0, 1, 2]

        self.optimized_morphology = am.ArrayMorphology(
            vertices=self.valid_vertices,
            connectivity=self.valid_connectivity,
            id='test_arraymorph')

        proximal_point = neuroml.Point3DWithDiam(
            x=0.1,
            y=0.2,
            z=0.3,
            diameter=1.1,
        )

        distal_point = neuroml.Point3DWithDiam(
            x=0.0,
            y=0.0,
            z=0.0,
            diameter=1.1,
        )

        soma = neuroml.Segment(
            proximal=proximal_point,
            distal=distal_point,
        )
        self.small_morphology = am.ArrayMorphology()
        self.small_morphology.segments.append(soma)
예제 #8
0
    def test_segmentlist_setter_by_inference(self):

        p = neuroml.Point3DWithDiam(x=0.9, y=0.0, z=0.0, diameter=0.1)

        d = neuroml.Point3DWithDiam(x=0.0, y=0.0, z=0.0, diameter=0.1)

        new_segment = neuroml.Segment(proximal=p, distal=d)

        self.optimized_morphology.segments[2] = new_segment
        self.assertEqual(self.optimized_morphology.segments[2].proximal.x, 0.9)
예제 #9
0
    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 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()
import neuroml

doc = loaders.NeuroMLLoader.load('./test_files/Purk2M9s.nml')

mycell = doc.cells[0]

#extract the morphology:
my_morphology = mycell.morphology

#randomly  change a segment id:
my_morphology.segments[33].id = 'random_test'

newcell = neuroml.Cell()
newcell.id = "some random cell"

new_morphology = neuroml.Morphology()
newcell.morphology = new_morphology

new_morphology.id = 'some random morphology'

#add a few segments to that morphology:
for i in range(10):
    segment = neuroml.Segment()
    segment.id = "some random segment"
    new_morphology.add_segment(segment)

doc.add_cell(newcell)

f = open('./tmp/test_load_and_manipulate.xml', 'w')
doc.export(f, 0)
예제 #12
0
    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
예제 #13
0
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()
예제 #14
0
    def __init__(self,
                 k_fast_specific_gbar=36.0,
                 k_slow_specific_gbar=0.0,
                 ca_channel_specific_gbar=120.0,
                 ca_h_A_F=20.0,
                 k_tau_factor=1.0,
                 ca_tau_factor=1.0,
                 nocompile=True):

        #	print 'tau factor is:'
        #	print tau_factor
        k_tau_factor = float(k_tau_factor)
        ca_tau_factor = float(ca_tau_factor)
        ca_h_A_F = float(ca_h_A_F)
        self.k_fast_specific_gbar = float(k_fast_specific_gbar)
        self.k_slow_specific_gbar = float(k_slow_specific_gbar)
        self.ca_channel_specific_gbar = float(ca_channel_specific_gbar)

        #First build a compartment, I infered these dimensions from the hyperpolarizing pulses
        p = neuroml.Point3DWithDiam(x=0.0, y=0.0, z=0.0, diameter=800.0)

        d = neuroml.Point3DWithDiam(x=800.0, y=800.0, z=800.0, diameter=800.0)

        compartment = neuroml.Segment(proximal=p, distal=d)

        #create a leak ion channel:
        leak = neuroml.IonChannel(id="passive",
                                  type="ionChannelPassive",
                                  conductance="10pS")

        #create membrane properties:
        membrane_properties = neuroml.MembraneProperties()

        leak_density = neuroml.ChannelDensity(id="leak",
                                              ion_channels="passive",
                                              cond_density="3.0 S_per_m2",
                                              erev="-54.3mV")

        membrane_properties.channel_densities.append(leak_density)

        #        self.passive = kinetics.PassiveProperties(init_vm=-30.0,
        #                                                  rm=1/0.3,
        #                                                  cm=10.0, #1.0
        #                                                  ra=0.03)

        #leave leak current out for now
        #Create a LeakCurrent object:
        #	self.leak = kinetics.LeakCurrent(em=-30.0)

        #get a Morphology object from the compartment: (no longer needed?)
        #self.morphology = self.compartment.morphology

        #insert the passive properties and leak current into the morphology:

        self.cell.leak_current = self.leak
        #	self.morphology.passive_properties = self.passive
        #	self.morphology.leak_current = self.leak

        #create two current clamp stimuli:
        self.stim = kinetics.IClamp(current=0.25, delay=100.0, duration=1000.0)

        #problem with Pyramidal here, inserting this overrides the previous?!
        #create a current clamp stimulus:
        #            self.stim2 = kinetics.IClamp(current=0.10,
        #                                   delay=600.0,
        #                                   duration=500.0)

        #insert the stimulus into the morphology
        self.morphology[0].insert(self.stim)

        if nocompile == False:
            #create Ca ion channel:
            ca_channel = kinetics.HHChannel(
                name='ca',
                specific_gbar=self.ca_channel_specific_gbar,
                ion='ca',
                e_rev=20.0,
                x_power=3.0,
                y_power=1.0)

            #create K fast ion channel:
            k_fast = kinetics.HHChannel(
                name='kfast',
                specific_gbar=self.k_fast_specific_gbar,
                ion='k',
                e_rev=-10.0,
                x_power=4.0,
                y_power=0.0)

            k_slow = kinetics.HHChannel(
                name='kslow',
                specific_gbar=self.k_slow_specific_gbar,
                ion='k',
                e_rev=-10.0,
                x_power=4.0,
                y_power=0.0)

            #create dicts containing gating parameters:
            ca_m_params = {
                'A_A': 0.1 * 25.0 * ca_tau_factor,
                'A_B': -0.1 * ca_tau_factor,
                'A_C': -1.0,
                'A_D': -25.0,
                'A_F': -10.0,
                'B_A': 4.0 * ca_tau_factor,
                'B_B': 0.0 * ca_tau_factor,
                'B_C': 0.0,
                'B_D': 0.0,
                'B_F': 18.0
            }

            ca_h_params = {
                'A_A': 0.07 * ca_tau_factor,
                'A_B': 0.0 * ca_tau_factor,
                'A_C': 0.0,
                'A_D': 0.0,
                'A_F': ca_h_A_F,  #20
                'B_A': 1.0 * ca_tau_factor,
                'B_B': 0.0 * ca_tau_factor,
                'B_C': 1.0,
                'B_D': -30.0,
                'B_F': -10.0
            }

            k_fast_n_params = {
                'A_A': 0.01 * (10.0) * k_tau_factor,
                'A_B': -0.01 * k_tau_factor,  #0.01
                'A_C': -1.0,
                'A_D': -10.0,
                'A_F': -10.0,
                'B_A': 0.125 * k_tau_factor,
                'B_B': 0.0 * k_tau_factor,
                'B_C': 0.0,
                'B_D': 0.0,
                'B_F': 80.0
            }

            k_fast_h_params = {
                'A_A': 6.6 * k_tau_factor,
                'A_B': 0.0 * k_tau_factor,
                'A_C': 1.0,
                'A_D': 15.6,
                'A_F': 10.0,
                'B_A': 6.6 * k_tau_factor,
                'B_B': 0.0 * k_tau_factor,
                'B_C': 1.0,
                'B_D': 15.6,
                'B_F': -10.0
            }

            k_slow_n_params = {
                'A_A': 0.01 * (10.0),
                'A_B': -0.01,
                'A_C': -2.0,
                'A_D': -10.0,
                'A_F': -10.0,
                'B_A': 0.125,
                'B_B': 0.0,
                'B_C': 0.0,
                'B_D': 0.0,
                'B_F': 80.0
            }

            #setup the channel gating parameters:
            ca_channel.setup_alpha(gate='X',
                                   params=ca_m_params,
                                   vdivs=150,
                                   vmin=-30,
                                   vmax=120)

            ca_channel.setup_alpha(gate='Y',
                                   params=ca_h_params,
                                   vdivs=150,
                                   vmin=-30,
                                   vmax=120)

            k_fast.setup_alpha(gate='X',
                               params=k_fast_n_params,
                               vdivs=150,
                               vmin=-30,
                               vmax=120)

            k_fast.setup_alpha(gate='Y',
                               params=k_fast_h_params,
                               vdivs=300,
                               vmin=-150,
                               vmax=150)

            k_slow.setup_alpha(gate='X',
                               params=k_slow_n_params,
                               vdivs=150,
                               vmin=-30,
                               vmax=120)
        else:

            ca_attributes = {
                'gbar': self.ca_channel_specific_gbar,
                'h_A_F': ca_h_A_F,
                'm_A_A': 0.1 * 25.0 * ca_tau_factor,
                'm_A_B': -0.1 * ca_tau_factor,
                'm_B_A': 4.0 * ca_tau_factor,
                'm_B_B': 0.0 * ca_tau_factor,
                'h_A_A': 0.07 * ca_tau_factor,
                'h_A_B': 0.0 * ca_tau_factor,
                'h_A_F': ca_h_A_F,  #20
                'h_B_A': 1.0 * ca_tau_factor,
                'h_B_B': 0.0 * ca_tau_factor
            }

            kfast_attributes = {
                'gbar': self.k_fast_specific_gbar,
                'm_A_A': 0.01 * (10.0) * k_tau_factor,
                'm_A_B': -0.01 * k_tau_factor,  #0.01
                'm_B_A': 0.125 * k_tau_factor,
                'm_B_B': 0.0 * k_tau_factor
            }
            #bug in pyramidal, if Y == 0 (no inactivation gates) it doesn't compile these values, but it should
            #				'h_A_A': 6.6*k_tau_factor,
            #				'h_A_B': 0.0*k_tau_factor,
            #				'h_B_A': 6.6*k_tau_factor,
            #				'h_B_B': 0.0*k_tau_factor}

            kslow_attributes = {'gbar': self.k_slow_specific_gbar}

            ca_channel = kinetics.Nmodl('ca', ca_attributes)
            k_fast = kinetics.Nmodl('kfast', kfast_attributes)
            k_slow = kinetics.Nmodl('kslow', kslow_attributes)

    #insert the channels:
        self.morphology[0].insert(ca_channel)
        self.morphology[0].insert(k_fast)
        self.morphology[0].insert(k_slow)

        #create the NEURON environment
        self.neuron_env = envs.NeuronEnv(sim_time=100, dt=1e-2)

        #import morphology into environment:
        self.neuron_env.import_cell(self.morphology)
예제 #15
0
#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)

    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)

doc.cells[0].morphology.segments += axon_segments

nml_file = './tmp/modified_morphology.nml'
예제 #16
0
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
예제 #17
0
    def setUp(self):
        self.test_morphology = neuroml.Morphology()
        self.test_morphology.id = "TestMorph"

        for i in range(10):
            self.test_morphology.segments.append(neuroml.Segment())