def generate_lems(glif_dir, curr_pA, show_plot=True):

    os.chdir(glif_dir)
    
    with open('model_metadata.json', "r") as json_file:
        model_metadata = json.load(json_file)

    with open('neuron_config.json', "r") as json_file:
        neuron_config = json.load(json_file)

    with open('ephys_sweeps.json', "r") as json_file:
        ephys_sweeps = json.load(json_file)

    template_cell = '''<Lems>

      <%s %s/>

    </Lems>
    '''

    type = '???'
    print(model_metadata['name'])
    if '(LIF)' in model_metadata['name']:
        type = 'glifCell'
    if '(LIF-ASC)' in model_metadata['name']:
        type = 'glifAscCell'
    if '(LIF-R)' in model_metadata['name']:
        type = 'glifRCell'
    if '(LIF-R-ASC)' in model_metadata['name']:
        type = 'glifRAscCell'
    if '(LIF-R-ASC-A)' in model_metadata['name']:
        type = 'glifRAscATCell'
        
    cell_id = 'GLIF_%s'%glif_dir

    attributes = ""

    attributes +=' id="%s"'%cell_id
    attributes +='\n            C="%s F"'%neuron_config["C"]
    attributes +='\n            leakReversal="%s V"'%neuron_config["El"]
    attributes +='\n            reset="%s V"'%neuron_config["El"]
    attributes +='\n            thresh="%s V"'%( float(neuron_config["th_inf"]) * float(neuron_config["coeffs"]["th_inf"]))
    attributes +='\n            leakConductance="%s S"'%(1/float(neuron_config["R_input"]))
    
    if 'Asc' in type:
        attributes +='\n            tau1="%s s"'%neuron_config["asc_tau_array"][0]
        attributes +='\n            tau2="%s s"'%neuron_config["asc_tau_array"][1]
        attributes +='\n            amp1="%s A"'% ( float(neuron_config["asc_amp_array"][0]) * float(neuron_config["coeffs"]["asc_amp_array"][0]) )
        attributes +='\n            amp2="%s A"'% ( float(neuron_config["asc_amp_array"][1]) * float(neuron_config["coeffs"]["asc_amp_array"][1]) )
        
    if 'glifR' in type:
        attributes +='\n            bs="%s per_s"'%neuron_config["threshold_dynamics_method"]["params"]["b_spike"]
        attributes +='\n            deltaThresh="%s V"'%neuron_config["threshold_dynamics_method"]["params"]["a_spike"]
        attributes +='\n            fv="%s"'%neuron_config["voltage_reset_method"]["params"]["a"]
        attributes +='\n            deltaV="%s V"'%neuron_config["voltage_reset_method"]["params"]["b"]
        
    if 'glifRAscATCell' in type:
        attributes +='\n            bv="%s per_s"'%neuron_config["threshold_dynamics_method"]["params"]["b_voltage"]
        attributes +='\n            a="%s per_s"'%neuron_config["threshold_dynamics_method"]["params"]["a_voltage"]
        

    file_contents = template_cell%(type, attributes)

    print(file_contents)

    cell_file_name = '%s.xml'%(cell_id)
    cell_file = open(cell_file_name,'w')
    cell_file.write(file_contents)
    cell_file.close()


    import opencortex.build as oc

    nml_doc, network = oc.generate_network("Test_%s"%glif_dir)

    pop = oc.add_single_cell_population(network,
                                         'pop_%s'%glif_dir,
                                         cell_id)


    pg = oc.add_pulse_generator(nml_doc,
                           id="pg0",
                           delay="100ms",
                           duration="1000ms",
                           amplitude="%s pA"%curr_pA)


    oc.add_inputs_to_population(network,
                                "Stim0",
                                pop,
                                pg.id,
                                all_cells=True)



    nml_file_name = '%s.net.nml'%network.id
    oc.save_network(nml_doc, nml_file_name, validate=True)
    

    thresh = 'thresh'
    if 'glifR' in type:
        thresh = 'threshTotal'

    lems_file_name = oc.generate_lems_simulation(nml_doc, 
                                network, 
                                nml_file_name, 
                                include_extra_lems_files = [cell_file_name,'../GLIFs.xml'],
                                duration =      1200, 
                                dt =            0.01,
                                gen_saves_for_quantities = {'thresh.dat':['pop_%s/0/GLIF_%s/%s'%(glif_dir,glif_dir,thresh)]},
                                gen_plots_for_quantities = {'Threshold':['pop_%s/0/GLIF_%s/%s'%(glif_dir,glif_dir,thresh)]})
    
    results = pynml.run_lems_with_jneuroml(lems_file_name,
                                     nogui=True,
                                     load_saved_data=True)

    print("Ran simulation; results reloaded for: %s"%results.keys())
    
    info = "Model %s; %spA stimulation"%(glif_dir,curr_pA)

    times = [results['t']]
    vs = [results['pop_%s/0/GLIF_%s/v'%(glif_dir,glif_dir)]]
    labels = ['LEMS - jNeuroML']

    original_model_v = 'original.v.dat'
    if os.path.isfile(original_model_v):
        data, indices = pynml.reload_standard_dat_file(original_model_v)
        times.append(data['t'])
        vs.append(data[0])
        labels.append('Allen SDK')


    pynml.generate_plot(times,
                        vs, 
                        "Membrane potential; %s"%info, 
                        xaxis = "Time (s)", 
                        yaxis = "Voltage (V)", 
                        labels = labels,
                        grid = True,
                        show_plot_already=False,
                        save_figure_to='Comparison_%ipA.png'%(curr_pA))

    times = [results['t']]
    vs = [results['pop_%s/0/GLIF_%s/%s'%(glif_dir,glif_dir,thresh)]]
    labels = ['LEMS - jNeuroML']

    original_model_th = 'original.thresh.dat'
    if os.path.isfile(original_model_th):
        data, indeces = pynml.reload_standard_dat_file(original_model_th)
        times.append(data['t'])
        vs.append(data[0])
        labels.append('Allen SDK')


    pynml.generate_plot(times,
                        vs, 
                        "Threshold; %s"%info, 
                        xaxis = "Time (s)", 
                        yaxis = "Voltage (V)", 
                        labels = labels,
                        grid = True,
                        show_plot_already=show_plot,
                        save_figure_to='Comparison_Threshold_%ipA.png'%(curr_pA))
                            
    readme = '''
## Model: %(id)s

### Original model

%(name)s

[Allen Cell Types DB electrophysiology page for specimen](http://celltypes.brain-map.org/mouse/experiment/electrophysiology/%(spec)s)

[Neuron configuration](neuron_config.json); [model metadata](model_metadata.json); [electrophysiology summary](ephys_sweeps.json)

#### Original traces:

**Membrane potential**

Current injection of %(curr)s pA

![Original](MembranePotential_%(curr)spA.png)

**Threshold**

![Threshold](Threshold_%(curr)spA.png)

### Conversion to NeuroML 2

LEMS version of this model: [GLIF_%(id)s.xml](GLIF_%(id)s.xml)

[Definitions of LEMS Component Types](../GLIFs.xml) for GLIFs.

This model can be run locally by installing [jNeuroML](https://github.com/NeuroML/jNeuroML) and running:

    jnml LEMS_Test_%(id)s.xml

#### Comparison:

**Membrane potential**

Current injection of %(curr)s pA

![Comparison](Comparison_%(curr)spA.png)

**Threshold**

![Comparison](Comparison_Threshold_%(curr)spA.png)'''
    
    readme_file = open('README.md','w')
    curr_str = str(curr_pA)
    # @type curr_str str
    if curr_str.endswith('.0'):
        curr_str = curr_str[:-2]
    readme_file.write(readme%{"id":glif_dir,"name":model_metadata['name'],"spec":model_metadata["specimen_id"],"curr":curr_str})
    readme_file.close()

    os.chdir('..')
    
    return model_metadata, neuron_config, ephys_sweeps
