Exemplo n.º 1
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()
def create_GoC(runid):

    ### ---------- Load Params
    noPar = True
    pfile = Path('cellparams_file.pkl')
    keepFile = open('useParams_FI_14_25.pkl', 'rb')
    runid = pkl.load(keepFile)[runid]
    keepFile.close()
    print('Running morphology for parameter set = ', runid)

    if pfile.exists():
        print('Reading parameters from file:')
        file = open('cellparams_file.pkl', 'rb')
        params_list = pkl.load(file)
        if len(params_list) > runid:
            p = params_list[runid]
            file.close()
    if noPar:
        p = icp.get_channel_params(runid)

    # Creating document for cell
    gocID = 'Golgi_040408_C1_' + format(runid, '05d')
    goc = nml.Cell(id=gocID)  #--------simid
    cell_doc = nml.NeuroMLDocument(id=gocID)
    cell_doc.cells.append(goc)

    ### Load morphology
    morpho_fname = 'Golgi_040408_C1.cell.nml'
    morpho_file = pynml.read_neuroml2_file(morpho_fname)
    morpho = morpho_file.cells[0].morphology
    cell_doc.includes.append(nml.IncludeType(href=morpho_fname))
    goc.morphology = morpho

    ### ---------- Channels
    na_fname = 'Golgi_Na.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=na_fname))
    nar_fname = 'Golgi_NaR.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=nar_fname))
    nap_fname = 'Golgi_NaP.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=nap_fname))

    ka_fname = 'Golgi_KA.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=ka_fname))
    sk2_fname = 'Golgi_SK2.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=sk2_fname))
    km_fname = 'Golgi_KM.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=km_fname))
    kv_fname = 'Golgi_KV.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=kv_fname))
    bk_fname = 'Golgi_BK.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=bk_fname))

    cahva_fname = 'Golgi_CaHVA.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=cahva_fname))
    calva_fname = 'Golgi_CaLVA.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=calva_fname))

    hcn1f_fname = 'Golgi_HCN1f.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=hcn1f_fname))
    hcn1s_fname = 'Golgi_HCN1s.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=hcn1s_fname))
    hcn2f_fname = 'Golgi_HCN2f.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=hcn2f_fname))
    hcn2s_fname = 'Golgi_HCN2s.channel.nml'
    cell_doc.includes.append(nml.IncludeType(href=hcn2s_fname))

    leak_fname = 'Golgi_lkg.channel.nml'
    #leak_ref 	= nml.IncludeType( href=leak_fname)
    cell_doc.includes.append(nml.IncludeType(href=leak_fname))
    calc_fname = 'Golgi_CALC.nml'
    cell_doc.includes.append(nml.IncludeType(href=calc_fname))
    calc = pynml.read_neuroml2_file(
        calc_fname).decaying_pool_concentration_models[0]

    calc2_fname = 'Golgi_CALC2.nml'
    cell_doc.includes.append(nml.IncludeType(href=calc2_fname))

    goc_2pools_fname = 'GoC_2Pools.cell.nml'
    ### ------Biophysical Properties
    biophys = nml.BiophysicalProperties(id='biophys_' + gocID)
    goc.biophysical_properties = biophys

    # Inproperties
    '''
	res = nml.Resistivity( p["ra"] )		# --------- "0.1 kohm_cm" 
	ca_species = nml.Species( id="ca", ion="ca", concentration_model=calc.id, initial_concentration ="5e-5 mM", initial_ext_concentration="2 mM" )
	ca2_species = nml.Species( id="ca2", ion="ca2", concentration_model="Golgi_CALC2", initial_concentration ="5e-5 mM", initial_ext_concentration="2 mM" )
	intracellular = nml.IntracellularProperties(  )
	intracellular.resistivities.append( res )
	intracellular.species.append( ca_species )
	'''
    intracellular = pynml.read_neuroml2_file(goc_2pools_fname).cells[
        0].biophysical_properties.intracellular_properties
    biophys.intracellular_properties = intracellular

    # Membrane properties ------- cond
    memb = nml.MembraneProperties()
    biophys.membrane_properties = memb

    #pynml.read_neuroml2_file(leak_fname).ion_channel[0].id -> can't read ion channel passive
    chan_leak = nml.ChannelDensity(ion_channel="LeakConductance",
                                   cond_density=p["leak_cond"],
                                   erev="-55 mV",
                                   ion="non_specific",
                                   id="Leak")
    memb.channel_densities.append(chan_leak)

    chan_na = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(na_fname).ion_channel[0].id,
        cond_density=p["na_cond"],
        erev="87.39 mV",
        ion="na",
        id="Golgi_Na_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_na)
    chan_nap = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(nap_fname).ion_channel[0].id,
        cond_density=p["nap_cond"],
        erev="87.39 mV",
        ion="na",
        id="Golgi_NaP_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_nap)
    chan_nar = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(nar_fname).ion_channel[0].id,
        cond_density=p["nar_cond"],
        erev="87.39 mV",
        ion="na",
        id="Golgi_NaR_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_nar)
    chan_ka = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(ka_fname).ion_channel[0].id,
        cond_density=p["ka_cond"],
        erev="-84.69 mV",
        ion="k",
        id="Golgi_KA_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_ka)
    chan_sk = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(sk2_fname).ion_channel_kses[0].id,
        cond_density=p["sk2_cond"],
        erev="-84.69 mV",
        ion="k",
        id="Golgi_KAHP_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_sk)
    chan_kv = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(kv_fname).ion_channel[0].id,
        cond_density=p["kv_cond"],
        erev="-84.69 mV",
        ion="k",
        id="Golgi_KV_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_kv)
    chan_km = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(km_fname).ion_channel[0].id,
        cond_density=p["km_cond"],
        erev="-84.69 mV",
        ion="k",
        id="Golgi_KM_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_km)
    chan_bk = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(bk_fname).ion_channel[0].id,
        cond_density=p["bk_cond"],
        erev="-84.69 mV",
        ion="k",
        id="Golgi_BK_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_bk)
    chan_h1f = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(hcn1f_fname).ion_channel[0].id,
        cond_density=p["hcn1f_cond"],
        erev="-20 mV",
        ion="h",
        id="Golgi_hcn1f_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_h1f)
    chan_h1s = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(hcn1s_fname).ion_channel[0].id,
        cond_density=p["hcn1s_cond"],
        erev="-20 mV",
        ion="h",
        id="Golgi_hcn1s_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_h1s)
    chan_h2f = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(hcn2f_fname).ion_channel[0].id,
        cond_density=p["hcn2f_cond"],
        erev="-20 mV",
        ion="h",
        id="Golgi_hcn2f_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_h2f)
    chan_h2s = nml.ChannelDensity(
        ion_channel=pynml.read_neuroml2_file(hcn2s_fname).ion_channel[0].id,
        cond_density=p["hcn2s_cond"],
        erev="-20 mV",
        ion="h",
        id="Golgi_hcn2s_soma_group",
        segment_groups="soma_group")
    memb.channel_densities.append(chan_h2s)
    chan_hva = nml.ChannelDensityNernst(
        ion_channel=pynml.read_neuroml2_file(cahva_fname).ion_channel[0].id,
        cond_density=p["cahva_cond"],
        ion="ca",
        id="Golgi_Ca_HVA_soma_group",
        segment_groups="soma_group")
    memb.channel_density_nernsts.append(chan_hva)
    chan_lva = nml.ChannelDensityNernst(
        ion_channel=pynml.read_neuroml2_file(calva_fname).ion_channel[0].id,
        cond_density=p["calva_cond"],
        ion="ca2",
        id="Golgi_Ca_LVA_soma_group",
        segment_groups="soma_group")
    memb.channel_density_nernsts.append(chan_lva)

    memb.spike_threshes.append(nml.SpikeThresh("0 mV"))
    memb.specific_capacitances.append(
        nml.SpecificCapacitance("1.0 uF_per_cm2"))
    memb.init_memb_potentials.append(nml.InitMembPotential("-60 mV"))

    goc_filename = '{}.cell.nml'.format(gocID)
    pynml.write_neuroml2_file(cell_doc, goc_filename)

    return True
cd_k = neuroml.ChannelDensity(id="k_chan",
                              segment_groups="all",
                              ion="k",
                              ion_channel="K_BC",
                              erev="-90 mV",
                              cond_density="30 mS_per_cm2")
channel_densities.append(cd_k)

specific_capacitances = []

specific_capacitances.append(
    neuroml.SpecificCapacitance(value='1.0 uF_per_cm2', segment_groups='all'))

init_memb_potentials = [
    neuroml.InitMembPotential(value="-80 mV", segment_groups='all')
]

membrane_properties = neuroml.MembraneProperties(
    channel_densities=channel_densities,
    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(