示例#1
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")
示例#2
0
    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
示例#3
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
示例#4
0
        if (sg.id.startswith('ModelViewParm')) and len(sg.members)==0:
            replace = {}
            replace['soma_'] = 'soma'
            replace['axon_'] = 'axon'
            replace['apic_'] = 'apic'
            replace['dend_'] = 'dend'
            for prefix in replace.keys():
                all_match = True
                for inc in sg.includes:
                    #print inc
                    all_match = all_match and inc.segment_groups.startswith(prefix)
                if all_match:
                    print("Replacing group named %s with %s"%(sg.id,replace[prefix]))
                    sg.id = replace[prefix]

    cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="soma_group", includes=[neuroml.Include("soma")]))
    cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="axon_group", includes=[neuroml.Include("axon")]))
    cell.morphology.segment_groups.append(neuroml.SegmentGroup(id="dendrite_group", includes=[neuroml.Include("dend")]))
    
    with open(manifest_info['biophys'][0]["model_file"][1], "r") as json_file:
        cell_info = json.load(json_file)
        
    
    membrane_properties = neuroml.MembraneProperties()
    
    for sc in cell_info['passive'][0]['cm']:
        membrane_properties.specific_capacitances.append(neuroml.SpecificCapacitance(value='%s uF_per_cm2'%sc['cm'],
                                            segment_groups=sc['section']))
                                            
    for chan in cell_info['genome']:
        chan_name = chan['mechanism']
        print(' > Adding groups from: %s' % groups_info_file)
        groups = {}
        current_group = None
        for line in open(groups_info_file):
            if not line.startswith('//'):
                if line.startswith('- '):
                    current_group = line[2:-1]
                    print(' > Adding group: [%s]' % current_group)
                    groups[current_group] = []
                else:
                    section = line.split('.')[1].strip()
                    segment_group = section.replace('[', '_').replace(']', '')
                    groups[current_group].append(segment_group)

        for g in groups.keys():
            new_seg_group = neuroml.SegmentGroup(id=g)
            cell.morphology.segment_groups.append(new_seg_group)
            for sg in groups[g]:
                new_seg_group.includes.append(neuroml.Include(sg))
            if g in ['basal', 'apical']:
                new_seg_group.inhomogeneous_parameters.append(
                    neuroml.InhomogeneousParameter(
                        id="PathLengthOver_" + g,
                        variable="p",
                        metric="Path Length from root",
                        proximal=neuroml.ProximalDetails(
                            translation_start="0")))

        ignore_chans = [
            'Ih', 'Ca_HVA', 'Ca_LVAst', 'Ca', "SKv3_1", "SK_E2",
            "CaDynamics_E2", "Nap_Et2", "Im", "K_Tst", "NaTa_t", "K_Pst",
示例#6
0
def process_celldir(inputs):
    """Process cell directory"""

    count, cell_dir, nml2_cell_dir, total_count = inputs
    local_nml2_cell_dir = os.path.join("..", nml2_cell_dir)

    print(
        '\n\n************************************************************\n\n'
        'Parsing %s (cell %i/%i)\n' % (cell_dir, count, total_count))

    if os.path.isdir(cell_dir):
        old_cwd = os.getcwd()
        os.chdir(cell_dir)
    else:
        old_cwd = os.getcwd()
        os.chdir('../' + cell_dir)

    if make_zips:
        nml2_cell_dir = '%s/%s' % (zips_dir, cell_dir)
        if not os.path.isdir(nml2_cell_dir):
            os.mkdir(nml2_cell_dir)

    print("Generating into %s" % nml2_cell_dir)

    bbp_ref = None

    template_file = open('template.hoc', 'r')
    for line in template_file:
        if line.startswith('begintemplate '):
            bbp_ref = line.split(' ')[1].strip()
            print(
                ' > Assuming cell in directory %s is in a template named %s' %
                (cell_dir, bbp_ref))

    load_cell_file = 'loadcell.hoc'

    variables = {}

    variables['cell'] = bbp_ref
    variables['groups_info_file'] = groups_info_file

    template = """
///////////////////////////////////////////////////////////////////////////////
//
//   NOTE: This file is not part of the original BBP cell model distribution
//   It has been generated by ../ParseAll.py to facilitate loading of the cell
//   into NEURON for exporting the model morphology to NeuroML2
//
//////////////////////////////////////////////////////////////////////////////

load_file("stdrun.hoc")

objref cvode
cvode = new CVode()
cvode.active(1)

//======================== settings ===================================

v_init = -80

hyp_amp = -0.062866
step_amp = 0.3112968
tstop = 3000

//=================== creating cell object ===========================
load_file("import3d.hoc")
objref cell

// Using 1 to force loading of the file, in case file with same name was loaded
// before...
load_file(1, "constants.hoc")
load_file(1, "morphology.hoc")
load_file(1, "biophysics.hoc")
print "Loaded morphology and biophysics..."

load_file(1, "synapses/synapses.hoc")
load_file(1, "template.hoc")
print "Loaded template..."

load_file(1, "createsimulation.hoc")


create_cell(0)
print "Created new cell using loadcell.hoc: {{ cell }}"

define_shape()

wopen("{{ groups_info_file }}")

fprint("//Saving information on groups in this cell...\\n")

fprint("- somatic\\n")
forsec {{ cell }}[0].somatic {
    fprint("%s\\n",secname())
}

fprint("- basal\\n")
forsec {{ cell }}[0].basal {
    fprint("%s\\n",secname())
}

fprint("- axonal\\n")
forsec {{ cell }}[0].axonal {
    fprint("%s\\n",secname())
}
fprint("- apical\\n")
forsec {{ cell }}[0].apical {
    fprint("%s\\n",secname())
}
wopen()
        """

    t = Template(template)

    contents = t.render(variables)

    load_cell = open(load_cell_file, 'w')
    load_cell.write(contents)
    load_cell.close()

    print(' > Written %s' % load_cell_file)

    if os.path.isfile(load_cell_file):

        cell_info = parse_cell_info_file(cell_dir)

        nml_file_name = "%s.net.nml" % bbp_ref
        nml_net_loc = "%s/%s" % (local_nml2_cell_dir, nml_file_name)
        nml_cell_file = "%s_0_0.cell.nml" % bbp_ref
        nml_cell_loc = "%s/%s" % (local_nml2_cell_dir, nml_cell_file)

        print(' > Loading %s and exporting to %s' %
              (load_cell_file, nml_net_loc))

        export_to_neuroml2(load_cell_file,
                           nml_net_loc,
                           separateCellFiles=True,
                           includeBiophysicalProperties=False)

        print(' > Exported to: %s and %s using %s' %
              (nml_net_loc, nml_cell_loc, load_cell_file))

        nml_doc = pynml.read_neuroml2_file(nml_cell_loc)

        cell = nml_doc.cells[0]

        print(' > Adding groups from: %s' % groups_info_file)
        groups = {}
        current_group = None
        for line in open(groups_info_file):
            if not line.startswith('//'):
                if line.startswith('- '):
                    current_group = line[2:-1]
                    print(' > Adding group: [%s]' % current_group)
                    groups[current_group] = []
                else:
                    section = line.split('.')[1].strip()
                    segment_group = section.replace('[', '_').replace(']', '')
                    groups[current_group].append(segment_group)

        for g in groups.keys():
            new_seg_group = neuroml.SegmentGroup(id=g)
            cell.morphology.segment_groups.append(new_seg_group)
            for sg in groups[g]:
                new_seg_group.includes.append(neuroml.Include(sg))
            if g in ['basal', 'apical']:
                new_seg_group.inhomogeneous_parameters.append(
                    neuroml.InhomogeneousParameter(
                        id="PathLengthOver_" + g,
                        variable="p",
                        metric="Path Length from root",
                        proximal=neuroml.ProximalDetails(
                            translation_start="0")))

        ignore_chans = [
            'Ih', 'Ca_HVA', 'Ca_LVAst', 'Ca', "SKv3_1", "SK_E2",
            "CaDynamics_E2", "Nap_Et2", "Im", "K_Tst", "NaTa_t", "K_Pst",
            "NaTs2_t"
        ]

        # ignore_chans=['StochKv','StochKv_deterministic']
        ignore_chans = []

        bp, incl_chans = get_biophysical_properties(
            cell_info['e-type'],
            ignore_chans=ignore_chans,
            templates_json="../templates.json")

        cell.biophysical_properties = bp

        print("Set biophysical properties")

        notes = ''
        notes += \
            "\n\nExport of a cell model obtained from the BBP Neocortical" \
            "Microcircuit Collaboration Portal into NeuroML2" \
            "\n\n******************************************************\n*" \
            "  This export to NeuroML2 has not yet been fully validated!!" \
            "\n*  Use with caution!!\n***********************************" \
            "*******************\n\n"

        if len(ignore_chans) > 0:
            notes += "Ignored channels = %s\n\n" % ignore_chans

        notes += "For more information on this cell model see: " \
            "https://bbp.epfl.ch/nmc-portal/microcircuit#/metype/%s/" \
            "details\n\n" % cell_info['me-type']

        cell.notes = notes
        for channel in incl_chans:

            nml_doc.includes.append(neuroml.IncludeType(href="%s" % channel))

            if make_zips:
                print("Copying %s to zip folder" % channel)
                shutil.copyfile('../../NeuroML2/%s' % channel,
                                '%s/%s' % (local_nml2_cell_dir, channel))

        pynml.write_neuroml2_file(nml_doc, nml_cell_loc)

        stim_ref = 'stepcurrent3'
        stim_ref_hyp = '%s_hyp' % stim_ref
        stim_sim_duration = 3000
        stim_hyp_amp, stim_amp = get_stimulus_amplitudes(bbp_ref)
        stim_del = '700ms'
        stim_dur = '2000ms'

        new_net_loc = "%s/%s.%s.net.nml" % (local_nml2_cell_dir, bbp_ref,
                                            stim_ref)
        new_net_doc = pynml.read_neuroml2_file(nml_net_loc)

        new_net_doc.notes = notes

        stim_hyp = neuroml.PulseGenerator(id=stim_ref_hyp,
                                          delay="0ms",
                                          duration="%sms" % stim_sim_duration,
                                          amplitude=stim_hyp_amp)
        new_net_doc.pulse_generators.append(stim_hyp)
        stim = neuroml.PulseGenerator(id=stim_ref,
                                      delay=stim_del,
                                      duration=stim_dur,
                                      amplitude=stim_amp)
        new_net_doc.pulse_generators.append(stim)

        new_net = new_net_doc.networks[0]

        pop_id = new_net.populations[0].id
        pop_comp = new_net.populations[0].component
        input_list = neuroml.InputList(id="%s_input" % stim_ref_hyp,
                                       component=stim_ref_hyp,
                                       populations=pop_id)

        syn_input = neuroml.Input(id=0,
                                  target="../%s/0/%s" % (pop_id, pop_comp),
                                  destination="synapses")

        input_list.input.append(syn_input)
        new_net.input_lists.append(input_list)

        input_list = neuroml.InputList(id="%s_input" % stim_ref,
                                       component=stim_ref,
                                       populations=pop_id)

        syn_input = neuroml.Input(id=0,
                                  target="../%s/0/%s" % (pop_id, pop_comp),
                                  destination="synapses")

        input_list.input.append(syn_input)
        new_net.input_lists.append(input_list)

        pynml.write_neuroml2_file(new_net_doc, new_net_loc)

        generate_lems_file_for_neuroml(cell_dir,
                                       new_net_loc,
                                       "network",
                                       stim_sim_duration,
                                       0.025,
                                       "LEMS_%s.xml" % cell_dir,
                                       local_nml2_cell_dir,
                                       copy_neuroml=False,
                                       seed=1234)

        pynml.nml2_to_svg(nml_net_loc)

        clear_neuron()

        pop = neuroml.Population(id="Pop_%s" % bbp_ref,
                                 component=bbp_ref + '_0_0',
                                 type="populationList")

        inst = neuroml.Instance(id="0")
        pop.instances.append(inst)

        width = 6
        X = count % width
        Z = (count - X) / width
        inst.location = neuroml.Location(x=300 * X, y=0, z=300 * Z)

        count += 1

        if make_zips:
            zip_file = "%s/%s.zip" % (zips_dir, cell_dir)
            print("Creating zip file: %s" % zip_file)
            with zipfile.ZipFile(zip_file, 'w') as myzip:

                for next_file in os.listdir(local_nml2_cell_dir):
                    next_file = '%s/%s' % (local_nml2_cell_dir, next_file)
                    arcname = next_file[len(zips_dir):]
                    print("Adding : %s as %s" % (next_file, arcname))
                    myzip.write(next_file, arcname)

        os.chdir(old_cwd)

        return nml_cell_file, pop
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()
import neuroml

import neuroml.loaders as loaders
import neuroml.writers as writers

fn = 'BC2.cell.nml'
doc = loaders.NeuroMLLoader.load(fn)
print("Loaded morphology file from: " + fn)

cell = doc.cells[0]

axon_seg_group = neuroml.SegmentGroup(
    id="axon_group", neuro_lex_id="GO:0030424"
)  # See http://amigo.geneontology.org/amigo/term/GO:0030424
soma_seg_group = neuroml.SegmentGroup(id="soma_group",
                                      neuro_lex_id="GO:0043025")
dend_seg_group = neuroml.SegmentGroup(id="dendrite_group",
                                      neuro_lex_id="GO:0030425")
inhomogeneous_parameter = neuroml.InhomogeneousParameter(
    id="PathLengthOverDendrites", variable="p", metric="Path Length from root")
dend_seg_group.inhomogeneous_parameters.append(inhomogeneous_parameter)

apic_dend_seg_group = neuroml.SegmentGroup(id="apic_dendrite_group")

included_sections = []
for seg in cell.morphology.segments:
    neuron_section_name = seg.name[seg.name.index('_') + 1:]

    if not neuron_section_name in included_sections:
        if 'axon' in seg.name:
            axon_seg_group.includes.append(
            replace['axon_'] = 'axon'
            replace['apic_'] = 'apic'
            replace['dend_'] = 'dend'
            for prefix in replace.keys():
                all_match = True
                for inc in sg.includes:
                    #print inc
                    all_match = all_match and inc.segment_groups.startswith(
                        prefix)
                if all_match:
                    print("Replacing group named %s with %s" %
                          (sg.id, replace[prefix]))
                    sg.id = replace[prefix]

    cell.morphology.segment_groups.append(
        neuroml.SegmentGroup(id="soma_group",
                             includes=[neuroml.Include("soma")]))
    cell.morphology.segment_groups.append(
        neuroml.SegmentGroup(id="axon_group",
                             includes=[neuroml.Include("axon")]))
    cell.morphology.segment_groups.append(
        neuroml.SegmentGroup(id="dendrite_group",
                             includes=[neuroml.Include("dend")]))

    with open(manifest_info['biophys'][0]["model_file"][1], "r") as json_file:
        cell_info = json.load(json_file)

    membrane_properties = neuroml.MembraneProperties()

    for sc in cell_info['passive'][0]['cm']:
        membrane_properties.specific_capacitances.append(
            neuroml.SpecificCapacitance(value='%s uF_per_cm2' % sc['cm'],