import opencortex.build as oc

nml_doc, network = oc.generate_network("IClamps")

oc.add_cell_and_channels(nml_doc, '../NeuroML2/prototypes/izhikevich/RS.cell.nml', 'RS')
oc.add_cell_and_channels(nml_doc, '../NeuroML2/prototypes/acnet2/pyr_4_sym_soma.cell.nml', 'pyr_4_sym_soma')
#oc.add_cell_and_channels(nml_doc, '../NeuroML2/prototypes/BlueBrainProject_NMC/cADpyr229_L23_PC_5ecbf9b163_0_0.cell.nml', 'cADpyr229_L23_PC_5ecbf9b163_0_0')

popIzh = oc.add_single_cell_population(network,
                                     'popIzh',
                                     'RS')

popHH = oc.add_single_cell_population(network,
                                     'popHH',
                                     'pyr_4_sym_soma',
                                     z=100)
'''
popBBP = oc.add_single_cell_population(network,
                                     'popBBP',
                                     'cADpyr229_L23_PC_5ecbf9b163_0_0',
                                     z=200)'''
                                     
pgIzh = oc.add_pulse_generator(nml_doc,
                       id="pgIzh",
                       delay="100ms",
                       duration="300ms",
                       amplitude="0.7nA")
                                     
pgHH = oc.add_pulse_generator(nml_doc,
                       id="pgHH",
Exemple #3
0
def generate(reference = "Balanced",
             num_bbp =1,
             scalePops = 1,
             scalex=1,
             scaley=1,
             scalez=1,
             connections=True,
             duration = 1000,
             global_delay = 0,
             format='xml'):

    num_exc = scale_pop_size(80,scalePops)
    num_inh = scale_pop_size(40,scalePops)
    
    nml_doc, network = oc.generate_network(reference)

    oc.add_cell_and_channels(nml_doc, 'AllenInstituteCellTypesDB_HH/HH_464198958.cell.nml','HH_464198958')
    oc.add_cell_and_channels(nml_doc, 'AllenInstituteCellTypesDB_HH/HH_471141261.cell.nml','HH_471141261')
    
    if num_bbp>0:
        oc.add_cell_and_channels(nml_doc, 'BlueBrainProject_NMC/cADpyr229_L23_PC_5ecbf9b163_0_0.cell.nml', 'cADpyr229_L23_PC_5ecbf9b163_0_0')

    xDim = 400*scalex
    yDim = 500*scaley
    zDim = 300*scalez

    xs = -200
    ys = -150
    zs = 100

    #####   Synapses

    synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="1nS",
                             erev="0mV", tau_rise="0.5ms", tau_decay="5ms")

    synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="2nS",
                             erev="-80mV", tau_rise="1ms", tau_decay="20ms")

    #####   Input types


    pfs1 = oc.add_poisson_firing_synapse(nml_doc,
                                       id="psf1",
                                       average_rate="150 Hz",
                                       synapse_id=synAmpa1.id)


    #####   Populations

    popExc = oc.add_population_in_rectangular_region(network,
                                                  'popExc',
                                                  'HH_464198958',
                                                  num_exc,
                                                  xs,ys,zs,
                                                  xDim,yDim,zDim)

    popInh = oc.add_population_in_rectangular_region(network,
                                                  'popInh',
                                                  'HH_471141261',
                                                  num_inh,
                                                  xs,ys,zs,
                                                  xDim,yDim,zDim)
    if num_bbp == 1:
        popBBP = oc.add_single_cell_population(network,
                                             'popBBP',
                                             'cADpyr229_L23_PC_5ecbf9b163_0_0',
                                             z=200)
    elif num_bbp > 1:

        popBBP = oc.add_population_in_rectangular_region(network,
                                                      'popBBP',
                                                      'cADpyr229_L23_PC_5ecbf9b163_0_0',
                                                      num_bbp,
                                                      xs,ys,zs,
                                                      xDim,yDim,zDim)


    #####   Projections

    total_conns = 0
    if connections:
        proj = oc.add_probabilistic_projection(network, "proj0",
                                        popExc, popExc,
                                        synAmpa1.id, 0.3, delay = global_delay)
        total_conns += len(proj.connection_wds)

        proj = oc.add_probabilistic_projection(network, "proj1",
                                        popExc, popInh,
                                        synAmpa1.id, 0.5, delay = global_delay)
        total_conns += len(proj.connection_wds)

        proj = oc.add_probabilistic_projection(network, "proj3",
                                        popInh, popExc,
                                        synGaba1.id, 0.7, delay = global_delay)
        total_conns += len(proj.connection_wds)

        proj = oc.add_probabilistic_projection(network, "proj4",
                                        popInh, popInh,
                                        synGaba1.id, 0.5, delay = global_delay)
        total_conns += len(proj.connection_wds)



        if num_bbp>0:
            proj = oc.add_probabilistic_projection(network, "proj5",
                                            popExc, popBBP,
                                            synAmpa1.id, 0.5, delay = global_delay)
                                        
        total_conns += len(proj.connection_wds)

    #####   Inputs

    oc.add_inputs_to_population(network, "Stim0",
                                popExc, pfs1.id,
                                all_cells=True)



    #####   Save NeuroML and LEMS Simulation files      
    
    if num_bbp != 1:
        new_reference = 'Balanced_%scells_%sconns'%(num_bbp+num_exc+num_inh,total_conns)
        network.id = new_reference
        nml_doc.id = new_reference

    nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml')
    oc.save_network(nml_doc, 
                    nml_file_name, 
                    validate=(format=='xml'),
                    format = format)

    if format=='xml':
        lems_file_name = oc.generate_lems_simulation(nml_doc, network, 
                                nml_file_name, 
                                duration =      duration, 
                                dt =            0.025)
    else:
        lems_file_name = None
                                
    return nml_doc, nml_file_name, lems_file_name
Exemple #4
0
def generate_lems(glif_dir, curr_pA, show_plot=True):

    os.chdir(glif_dir)

    with open('model_metadata.json', "r") as json_file:
        model_metadata = json.load(json_file)

    with open('neuron_config.json', "r") as json_file:
        neuron_config = json.load(json_file)

    with open('ephys_sweeps.json', "r") as json_file:
        ephys_sweeps = json.load(json_file)

    template_cell = '''<Lems>

      <%s %s/>

    </Lems>
    '''

    type = '???'
    print(model_metadata['name'])
    if '(LIF)' in model_metadata['name']:
        type = 'glifCell'
    if '(LIF-ASC)' in model_metadata['name']:
        type = 'glifAscCell'
    if '(LIF-R)' in model_metadata['name']:
        type = 'glifRCell'
    if '(LIF-R-ASC)' in model_metadata['name']:
        type = 'glifRAscCell'
    if '(LIF-R-ASC-A)' in model_metadata['name']:
        type = 'glifRAscATCell'

    cell_id = 'GLIF_%s' % glif_dir

    attributes = ""

    attributes += ' id="%s"' % cell_id
    attributes += '\n            C="%s F"' % neuron_config["C"]
    attributes += '\n            leakReversal="%s V"' % neuron_config["El"]
    attributes += '\n            reset="%s V"' % neuron_config["El"]
    attributes += '\n            thresh="%s V"' % (float(
        neuron_config["th_inf"]) * float(neuron_config["coeffs"]["th_inf"]))
    attributes += '\n            leakConductance="%s S"' % (
        1 / float(neuron_config["R_input"]))

    if 'Asc' in type:
        attributes += '\n            tau1="%s s"' % neuron_config[
            "asc_tau_array"][0]
        attributes += '\n            tau2="%s s"' % neuron_config[
            "asc_tau_array"][1]
        attributes += '\n            amp1="%s A"' % (
            float(neuron_config["asc_amp_array"][0]) *
            float(neuron_config["coeffs"]["asc_amp_array"][0]))
        attributes += '\n            amp2="%s A"' % (
            float(neuron_config["asc_amp_array"][1]) *
            float(neuron_config["coeffs"]["asc_amp_array"][1]))

    if 'glifR' in type:
        attributes += '\n            bs="%s per_s"' % neuron_config[
            "threshold_dynamics_method"]["params"]["b_spike"]
        attributes += '\n            deltaThresh="%s V"' % neuron_config[
            "threshold_dynamics_method"]["params"]["a_spike"]
        attributes += '\n            fv="%s"' % neuron_config[
            "voltage_reset_method"]["params"]["a"]
        attributes += '\n            deltaV="%s V"' % neuron_config[
            "voltage_reset_method"]["params"]["b"]

    if 'glifRAscATCell' in type:
        attributes += '\n            bv="%s per_s"' % neuron_config[
            "threshold_dynamics_method"]["params"]["b_voltage"]
        attributes += '\n            a="%s per_s"' % neuron_config[
            "threshold_dynamics_method"]["params"]["a_voltage"]

    file_contents = template_cell % (type, attributes)

    print(file_contents)

    cell_file_name = '%s.xml' % (cell_id)
    cell_file = open(cell_file_name, 'w')
    cell_file.write(file_contents)
    cell_file.close()

    import opencortex.build as oc

    nml_doc, network = oc.generate_network("Test_%s" % glif_dir)

    pop = oc.add_single_cell_population(network, 'pop_%s' % glif_dir, cell_id)

    pg = oc.add_pulse_generator(nml_doc,
                                id="pg0",
                                delay="100ms",
                                duration="1000ms",
                                amplitude="%s pA" % curr_pA)

    oc.add_inputs_to_population(network, "Stim0", pop, pg.id, all_cells=True)

    nml_file_name = '%s.net.nml' % network.id
    oc.save_network(nml_doc, nml_file_name, validate=True)

    thresh = 'thresh'
    if 'glifR' in type:
        thresh = 'threshTotal'

    lems_file_name = oc.generate_lems_simulation(
        nml_doc,
        network,
        nml_file_name,
        include_extra_lems_files=[cell_file_name, '../GLIFs.xml'],
        duration=1200,
        dt=0.01,
        gen_saves_for_quantities={
            'thresh.dat':
            ['pop_%s/0/GLIF_%s/%s' % (glif_dir, glif_dir, thresh)]
        },
        gen_plots_for_quantities={
            'Threshold':
            ['pop_%s/0/GLIF_%s/%s' % (glif_dir, glif_dir, thresh)]
        })

    results = pynml.run_lems_with_jneuroml(lems_file_name,
                                           nogui=True,
                                           load_saved_data=True)

    print("Ran simulation; results reloaded for: %s" % results.keys())

    info = "Model %s; %spA stimulation" % (glif_dir, curr_pA)

    times = [results['t']]
    vs = [results['pop_%s/0/GLIF_%s/v' % (glif_dir, glif_dir)]]
    labels = ['LEMS - jNeuroML']

    original_model_v = 'original.v.dat'
    if os.path.isfile(original_model_v):
        data, indices = pynml.reload_standard_dat_file(original_model_v)
        times.append(data['t'])
        vs.append(data[0])
        labels.append('Allen SDK')

    pynml.generate_plot(times,
                        vs,
                        "Membrane potential; %s" % info,
                        xaxis="Time (s)",
                        yaxis="Voltage (V)",
                        labels=labels,
                        grid=True,
                        show_plot_already=False,
                        save_figure_to='Comparison_%ipA.png' % (curr_pA))

    times = [results['t']]
    vs = [results['pop_%s/0/GLIF_%s/%s' % (glif_dir, glif_dir, thresh)]]
    labels = ['LEMS - jNeuroML']

    original_model_th = 'original.thresh.dat'
    if os.path.isfile(original_model_th):
        data, indeces = pynml.reload_standard_dat_file(original_model_th)
        times.append(data['t'])
        vs.append(data[0])
        labels.append('Allen SDK')

    pynml.generate_plot(times,
                        vs,
                        "Threshold; %s" % info,
                        xaxis="Time (s)",
                        yaxis="Voltage (V)",
                        labels=labels,
                        grid=True,
                        show_plot_already=show_plot,
                        save_figure_to='Comparison_Threshold_%ipA.png' %
                        (curr_pA))

    readme = '''
## Model: %(id)s

### Original model

%(name)s

[Allen Cell Types DB electrophysiology page for specimen](http://celltypes.brain-map.org/mouse/experiment/electrophysiology/%(spec)s)

[Neuron configuration](neuron_config.json); [model metadata](model_metadata.json); [electrophysiology summary](ephys_sweeps.json)

#### Original traces:

**Membrane potential**

Current injection of %(curr)s pA

![Original](MembranePotential_%(curr)spA.png)

**Threshold**

![Threshold](Threshold_%(curr)spA.png)

### Conversion to NeuroML 2

LEMS version of this model: [GLIF_%(id)s.xml](GLIF_%(id)s.xml)

[Definitions of LEMS Component Types](../GLIFs.xml) for GLIFs.

This model can be run locally by installing [jNeuroML](https://github.com/NeuroML/jNeuroML) and running:

    jnml LEMS_Test_%(id)s.xml

#### Comparison:

**Membrane potential**

Current injection of %(curr)s pA

![Comparison](Comparison_%(curr)spA.png)

**Threshold**

![Comparison](Comparison_Threshold_%(curr)spA.png)'''

    readme_file = open('README.md', 'w')
    curr_str = str(curr_pA)
    # @type curr_str str
    if curr_str.endswith('.0'):
        curr_str = curr_str[:-2]
    readme_file.write(
        readme % {
            "id": glif_dir,
            "name": model_metadata['name'],
            "spec": model_metadata["specimen_id"],
            "curr": curr_str
        })
    readme_file.close()

    os.chdir('..')

    return model_metadata, neuron_config, ephys_sweeps