Example #1
0
def create_olm_network():
    """Create the network

    :returns: name of network nml file
    """
    net_doc = NeuroMLDocument(id="network", notes="OLM cell network")
    net_doc_fn = "olm_example_net.nml"
    net_doc.includes.append(IncludeType(href=create_olm_cell()))
    # Create a population: convenient to create many cells of the same type
    pop = Population(id="pop0",
                     notes="A population for our cell",
                     component="olm",
                     size=1,
                     type="populationList")
    pop.instances.append(Instance(id=1, location=Location(0., 0., 0.)))
    # Input
    pulsegen = PulseGenerator(id="pg_olm",
                              notes="Simple pulse generator",
                              delay="100ms",
                              duration="100ms",
                              amplitude="0.08nA")

    exp_input = ExplicitInput(target="pop0[0]", input="pg_olm")

    net = Network(id="single_olm_cell_network",
                  note="A network with a single population")
    net_doc.pulse_generators.append(pulsegen)
    net.explicit_inputs.append(exp_input)
    net.populations.append(pop)
    net_doc.networks.append(net)

    pynml.write_neuroml2_file(nml2_doc=net_doc,
                              nml2_file_name=net_doc_fn,
                              validate=True)
    return net_doc_fn
Example #2
0
def create_na_channel():
    """Create the Na channel.

    This will create the Na channel and save it to a file.
    It will also validate this file.

    returns: name of the created file
    """
    na_channel = IonChannelHH(id="na_channel", notes="Sodium channel for HH cell", conductance="10pS", species="na")
    gate_m = GateHHRates(id="na_m", instances="3", notes="m gate for na channel")

    m_forward_rate = HHRate(type="HHExpLinearRate", rate="1per_ms", midpoint="-40mV", scale="10mV")
    m_reverse_rate = HHRate(type="HHExpRate", rate="4per_ms", midpoint="-65mV", scale="-18mV")
    gate_m.forward_rate = m_forward_rate
    gate_m.reverse_rate = m_reverse_rate
    na_channel.gate_hh_rates.append(gate_m)

    gate_h = GateHHRates(id="na_h", instances="1", notes="h gate for na channel")
    h_forward_rate = HHRate(type="HHExpRate", rate="0.07per_ms", midpoint="-65mV", scale="-20mV")
    h_reverse_rate = HHRate(type="HHSigmoidRate", rate="1per_ms", midpoint="-35mV", scale="10mV")
    gate_h.forward_rate = h_forward_rate
    gate_h.reverse_rate = h_reverse_rate
    na_channel.gate_hh_rates.append(gate_h)

    na_channel_doc = NeuroMLDocument(id="na_channel", notes="Na channel for HH neuron")
    na_channel_fn = "HH_example_na_channel.nml"
    na_channel_doc.ion_channel_hhs.append(na_channel)

    pynml.write_neuroml2_file(nml2_doc=na_channel_doc, nml2_file_name=na_channel_fn, validate=True)

    return na_channel_fn
Example #3
0
def create_leak_channel():
    """Create a leak channel

    This will create the leak channel and save it to a file.
    It will also validate this file.

    :returns: name of leak channel nml file
    """
    leak_channel = IonChannelHH(id="leak_channel", conductance="10pS", notes="Leak conductance")
    leak_channel_doc = NeuroMLDocument(id="leak_channel", notes="leak channel for HH neuron")
    leak_channel_fn = "HH_example_leak_channel.nml"
    leak_channel_doc.ion_channel_hhs.append(leak_channel)

    pynml.write_neuroml2_file(nml2_doc=leak_channel_doc, nml2_file_name=leak_channel_fn, validate=True)

    return leak_channel_fn
Example #4
0
def create_k_channel():
    """Create the K channel

    This will create the K channel and save it to a file.
    It will also validate this file.

    :returns: name of the K channel file
    """
    k_channel = IonChannelHH(id="k_channel", notes="Potassium channel for HH cell", conductance="10pS", species="k")
    gate_n = GateHHRates(id="k_n", instances="4", notes="n gate for k channel")
    n_forward_rate = HHRate(type="HHExpLinearRate", rate="0.1per_ms", midpoint="-55mV", scale="10mV")
    n_reverse_rate = HHRate(type="HHExpRate", rate="0.125per_ms", midpoint="-65mV", scale="-80mV")
    gate_n.forward_rate = n_forward_rate
    gate_n.reverse_rate = n_reverse_rate
    k_channel.gate_hh_rates.append(gate_n)

    k_channel_doc = NeuroMLDocument(id="k_channel", notes="k channel for HH neuron")
    k_channel_fn = "HH_example_k_channel.nml"
    k_channel_doc.ion_channel_hhs.append(k_channel)

    pynml.write_neuroml2_file(nml2_doc=k_channel_doc, nml2_file_name=k_channel_fn, validate=True)

    return k_channel_fn
     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'%(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"%(nml2_cell_dir,bbp_ref, stim_ref)
 new_net_doc = pynml.read_neuroml2_file(nml_net_loc)
 
 new_net_doc.notes = notes
 
 #<pulseGenerator id="Gran_10pA" delay="100.0ms" duration="500.0ms" amplitude="1.0E-5uA"/>
Example #6
0
    ca_file.write(xml)
    ca_file.close()
        
         
                        
    intracellular_properties = neuroml.IntracellularProperties(resistivities=resistivities, species=species)

            
    biophysical_properties = neuroml.BiophysicalProperties(id="biophys",
                                          intracellular_properties=intracellular_properties,
                                          membrane_properties=membrane_properties)
                                          
    cell.biophysical_properties = biophysical_properties
    
    
    pynml.write_neuroml2_file(nml_doc, nml_cell_loc)
    
    
    pynml.nml2_to_svg(nml_cell_loc)
    
    
    pref_duration_ms = 2500
    pref_dt_ms = 0.005 # used in Allen Neuron runs
    

    new_nml_file_name = "Network_%s.net.nml"%model_id
    
    new_net_loc = "%s/%s"%(nml2_cell_dir, new_nml_file_name)
    new_net_doc = pynml.read_neuroml2_file(nml_net_loc)
    new_net = new_net_doc.networks[0]
    new_net_doc.notes = notes
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 create_GoC_network(duration, dt, seed, runid, run=False):

    ### ---------- Load Params
    noPar = True
    pfile = Path('params_file.pkl')
    if pfile.exists():
        print('Reading parameters from file:')
        file = open('params_file.pkl', 'rb')
        params_list = pkl.load(file)
        if len(params_list) > runid:
            p = params_list[runid]
            file.close()
    if noPar:
        p = inp.get_simulation_params(runid)

    ### ---------- Component types
    goc_filename = 'GoC.cell.nml'  # Golgi cell with channels
    goc_file = pynml.read_neuroml2_file(goc_filename)
    goc_type = goc_file.cells[0]
    goc_ref = nml.IncludeType(href=goc_filename)

    gj = nml.GapJunction(id="GJ_0", conductance="426pS")  # GoC synapse

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id="gocNetwork",
                      type="networkWithTemperature",
                      temperature="23 degC")

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=p["nGoC"])
    for goc in range(p["nGoC"]):
        inst = nml.Instance(id=goc)
        goc_pop.instances.append(inst)
        inst.location = nml.Location(x=p["GoC_pos"][goc, 0],
                                     y=p["GoC_pos"][goc, 1],
                                     z=p["GoC_pos"][goc, 2])
    net.populations.append(goc_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(goc_ref)
    net_doc.gap_junctions.append(gj)

    ### ------------ Connectivity

    ### 1. Input Current to one cell
    ctr = 0
    for goc in p["Test_GoC"]:
        for jj in range(p["nSteps"]):
            input_id = 'stim_{}'.format(ctr)
            istep = nml.PulseGenerator(
                id=input_id,
                delay='{} ms'.format(p["iDuration"] * jj + p["iRest"] *
                                     (jj + 1)),
                duration='{} ms'.format(p["iDuration"]),
                amplitude='{} pA'.format(p["iAmp"][jj]))
            net_doc.pulse_generators.append(istep)

            input_list = nml.InputList(id='ilist_{}'.format(ctr),
                                       component=istep.id,
                                       populations=goc_pop.id)
            curr_inj = nml.Input('0',
                                 target="../%s[%i]" % (goc_pop.id, goc),
                                 destination="synapses")
            input_list.input.append(curr_inj)
            net.input_lists.append(input_list)
            ctr += 1

    ### 2. Electrical coupling between GoCs

    GoCCoupling = nml.ElectricalProjection(id="gocGJ",
                                           presynaptic_population=goc_pop.id,
                                           postsynaptic_population=goc_pop.id)
    net.electrical_projections.append(GoCCoupling)
    dend_id = [1, 2, 5]
    for jj in range(p["GJ_pairs"].shape[0]):
        conn = nml.ElectricalConnectionInstanceW(
            id=jj,
            pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj, 0],
                                          goc_type.id),
            pre_segment=dend_id[p["GJ_loc"][jj, 0]],
            pre_fraction_along='0.5',
            post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj, 1],
                                           goc_type.id),
            post_segment=dend_id[p["GJ_loc"][jj, 1]],
            post_fraction_along='0.5',
            synapse=gj.id,
            weight=p["GJ_wt"][jj])
        GoCCoupling.electrical_connection_instance_ws.append(conn)

    ### --------------  Write files

    net_filename = 'gocNetwork.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)

    simid = 'sim_gocnet_' + goc_type.id + '_run_{}'.format(runid)
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)
    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    ctr = 0
    for jj in p["Test_GoC"]:
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, ctr, goc_type.id))
        ctr += 1

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
Example #9
0
    def run_individual(self, sim_var, show=False):
        """
        Run an individual simulation.

        The candidate data has been flattened into the sim_var dict. The
        sim_var dict contains parameter:value key value pairs, which are
        applied to the model before it is simulated.

        """
        
        nml_doc = read_neuroml2_file(self.neuroml_file, 
                                     include_includes=True,
                                     verbose = True,
                                     already_included = [])
                                     
        
        for var_name in sim_var.keys():
            words = var_name.split('/')
            type, id1 = words[0].split(':')
            if ':' in words[1]:
                variable, id2 = words[1].split(':')
            else:
                variable = words[1]
                id2 = None
            
            units = words[2]
            value = sim_var[var_name]
            
            print_comment_v('  Changing value of %s (%s) in %s (%s) to: %s %s'%(variable, id2, type, id1, value, units))
            
            if type == 'cell':
                cell = None
                for c in nml_doc.cells:
                    if c.id == id1:
                        cell = c
                        
                if variable == 'channelDensity':
                    
                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.id == id2:
                            chanDens = cd
                            
                    chanDens.cond_density = '%s %s'%(value, units)
                    
                elif variable == 'erev_id': # change all values of erev in channelDensity elements with only this id
                    
                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.id == id2:
                            chanDens = cd
                            
                    chanDens.erev = '%s %s'%(value, units)
                    
                elif variable == 'erev_ion': # change all values of erev in channelDensity elements with this ion
                    
                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.ion == id2:
                            chanDens = cd
                            
                    chanDens.erev = '%s %s'%(value, units)
                    
                elif variable == 'specificCapacitance': 
                    
                    specCap = None
                    for sc in cell.biophysical_properties.membrane_properties.specific_capacitances:
                        if (sc.segment_groups == None and id2 == 'all') or sc.segment_groups == id2 :
                            specCap = sc
                            
                    specCap.value = '%s %s'%(value, units)
                    
                else:
                    print_comment_v('Unknown variable (%s) in variable expression: %s'%(variable, var_name))
                    exit()
                
            elif type == 'izhikevich2007Cell':
                izhcell = None
                for c in nml_doc.izhikevich2007_cells:
                    if c.id == id1:
                        izhcell = c
                        
                izhcell.__setattr__(variable, '%s %s'%(value, units))
                
            else:
                print_comment_v('Unknown type (%s) in variable expression: %s'%(type, var_name))
       
                            
                                     
        new_neuroml_file =  '%s/%s'%(self.generate_dir,os.path.basename(self.neuroml_file))
        if new_neuroml_file == self.neuroml_file:
            print_comment_v('Cannot use a directory for generating into (%s) which is the same location of the NeuroML file (%s)!'% \
                      (self.neuroml_file, self.generate_dir))
                      
        write_neuroml2_file(nml_doc, new_neuroml_file)
    
            
        sim = NeuroMLSimulation(self.ref, 
                             neuroml_file = new_neuroml_file,
                             target = self.target,
                             sim_time = self.sim_time, 
                             dt = self.dt, 
                             simulator = self.simulator, 
                             generate_dir = self.generate_dir)
        
        sim.go()
        
        if show:
            sim.show()
    
        return sim.t, sim.volts
Example #10
0
                                amplitude=stim)
    nml_doc.pulse_generators.append(pg)

    pop = 'Pop_Mitral_0_%i'%i
    # Add these to cells
    input_list = nml.InputList(id=input_id,
                             component=pg.id,
                             populations=pop)
    input = nml.Input(id='0', 
                          target="../%s[%i]"%(pop, i), 
                          destination="synapses")  
    input_list.input.append(input)
    nml_doc.networks[0].input_lists.append(input_list)
    

pynml.write_neuroml2_file(nml_doc, nml_file1)

plots = {}
saves = {}
for i in range(number_cells):
    p = []
    plots['Mitral_0_%i'%i] = p
    p.append('Pop_Mitral_0_%i/0/Mitral_0_%i/0/v'%(i,i))
    #p.append('Pop_Mitral_0_%i/0/Mitral_0_%i/681/v'%(i,i))
    #p.append('Pop_Mitral_0_%i/0/Mitral_0_%i/20/v'%(i,i))
    p.append('Pop_Mitral_0_%i/0/Mitral_0_%i/43/v'%(i,i))
    #save_plot.append('Pop_Mitral_0_%i/0/Mitral_0_%i/682/v'%(i,i))
    #save_plot.append('Pop_Mitral_0_%i/0/Mitral_0_%i/20/v'%(i,i))
    #save_plot.append('Pop_Mitral_0_%i/0/Mitral_0_%i/43/v'%(i,i))
    
print plots
Example #11
0
def exportToNML(cells):

    nml_net_file = "../NeuroML2/GranuleCells/Exported/GCnet%iG.net.nml" % len(cells)
    export_to_neuroml2(None,
                       nml_net_file,
                       includeBiophysicalProperties=False,
                       separateCellFiles=True)

    # Rename files so their cell GIDs are preserved
    for gcid in cells.keys():
        fileId = cells[gcid]['index']
        oldFile = '../NeuroML2/GranuleCells/Exported/Granule_0_%i.cell.nml' % fileId
        newFile = '../NeuroML2/GranuleCells/Exported/Granule_0_%i.cell.nml_TEMP' % gcid

        # Using TEMP files to avoid naming conflicts
        os.rename(oldFile, newFile)

    # Remove temp files after all have been renamed
    for gcid in cells.keys():
        oldFile = '../NeuroML2/GranuleCells/Exported/Granule_0_%i.cell.nml_TEMP' % gcid
        newFile = '../NeuroML2/GranuleCells/Exported/Granule_0_%i.cell.nml' % gcid
        os.rename(oldFile, newFile)


    for gcid in cells.keys():

        cell, nml_doc, nml_cell_file = readGCnml(gcid)
        
        print("Loaded GC cell %i with %i segments"%(gcid, len(cell.morphology.segments)))

        # Change cell ID to preserve GCID
        cell.id = "Granule_0_%i" % gcid

        # Change segment ids to start at 0 and increment
        exportHelper.resetRoot(cell)

        # Replace ModelViewParmSubset_N groups with all, axon, soma, dendrite groups
        buildStandardSegmentGroups(cell)

        # Add channel placeholders
        nml_doc.includes.append(neuroml.IncludeType(href="channelIncludesPLACEHOLDER"))
        cell.biophysical_properties = neuroml.BiophysicalProperties(id="biophysPLACEHOLDER")
        cell.morphology.segments.append(neuroml.Segment(id="spinePLACEHOLDER"))

        # Save the new NML
        pynml.write_neuroml2_file(nml_doc, nml_cell_file)


        # Replace placeholders with contents from GranuleCell...xml files
        replaceChannelPlaceholders(nml_cell_file)

        cell, nml_doc, nml_cell_file = readGCnml(gcid)

        # Fix the fractionAlong parent segment bug ( https://github.com/NeuroML/org.neuroml.export/issues/46 )
        exportHelper.splitSegmentAlongFraction(cell, "Seg0_priden", "priden", 0.8, "Seg0_priden2_0")

        # Orient cell along the versor
        versor = granules.granule_position_orientation(gcid)[1]

        for seg in cell.morphology.segments:
            segLength = seg.length

            if seg.parent is not None:
                parentDistal = [parent for parent in cell.morphology.segments if parent.id == seg.parent.segments][0].distal
                seg.proximal.x = parentDistal.x
                seg.proximal.y = parentDistal.y
                seg.proximal.z = parentDistal.z

            seg.distal = setAlongVersor(seg.distal, versor, seg.proximal, segLength)

        # Make sure spine is in the all group
        [group for group in cell.morphology.segment_groups if group.id == 'all'][0]\
            .includes\
            .append(neuroml.Include(segment_groups='spine_group'))\

        # and Dendrite group
        [group for group in cell.morphology.segment_groups if group.id == 'dendrite_group'][0]\
            .includes\
            .append(neuroml.Include(segment_groups='spine_group'))

        # Save orientation
        pynml.write_neuroml2_file(nml_doc, nml_cell_file)

        print(nml_cell_file)
Example #12
0
def create_olm_cell():
    """Create the complete cell.

    :returns: cell object
    """
    nml_cell_doc = NeuroMLDocument(id="oml_cell")
    cell = create_cell("olm")
    nml_cell_file = cell.id + ".cell.nml"

    # Add two soma segments
    diam = 10.0
    soma_0 = add_segment(cell,
                         prox=[0.0, 0.0, 0.0, diam],
                         dist=[0.0, 10., 0.0, diam],
                         name="Seg0_soma_0",
                         group="soma_0")

    soma_1 = add_segment(cell,
                         prox=None,
                         dist=[0.0, 10. + 10., 0.0, diam],
                         name="Seg1_soma_0",
                         parent=soma_0,
                         group="soma_0")

    # Add axon segments
    diam = 1.5
    axon_0 = add_segment(cell,
                         prox=[0.0, 0.0, 0.0, diam],
                         dist=[0.0, -75, 0.0, diam],
                         name="Seg0_axon_0",
                         parent=soma_0,
                         fraction_along=0.0,
                         group="axon_0")
    axon_1 = add_segment(cell,
                         prox=None,
                         dist=[0.0, -150, 0.0, diam],
                         name="Seg1_axon_0",
                         parent=axon_0,
                         group="axon_0")

    # Add 2 dendrite segments

    diam = 3.0
    dend_0_0 = add_segment(cell,
                           prox=[0.0, 20, 0.0, diam],
                           dist=[100, 120, 0.0, diam],
                           name="Seg0_dend_0",
                           parent=soma_1,
                           fraction_along=1,
                           group="dend_0")

    dend_1_0 = add_segment(cell,
                           prox=None,
                           dist=[177, 197, 0.0, diam],
                           name="Seg1_dend_0",
                           parent=dend_0_0,
                           fraction_along=1,
                           group="dend_0")

    dend_0_1 = add_segment(cell,
                           prox=[0.0, 20, 0.0, diam],
                           dist=[-100, 120, 0.0, diam],
                           name="Seg0_dend_1",
                           parent=soma_1,
                           fraction_along=1,
                           group="dend_1")
    dend_1_1 = add_segment(cell,
                           prox=None,
                           dist=[-177, 197, 0.0, diam],
                           name="Seg1_dend_1",
                           parent=dend_0_1,
                           fraction_along=1,
                           group="dend_1")

    # XXX: For segment groups to be correctly mapped to sections in NEURON,
    # they must include the correct neurolex ID
    for section_name in ["soma_0", "axon_0", "dend_0", "dend_1"]:
        section_group = get_seg_group_by_id(section_name, cell)
        section_group.neuro_lex_id = 'sao864921383'

    den_seg_group = get_seg_group_by_id("dendrite_group", cell)
    den_seg_group.includes.append(Include(segment_groups="dend_0"))
    den_seg_group.includes.append(Include(segment_groups="dend_1"))
    den_seg_group.properties.append(Property(tag="color", value="0.8 0 0"))

    ax_seg_group = get_seg_group_by_id("axon_group", cell)
    ax_seg_group.includes.append(Include(segment_groups="axon_0"))
    ax_seg_group.properties.append(Property(tag="color", value="0 0.8 0"))

    soma_seg_group = get_seg_group_by_id("soma_group", cell)
    soma_seg_group.includes.append(Include(segment_groups="soma_0"))

    soma_seg_group.properties.append(Property(tag="color", value="0 0 0.8"))

    # Other cell properties
    set_init_memb_potential(cell, "-67mV")
    set_resistivity(cell, "0.15 kohm_cm")
    set_specific_capacitance(cell, "1.3 uF_per_cm2")

    # channels
    # leak
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="leak_all",
                        cond_density="0.01 mS_per_cm2",
                        ion_channel="leak_chan",
                        ion_chan_def_file="olm-example/leak_chan.channel.nml",
                        erev="-67mV",
                        ion="non_specific")
    # HCNolm_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="HCNolm_soma",
                        cond_density="0.5 mS_per_cm2",
                        ion_channel="HCNolm",
                        ion_chan_def_file="olm-example/HCNolm.channel.nml",
                        erev="-32.9mV",
                        ion="h",
                        group="soma_group")
    # Kdrfast_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Kdrfast_soma",
                        cond_density="73.37 mS_per_cm2",
                        ion_channel="Kdrfast",
                        ion_chan_def_file="olm-example/Kdrfast.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="soma_group")
    # Kdrfast_dendrite
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Kdrfast_dendrite",
                        cond_density="105.8 mS_per_cm2",
                        ion_channel="Kdrfast",
                        ion_chan_def_file="olm-example/Kdrfast.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="dendrite_group")
    # Kdrfast_axon
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Kdrfast_axon",
                        cond_density="117.392 mS_per_cm2",
                        ion_channel="Kdrfast",
                        ion_chan_def_file="olm-example/Kdrfast.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="axon_group")
    # KvAolm_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="KvAolm_soma",
                        cond_density="4.95 mS_per_cm2",
                        ion_channel="KvAolm",
                        ion_chan_def_file="olm-example/KvAolm.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="soma_group")
    # KvAolm_dendrite
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="KvAolm_dendrite",
                        cond_density="2.8 mS_per_cm2",
                        ion_channel="KvAolm",
                        ion_chan_def_file="olm-example/KvAolm.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="dendrite_group")
    # Nav_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Nav_soma",
                        cond_density="10.7 mS_per_cm2",
                        ion_channel="Nav",
                        ion_chan_def_file="olm-example/Nav.channel.nml",
                        erev="50mV",
                        ion="na",
                        group="soma_group")
    # Nav_dendrite
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Nav_dendrite",
                        cond_density="23.4 mS_per_cm2",
                        ion_channel="Nav",
                        ion_chan_def_file="olm-example/Nav.channel.nml",
                        erev="50mV",
                        ion="na",
                        group="dendrite_group")
    # Nav_axon
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Nav_axon",
                        cond_density="17.12 mS_per_cm2",
                        ion_channel="Nav",
                        ion_chan_def_file="olm-example/Nav.channel.nml",
                        erev="50mV",
                        ion="na",
                        group="axon_group")

    nml_cell_doc.cells.append(cell)
    pynml.write_neuroml2_file(nml_cell_doc, nml_cell_file, True, True)
    return nml_cell_file
Example #13
0
def __main__():
    num_cells_to_export = 1

    cells = []
    for mgid in range(num_cells_to_export):
      print mgid
      cells.append(mkmitral(mgid))

    nml_net_file = "../NeuroML2/MitralCells/Exported/PartialBulb_%iMTCells.net.nml" % num_cells_to_export
    export_to_neuroml2(None, 
                       nml_net_file,
                       includeBiophysicalProperties=False,
                       separateCellFiles=True)

    for i in range(num_cells_to_export):

        print("Processing cell %i out of %i"%(i, num_cells_to_export))

        nml_cell_file = "../NeuroML2/MitralCells/Exported/Mitral_0_%i.cell.nml" % i

        nml_doc = pynml.read_neuroml2_file(nml_cell_file)

        cell = nml_doc.cells[0]

        import pydevd
        pydevd.settrace('10.211.55.3', port=4200, stdoutToServer=True, stderrToServer=True, suspend=True)
        
        # Set root to id=0 and increment others
        exportHelper.resetRoot(cell)

        somaSeg = [seg for seg in cell.morphology.segments if seg.name == "Seg0_soma"][0]
        initialSeg = [seg for seg in cell.morphology.segments if seg.name == "Seg0_initialseg"][0]
        hillockSeg = [seg for seg in cell.morphology.segments if seg.name == "Seg0_hillock"][0]

        # Fix initial and hillock segs by moving them to the soma
        hillockSeg.proximal = pointMovedByOffset(hillockSeg.proximal, somaSeg.distal)
        hillockSeg.distal = pointMovedByOffset(hillockSeg.distal, somaSeg.distal)
        initialSeg.proximal = pointMovedByOffset(initialSeg.proximal, somaSeg.distal)
        initialSeg.distal = pointMovedByOffset(initialSeg.distal, somaSeg.distal)

        # Move everything back to the origin
        originOffset = type("", (), dict(x = -somaSeg.proximal.x, y = -somaSeg.proximal.y, z = -somaSeg.proximal.z ))()

        for seg in cell.morphology.segments:
            seg.proximal = pointMovedByOffset(seg.proximal, originOffset)
            seg.distal =   pointMovedByOffset(seg.distal, originOffset)

        # Replace ModelViewParmSubset_N groups with all, axon, soma, dendrite groups
        buildStandardSegmentGroups(cell)

        # Add channel placeholders
        nml_doc.includes.append(neuroml.IncludeType(href="channelIncludesPLACEHOLDER"))
        cell.biophysical_properties = neuroml.BiophysicalProperties(id="biophysPLACEHOLDER")

        # Save the new NML
        pynml.write_neuroml2_file(nml_doc, nml_cell_file)

        # Replace placeholders with contents from MitralCell...xml files
        replaceChannelPlaceholders(nml_cell_file)

        print("COMPLETED: " + nml_cell_file)

    print("DONE")
Example #14
0
def generate_current_vs_frequency_curve(nml2_file, 
                                        cell_id, 
                                        start_amp_nA, 
                                        end_amp_nA, 
                                        step_nA, 
                                        analysis_duration, 
                                        analysis_delay, 
                                        dt = 0.05,
                                        temperature = "32degC",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        plot_if=True,
                                        plot_iv=False,
                                        xlim_if =              None,
                                        ylim_if =              None,
                                        xlim_iv =              None,
                                        ylim_iv =              None,
                                        show_plot_already=True, 
                                        save_if_figure_to=None, 
                                        save_iv_figure_to=None, 
                                        simulator="jNeuroML",
                                        include_included=True):
                                            
                                            
    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np
    
    print_comment_v("Generating FI curve for cell %s in %s using %s (%snA->%snA; %snA steps)"%
        (cell_id, nml2_file, simulator, start_amp_nA, end_amp_nA, step_nA))
    
    sim_id = 'iv_%s'%cell_id
    duration = analysis_duration+analysis_delay
    ls = LEMSSimulation(sim_id, duration, dt)
    
    ls.include_neuroml2_file(nml2_file, include_included=include_included)
    
    stims = []
    amp = start_amp_nA
    while amp<=end_amp_nA : 
        stims.append(amp)
        amp+=step_nA
        
    
    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s"%cell_id,
                        component=cell_id,
                        size=number_cells)
    

    # create network and add populations
    net_id = "network_of_%s"%cell_id
    net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(nml2_file))
    net.populations.append(pop)
    
    for i in range(number_cells):
        stim_amp = "%snA"%stims[i]
        input_id = ("input_%s"%stim_amp).replace('.','_').replace('-','min')
        pg = nml.PulseGenerator(id=input_id,
                                    delay="0ms",
                                    duration="%sms"%duration,
                                    amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id,
                                 component=pg.id,
                                 populations=pop.id)
        input = nml.Input(id='0', 
                              target="../%s[%i]"%(pop.id, i), 
                              destination="synapses")  
        input_list.input.append(input)
        net.input_lists.append(input_list)
    
    
    net_file_name = '%s.net.nml'%sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)
    
    disp0 = 'Voltage_display'
    ls.create_display(disp0,"Voltages", "-90", "50")
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat"%sim_id)
    
    for i in range(number_cells):
        ref = "v_cell%i"%i
        quantity = "%s[%i]/v"%(pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color())
    
        ls.add_column_to_output_file(of0, ref, quantity)
    
    lems_file_name = ls.save_to_file()
    
    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
                                                
    
    #print(results.keys())
    if_results = {}
    iv_results = {}
    for i in range(number_cells):
        t = np.array(results['t'])*1000
        v = np.array(results["%s[%i]/v"%(pop.id, i)])*1000
        
        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm['maxima_times']
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= analysis_delay and s < (analysis_duration+analysis_delay):
                    count+=1
            freq = 1000 * count/float(analysis_duration)
                    
        mean_freq = mean_spike_frequency(spike_times) 
        # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq
        
        if freq == 0:
            iv_results[stims[i]] = v[-1]
        
    if plot_if:
        
        stims = sorted(if_results.keys())
        stims_pA = [ii*1000 for ii in stims]
        
        freqs = [if_results[s] for s in stims]
            
        pynml.generate_plot([stims_pA],
                            [freqs], 
                            "Frequency versus injected current for: %s"%nml2_file, 
                            colors = ['k'], 
                            linestyles=['-'],
                            markers=['o'],
                            xaxis = 'Input current (pA)', 
                            yaxis = 'Firing frequency (Hz)',
                            xlim = xlim_if,
                            ylim = ylim_if,
                            grid = True,
                            show_plot_already=False,
                            save_figure_to = save_if_figure_to)
    if plot_iv:
        
        stims = sorted(iv_results.keys())
        stims_pA = [ii*1000 for ii in sorted(iv_results.keys())]
        vs = [iv_results[s] for s in stims]
            
        pynml.generate_plot([stims_pA],
                            [vs], 
                            "Final membrane potential versus injected current for: %s"%nml2_file, 
                            colors = ['k'], 
                            linestyles=['-'],
                            markers=['o'],
                            xaxis = 'Input current (pA)', 
                            yaxis = 'Membrane potential (mV)', 
                            xlim = xlim_iv,
                            ylim = ylim_iv,
                            grid = True,
                            show_plot_already=False,
                            save_figure_to = save_iv_figure_to)
    
    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()
        
        
    return if_results
Example #15
0
def create_GoC_network( duration, dt, seed, N_goc=0, run=False, prob_type='Boltzmann', GJw_type='Vervaeke2010' ):


	goc_filename = 'GoC.cell.nml'
	goc_file = pynml.read_neuroml2_file( goc_filename )
	goc_type = goc_file.cells[0]
	
	GJ_filename = 'GapJuncCML.nml'
	GJ_file = pynml.read_neuroml2_file( GJ_filename )
	GJ_type = GJ_file.gap_junctions[0]

	MFSyn_filename = 'MF_GoC_Syn.nml'
	mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename )
	MFSyn_type = mfsyn_file.exp_three_synapses[0]
	
	MF20Syn_filename = 'MF_GoC_SynMult.nml'
	mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename )
	MF20Syn_type = mf20syn_file.exp_three_synapses[0]
	
	# Distribute cells in 3D
	if N_goc>0:
		GoC_pos = nu.GoC_locate(N_goc)
	else:
		GoC_pos = nu.GoC_density_locate()
		N_goc = GoC_pos.shape[0]
		
	# get GJ connectivity
	GJ_pairs, GJWt = nu.GJ_conn( GoC_pos, prob_type, GJw_type )
	tmp1, tmp2 = valnet.gapJuncAnalysis( GJ_pairs, GJWt )
	print("Number of gap junctions per cell: ", tmp1)
	print("Net GJ conductance per cell:", tmp2)
	
	# Create pop List
	goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=N_goc )
	
	# Create NML document for network specification
	net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" )
	net_doc = nml.NeuroMLDocument( id=net.id )
	net_doc.networks.append( net )
	net_doc.includes.append( goc_type )
	
	net.populations.append( goc_pop )
	
	#Add locations for GoC instances in the population:
	for goc in range(N_goc):
		inst = nml.Instance( id=goc )
		goc_pop.instances.append( inst )
		inst.location = nml.Location( x=GoC_pos[goc,0], y=GoC_pos[goc,1], z=GoC_pos[goc,2] )
		
	# Define input spiketrains
	input_type = 'spikeGenerator'#'spikeGeneratorPoisson'
	lems_inst_doc = lems.Model()
	mf_inputs = lems.Component( "MF_Input", input_type)
	mf_inputs.set_parameter("period", "2000 ms" )
	#mf_inputs.set_parameter("averageRate", "50 Hz")
	lems_inst_doc.add( mf_inputs )
	
	#synapse_type = 'alphaCurrentSynapse'
	#alpha_syn = lems.Component( "AlphaSyn", synapse_type)
	#alpha_syn.set_parameter("tau", "30 ms" )
	#alpha_syn.set_parameter("ibase", "200 pA")
	#lems_inst_doc.add( alpha_syn )
	
	# Define MF input population
	
	N_mf = 15
	#MF_pop = nml.Population(id=mf_inputs.id+"_pop", component=mf_inputs.id, type="populationList", size=N_mf)
	#net.populations.append( MF_pop )

	mf_type2 = 'spikeGeneratorPoisson'
	#mf_poisson = lems.Component( "MF_Poisson", mf_type2)
	#mf_poisson.set_parameter("averageRate", "5 Hz")
	#lems_inst_doc.add( mf_poisson )
	# adding in neuroml document instead of mf_poisson
	mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" )
	net_doc.spike_generator_poissons.append( mf_poisson )
	
	net_doc.includes.append( goc_type )
	MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=N_mf)
	net.populations.append( MF_Poisson_pop )
	MF_pos = nu.GoC_locate( N_mf )
	for mf in range( N_mf ):
		inst = nml.Instance(id=mf)
		MF_Poisson_pop.instances.append( inst )
		inst.location = nml.Location( x=MF_pos[mf,0], y=MF_pos[mf,1], z=MF_pos[mf,2] )
		
	# Setup Mf->GoC synapses
	#MFprojection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_pop.id, postsynaptic_population=goc_pop.id, synapse=alpha_syn.id)
	#net.projections.append(MFprojection)

	MF2projection = nml.Projection(id="MF2toGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id)#alpha_syn.id
	net.projections.append(MF2projection)


	#Get list of MF->GoC synapse
	mf_synlist = nu.randdist_MF_syn( N_mf, N_goc, pConn=0.3)
	nMFSyn = mf_synlist.shape[1]
	for syn in range( nMFSyn ):
		mf, goc = mf_synlist[:, syn]
		conn2 = nml.Connection(id=syn, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		MF2projection.connections.append(conn2)
		
		
	# Burst of MF input (as explicit input)
	mf_bursttype = 'transientPoissonFiringSynapse'
	mf_burst = lems.Component( "MF_Burst", mf_bursttype)
	mf_burst.set_parameter( "averageRate", "100 Hz" )
	mf_burst.set_parameter( "delay", "2000 ms" )
	mf_burst.set_parameter( "duration", "500 ms" )
	mf_burst.set_parameter( "synapse", MF20Syn_type.id )
	mf_burst.set_parameter( "spikeTarget", './{}'.format(MF20Syn_type.id) )
	lems_inst_doc.add( mf_burst )
	
	
	# Add few burst inputs
	n_bursts = 4
	gocPerm = np.random.permutation( N_goc )
	ctr = 0
	for gg in range(4):
		goc = gocPerm[gg]
		for jj in range( n_bursts ):
			inst = nml.ExplicitInput( id=ctr, target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), input=mf_burst.id, synapse=MF20Syn_type.id, spikeTarget='./{}'.format(MF20Syn_type.id))
			net.explicit_inputs.append( inst )
			ctr += 1
		
	
	'''
	one-to-one pairing of MF and GoC -> no shared inputs
	for goc in range(N_mf):
		#inst = nml.Instance(id=goc)
		#MF_pop.instances.append( inst )
		#inst.location = nml.Location( x=GoC_pos[goc,0], y=GoC_pos[goc,1], z=GoC_pos[goc,2]+100 )
		#conn = nml.Connection(id=goc, pre_cell_id='../{}/{}/{}'.format(MF_pop.id, goc, mf_inputs.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		#MFprojection.connections.append(conn)

		goc2 = N_goc-goc-1
		inst2 = nml.Instance(id=goc)
		MF_Poisson_pop.instances.append( inst2 )
		inst2.location = nml.Location( x=GoC_pos[goc2,0], y=GoC_pos[goc2,1], z=GoC_pos[goc2,2]+100 )
		conn2 = nml.Connection(id=goc, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, goc, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc2, goc_type.id), post_segment_id='0', post_fraction_along="0.5")
		MF2projection.connections.append(conn2)

	'''
	
	# Add electrical synapses
	GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id )
	
	#print(GJ_pairs)
	gj = nml.GapJunction( id="GJ_0", conductance="426pS" )
	net_doc.gap_junctions.append(gj)
	nGJ = GJ_pairs.shape[0]
	for jj in range( nGJ ):
		#gj.append( lems.Component( "GJ_%d"%jj, 'gapJunction') )
		#gj[jj].set_parameter( "conductance", "%fnS"%(GJWt[jj]) )
		#gj = nml.GapJunction(id="GJ_%d"%jj, conductance="%fnS"%(GJWt[jj]))
		#net_doc.gap_junctions.append(gj)
		#lems_inst_doc.add( gj[jj] )
		#print("%fnS"%(GJWt[jj]*0.426))
		conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj,0], goc_type.id), pre_segment='1', pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj,1], goc_type.id), post_segment='1', post_fraction_along='0.5', synapse=gj.id, weight=GJWt[jj] )#synapse="GapJuncCML" synapse=gj.id , conductance="100E-9mS"
		# ------------ need to create GJ component
		GoCCoupling.electrical_connection_instance_ws.append( conn )
	
	net.electrical_projections.append( GoCCoupling )	
		
		
		
	net_filename = 'gocNetwork.nml'
	pynml.write_neuroml2_file( net_doc, net_filename )
	lems_filename = 'instances.xml'
	pynml.write_lems_file( lems_inst_doc, lems_filename, validate=False )

	simid = 'sim_gocnet'+goc_type.id
	ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed )
	ls.assign_simulation_target( net.id )
	
	#ls.include_lems_file( 'Synapses.xml', include_included=False)
	#ls.include_lems_file( 'Inputs.xml', include_included=False)
	ls.include_neuroml2_file( net_filename)
	ls.include_neuroml2_file( goc_filename)
	ls.include_neuroml2_file( GJ_filename)
	ls.include_neuroml2_file( MFSyn_filename)
	ls.include_neuroml2_file( MF20Syn_filename)
	ls.include_lems_file( lems_filename, include_included=False)
	
	
	# Specify outputs
	eof0 = 'Events_file'
	ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME')
	for jj in range( goc_pop.size):
		ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format( goc_pop.id, jj, goc_type.id), 'spike' )
		
	of0 = 'Volts_file'
	ls.create_output_file(of0, "%s.v.dat"%simid)
	for jj in range( goc_pop.size ):
		ls.add_column_to_output_file(of0, jj, '{}/{}/{}/v'.format( goc_pop.id, jj, goc_type.id))
		
	#Create Lems file to run
	lems_simfile = ls.save_to_file()

	#res = pynml.run_lems_with_jneuroml( lems_simfile, max_memory="1G",nogui=True, plot=False)
	#res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False)
	res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", compile_mods = False,nogui=True, plot=False)
	#res=True
	return res
def generate_grc_layer_network(
        runID,
        correlationRadius,
        NADT,
        duration,
        dt,
        minimumISI,  # ms
        ONRate,  # Hz
        OFFRate,  # Hz
        run=False):
    ########################################
    # Load parameters for this run
    file = open('../params_file.pkl', 'r')
    p = pkl.load(file)
    N_syn = p['N_syn'][int(runID) - 1]
    f_mf = p['f_mf'][int(runID) - 1]
    run_num = p['run_num'][int(runID) - 1]
    file.close()
    #################################################################################
    # Get connectivity matrix between cells
    file = open('../../network_structures/GCLconnectivity_' + str(N_syn) +
                '.pkl')
    p = pkl.load(file)
    conn_mat = p['conn_mat']
    N_mf, N_grc = conn_mat.shape
    assert (np.all(conn_mat.sum(
        axis=0) == N_syn)), 'Connectivity matrix is incorrect.'
    # Get MF activity pattern
    if correlationRadius == 0:  # Activate MFs randomly
        N_mf_ON = int(N_mf * f_mf)
        mf_indices_ON = random.sample(range(N_mf), N_mf_ON)
        mf_indices_ON.sort()
    elif correlationRadius > 0:  # Spatially correlated MFs
        f_mf_range = np.linspace(.05, .95, 19)
        f_mf_ix = np.where(f_mf_range == f_mf)[0][0]
        p = io.loadmat('../../input_statistics/mf_patterns_r' +
                       str(correlationRadius) + '.mat')
        R = p['Rs'][:, :, f_mf_ix]
        g = p['gs'][f_mf_ix]
        t = np.dot(R.transpose(), np.random.randn(N_mf))
        S = (t > -g * np.ones(N_mf))
        mf_indices_ON = np.where(S)[0]
        N_mf_ON = len(mf_indices_ON)
    #
    N_mf_OFF = N_mf - N_mf_ON
    mf_indices_OFF = [x for x in range(N_mf) if x not in mf_indices_ON]
    mf_indices_OFF.sort()
    #################################################################################
    # load NeuroML components, LEMS components and LEMS componentTypes from external files
    # Spike generator (for Poisson MF spiking)
    spike_generator_file_name = "../../grc_lemsDefinitions/spikeGenerators.xml"
    spike_generator_doc = pynml.read_lems_file(spike_generator_file_name)
    # Integrate-and-fire GC model
    # if NADT = 1, loads model GC
    iaf_nml2_file_name = "../../grc_lemsDefinitions/IaF_GrC.nml" if NADT == 0 else "../../grc_lemsDefinitions/IaF_GrC_" + '{:.2f}'.format(
        f_mf) + ".nml"
    iaF_GrC_doc = pynml.read_neuroml2_file(iaf_nml2_file_name)
    iaF_GrC = iaF_GrC_doc.iaf_ref_cells[0]
    # AMPAR and NMDAR mediated synapses
    ampa_syn_filename = "../../grc_lemsDefinitions/RothmanMFToGrCAMPA_" + str(
        N_syn) + ".xml"
    nmda_syn_filename = "../../grc_lemsDefinitions/RothmanMFToGrCNMDA_" + str(
        N_syn) + ".xml"
    rothmanMFToGrCAMPA_doc = pynml.read_lems_file(ampa_syn_filename)
    rothmanMFToGrCNMDA_doc = pynml.read_lems_file(nmda_syn_filename)
    #
    # Define components from the componentTypes we just loaded
    # Refractory poisson input -- representing active MF
    spike_generator_ref_poisson_type = spike_generator_doc.component_types[
        'spikeGeneratorRefPoisson']
    lems_instances_doc = lems.Model()
    spike_generator_on = lems.Component("mossySpikerON",
                                        spike_generator_ref_poisson_type.name)
    spike_generator_on.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_on.set_parameter("averageRate", "%s Hz" % ONRate)
    lems_instances_doc.add(spike_generator_on)
    # Refractory poisson input -- representing silent MF
    spike_generator_off = lems.Component("mossySpikerOFF",
                                         spike_generator_ref_poisson_type.name)
    spike_generator_off.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_off.set_parameter("averageRate", "%s Hz" % OFFRate)
    lems_instances_doc.add(spike_generator_off)
    # Synapses
    rothmanMFToGrCAMPA = rothmanMFToGrCAMPA_doc.components[
        'RothmanMFToGrCAMPA'].id
    rothmanMFToGrCNMDA = rothmanMFToGrCNMDA_doc.components[
        'RothmanMFToGrCNMDA'].id
    #
    # Create ON MF, OFF MF, and GC populations
    GrCPop = nml.Population(id="GrCPop", component=iaF_GrC.id, size=N_grc)
    mossySpikersPopON = nml.Population(id=spike_generator_on.id + "Pop",
                                       component=spike_generator_on.id,
                                       size=N_mf_ON)
    mossySpikersPopOFF = nml.Population(id=spike_generator_off.id + "Pop",
                                        component=spike_generator_off.id,
                                        size=N_mf_OFF)
    #
    # Create network and add populations
    net = nml.Network(id="network")
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net.populations.append(GrCPop)
    net.populations.append(mossySpikersPopON)
    net.populations.append(mossySpikersPopOFF)
    #
    # MF-GC connectivity
    # First connect ON MFs to GCs
    for mf_ix_ON in range(N_mf_ON):
        mf_ix = mf_indices_ON[mf_ix_ON]
        # Find which GCs are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            # Add AMPAR and NMDAR mediated synapses
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.SynapticConnection(
                    from_='{}[{}]'.format(mossySpikersPopON.id, mf_ix_ON),
                    synapse=synapse,
                    to='GrCPop[{}]'.format(grc_ix))
                net.synaptic_connections.append(connection)
    #
    # Now connect OFF MFs to GCs
    for mf_ix_OFF in range(N_mf_OFF):
        mf_ix = mf_indices_OFF[mf_ix_OFF]
        # Find which GCs are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            # Add AMPAR and NMDAR mediated synapses
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.SynapticConnection(
                    from_='{}[{}]'.format(mossySpikersPopOFF.id, mf_ix_OFF),
                    synapse=synapse,
                    to='GrCPop[{}]'.format(grc_ix))
                net.synaptic_connections.append(connection)
    #
    # Write network to file
    net_file_name = 'generated_network_' + runID + '.net.nml'
    pynml.write_neuroml2_file(net_doc, net_file_name)
    # Write LEMS instances to file
    lems_instances_file_name = 'instances_' + runID + '.xml'
    pynml.write_lems_file(lems_instances_doc,
                          lems_instances_file_name,
                          validate=False)
    # Create a LEMSSimulation to manage creation of LEMS file
    ls = LEMSSimulation('sim_' + runID,
                        duration,
                        dt,
                        lems_seed=int(np.round(1000 * random.random())))
    # Point to network as target of simulation
    ls.assign_simulation_target(net.id)
    # Include generated/existing NeuroML2 files
    ls.include_neuroml2_file(iaf_nml2_file_name)
    ls.include_lems_file(spike_generator_file_name, include_included=False)
    ls.include_lems_file(lems_instances_file_name)
    ls.include_lems_file(ampa_syn_filename, include_included=False)
    ls.include_lems_file(nmda_syn_filename, include_included=False)
    ls.include_neuroml2_file(net_file_name)
    # Specify Displays and Output Files
    # Details for saving output files
    basedir = '../data_r' + str(
        correlationRadius) + '/' if NADT == 0 else '../data_r' + str(
            correlationRadius) + '_NADT/'
    end_filename = str(N_syn) + '_{:.2f}'.format(f_mf) + '_' + str(
        run_num)  # Add parameter values to spike time filename
    # Save MF spike times under basedir + MF_spikes_ + end_filename
    eof0 = 'MFspikes_file'
    ls.create_event_output_file(eof0,
                                basedir + "MF_spikes_" + end_filename + ".dat")
    # ON MFs
    for i in range(mossySpikersPopON.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_ON[i], "%s[%i]" % (mossySpikersPopON.id, i),
            'spike')
    # OFF MFs
    for i in range(mossySpikersPopOFF.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_OFF[i], "%s[%i]" % (mossySpikersPopOFF.id, i),
            'spike')
    # Save GC spike times under basedir + GrC_spikes_ + end_filename
    eof1 = 'GrCspikes_file'
    ls.create_event_output_file(
        eof1, basedir + "GrC_spikes_" + end_filename + ".dat")
    #
    for i in range(GrCPop.size):
        ls.add_selection_to_event_output_file(eof1, i,
                                              "%s[%i]" % (GrCPop.id, i),
                                              'spike')
    #
    lems_file_name = ls.save_to_file()
    #
    if run:
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               max_memory="8G",
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False)

        return results
Example #17
0
def generate_grc_layer_network(
        p_mf_ON,
        duration,
        dt,
        minimumISI,  # ms
        ONRate,  # Hz 
        OFFRate,  # Hz
        run=False):

    # Load connectivity matrix

    file = open('GCLconnectivity.pkl')
    p = pkl.load(file)
    conn_mat = p['conn_mat']
    N_mf, N_grc = conn_mat.shape
    assert (np.all(conn_mat.sum(
        axis=0) == 4)), 'Connectivity matrix is incorrect.'

    # Load GrC and MF rosette positions

    grc_pos = p['grc_pos']
    glom_pos = p['glom_pos']

    # Choose which mossy fibers are on, which are off

    N_mf_ON = int(N_mf * p_mf_ON)
    mf_indices_ON = random.sample(range(N_mf), N_mf_ON)
    mf_indices_ON.sort()

    N_mf_OFF = N_mf - N_mf_ON
    mf_indices_OFF = [x for x in range(N_mf) if x not in mf_indices_ON]
    mf_indices_OFF.sort()

    # load NeuroML components, LEMS components and LEMS componentTypes from external files

    ##spikeGeneratorRefPoisson is now a standard nml type...
    ##spike_generator_doc = pynml.read_lems_file(spike_generator_file_name)

    iaF_GrC = nml.IafRefCell(id="iaF_GrC",
                             refract="2ms",
                             C="3.22pF",
                             thresh="-40mV",
                             reset="-63mV",
                             leak_conductance="1.498nS",
                             leak_reversal="-79.67mV")

    ampa_syn_filename = "RothmanMFToGrCAMPA.xml"
    nmda_syn_filename = "RothmanMFToGrCNMDA.xml"

    rothmanMFToGrCAMPA_doc = pynml.read_lems_file(ampa_syn_filename)
    rothmanMFToGrCNMDA_doc = pynml.read_lems_file(nmda_syn_filename)

    # define some components from the componentTypes we just loaded
    ##spike_generator_ref_poisson_type = spike_generator_doc.component_types['spikeGeneratorRefPoisson']

    lems_instances_doc = lems.Model()
    spike_generator_ref_poisson_type_name = 'spikeGeneratorRefPoisson'

    spike_generator_on = lems.Component("mossySpikerON",
                                        spike_generator_ref_poisson_type_name)
    spike_generator_on.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_on.set_parameter("averageRate", "%s Hz" % ONRate)
    lems_instances_doc.add(spike_generator_on)

    spike_generator_off = lems.Component(
        "mossySpikerOFF", spike_generator_ref_poisson_type_name)
    spike_generator_off.set_parameter("minimumISI", "%s ms" % minimumISI)
    spike_generator_off.set_parameter("averageRate", "%s Hz" % OFFRate)
    lems_instances_doc.add(spike_generator_off)

    rothmanMFToGrCAMPA = rothmanMFToGrCAMPA_doc.components[
        'RothmanMFToGrCAMPA'].id
    rothmanMFToGrCNMDA = rothmanMFToGrCNMDA_doc.components[
        'RothmanMFToGrCNMDA'].id

    # create populations
    GrCPop = nml.Population(id=iaF_GrC.id + "Pop",
                            component=iaF_GrC.id,
                            type="populationList",
                            size=N_grc)
    GrCPop.properties.append(nml.Property(tag='color', value='0 0 0.8'))
    GrCPop.properties.append(nml.Property(tag='radius', value=2))
    mossySpikersPopON = nml.Population(id=spike_generator_on.id + "Pop",
                                       component=spike_generator_on.id,
                                       type="populationList",
                                       size=N_mf_ON)
    mossySpikersPopON.properties.append(
        nml.Property(tag='color', value='0.8 0 0'))
    mossySpikersPopON.properties.append(nml.Property(tag='radius', value=2))
    mossySpikersPopOFF = nml.Population(id=spike_generator_off.id + "Pop",
                                        component=spike_generator_off.id,
                                        size=N_mf_OFF)
    mossySpikersPopOFF.properties.append(
        nml.Property(tag='color', value='0 0.8 0'))
    mossySpikersPopOFF.properties.append(nml.Property(tag='radius', value=2))

    # create network and add populations
    net = nml.Network(id="network")
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.iaf_ref_cells.append(iaF_GrC)
    net.populations.append(GrCPop)
    net.populations.append(mossySpikersPopON)
    net.populations.append(mossySpikersPopOFF)

    #net_doc.includes.append(nml.IncludeType(href=iaf_nml2_file_name))

    # Add locations for GCs

    for grc in range(N_grc):
        inst = nml.Instance(id=grc)
        GrCPop.instances.append(inst)
        inst.location = nml.Location(x=grc_pos[grc, 0],
                                     y=grc_pos[grc, 1],
                                     z=grc_pos[grc, 2])

    # ON MFs: locations and connectivity

    ONprojectionAMPA = nml.Projection(
        id="ONProjAMPA",
        presynaptic_population=mossySpikersPopON.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCAMPA)
    ONprojectionNMDA = nml.Projection(
        id="ONProjNMDA",
        presynaptic_population=mossySpikersPopON.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCNMDA)
    net.projections.append(ONprojectionAMPA)
    net.projections.append(ONprojectionNMDA)

    ix = 0
    for mf_ix_ON in range(N_mf_ON):
        mf_ix = mf_indices_ON[mf_ix_ON]
        inst = nml.Instance(id=mf_ix_ON)
        mossySpikersPopON.instances.append(inst)
        inst.location = nml.Location(x=glom_pos[mf_ix, 0],
                                     y=glom_pos[mf_ix, 1],
                                     z=glom_pos[mf_ix, 2])
        # find which granule cells are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.Connection(
                    id=ix,
                    pre_cell_id='../{}/{}/{}'.format(mossySpikersPopON.id,
                                                     mf_ix_ON,
                                                     spike_generator_on.id),
                    post_cell_id='../{}/{}/{}'.format(GrCPop.id, grc_ix,
                                                      iaF_GrC.id))
                ONprojectionAMPA.connections.append(connection)
                ONprojectionNMDA.connections.append(connection)
                ix = ix + 1

    # OFF MFs: locations and connectivity

    OFFprojectionAMPA = nml.Projection(
        id="OFFProjAMPA",
        presynaptic_population=mossySpikersPopOFF.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCAMPA)
    OFFprojectionNMDA = nml.Projection(
        id="OFFProjNMDA",
        presynaptic_population=mossySpikersPopOFF.id,
        postsynaptic_population=GrCPop.id,
        synapse=rothmanMFToGrCNMDA)
    net.projections.append(OFFprojectionAMPA)
    net.projections.append(OFFprojectionNMDA)

    ix = 0
    for mf_ix_OFF in range(N_mf_OFF):
        mf_ix = mf_indices_OFF[mf_ix_OFF]
        inst = nml.Instance(id=mf_ix_OFF)
        mossySpikersPopOFF.instances.append(inst)
        inst.location = nml.Location(x=glom_pos[mf_ix, 0],
                                     y=glom_pos[mf_ix, 1],
                                     z=glom_pos[mf_ix, 2])
        # find which granule cells are neighbors
        innervated_grcs = np.where(conn_mat[mf_ix, :] == 1)[0]
        for grc_ix in innervated_grcs:
            for synapse in [rothmanMFToGrCAMPA, rothmanMFToGrCNMDA]:
                connection = nml.Connection(
                    id=ix,
                    pre_cell_id='../{}/{}/{}'.format(mossySpikersPopOFF.id,
                                                     mf_ix_OFF,
                                                     spike_generator_on.id),
                    post_cell_id='../{}/{}/{}'.format(GrCPop.id, grc_ix,
                                                      iaF_GrC.id))
                OFFprojectionAMPA.connections.append(connection)
                OFFprojectionNMDA.connections.append(connection)
                ix = ix + 1

    # Write network to file
    net_file_name = 'OSBnet.nml'
    pynml.write_neuroml2_file(net_doc, net_file_name)

    # Write LEMS instances to file
    lems_instances_file_name = 'instances.xml'
    pynml.write_lems_file(lems_instances_doc,
                          lems_instances_file_name,
                          validate=False)

    # Create a LEMSSimulation to manage creation of LEMS file
    ls = LEMSSimulation(
        'sim', duration, dt,
        simulation_seed=123)  # int(np.round(1000*random.random())))

    # Point to network as target of simulation
    ls.assign_simulation_target(net.id)

    # Include generated/existing NeuroML2 files
    ###ls.include_lems_file(spike_generator_file_name, include_included=False)
    ls.include_lems_file(lems_instances_file_name)
    ls.include_lems_file(ampa_syn_filename, include_included=False)
    ls.include_lems_file(nmda_syn_filename, include_included=False)
    ls.include_neuroml2_file(net_file_name)

    # Specify Displays and Output Files

    basedir = ''

    eof0 = 'Volts_file'
    ls.create_event_output_file(eof0, basedir + "MF_spikes.dat")

    for i in range(mossySpikersPopON.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_ON[i], '{}/{}/{}'.format(mossySpikersPopON.id, i,
                                                      spike_generator_on.id),
            'spike')

    for i in range(mossySpikersPopOFF.size):
        ls.add_selection_to_event_output_file(
            eof0, mf_indices_OFF[i],
            '{}/{}/{}'.format(mossySpikersPopOFF.id, i,
                              spike_generator_on.id), 'spike')

    eof1 = 'GrCspike_file'
    ls.create_event_output_file(eof1, basedir + "GrC_spikes.dat")

    for i in range(GrCPop.size):
        ls.add_selection_to_event_output_file(
            eof1, i, '{}/{}/{}'.format(GrCPop.id, i, iaF_GrC.id), 'spike')

    lems_file_name = ls.save_to_file()

    if run:
        print('Running the generated LEMS file: %s for simulation of %sms' %
              (lems_file_name, duration))
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               max_memory="8G",
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False)

        return results
def generate_network_for_sweeps(cell_type, dataset_id, cell_file_name, cell_id, target_dir, data_dir="../../data"):

    target_sweep_numbers = DH.DATASET_TARGET_SWEEPS[dataset_id]

    net_id = "network_%s_%s"%(dataset_id, cell_type)
    net = neuroml.Network(id=net_id, type="networkWithTemperature", temperature=DH.SIMULATION_TEMPERATURE)


    net_doc = neuroml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)

    net_doc.includes.append(neuroml.IncludeType(cell_file_name))


    number_cells = len(target_sweep_numbers)
    pop = neuroml.Population(id="Pop0",
                        component=cell_id,
                        size=number_cells,
                        type="populationList")
                        
    net.populations.append(pop)
    for i in range(number_cells):
        location = neuroml.Location(x=100*i,y=0,z=0)
        pop.instances.append(neuroml.Instance(id=i,location=location))

    print target_sweep_numbers
    f = "%s/%s_analysis.json"%(data_dir,dataset_id)
    with open(f, "r") as json_file:
        data = json.load(json_file) 

    id = data['data_set_id']
    sweeps = data['sweeps']

    print("Looking at data analysis in %s (dataset: %s)"%(f,id))

    index = 0
    for s in target_sweep_numbers:
        current = float(sweeps['%i'%s]["sweep_metadata"]["aibs_stimulus_amplitude_pa"])
        print("Sweep %s (%s pA)"%(s, current))

        stim_amp = "%s pA"%current
        input_id = ("input_%i"%s)
        pg = neuroml.PulseGenerator(id=input_id,
                                    delay="270ms",
                                    duration="1000ms",
                                    amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        input_list = neuroml.InputList(id=input_id,
                                 component=pg.id,
                                 populations=pop.id)
        input = neuroml.Input(id='0', 
                              target="../%s/%i/%s"%(pop.id, index, cell_id), 
                              destination="synapses")
        index+=1
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = '%s/%s.net.nml'%(target_dir,net_id)
    
    print("Saving generated network to: %s"%net_file_name)
    pynml.write_neuroml2_file(net_doc, net_file_name)
    
    return net_file_name
def create_GoC_network(duration=2000,
                       dt=0.025,
                       seed=123,
                       runid=0,
                       run=False,
                       minI=-75,
                       maxI=200,
                       iStep=25,
                       iDur=400,
                       iRest=500):

    file = open('useParams_SpontFreq_7_pm_2.pkl', 'rb')
    use_params = pkl.load(file)["useParams"]
    file.close()

    runid = use_params[0][runid]
    print('Using parameter set = ', runid)
    ### ---------- Component types
    gocID = 'GoC_' + format(runid, '05d')
    goc_filename = '{}.cell.nml'.format(gocID)
    goc_type = pynml.read_neuroml2_file(goc_filename).cells[0]

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id='GoCNet_' + format(runid, '05d'),
                      type="networkWithTemperature",
                      temperature="23 degC")

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=1)
    inst = nml.Instance(id=0)
    goc_pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(goc_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(href=goc_filename))

    # Add Current Injection
    ctr = 0
    goc = 0
    p = {
        "iAmp": np.arange(minI, maxI + iStep / 2, iStep),
        "iDuration": iDur,
        "iRest": iRest
    }
    p["nSteps"] = p["iAmp"].shape[0]

    for jj in range(p["nSteps"]):
        input_id = 'stim_{}'.format(ctr)
        istep = nml.PulseGenerator(id=input_id,
                                   delay='{} ms'.format(p["iDuration"] * jj +
                                                        p["iRest"] * (jj + 1)),
                                   duration='{} ms'.format(p["iDuration"]),
                                   amplitude='{} pA'.format(p["iAmp"][jj]))
        net_doc.pulse_generators.append(istep)

        input_list = nml.InputList(id='ilist_{}'.format(ctr),
                                   component=istep.id,
                                   populations=goc_pop.id)
        curr_inj = nml.Input('0',
                             target="../%s[%i]" % (goc_pop.id, goc),
                             destination="synapses")
        input_list.input.append(curr_inj)
        net.input_lists.append(input_list)
        ctr += 1

    ### --------------  Write files

    net_filename = 'GoCNet_istep_' + format(runid, '05d') + '.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)

    simid = 'sim_gocnet_istep_' + goc_type.id
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)
    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    for jj in range(goc_pop.size):
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, jj, goc_type.id))

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
Example #20
0
def generate_current_vs_frequency_curve(nml2_file, 
                                        cell_id, 
                                        start_amp_nA =          -0.1, 
                                        end_amp_nA =            0.1,
                                        step_nA =               0.01, 
                                        custom_amps_nA =        [], 
                                        analysis_duration =     1000, 
                                        analysis_delay =        0, 
                                        pre_zero_pulse =        0,
                                        post_zero_pulse =       0,
                                        dt =                    0.05,
                                        temperature =           "32degC",
                                        spike_threshold_mV =    0.,
                                        plot_voltage_traces =   False,
                                        plot_if =               True,
                                        plot_iv =               False,
                                        xlim_if =               None,
                                        ylim_if =               None,
                                        xlim_iv =               None,
                                        ylim_iv =               None,
                                        label_xaxis =           True,
                                        label_yaxis =           True,
                                        show_volts_label =      True,
                                        grid =                  True,
                                        font_size =             12,
                                        if_iv_color =           'k',
                                        linewidth =             1,
                                        bottom_left_spines_only = False,
                                        show_plot_already =     True, 
                                        save_voltage_traces_to = None, 
                                        save_if_figure_to =     None, 
                                        save_iv_figure_to =     None, 
                                        save_if_data_to =       None, 
                                        save_iv_data_to =       None, 
                                        simulator =             "jNeuroML",
                                        num_processors =        1,
                                        include_included =      True,
                                        title_above_plot =      False,
                                        return_axes =           False,
                                        verbose =               False):
                                            
    print_comment("Running generate_current_vs_frequency_curve() on %s (%s)"%(nml2_file,os.path.abspath(nml2_file)), verbose)                
    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np
    traces_ax = None
    if_ax = None
    iv_ax = None
    
    
    sim_id = 'iv_%s'%cell_id
    total_duration = pre_zero_pulse+analysis_duration+analysis_delay+post_zero_pulse
    pulse_duration = analysis_duration+analysis_delay
    end_stim = pre_zero_pulse+analysis_duration+analysis_delay
    ls = LEMSSimulation(sim_id, total_duration, dt)
    
    ls.include_neuroml2_file(nml2_file, include_included=include_included)
    
    stims = []
    if len(custom_amps_nA)>0:
        stims = [float(a) for a in custom_amps_nA]
        stim_info = ['%snA'%float(a) for a in custom_amps_nA]
    else:
        amp = start_amp_nA
        while amp<=end_amp_nA : 
            stims.append(amp)
            amp+=step_nA
        
        stim_info = '(%snA->%snA; %s steps of %snA; %sms)'%(start_amp_nA, end_amp_nA, len(stims), step_nA, total_duration)
        
    print_comment_v("Generating an IF curve for cell %s in %s using %s %s"%
        (cell_id, nml2_file, simulator, stim_info))
        
    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s"%cell_id,
                        component=cell_id,
                        size=number_cells)
    

    # create network and add populations
    net_id = "network_of_%s"%cell_id
    net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(nml2_file))
    net.populations.append(pop)

    for i in range(number_cells):
        stim_amp = "%snA"%stims[i]
        input_id = ("input_%s"%stim_amp).replace('.','_').replace('-','min')
        pg = nml.PulseGenerator(id=input_id,
                                    delay="%sms"%pre_zero_pulse,
                                    duration="%sms"%pulse_duration,
                                    amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id,
                                 component=pg.id,
                                 populations=pop.id)
        input = nml.Input(id='0', 
                              target="../%s[%i]"%(pop.id, i), 
                              destination="synapses")  
        input_list.input.append(input)
        net.input_lists.append(input_list)
    
    
    net_file_name = '%s.net.nml'%sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)
    
    disp0 = 'Voltage_display'
    ls.create_display(disp0,"Voltages", "-90", "50")
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat"%sim_id)
    
    for i in range(number_cells):
        ref = "v_cell%i"%i
        quantity = "%s[%i]/v"%(pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color())
    
        ls.add_column_to_output_file(of0, ref, quantity)
    
    lems_file_name = ls.save_to_file()
    
    print_comment("Written LEMS file %s (%s)"%(lems_file_name,os.path.abspath(lems_file_name)), verbose)   

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False,
                                                verbose=verbose)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False,
                                                verbose=verbose)
    elif simulator == "jNeuroML_NetPyNE":
        results = pynml.run_lems_with_jneuroml_netpyne(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False,
                                                num_processors = num_processors,
                                                verbose=verbose)
    else:
        raise Exception("Sorry, cannot yet run current vs frequency analysis using simulator %s"%simulator)
    
    print_comment("Completed run in simulator %s (results: %s)"%(simulator,results.keys()), verbose)  
        
    #print(results.keys())
    times_results = []
    volts_results = []
    volts_labels = []
    if_results = {}
    iv_results = {}
    for i in range(number_cells):
        t = np.array(results['t'])*1000
        v = np.array(results["%s[%i]/v"%(pop.id, i)])*1000

        if plot_voltage_traces:
            times_results.append(t)
            volts_results.append(v)
            volts_labels.append("%s nA"%stims[i])
            
        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm['maxima_times']
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= pre_zero_pulse + analysis_delay and s < (pre_zero_pulse + analysis_duration+analysis_delay):
                    count+=1
            freq = 1000 * count/float(analysis_duration)
                    
        mean_freq = mean_spike_frequency(spike_times) 
        #print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq
        
        if freq == 0:
            if post_zero_pulse==0:
                iv_results[stims[i]] = v[-1]
            else:
                v_end = None
                for j in range(len(t)):
                    if v_end==None and t[j]>=end_stim:
                        v_end = v[j]
                iv_results[stims[i]] = v_end
            
    if plot_voltage_traces:
            
        traces_ax = pynml.generate_plot(times_results,
                            volts_results, 
                            "Membrane potential traces for: %s"%nml2_file, 
                            xaxis = 'Time (ms)' if label_xaxis else ' ', 
                            yaxis = 'Membrane potential (mV)' if label_yaxis else '',
                            xlim = [total_duration*-0.05,total_duration*1.05],
                            show_xticklabels = label_xaxis,
                            font_size = font_size,
                            bottom_left_spines_only = bottom_left_spines_only,
                            grid = False,
                            labels = volts_labels if show_volts_label else [],
                            show_plot_already=False,
                            save_figure_to = save_voltage_traces_to,
                            title_above_plot = title_above_plot,
                            verbose=verbose)
    
        
    if plot_if:
        
        stims = sorted(if_results.keys())
        stims_pA = [ii*1000 for ii in stims]
        
        freqs = [if_results[s] for s in stims]
        
        if_ax = pynml.generate_plot([stims_pA],
                            [freqs], 
                            "Firing frequency versus injected current for: %s"%nml2_file, 
                            colors = [if_iv_color], 
                            linestyles=['-'],
                            markers=['o'],
                            linewidths = [linewidth],
                            xaxis = 'Input current (pA)' if label_xaxis else ' ', 
                            yaxis = 'Firing frequency (Hz)' if label_yaxis else '',
                            xlim = xlim_if,
                            ylim = ylim_if,
                            show_xticklabels = label_xaxis,
                            show_yticklabels = label_yaxis,
                            font_size = font_size,
                            bottom_left_spines_only = bottom_left_spines_only,
                            grid = grid,
                            show_plot_already=False,
                            save_figure_to = save_if_figure_to,
                            title_above_plot = title_above_plot,
                            verbose=verbose)
                            
        if save_if_data_to:
            with open(save_if_data_to,'w') as if_file:
                for i in range(len(stims_pA)):
                    if_file.write("%s\t%s\n"%(stims_pA[i],freqs[i]))
    if plot_iv:
        
        stims = sorted(iv_results.keys())
        stims_pA = [ii*1000 for ii in sorted(iv_results.keys())]
        vs = [iv_results[s] for s in stims]
        
        xs = []
        ys = []
        xs.append([])
        ys.append([])
        
        for si in range(len(stims)):
            stim = stims[si]
            if len(custom_amps_nA)==0 and si>1 and (stims[si]-stims[si-1])>step_nA*1.01:
                xs.append([])
                ys.append([])
                
            xs[-1].append(stim*1000)
            ys[-1].append(iv_results[stim])
            
        iv_ax = pynml.generate_plot(xs,
                            ys, 
                            "V at %sms versus I below threshold for: %s"%(end_stim,nml2_file), 
                            colors = [if_iv_color for s in xs], 
                            linestyles=['-' for s in xs],
                            markers=['o' for s in xs],
                            xaxis = 'Input current (pA)' if label_xaxis else '', 
                            yaxis = 'Membrane potential (mV)' if label_yaxis else '', 
                            xlim = xlim_iv,
                            ylim = ylim_iv,
                            show_xticklabels = label_xaxis,
                            show_yticklabels = label_yaxis,
                            font_size = font_size,
                            linewidths = [linewidth for s in xs],
                            bottom_left_spines_only = bottom_left_spines_only,
                            grid = grid,
                            show_plot_already=False,
                            save_figure_to = save_iv_figure_to,
                            title_above_plot = title_above_plot,
                            verbose=verbose)
                            
                            
        if save_iv_data_to:
            with open(save_iv_data_to,'w') as iv_file:
                for i in range(len(stims_pA)):
                    iv_file.write("%s\t%s\n"%(stims_pA[i],vs[i]))
    
    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()
        
    if return_axes:
        return traces_ax, if_ax, iv_ax
        
    return if_results
Example #21
0
def create_GoC_network(duration=2000, dt=0.025, seed=123, runid=0, run=False):

    keepFile = open('useParams_FI_14_25.pkl', 'rb')
    runid = pkl.load(keepFile)[runid]
    keepFile.close()

    ### ---------- Component types
    gocID = 'Golgi_040408_C1_' + format(runid, '05d')
    goc_filename = '{}.cell.nml'.format(gocID)
    goc_type = pynml.read_neuroml2_file(goc_filename).cells[0]

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id='MorphoNet_' + format(runid, '05d'),
                      type="networkWithTemperature",
                      temperature="23 degC")

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=1)
    inst = nml.Instance(id=0)
    goc_pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(goc_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(href=goc_filename))

    ### --------------  Write files

    net_filename = 'Morpho1_' + format(runid, '05d') + '.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)

    simid = 'sim_morpho1_' + goc_type.id
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)
    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    for jj in range(goc_pop.size):
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, jj, goc_type.id))

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
Example #22
0
    def run_individual(self, sim_var, show=False):
        """
        Run an individual simulation.

        The candidate data has been flattened into the sim_var dict. The
        sim_var dict contains parameter:value key value pairs, which are
        applied to the model before it is simulated.

        """

        nml_doc = read_neuroml2_file(self.neuroml_file,
                                     include_includes=True,
                                     verbose=True,
                                     already_included=[])

        for var_name in sim_var.keys():
            words = var_name.split('/')
            type, id1 = words[0].split(':')
            if ':' in words[1]:
                variable, id2 = words[1].split(':')
            else:
                variable = words[1]
                id2 = None

            units = words[2]
            value = sim_var[var_name]

            print_comment_v(
                '  Changing value of %s (%s) in %s (%s) to: %s %s' %
                (variable, id2, type, id1, value, units))

            if type == 'cell':
                cell = None
                for c in nml_doc.cells:
                    if c.id == id1:
                        cell = c

                if variable == 'channelDensity':

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.id == id2:
                            chanDens = cd

                    chanDens.cond_density = '%s %s' % (value, units)

                elif variable == 'erev_id':  # change all values of erev in channelDensity elements with only this id

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.id == id2:
                            chanDens = cd

                    chanDens.erev = '%s %s' % (value, units)

                elif variable == 'erev_ion':  # change all values of erev in channelDensity elements with this ion

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.ion == id2:
                            chanDens = cd

                    chanDens.erev = '%s %s' % (value, units)

                elif variable == 'specificCapacitance':

                    specCap = None
                    for sc in cell.biophysical_properties.membrane_properties.specific_capacitances:
                        if (sc.segment_groups == None
                                and id2 == 'all') or sc.segment_groups == id2:
                            specCap = sc

                    specCap.value = '%s %s' % (value, units)

                else:
                    print_comment_v(
                        'Unknown variable (%s) in variable expression: %s' %
                        (variable, var_name))
                    exit()

            elif type == 'izhikevich2007Cell':
                izhcell = None
                for c in nml_doc.izhikevich2007_cells:
                    if c.id == id1:
                        izhcell = c

                izhcell.__setattr__(variable, '%s %s' % (value, units))

            else:
                print_comment_v(
                    'Unknown type (%s) in variable expression: %s' %
                    (type, var_name))

        new_neuroml_file = '%s/%s' % (self.generate_dir,
                                      os.path.basename(self.neuroml_file))
        if new_neuroml_file == self.neuroml_file:
            print_comment_v('Cannot use a directory for generating into (%s) which is the same location of the NeuroML file (%s)!'% \
                      (self.neuroml_file, self.generate_dir))

        write_neuroml2_file(nml_doc, new_neuroml_file)

        sim = NeuroMLSimulation(self.ref,
                                neuroml_file=new_neuroml_file,
                                target=self.target,
                                sim_time=self.sim_time,
                                dt=self.dt,
                                simulator=self.simulator,
                                generate_dir=self.generate_dir)

        sim.go()

        if show:
            sim.show()

        return sim.t, sim.volts
Example #23
0
def generate_current_vs_frequency_curve(
    nml2_file,
    cell_id,
    start_amp_nA,
    end_amp_nA,
    step_nA,
    analysis_duration,
    analysis_delay,
    dt=0.05,
    temperature="32degC",
    spike_threshold_mV=0.0,
    plot_voltage_traces=False,
    plot_if=True,
    simulator="jNeuroML",
):

    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np

    sim_id = "iv_%s" % cell_id
    duration = analysis_duration + analysis_delay
    ls = LEMSSimulation(sim_id, duration, dt)

    ls.include_neuroml2_file(nml2_file)

    stims = []
    amp = start_amp_nA
    while amp <= end_amp_nA:
        stims.append(amp)
        amp += step_nA

    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s" % cell_id, component=cell_id, size=number_cells)

    # create network and add populations
    net_id = "network_of_%s" % cell_id
    net = nml.Network(id=net_id, type="networkWithTemperature", temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net.populations.append(pop)

    for i in range(number_cells):
        stim_amp = "%snA" % stims[i]
        input_id = ("input_%s" % stim_amp).replace(".", "_")
        pg = nml.PulseGenerator(id=input_id, delay="0ms", duration="%sms" % duration, amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id, component=pg.id, populations=pop.id)
        input = nml.Input(id="0", target="../%s[%i]" % (pop.id, i), destination="synapses")
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = "%s.net.nml" % sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)

    disp0 = "Voltage_display"
    ls.create_display(disp0, "Voltages", "-90", "50")
    of0 = "Volts_file"
    ls.create_output_file(of0, "%s.v.dat" % sim_id)

    for i in range(number_cells):
        ref = "v_cell%i" % i
        quantity = "%s[%i]/v" % (pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV", pynml.get_next_hex_color())

        ls.add_column_to_output_file(of0, ref, quantity)

    lems_file_name = ls.save_to_file()

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(
            lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces
        )
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(
            lems_file_name, nogui=True, load_saved_data=True, plot=plot_voltage_traces
        )

    # print(results.keys())
    if_results = {}
    for i in range(number_cells):
        t = np.array(results["t"]) * 1000
        v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000

        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm["maxima_times"]
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= analysis_delay and s < (analysis_duration + analysis_delay):
                    count += 1
            freq = 1000 * count / float(analysis_duration)

        mean_freq = mean_spike_frequency(spike_times)
        # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq

    if plot_if:

        from matplotlib import pyplot as plt

        plt.xlabel("Input current (nA)")
        plt.ylabel("Firing frequency (Hz)")
        plt.grid("on")
        stims = sorted(if_results.keys())
        freqs = []
        for s in stims:
            freqs.append(if_results[s])
        plt.plot(stims, freqs, "o")

        plt.show()

    return if_results
Example #24
0
def export(num_cells_to_export=5):
    cells = []

    for mgid in range(num_cells_to_export):
        print mgid
        cells.append(mkmitral(mgid))

    nml_net_file = "../NeuroML2/MitralCells/Exported/PartialBulb_%iMTCells.net.nml" % num_cells_to_export
    export_to_neuroml2(None,
                       nml_net_file,
                       includeBiophysicalProperties=False,
                       separateCellFiles=True)

    for i in range(num_cells_to_export):
        print("Processing cell %i out of %i" % (i, num_cells_to_export))
        nml_cell_file = "../NeuroML2/MitralCells/Exported/Mitral_0_%i.cell.nml" % i
        nml_doc = pynml.read_neuroml2_file(nml_cell_file)
        cell = nml_doc.cells[0]

        soma_seg = next(seg for seg in cell.morphology.segments
                        if seg.name == "Seg0_soma")
        initial_seg = next(seg for seg in cell.morphology.segments
                           if seg.name == "Seg0_initialseg")
        hillock_seg = next(seg for seg in cell.morphology.segments
                           if seg.name == "Seg0_hillock")

        # Ensure hillock parent is soma
        hillock_seg.parent.segments = soma_seg.id

        # Fix initial and hillock segs by moving them to the soma
        hillock_seg.proximal = pointMovedByOffset(hillock_seg.proximal,
                                                  soma_seg.distal)
        hillock_seg.distal = pointMovedByOffset(hillock_seg.distal,
                                                soma_seg.distal)
        initial_seg.proximal = pointMovedByOffset(initial_seg.proximal,
                                                  soma_seg.distal)
        initial_seg.distal = pointMovedByOffset(initial_seg.distal,
                                                soma_seg.distal)

        # Set root to id=0 and increment others
        exportHelper.resetRoot(cell)

        # TODO: cell.position(x,y,z) used for cell positioning in networks does not work as expected
        # See: https://github.com/NeuroML/jNeuroML/issues/55
        # Skipping the translation for now
        # # Move everything back to the origin
        # originOffset = type("", (), dict(x = -soma_seg.proximal.x, y = -soma_seg.proximal.y, z = -soma_seg.proximal.z ))()
        #
        # for seg in cell.morphology.segments:
        #     seg.proximal = pointMovedByOffset(seg.proximal, originOffset)
        #     seg.distal =   pointMovedByOffset(seg.distal, originOffset)

        # Replace ModelViewParmSubset_N groups with all, axon, soma, dendrite groups
        buildStandardSegmentGroups(cell)

        # Add channel placeholders
        nml_doc.includes.append(
            neuroml.IncludeType(href="channelIncludesPLACEHOLDER"))
        cell.biophysical_properties = neuroml.BiophysicalProperties(
            id="biophysPLACEHOLDER")

        # Save the new NML
        pynml.write_neuroml2_file(nml_doc, nml_cell_file)

        # Replace placeholders with contents from MitralCell...xml files
        replaceChannelPlaceholders(nml_cell_file)

        print("COMPLETED: " + nml_cell_file)

    print("DONE")
        
        cell = nml_doc.izhikevich2007_cells[0]
        
        print("Extracted cell: %s from tuned model"%cell.id)
        
        new_id = '%s_%s'%(type, dataset)
        new_cell_doc = neuroml.NeuroMLDocument(id=new_id)
        cell.id = new_id
        
        cell.notes = "Cell model tuned to Allen Institute Cell Types Database, dataset: "+ \
                     "%s\n\nTuning procedure metadata:\n\n%s\n"%(dataset, pp.pformat(r2))
        
        new_cell_doc.izhikevich2007_cells.append(cell)
        new_cell_file = 'tuned_cells/%s.cell.nml'%new_id
        
        pynml.write_neuroml2_file(new_cell_doc, new_cell_file)
        


    ####  Run a 'quick' optimisation for HH cell model
    elif '-quick' in sys.argv:

        simulator  = 'jNeuroML_NEURON'
        
        dataset = 471141261
        ref = 'network_%s_HH'%(dataset)
        
        report = run_one_optimisation('AllenTestQ',
                            1234,
                            parameters =       parameters_hh,
                            max_constraints =  max_constraints_hh,
Example #26
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 create_GoC_network(duration,
                       dt,
                       seed,
                       N_goc=0,
                       N_mf=15,
                       run=False,
                       prob_type='Boltzmann',
                       GJw_type='Vervaeke2010'):

    ### ---------- Component types
    goc_filename = 'GoC.cell.nml'  # Golgi cell with channels
    goc_file = pynml.read_neuroml2_file(goc_filename)
    goc_type = goc_file.cells[0]
    goc_ref = nml.IncludeType(href=goc_filename)

    MFSyn_filename = 'MF_GoC_Syn.nml'  # small conductance synapse for background inputs
    mfsyn_file = pynml.read_neuroml2_file(MFSyn_filename)
    MFSyn_type = mfsyn_file.exp_three_synapses[0]
    mfsyn_ref = nml.IncludeType(href=MFSyn_filename)

    MF20Syn_filename = 'MF_GoC_SynMult.nml'  # multi-syn conductance for strong/coincident transient input
    mf20syn_file = pynml.read_neuroml2_file(MF20Syn_filename)
    MF20Syn_type = mf20syn_file.exp_three_synapses[0]
    mf20syn_ref = nml.IncludeType(href=MF20Syn_filename)

    mf_type2 = 'spikeGeneratorPoisson'  # Spike source for background inputs
    mf_poisson = nml.SpikeGeneratorPoisson(
        id="MF_Poisson", average_rate="5 Hz")  # Not tuned to any data - qqq !

    mf_bursttype = 'transientPoissonFiringSynapse'  # Burst of MF input (as explicit input)
    mf_burst = nml.TransientPoissonFiringSynapse(id="MF_Burst",
                                                 average_rate="100 Hz",
                                                 delay="2000 ms",
                                                 duration="500 ms",
                                                 synapse=MF20Syn_type.id,
                                                 spike_target='./{}'.format(
                                                     MF20Syn_type.id))

    gj = nml.GapJunction(id="GJ_0", conductance="426pS")  # GoC synapse

    ### --------- Populations

    # Build network to specify cells and connectivity
    net = nml.Network(id="gocNetwork",
                      type="networkWithTemperature",
                      temperature="23 degC")

    ### Golgi cells
    if N_goc > 0:
        GoC_pos = nu.GoC_locate(N_goc)
    else:
        GoC_pos = nu.GoC_density_locate()
        N_goc = GoC_pos.shape[0]

    # Create GoC population
    goc_pop = nml.Population(id=goc_type.id + "Pop",
                             component=goc_type.id,
                             type="populationList",
                             size=N_goc)
    for goc in range(N_goc):
        inst = nml.Instance(id=goc)
        goc_pop.instances.append(inst)
        inst.location = nml.Location(x=GoC_pos[goc, 0],
                                     y=GoC_pos[goc, 1],
                                     z=GoC_pos[goc, 2])
    net.populations.append(goc_pop)

    ### MF population
    MF_Poisson_pop = nml.Population(id=mf_poisson.id + "_pop",
                                    component=mf_poisson.id,
                                    type="populationList",
                                    size=N_mf)
    MF_pos = nu.GoC_locate(N_mf)
    for mf in range(N_mf):
        inst = nml.Instance(id=mf)
        MF_Poisson_pop.instances.append(inst)
        inst.location = nml.Location(x=MF_pos[mf, 0],
                                     y=MF_pos[mf, 1],
                                     z=MF_pos[mf, 2])
    net.populations.append(MF_Poisson_pop)

    # Create NML document for network specification
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(goc_ref)
    net_doc.includes.append(mfsyn_ref)
    net_doc.includes.append(mf20syn_ref)
    net_doc.spike_generator_poissons.append(mf_poisson)
    net_doc.transient_poisson_firing_synapses.append(mf_burst)
    net_doc.gap_junctions.append(gj)

    ### ------------ Connectivity

    ### background excitatory inputs: 	MF to GoC populations
    MFProjection = nml.Projection(id="MFtoGoC",
                                  presynaptic_population=MF_Poisson_pop.id,
                                  postsynaptic_population=goc_pop.id,
                                  synapse=MFSyn_type.id)
    net.projections.append(MFProjection)

    #Get list of MF->GoC synapse
    mf_synlist = nu.randdist_MF_syn(N_mf, N_goc,
                                    pConn=0.3)  # Not tuned to any data - qqq!
    nMFSyn = mf_synlist.shape[1]
    for syn in range(nMFSyn):
        mf, goc = mf_synlist[:, syn]
        conn2 = nml.Connection(
            id=syn,
            pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf,
                                             mf_poisson.id),
            post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id),
            post_segment_id='0',
            post_fraction_along="0.5")  #on soma
        MFProjection.connections.append(conn2)

    ### Add few burst inputs
    n_bursts = 4
    gocPerm = np.random.permutation(
        N_goc)  # change to central neurons later -qqq !!!
    ctr = 0
    for gg in range(4):
        goc = gocPerm[gg]
        for jj in range(n_bursts):
            inst = nml.ExplicitInput(
                id=ctr,
                target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id),
                input=mf_burst.id,
                synapse=MF20Syn_type.id,
                spikeTarget='./{}'.format(MF20Syn_type.id))
            net.explicit_inputs.append(inst)
            ctr += 1

    ### Electrical coupling between GoCs

    # get GJ connectivity
    GJ_pairs, GJWt = nu.GJ_conn(GoC_pos, prob_type, GJw_type)
    #tmp1, tmp2 = valnet.gapJuncAnalysis( GJ_pairs, GJWt )
    #print("Number of gap junctions per cell: ", tmp1)
    #print("Net GJ conductance per cell:", tmp2)

    # Add electrical synapses
    GoCCoupling = nml.ElectricalProjection(id="gocGJ",
                                           presynaptic_population=goc_pop.id,
                                           postsynaptic_population=goc_pop.id)
    nGJ = GJ_pairs.shape[0]
    for jj in range(nGJ):
        conn = nml.ElectricalConnectionInstanceW(
            id=jj,
            pre_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj, 0],
                                          goc_type.id),
            pre_segment='1',
            pre_fraction_along='0.5',
            post_cell='../{}/{}/{}'.format(goc_pop.id, GJ_pairs[jj, 1],
                                           goc_type.id),
            post_segment='1',
            post_fraction_along='0.5',
            synapse=gj.id,
            weight=GJWt[jj])
        GoCCoupling.electrical_connection_instance_ws.append(conn)
    net.electrical_projections.append(GoCCoupling)

    ### --------------  Write files

    net_filename = 'gocNetwork.nml'
    pynml.write_neuroml2_file(net_doc, net_filename)
    #lems_filename = 'instances.xml'
    #pynml.write_lems_file( lems_inst_doc, lems_filename, validate=False )

    simid = 'sim_gocnet' + goc_type.id
    ls = LEMSSimulation(simid, duration=duration, dt=dt, simulation_seed=seed)
    ls.assign_simulation_target(net.id)

    ls.include_neuroml2_file(net_filename)
    ls.include_neuroml2_file(goc_filename)
    ls.include_neuroml2_file(MFSyn_filename)
    ls.include_neuroml2_file(MF20Syn_filename)
    #ls.include_lems_file( lems_filename, include_included=False)

    # Specify outputs
    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    for jj in range(goc_pop.size):
        ls.add_selection_to_event_output_file(
            eof0, jj, '{}/{}/{}'.format(goc_pop.id, jj, goc_type.id), 'spike')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    for jj in range(goc_pop.size):
        ls.add_column_to_output_file(
            of0, jj, '{}/{}/{}/v'.format(goc_pop.id, jj, goc_type.id))

    #Create Lems file to run
    lems_simfile = ls.save_to_file()

    if run:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  nogui=True,
                                                  plot=False)
    else:
        res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                                  max_memory="2G",
                                                  only_generate_scripts=True,
                                                  compile_mods=False,
                                                  nogui=True,
                                                  plot=False)

    return res
def create_GoC_network( duration, dt, seed, runid, run=False):

	### ---------- Load Params
	noPar = True
	pfile = Path('params_file.pkl')
	if pfile.exists():
		print('Reading parameters from file:')
		file = open('params_file.pkl','rb')
		params_list = pkl.load(file)
		if len(params_list)>runid:
			p = params_list[runid]
			file.close()
	if noPar:
		p = inp.get_simulation_params( runid )
    
	### ---------- Component types
	goc_filename = 'GoC.cell.nml'							# Golgi cell with channels
	goc_file = pynml.read_neuroml2_file( goc_filename )
	goc_type = goc_file.cells[0]
	goc_ref = nml.IncludeType( href=goc_filename )

	MFSyn_filename = 'MF_GoC_Syn.nml'						# small conductance synapse for background inputs
	mfsyn_file = pynml.read_neuroml2_file( MFSyn_filename )
	MFSyn_type = mfsyn_file.exp_three_synapses[0]
	mfsyn_ref = nml.IncludeType( href=MFSyn_filename )
	
	MF20Syn_filename = 'MF_GoC_SynMult.nml'					# multi-syn conductance for strong/coincident transient input
	mf20syn_file = pynml.read_neuroml2_file( MF20Syn_filename )
	MF20Syn_type = mf20syn_file.exp_three_synapses[0]
	mf20syn_ref = nml.IncludeType( href=MF20Syn_filename )

	mf_type2 = 'spikeGeneratorPoisson'						# Spike source for background inputs
	mf_poisson = nml.SpikeGeneratorPoisson( id = "MF_Poisson", average_rate="5 Hz" )	# Not tuned to any data - qqq !
	
	mf_bursttype = 'transientPoissonFiringSynapse'			# Burst of MF input (as explicit input)
	mf_burst = nml.TransientPoissonFiringSynapse( id="MF_Burst", average_rate="100 Hz", delay="2000 ms", duration="500 ms", synapse=MF20Syn_type.id, spike_target='./{}'.format(MF20Syn_type.id) )

	gj = nml.GapJunction( id="GJ_0", conductance="426pS" )	# GoC synapse
	
	### --------- Populations

	# Build network to specify cells and connectivity
	net = nml.Network( id="gocNetwork", type="networkWithTemperature" , temperature="23 degC" )
		
	# Create GoC population
	goc_pop = nml.Population( id=goc_type.id+"Pop", component = goc_type.id, type="populationList", size=p["nGoC"] )
	for goc in range( p["nGoC"] ):
		inst = nml.Instance( id=goc )
		goc_pop.instances.append( inst )
		inst.location = nml.Location( x=p["GoC_pos"][goc,0], y=p["GoC_pos"][goc,1], z=p["GoC_pos"][goc,2] )
	net.populations.append( goc_pop )


	### MF population
	MF_Poisson_pop = nml.Population(id=mf_poisson.id+"_pop", component=mf_poisson.id, type="populationList", size=p["nMF"])
	for mf in range( p["nMF"] ):
		inst = nml.Instance(id=mf)
		MF_Poisson_pop.instances.append( inst )
		inst.location = nml.Location( x=p["MF_pos"][mf,0], y=p["MF_pos"][mf,1], z=p["MF_pos"][mf,2] )		
	net.populations.append( MF_Poisson_pop )
	
	# Create NML document for network specification
	net_doc = nml.NeuroMLDocument( id=net.id )
	net_doc.networks.append( net )
	net_doc.includes.append( goc_ref )
	net_doc.includes.append( mfsyn_ref )
	net_doc.includes.append( mf20syn_ref )
	net_doc.spike_generator_poissons.append( mf_poisson )	
	net_doc.transient_poisson_firing_synapses.append( mf_burst )
	net_doc.gap_junctions.append(gj)
	
	
	### ------------ Connectivity

	### 1. Background excitatory inputs: 	MF to GoC populations
	MFProjection = nml.Projection(id="MFtoGoC", presynaptic_population=MF_Poisson_pop.id, postsynaptic_population=goc_pop.id, synapse=MFSyn_type.id)
	net.projections.append(MFProjection)

	# MF_> GoC synapses (with syn_count equivalent to integer scaling of Mf synapse strength)
	nMFSyn = p["MF_GoC_pairs"].shape[1]
	ctr=0
	for syn in range( nMFSyn ):
		mf, goc = p["MF_GoC_pairs"][:, syn]
		for syn_count in range(p["MF_GoC_wt"][ctr]):
			conn2 = nml.Connection(id=ctr, pre_cell_id='../{}/{}/{}'.format(MF_Poisson_pop.id, mf, mf_poisson.id), post_cell_id='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), post_segment_id='0', post_fraction_along="0.5")	#on soma
			MFProjection.connections.append(conn2)
			ctr+=1

	### 2. Perturbation as High Freq MF Inputs
	ctr=0
	for goc in p["Burst_GoC"]:
		for jj in range( p["nBurst"] ):				# Each Perturbed GoC gets nBurst random Burst sources
			inst = nml.ExplicitInput( id=ctr, target='../{}/{}/{}'.format(goc_pop.id, goc, goc_type.id), input=mf_burst.id, synapse=MF20Syn_type.id, spikeTarget='./{}'.format(MF20Syn_type.id))
			net.explicit_inputs.append( inst )
			ctr += 1

	### 3. Electrical coupling between GoCs
		
	GoCCoupling = nml.ElectricalProjection( id="gocGJ", presynaptic_population=goc_pop.id, postsynaptic_population=goc_pop.id )
	net.electrical_projections.append( GoCCoupling )
	dend_id = [1,2,5]
	for jj in range( p["GJ_pairs"].shape[0] ):
		conn = nml.ElectricalConnectionInstanceW( id=jj, pre_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,0], goc_type.id), pre_segment=dend_id[p["GJ_loc"][jj,0]], pre_fraction_along='0.5', post_cell='../{}/{}/{}'.format(goc_pop.id, p["GJ_pairs"][jj,1], goc_type.id), post_segment=dend_id[p["GJ_loc"][jj,1]], post_fraction_along='0.5', synapse=gj.id, weight=p["GJ_wt"][jj] )
		GoCCoupling.electrical_connection_instance_ws.append( conn )
		
		
	### --------------  Write files
		
	net_filename = 'gocNetwork.nml'
	pynml.write_neuroml2_file( net_doc, net_filename )

	simid = 'sim_gocnet_'+goc_type.id+'_run_{}'.format(runid)
	ls = LEMSSimulation( simid, duration=duration, dt=dt, simulation_seed=seed )
	ls.assign_simulation_target( net.id )
	ls.include_neuroml2_file( net_filename)
	ls.include_neuroml2_file( goc_filename)
	ls.include_neuroml2_file( MFSyn_filename)
	ls.include_neuroml2_file( MF20Syn_filename)
	
	
	# Specify outputs
	eof0 = 'Events_file'
	ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME')
	for jj in range( goc_pop.size):
		ls.add_selection_to_event_output_file( eof0, jj, '{}/{}/{}'.format( goc_pop.id, jj, goc_type.id), 'spike' )
		
	of0 = 'Volts_file'
	ls.create_output_file(of0, "%s.v.dat"%simid)
	for jj in range( goc_pop.size ):
		ls.add_column_to_output_file(of0, jj, '{}/{}/{}/v'.format( goc_pop.id, jj, goc_type.id))
		
	#Create Lems file to run
	lems_simfile = ls.save_to_file()

	if run:
		res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", nogui=True, plot=False)
	else:
		res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False)
	
	
	return res
Example #29
0
        cell = nml_doc.izhikevich2007_cells[0]

        print("Extracted cell: %s from tuned model" % cell.id)

        new_id = '%s_%s' % (type, dataset)
        new_cell_doc = neuroml.NeuroMLDocument(id=new_id)
        cell.id = new_id

        cell.notes = "Cell model tuned to Allen Institute Cell Types Database, dataset: "+ \
                     "%s\n\nTuning procedure metadata:\n\n%s\n"%(dataset, pp.pformat(r2))

        new_cell_doc.izhikevich2007_cells.append(cell)
        new_cell_file = 'tuned_cells/%s.cell.nml' % new_id

        pynml.write_neuroml2_file(new_cell_doc, new_cell_file)

    ####  Run a 'quick' optimisation for HH cell model
    elif '-quick' in sys.argv:

        simulator = 'jNeuroML_NEURON'

        dataset = 471141261
        ref = 'network_%s_HH' % (dataset)

        report = run_one_optimisation('AllenTestQ',
                                      1234,
                                      parameters=parameters_hh,
                                      max_constraints=max_constraints_hh,
                                      min_constraints=min_constraints_hh,
                                      population_size=10,
Example #30
0
def generate_Vm_vs_time_plot(nml2_file,
                             cell_id,
                             inj_amp_nA=80,
                             delay_ms=20,
                             inj_dur_ms=60,
                             sim_dur_ms=100,
                             dt=0.05,
                             plot_voltage_traces=False,
                             show_plot_already=True,
                             simulator="jNeuroML",
                             include_included=True):

    ref = "Test"
    print_comment_v(
        "Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"
        % (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms))

    sim_id = 'Vm_%s' % ref
    duration = sim_dur_ms
    ls = LEMSSimulation(sim_id, sim_dur_ms, dt)

    ls.include_neuroml2_file(nml2_file, include_included=include_included)
    ls.assign_simulation_target('network')
    nml_doc = nml.NeuroMLDocument(id=cell_id)

    nml_doc.includes.append(nml.IncludeType(href=nml2_file))

    net = nml.Network(id="network")
    nml_doc.networks.append(net)

    input_id = ("input_%s" % str(inj_amp_nA).replace('.', '_'))
    pg = nml.PulseGenerator(id=input_id,
                            delay="%sms" % delay_ms,
                            duration='%sms' % inj_dur_ms,
                            amplitude='%spA' % inj_amp_nA)
    nml_doc.pulse_generators.append(pg)

    pop_id = 'hhpop'
    pop = nml.Population(id=pop_id,
                         component='hhcell',
                         size=1,
                         type="populationList")

    inst = nml.Instance(id=0)
    pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(pop)

    # Add these to cells
    input_list = nml.InputList(id='il_%s' % input_id,
                               component=pg.id,
                               populations=pop_id)
    input = nml.Input(id='0',
                      target='../hhpop/0/hhcell',
                      destination="synapses")

    input_list.input.append(input)
    net.input_lists.append(input_list)

    sim_file_name = '%s.sim.nml' % sim_id
    pynml.write_neuroml2_file(nml_doc, sim_file_name)
    ls.include_neuroml2_file(sim_file_name)

    disp0 = 'Voltage_display'
    ls.create_display(disp0, "Voltages", "-90", "50")
    ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV')

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % sim_id)
    ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v")

    lems_file_name = ls.save_to_file()

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=plot_voltage_traces,
                                               show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=plot_voltage_traces,
                                                      show_plot_already=False)

    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()

    return of0
Example #31
0
def generate_current_vs_frequency_curve(nml2_file,
                                        cell_id,
                                        start_amp_nA=-0.1,
                                        end_amp_nA=0.1,
                                        step_nA=0.01,
                                        custom_amps_nA=[],
                                        analysis_duration=1000,
                                        analysis_delay=0,
                                        pre_zero_pulse=0,
                                        post_zero_pulse=0,
                                        dt=0.05,
                                        temperature="32degC",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        plot_if=True,
                                        plot_iv=False,
                                        xlim_if=None,
                                        ylim_if=None,
                                        xlim_iv=None,
                                        ylim_iv=None,
                                        label_xaxis=True,
                                        label_yaxis=True,
                                        show_volts_label=True,
                                        grid=True,
                                        font_size=12,
                                        if_iv_color='k',
                                        linewidth=1,
                                        bottom_left_spines_only=False,
                                        show_plot_already=True,
                                        save_voltage_traces_to=None,
                                        save_if_figure_to=None,
                                        save_iv_figure_to=None,
                                        save_if_data_to=None,
                                        save_iv_data_to=None,
                                        simulator="jNeuroML",
                                        num_processors=1,
                                        include_included=True,
                                        title_above_plot=False,
                                        return_axes=False,
                                        verbose=False):

    print_comment(
        "Running generate_current_vs_frequency_curve() on %s (%s)" %
        (nml2_file, os.path.abspath(nml2_file)), verbose)
    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np
    traces_ax = None
    if_ax = None
    iv_ax = None

    sim_id = 'iv_%s' % cell_id
    total_duration = pre_zero_pulse + analysis_duration + analysis_delay + post_zero_pulse
    pulse_duration = analysis_duration + analysis_delay
    end_stim = pre_zero_pulse + analysis_duration + analysis_delay
    ls = LEMSSimulation(sim_id, total_duration, dt)

    ls.include_neuroml2_file(nml2_file, include_included=include_included)

    stims = []
    if len(custom_amps_nA) > 0:
        stims = [float(a) for a in custom_amps_nA]
        stim_info = ['%snA' % float(a) for a in custom_amps_nA]
    else:
        amp = start_amp_nA
        while amp <= end_amp_nA:
            stims.append(amp)
            amp += step_nA

        stim_info = '(%snA->%snA; %s steps of %snA; %sms)' % (
            start_amp_nA, end_amp_nA, len(stims), step_nA, total_duration)

    print_comment_v("Generating an IF curve for cell %s in %s using %s %s" %
                    (cell_id, nml2_file, simulator, stim_info))

    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s" % cell_id,
                         component=cell_id,
                         size=number_cells)

    # create network and add populations
    net_id = "network_of_%s" % cell_id
    net = nml.Network(id=net_id,
                      type="networkWithTemperature",
                      temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(nml2_file))
    net.populations.append(pop)

    for i in range(number_cells):
        stim_amp = "%snA" % stims[i]
        input_id = ("input_%s" % stim_amp).replace('.',
                                                   '_').replace('-', 'min')
        pg = nml.PulseGenerator(id=input_id,
                                delay="%sms" % pre_zero_pulse,
                                duration="%sms" % pulse_duration,
                                amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id,
                                   component=pg.id,
                                   populations=pop.id)
        input = nml.Input(id='0',
                          target="../%s[%i]" % (pop.id, i),
                          destination="synapses")
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = '%s.net.nml' % sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)

    disp0 = 'Voltage_display'
    ls.create_display(disp0, "Voltages", "-90", "50")
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % sim_id)

    for i in range(number_cells):
        ref = "v_cell%i" % i
        quantity = "%s[%i]/v" % (pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV",
                               pynml.get_next_hex_color())

        ls.add_column_to_output_file(of0, ref, quantity)

    lems_file_name = ls.save_to_file()

    print_comment(
        "Written LEMS file %s (%s)" %
        (lems_file_name, os.path.abspath(lems_file_name)), verbose)

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=False,
                                               show_plot_already=False,
                                               verbose=verbose)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=False,
                                                      show_plot_already=False,
                                                      verbose=verbose)
    elif simulator == "jNeuroML_NetPyNE":
        results = pynml.run_lems_with_jneuroml_netpyne(
            lems_file_name,
            nogui=True,
            load_saved_data=True,
            plot=False,
            show_plot_already=False,
            num_processors=num_processors,
            verbose=verbose)
    else:
        raise Exception(
            "Sorry, cannot yet run current vs frequency analysis using simulator %s"
            % simulator)

    print_comment(
        "Completed run in simulator %s (results: %s)" %
        (simulator, results.keys()), verbose)

    #print(results.keys())
    times_results = []
    volts_results = []
    volts_labels = []
    if_results = {}
    iv_results = {}
    for i in range(number_cells):
        t = np.array(results['t']) * 1000
        v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000

        if plot_voltage_traces:
            times_results.append(t)
            volts_results.append(v)
            volts_labels.append("%s nA" % stims[i])

        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm['maxima_times']
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= pre_zero_pulse + analysis_delay and s < (
                        pre_zero_pulse + analysis_duration + analysis_delay):
                    count += 1
            freq = 1000 * count / float(analysis_duration)

        mean_freq = mean_spike_frequency(spike_times)
        #print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq

        if freq == 0:
            if post_zero_pulse == 0:
                iv_results[stims[i]] = v[-1]
            else:
                v_end = None
                for j in range(len(t)):
                    if v_end == None and t[j] >= end_stim:
                        v_end = v[j]
                iv_results[stims[i]] = v_end

    if plot_voltage_traces:

        traces_ax = pynml.generate_plot(
            times_results,
            volts_results,
            "Membrane potential traces for: %s" % nml2_file,
            xaxis='Time (ms)' if label_xaxis else ' ',
            yaxis='Membrane potential (mV)' if label_yaxis else '',
            xlim=[total_duration * -0.05, total_duration * 1.05],
            show_xticklabels=label_xaxis,
            font_size=font_size,
            bottom_left_spines_only=bottom_left_spines_only,
            grid=False,
            labels=volts_labels if show_volts_label else [],
            show_plot_already=False,
            save_figure_to=save_voltage_traces_to,
            title_above_plot=title_above_plot,
            verbose=verbose)

    if plot_if:

        stims = sorted(if_results.keys())
        stims_pA = [ii * 1000 for ii in stims]

        freqs = [if_results[s] for s in stims]

        if_ax = pynml.generate_plot(
            [stims_pA], [freqs],
            "Firing frequency versus injected current for: %s" % nml2_file,
            colors=[if_iv_color],
            linestyles=['-'],
            markers=['o'],
            linewidths=[linewidth],
            xaxis='Input current (pA)' if label_xaxis else ' ',
            yaxis='Firing frequency (Hz)' if label_yaxis else '',
            xlim=xlim_if,
            ylim=ylim_if,
            show_xticklabels=label_xaxis,
            show_yticklabels=label_yaxis,
            font_size=font_size,
            bottom_left_spines_only=bottom_left_spines_only,
            grid=grid,
            show_plot_already=False,
            save_figure_to=save_if_figure_to,
            title_above_plot=title_above_plot,
            verbose=verbose)

        if save_if_data_to:
            with open(save_if_data_to, 'w') as if_file:
                for i in range(len(stims_pA)):
                    if_file.write("%s\t%s\n" % (stims_pA[i], freqs[i]))
    if plot_iv:

        stims = sorted(iv_results.keys())
        stims_pA = [ii * 1000 for ii in sorted(iv_results.keys())]
        vs = [iv_results[s] for s in stims]

        xs = []
        ys = []
        xs.append([])
        ys.append([])

        for si in range(len(stims)):
            stim = stims[si]
            if len(custom_amps_nA) == 0 and si > 1 and (
                    stims[si] - stims[si - 1]) > step_nA * 1.01:
                xs.append([])
                ys.append([])

            xs[-1].append(stim * 1000)
            ys[-1].append(iv_results[stim])

        iv_ax = pynml.generate_plot(
            xs,
            ys,
            "V at %sms versus I below threshold for: %s" %
            (end_stim, nml2_file),
            colors=[if_iv_color for s in xs],
            linestyles=['-' for s in xs],
            markers=['o' for s in xs],
            xaxis='Input current (pA)' if label_xaxis else '',
            yaxis='Membrane potential (mV)' if label_yaxis else '',
            xlim=xlim_iv,
            ylim=ylim_iv,
            show_xticklabels=label_xaxis,
            show_yticklabels=label_yaxis,
            font_size=font_size,
            linewidths=[linewidth for s in xs],
            bottom_left_spines_only=bottom_left_spines_only,
            grid=grid,
            show_plot_already=False,
            save_figure_to=save_iv_figure_to,
            title_above_plot=title_above_plot,
            verbose=verbose)

        if save_iv_data_to:
            with open(save_iv_data_to, 'w') as iv_file:
                for i in range(len(stims_pA)):
                    iv_file.write("%s\t%s\n" % (stims_pA[i], vs[i]))

    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()

    if return_axes:
        return traces_ax, if_ax, iv_ax

    return if_results
    def run_individual(self, sim_var, show=False):
        """
        Run an individual simulation.

        The candidate data has been flattened into the sim_var dict. The
        sim_var dict contains parameter:value key value pairs, which are
        applied to the model before it is simulated.

        """
        
        nml_doc = read_neuroml2_file(self.neuroml_file, 
                                     include_includes=True,
                                     verbose = True)
                                     
        
        for var_name in sim_var.keys():
            words = var_name.split('/')
            type, id1 = words[0].split(':')
            variable, id2 = words[1].split(':')
            units = words[2]
            value = sim_var[var_name]
            
            print('Changing value of %s (%s) in %s (%s) to: %s %s'%(variable, id2, type, id1, value, units))
            
            if type == 'cell':
                cell = None
                for c in nml_doc.cells:
                    if c.id == id1:
                        cell = c
                        
                if variable == 'channelDensity':
                    
                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities:
                        if cd.id == id2:
                            chanDens = cd
                            
                    chanDens.cond_density = '%s %s'%(value, units)
                else:
                    print('Unknown variable (%s) in variable expression: %s'%(variable, var_name))
            else:
                print('Unknown type (%s) in variable expression: %s'%(type, var_name))
       
                            
                                     
        new_neuroml_file =  '%s/%s'%(self.generate_dir,os.path.basename(self.neuroml_file))
        if new_neuroml_file == self.neuroml_file:
            print('Cannot use a directory for generating into (%s) which is the same location of the NeuroML file (%s)!'% \
                      (self.neuroml_file, self.generate_dir))
                      
        write_neuroml2_file(nml_doc, new_neuroml_file)
    
            
        sim = NeuroMLSimulation(self.ref, 
                             neuroml_file = new_neuroml_file,
                             target = self.target,
                             sim_time = self.sim_time, 
                             dt = self.dt, 
                             simulator = self.simulator, 
                             generate_dir = self.generate_dir)
        
        sim.go()
        
        if show:
            sim.show()
    
        return sim.t, sim.volts
Example #33
0
def generate_Vm_vs_time_plot(nml2_file, 
                                        cell_id, 
                                        inj_amp_nA = 80,
                                        delay_ms = 20,
                                        inj_dur_ms = 60,
                                        sim_dur_ms = 100, 
                                        dt = 0.05,
                                        temperature = "32degC",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        show_plot_already=True, 
                                        simulator="jNeuroML",
                                        include_included=True):
                                            
	# simulation parameters                                            
    nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI
    
    ref = "Test"
    print_comment_v("Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"%
        (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms))
    
    sim_id = 'Vm_%s'%ref
    duration = sim_dur_ms
    ls = LEMSSimulation(sim_id, sim_dur_ms, dt)
    
    ls.include_neuroml2_file(nml2_file, include_included=include_included)
    ls.assign_simulation_target('network')
    nml_doc = nml.NeuroMLDocument(id=cell_id)
    
    nml_doc.includes.append(nml.IncludeType(href=nml2_file))
    
    net = nml.Network(id="network")
    nml_doc.networks.append(net)
    
    input_id = ("input_%s"%str(inj_amp_nA).replace('.','_'))
    pg = nml.PulseGenerator(id=input_id,
                                    delay="%sms"%delay_ms,
                                    duration='%sms'%inj_dur_ms,
                                    amplitude='%spA'%inj_amp_nA)
    nml_doc.pulse_generators.append(pg)
    
    
    pop_id = 'hhpop'
    pop = nml.Population(id=pop_id, component='hhcell', size=1, type="populationList")
    
    inst = nml.Instance(id=0)
    pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(pop)
    
    # Add these to cells
    input_list = nml.InputList(id='il_%s'%input_id,
                                 component=pg.id,
                                 populations=pop_id)
    input = nml.Input(id='0',  target='../hhpop/0/hhcell',
                              destination="synapses")  
    
    input_list.input.append(input)
    net.input_lists.append(input_list)
    
    sim_file_name = '%s.sim.nml'%sim_id
    pynml.write_neuroml2_file(nml_doc, sim_file_name)
    ls.include_neuroml2_file(sim_file_name)


    disp0 = 'Voltage_display'
    ls.create_display(disp0,"Voltages", "-90", "50")
    ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV')
    
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat"%sim_id)
    ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v")
    
    lems_file_name = ls.save_to_file()
    
    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
                                                
 
    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()
        
        
    return of0     
Example #34
0
def generate_current_vs_frequency_curve(nml2_file,
                                        cell_id,
                                        start_amp_nA,
                                        end_amp_nA,
                                        step_nA,
                                        analysis_duration,
                                        analysis_delay,
                                        dt=0.05,
                                        temperature="32degC",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        plot_if=True,
                                        plot_iv=False,
                                        xlim_if=None,
                                        ylim_if=None,
                                        xlim_iv=None,
                                        ylim_iv=None,
                                        show_plot_already=True,
                                        save_if_figure_to=None,
                                        save_iv_figure_to=None,
                                        simulator="jNeuroML",
                                        include_included=True):

    from pyelectro.analysis import max_min
    from pyelectro.analysis import mean_spike_frequency
    import numpy as np

    print_comment_v(
        "Generating FI curve for cell %s in %s using %s (%snA->%snA; %snA steps)"
        % (cell_id, nml2_file, simulator, start_amp_nA, end_amp_nA, step_nA))

    sim_id = 'iv_%s' % cell_id
    duration = analysis_duration + analysis_delay
    ls = LEMSSimulation(sim_id, duration, dt)

    ls.include_neuroml2_file(nml2_file, include_included=include_included)

    stims = []
    amp = start_amp_nA
    while amp <= end_amp_nA:
        stims.append(amp)
        amp += step_nA

    number_cells = len(stims)
    pop = nml.Population(id="population_of_%s" % cell_id,
                         component=cell_id,
                         size=number_cells)

    # create network and add populations
    net_id = "network_of_%s" % cell_id
    net = nml.Network(id=net_id,
                      type="networkWithTemperature",
                      temperature=temperature)
    ls.assign_simulation_target(net_id)
    net_doc = nml.NeuroMLDocument(id=net.id)
    net_doc.networks.append(net)
    net_doc.includes.append(nml.IncludeType(nml2_file))
    net.populations.append(pop)

    for i in range(number_cells):
        stim_amp = "%snA" % stims[i]
        input_id = ("input_%s" % stim_amp).replace('.',
                                                   '_').replace('-', 'min')
        pg = nml.PulseGenerator(id=input_id,
                                delay="0ms",
                                duration="%sms" % duration,
                                amplitude=stim_amp)
        net_doc.pulse_generators.append(pg)

        # Add these to cells
        input_list = nml.InputList(id=input_id,
                                   component=pg.id,
                                   populations=pop.id)
        input = nml.Input(id='0',
                          target="../%s[%i]" % (pop.id, i),
                          destination="synapses")
        input_list.input.append(input)
        net.input_lists.append(input_list)

    net_file_name = '%s.net.nml' % sim_id
    pynml.write_neuroml2_file(net_doc, net_file_name)
    ls.include_neuroml2_file(net_file_name)

    disp0 = 'Voltage_display'
    ls.create_display(disp0, "Voltages", "-90", "50")
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % sim_id)

    for i in range(number_cells):
        ref = "v_cell%i" % i
        quantity = "%s[%i]/v" % (pop.id, i)
        ls.add_line_to_display(disp0, ref, quantity, "1mV",
                               pynml.get_next_hex_color())

        ls.add_column_to_output_file(of0, ref, quantity)

    lems_file_name = ls.save_to_file()

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=plot_voltage_traces,
                                               show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=plot_voltage_traces,
                                                      show_plot_already=False)

    #print(results.keys())
    if_results = {}
    iv_results = {}
    for i in range(number_cells):
        t = np.array(results['t']) * 1000
        v = np.array(results["%s[%i]/v" % (pop.id, i)]) * 1000

        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        spike_times = mm['maxima_times']
        freq = 0
        if len(spike_times) > 2:
            count = 0
            for s in spike_times:
                if s >= analysis_delay and s < (analysis_duration +
                                                analysis_delay):
                    count += 1
            freq = 1000 * count / float(analysis_duration)

        mean_freq = mean_spike_frequency(spike_times)
        # print("--- %s nA, spike times: %s, mean_spike_frequency: %f, freq (%fms -> %fms): %f"%(stims[i],spike_times, mean_freq, analysis_delay, analysis_duration+analysis_delay, freq))
        if_results[stims[i]] = freq

        if freq == 0:
            iv_results[stims[i]] = v[-1]

    if plot_if:

        stims = sorted(if_results.keys())
        stims_pA = [ii * 1000 for ii in stims]

        freqs = [if_results[s] for s in stims]

        pynml.generate_plot([stims_pA], [freqs],
                            "Frequency versus injected current for: %s" %
                            nml2_file,
                            colors=['k'],
                            linestyles=['-'],
                            markers=['o'],
                            xaxis='Input current (pA)',
                            yaxis='Firing frequency (Hz)',
                            xlim=xlim_if,
                            ylim=ylim_if,
                            grid=True,
                            show_plot_already=False,
                            save_figure_to=save_if_figure_to)
    if plot_iv:

        stims = sorted(iv_results.keys())
        stims_pA = [ii * 1000 for ii in sorted(iv_results.keys())]
        vs = [iv_results[s] for s in stims]

        pynml.generate_plot(
            [stims_pA], [vs],
            "Final membrane potential versus injected current for: %s" %
            nml2_file,
            colors=['k'],
            linestyles=['-'],
            markers=['o'],
            xaxis='Input current (pA)',
            yaxis='Membrane potential (mV)',
            xlim=xlim_iv,
            ylim=ylim_iv,
            grid=True,
            show_plot_already=False,
            save_figure_to=save_iv_figure_to)

    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()

    return if_results
Example #35
0
def run_fitted_cell_simulation(sweeps_to_tune_against: List,
                               tuning_report: Dict,
                               simulation_id: str) -> None:
    """Run a simulation with the values obtained from the fitting

    :param tuning_report: tuning report from the optimser
    :type tuning_report: Dict
    :param simulation_id: text id of simulation
    :type simulation_id: str

    """
    # get the fittest variables
    fittest_vars = tuning_report["fittest vars"]
    C = str(fittest_vars["izhikevich2007Cell:Izh2007/C/pF"]) + "pF"
    k = str(
        fittest_vars["izhikevich2007Cell:Izh2007/k/nS_per_mV"]) + "nS_per_mV"
    vr = str(fittest_vars["izhikevich2007Cell:Izh2007/vr/mV"]) + "mV"
    vt = str(fittest_vars["izhikevich2007Cell:Izh2007/vt/mV"]) + "mV"
    vpeak = str(fittest_vars["izhikevich2007Cell:Izh2007/vpeak/mV"]) + "mV"
    a = str(fittest_vars["izhikevich2007Cell:Izh2007/a/per_ms"]) + "per_ms"
    b = str(fittest_vars["izhikevich2007Cell:Izh2007/b/nS"]) + "nS"
    c = str(fittest_vars["izhikevich2007Cell:Izh2007/c/mV"]) + "mV"
    d = str(fittest_vars["izhikevich2007Cell:Izh2007/d/pA"]) + "pA"

    # Create a simulation using our obtained parameters.
    # Note that the tuner generates a graph with the fitted values already, but
    # we want to keep a copy of our fitted cell also, so we'll create a NeuroML
    # Document ourselves also.
    sim_time = 1500.0
    simulation_doc = NeuroMLDocument(id="FittedNet")
    # Add an Izhikevich cell with some parameters to the document
    simulation_doc.izhikevich2007_cells.append(
        Izhikevich2007Cell(
            id="Izh2007",
            C=C,
            v0="-60mV",
            k=k,
            vr=vr,
            vt=vt,
            vpeak=vpeak,
            a=a,
            b=b,
            c=c,
            d=d,
        ))
    simulation_doc.networks.append(Network(id="Network0"))
    # Add a cell for each acquisition list
    popsize = len(sweeps_to_tune_against)
    simulation_doc.networks[0].populations.append(
        Population(id="Pop0", component="Izh2007", size=popsize))

    # Add a current source for each cell, matching the currents that
    # were used in the experimental study.
    counter = 0
    for acq in sweeps_to_tune_against:
        simulation_doc.pulse_generators.append(
            PulseGenerator(
                id="Stim{}".format(counter),
                delay="80ms",
                duration="1000ms",
                amplitude="{}pA".format(currents[acq]),
            ))
        simulation_doc.networks[0].explicit_inputs.append(
            ExplicitInput(target="Pop0[{}]".format(counter),
                          input="Stim{}".format(counter)))
        counter = counter + 1

    # Print a summary
    print(simulation_doc.summary())

    # Write to a neuroml file and validate it.
    reference = "FittedIzhFergusonPyr3"
    simulation_filename = "{}.net.nml".format(reference)
    write_neuroml2_file(simulation_doc, simulation_filename, validate=True)

    simulation = LEMSSimulation(
        sim_id=simulation_id,
        duration=sim_time,
        dt=0.1,
        target="Network0",
        simulation_seed=54321,
    )
    simulation.include_neuroml2_file(simulation_filename)
    simulation.create_output_file("output0", "{}.v.dat".format(simulation_id))
    counter = 0
    for acq in sweeps_to_tune_against:
        simulation.add_column_to_output_file("output0",
                                             "Pop0[{}]".format(counter),
                                             "Pop0[{}]/v".format(counter))
        counter = counter + 1
    simulation_file = simulation.save_to_file()
    # simulate
    run_lems_with_jneuroml(simulation_file,
                           max_memory="2G",
                           nogui=True,
                           plot=False)
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
Example #37
0
def tune_izh_model(acq_list: List, metrics_from_data: Dict,
                   currents: Dict) -> Dict:
    """Tune networks model against the data.

    Here we generate a network with the necessary number of Izhikevich cells,
    one for each current stimulus, and tune them against the experimental data.

    :param acq_list: list of indices of acquisitions/sweeps to tune against
    :type acq_list: list
    :param metrics_from_data: dictionary with the sweep number as index, and
        the dictionary containing metrics generated from the analysis
    :type metrics_from_data: dict
    :param currents: dictionary with sweep number as index and stimulus current
        value
    """

    # length of simulation of the cells---should match the length of the
    # experiment
    sim_time = 1500.0
    # Create a NeuroML template network simulation file that we will use for
    # the tuning
    template_doc = NeuroMLDocument(id="IzhTuneNet")
    # Add an Izhikevich cell with some parameters to the document
    template_doc.izhikevich2007_cells.append(
        Izhikevich2007Cell(
            id="Izh2007",
            C="100pF",
            v0="-60mV",
            k="0.7nS_per_mV",
            vr="-60mV",
            vt="-40mV",
            vpeak="35mV",
            a="0.03per_ms",
            b="-2nS",
            c="-50.0mV",
            d="100pA",
        ))
    template_doc.networks.append(Network(id="Network0"))
    # Add a cell for each acquisition list
    popsize = len(acq_list)
    template_doc.networks[0].populations.append(
        Population(id="Pop0", component="Izh2007", size=popsize))

    # Add a current source for each cell, matching the currents that
    # were used in the experimental study.
    counter = 0
    for acq in acq_list:
        template_doc.pulse_generators.append(
            PulseGenerator(
                id="Stim{}".format(counter),
                delay="80ms",
                duration="1000ms",
                amplitude="{}pA".format(currents[acq]),
            ))
        template_doc.networks[0].explicit_inputs.append(
            ExplicitInput(target="Pop0[{}]".format(counter),
                          input="Stim{}".format(counter)))
        counter = counter + 1

    # Print a summary
    print(template_doc.summary())

    # Write to a neuroml file and validate it.
    reference = "TuneIzhFergusonPyr3"
    template_filename = "{}.net.nml".format(reference)
    write_neuroml2_file(template_doc, template_filename, validate=True)

    # Now for the tuning bits

    # format is type:id/variable:id/units
    # supported types: cell/channel/izhikevich2007cell
    # supported variables:
    #  - channel: vShift
    #  - cell: channelDensity, vShift_channelDensity, channelDensityNernst,
    #  erev_id, erev_ion, specificCapacitance, resistivity
    #  - izhikevich2007Cell: all available attributes

    # we want to tune these parameters within these ranges
    # param: (min, max)
    parameters = {
        "izhikevich2007Cell:Izh2007/C/pF": (100, 300),
        "izhikevich2007Cell:Izh2007/k/nS_per_mV": (0.01, 2),
        "izhikevich2007Cell:Izh2007/vr/mV": (-70, -50),
        "izhikevich2007Cell:Izh2007/vt/mV": (-60, 0),
        "izhikevich2007Cell:Izh2007/vpeak/mV": (35, 70),
        "izhikevich2007Cell:Izh2007/a/per_ms": (0.001, 0.4),
        "izhikevich2007Cell:Izh2007/b/nS": (-10, 10),
        "izhikevich2007Cell:Izh2007/c/mV": (-65, -10),
        "izhikevich2007Cell:Izh2007/d/pA": (50, 500),
    }  # type: Dict[str, Tuple[float, float]]

    # Set up our target data and so on
    ctr = 0
    target_data = {}
    weights = {}
    for acq in acq_list:
        # data to fit to:
        # format: path/to/variable:metric
        # metric from pyelectro, for example:
        # https://pyelectro.readthedocs.io/en/latest/pyelectro.html?highlight=mean_spike_frequency#pyelectro.analysis.mean_spike_frequency
        mean_spike_frequency = "Pop0[{}]/v:mean_spike_frequency".format(ctr)
        average_last_1percent = "Pop0[{}]/v:average_last_1percent".format(ctr)
        first_spike_time = "Pop0[{}]/v:first_spike_time".format(ctr)

        # each metric can have an associated weight
        weights[mean_spike_frequency] = 1
        weights[average_last_1percent] = 1
        weights[first_spike_time] = 1

        # value of the target data from our data set
        target_data[mean_spike_frequency] = metrics_from_data[acq][
            "{}:mean_spike_frequency".format(acq)]
        target_data[average_last_1percent] = metrics_from_data[acq][
            "{}:average_last_1percent".format(acq)]
        target_data[first_spike_time] = metrics_from_data[acq][
            "{}:first_spike_time".format(acq)]

        # only add these if the experimental data includes them
        # these are only generated for traces with spikes
        if "{}:average_maximum".format(acq) in metrics_from_data[acq]:
            average_maximum = "Pop0[{}]/v:average_maximum".format(ctr)
            weights[average_maximum] = 1
            target_data[average_maximum] = metrics_from_data[acq][
                "{}:average_maximum".format(acq)]
        if "{}:average_minimum".format(acq) in metrics_from_data[acq]:
            average_minimum = "Pop0[{}]/v:average_minimum".format(ctr)
            weights[average_minimum] = 1
            target_data[average_minimum] = metrics_from_data[acq][
                "{}:average_minimum".format(acq)]

        ctr = ctr + 1

    # simulator to use
    simulator = "jNeuroML"

    return run_optimisation(
        # Prefix for new files
        prefix="TuneIzh",
        # Name of the NeuroML template file
        neuroml_file=template_filename,
        # Name of the network
        target="Network0",
        # Parameters to be fitted
        parameters=list(parameters.keys()),
        # Our max and min constraints
        min_constraints=[v[0] for v in parameters.values()],
        max_constraints=[v[1] for v in parameters.values()],
        # Weights we set for parameters
        weights=weights,
        # The experimental metrics to fit to
        target_data=target_data,
        # Simulation time
        sim_time=sim_time,
        # EC parameters
        population_size=100,
        max_evaluations=500,
        num_selected=30,
        num_offspring=50,
        mutation_rate=0.9,
        num_elites=3,
        # Seed value
        seed=12345,
        # Simulator
        simulator=simulator,
        dt=0.025,
        show_plot_already='-nogui' not in sys.argv,
        save_to_file="fitted_izhikevich_fitness.png",
        save_to_file_scatter="fitted_izhikevich_scatter.png",
        save_to_file_hist="fitted_izhikevich_hist.png",
        save_to_file_output="fitted_izhikevich_output.png",
        num_parallel_evaluations=4,
    )
Example #38
0
def generate_Vm_vs_time_plot(NML2_file, 
                                        cell_id, 
                                     #   inj_amp_nA = 80,
                                     #   delay_ms = 20,
                                     #   inj_dur_ms = 0.5,
                                        sim_dur_ms = 1000, 
                                        dt = 0.05,
                                        temperature = "35",
                                        spike_threshold_mV=0.,
                                        plot_voltage_traces=False,
                                        show_plot_already=True, 
                                        simulator="jNeuroML_NEURON",
                                        include_included=True):
                                            
	# simulation parameters                                            
    nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI
    
    ref = "iMC1_cell_1_origin"
    print_comment_v("Generating Vm(mV) vs Time(ms) plot for cell %s in %s using %s"% # (Inj %snA / %sms dur after %sms delay)"%
        (cell_id, NML2_file, simulator))#, inj_amp_nA, inj_dur_ms, delay_ms))
    
    sim_id = 'Vm_%s'%ref
    duration = sim_dur_ms
    ls = LEMSSimulation(sim_id, sim_dur_ms, dt)
    
    ls.include_neuroml2_file(NML2_file, include_included=include_included)
    ls.assign_simulation_target('network')
    nml_doc = nml.NeuroMLDocument(id=cell_id)
    
    nml_doc.includes.append(nml.IncludeType(href=NML2_file))
    
    net = nml.Network(id="network", type='networkWithTemperature', temperature='%sdegC'%temperature)
    nml_doc.networks.append(net)
    
    #input_id = ("input_%s"%str(inj_amp_nA).replace('.','_'))
    #pg = nml.PulseGenerator(id=input_id,
    #                                delay="%sms"%delay_ms,
    #                                duration='%sms'%inj_dur_ms,
    #                                amplitude='%spA'%inj_amp_nA)
    #nml_doc.pulse_generators.append(pg)
    
    
    pop_id = 'single_cell'
    pop = nml.Population(id=pop_id, component='iMC1_cell_1_origin', size=1, type="populationList")
    
    inst = nml.Instance(id=0)
    pop.instances.append(inst)
    inst.location = nml.Location(x=0, y=0, z=0)
    net.populations.append(pop)
    
    # Add these to cells
    #input_list = nml.InputList(id='il_%s'%input_id,
    #                             component=pg.id,
    #                             populations=pop_id)
    #input = nml.Input(id='0',  target='../hhpop/0/hhcell',
    #                          destination="synapses")  
    
    #input_list.input.append(input)
    #net.input_lists.append(input_list)
    
    sim_file_name = '%s.sim.nml'%sim_id
    pynml.write_neuroml2_file(nml_doc, sim_file_name)
    ls.include_neuroml2_file(sim_file_name)


    disp0 = 'Voltage_display'
    ls.create_display(disp0,"Voltages", "-90", "50")
    ls.add_line_to_display(disp0, "V", "hhpop/0/hhcell/v", scale='1mV')
    
    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat"%sim_id)
    ls.add_column_to_output_file(of0, "V", "hhpop/0/hhcell/v")
    
    lems_file_name = ls.save_to_file()
    
    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=plot_voltage_traces,
                                                show_plot_already=False)
                                                
 
    if show_plot_already:
        from matplotlib import pyplot as plt
        plt.show()
        #plt.plot("t","V")        
        #plt.title("Vm(mV) vs Time(ms) plot for cell %s in %s using %s (Inj %snA / %sms dur after %sms delay)"% 
        #    (cell_id, nml2_file, simulator, inj_amp_nA, inj_dur_ms, delay_ms))
        #plt.xlabel('Time (ms)')
        #plt.ylabel('Vmemb (mV)')
        #plt.legend(['Test'], loc='upper right')
        
        
    return of0     
Example #39
0
def create_cell():
    """Create the cell.

    :returns: name of the cell nml file
    """
    # Create the nml file and add the ion channels
    hh_cell_doc = NeuroMLDocument(id="cell", notes="HH cell")
    hh_cell_fn = "HH_example_cell.nml"
    hh_cell_doc.includes.append(IncludeType(href=create_na_channel()))
    hh_cell_doc.includes.append(IncludeType(href=create_k_channel()))
    hh_cell_doc.includes.append(IncludeType(href=create_leak_channel()))

    # Define a cell
    hh_cell = Cell(id="hh_cell", notes="A single compartment HH cell")

    # Define its biophysical properties
    bio_prop = BiophysicalProperties(id="hh_b_prop")
    #  notes="Biophysical properties for HH cell")

    # Membrane properties are a type of biophysical properties
    mem_prop = MembraneProperties()
    # Add membrane properties to the biophysical properties
    bio_prop.membrane_properties = mem_prop

    # Append to cell
    hh_cell.biophysical_properties = bio_prop

    # Channel density for Na channel
    na_channel_density = ChannelDensity(id="na_channels", cond_density="120.0 mS_per_cm2", erev="50.0 mV", ion="na", ion_channel="na_channel")
    mem_prop.channel_densities.append(na_channel_density)

    # Channel density for k channel
    k_channel_density = ChannelDensity(id="k_channels", cond_density="360 S_per_m2", erev="-77mV", ion="k", ion_channel="k_channel")
    mem_prop.channel_densities.append(k_channel_density)

    # Leak channel
    leak_channel_density = ChannelDensity(id="leak_channels", cond_density="3.0 S_per_m2", erev="-54.3mV", ion="non_specific", ion_channel="leak_channel")
    mem_prop.channel_densities.append(leak_channel_density)

    # Other membrane properties
    mem_prop.spike_threshes.append(SpikeThresh(value="-20mV"))
    mem_prop.specific_capacitances.append(SpecificCapacitance(value="1.0 uF_per_cm2"))
    mem_prop.init_memb_potentials.append(InitMembPotential(value="-65mV"))

    intra_prop = IntracellularProperties()
    intra_prop.resistivities.append(Resistivity(value="0.03 kohm_cm"))

    # Add to biological properties
    bio_prop.intracellular_properties = intra_prop

    # Morphology
    morph = Morphology(id="hh_cell_morph")
    #  notes="Simple morphology for the HH cell")
    seg = Segment(id="0", name="soma", notes="Soma segment")
    # We want a diameter such that area is 1000 micro meter^2
    # surface area of a sphere is 4pi r^2 = 4pi diam^2
    diam = math.sqrt(1000 / math.pi)
    proximal = distal = Point3DWithDiam(x="0", y="0", z="0", diameter=str(diam))
    seg.proximal = proximal
    seg.distal = distal
    morph.segments.append(seg)
    hh_cell.morphology = morph

    hh_cell_doc.cells.append(hh_cell)
    pynml.write_neuroml2_file(nml2_doc=hh_cell_doc, nml2_file_name=hh_cell_fn, validate=True)
    return hh_cell_fn
Example #40
0
def __main__():
    import customsim
    import modeldata

    MCs = 1
    GCsPerMC = 1

    networkTemplate = FileTemplate("../NeuroML2/Networks/NetworkTemplate.xml")
    includeTemplate = FileTemplate("../NeuroML2/Networks/IncludeTemplate.xml")
    populationTemplate = FileTemplate("../NeuroML2/Networks/PopulationTemplate.xml")
    projectionTemplate = FileTemplate("../NeuroML2/Networks/ProjectionTemplate.xml")

    customsim.setup(MCs, GCsPerMC)
    model = modeldata.getmodel()

    netFile = "../NeuroML2/Networks/Bulb_%iMC_%iGC.net.nml" % (len(model.mitral_gids), len(model.granule_gids))

    includes = ""
    populations = ""
    projections = ""

    mcNMLs = {}
    gcNMLs = {}

#import pydevd
#pydevd.settrace('10.211.55.3', port=4200, stdoutToServer=True, stderrToServer=True)

    # Make MC includes and populations
    for mcgid in model.mitral_gids:

        includes += includeTemplate.text\
            .replace("[CellType]", "Mitral")\
            .replace("[GID]", `mcgid`)

        populations += populationTemplate.text\
            .replace("[CellType]", "Mitral")\
            .replace("[GID]", `mcgid`)\
            .replace("[X]", `model.mitrals[mcgid].x`)\
            .replace("[Y]", `model.mitrals[mcgid].y`)\
            .replace("[Z]", `model.mitrals[mcgid].z`)

        # Retain mitral cell NML
        mcNML = pynml\
                .read_neuroml2_file("../NeuroML2/MitralCells/Exported/Mitral_0_%i.cell.nml" % mcgid)\
                .cells[0]
        
        mcNMLs.update({mcgid:mcNML})

    # Make GC includes and populations
    import granules
    from neuroml.nml.nml import NeuroMLDocument

    for gcgid in model.granule_gids:

        includes += includeTemplate.text\
            .replace("[CellType]", "Granule")\
            .replace("[GID]", `gcgid`)

        populations += populationTemplate.text\
            .replace("[CellType]", "Granule")\
            .replace("[GID]", `gcgid`)\
            .replace("[X]", `granules.gid2pos[gcgid][0]`)\
            .replace("[Y]", `granules.gid2pos[gcgid][1]`)\
            .replace("[Z]", `granules.gid2pos[gcgid][2]`)

        # Retain granule cell NML
        gcNML = pynml\
                .read_neuroml2_file("../NeuroML2/GranuleCells/Exported/Granule_0_%i.cell.nml" % gcgid)\

        gcNMLs.update({gcgid:gcNML})

    # Add a projection for each synapse
    synCount = len(model.mgrss.keys())
    curSyn = 0

    for sgid in model.mgrss.keys():

        print('Building synapse %i of %i' % (curSyn+1,synCount))

        synapse = model.mgrss[sgid]

        nsecden = model.mitrals[synapse.mgid].secden[synapse.isec].nseg
        secdenIndex = min(nsecden-1, int(synapse.xm * nsecden))
        postSegmentId = [seg.id\
                         for seg in mcNMLs[synapse.mgid].morphology.segments\
                         if seg.name == "Seg%i_secden_%i"%(secdenIndex,synapse.isec)\
                        ][0]

        gcNML = gcNMLs[synapse.ggid].cells[0]

        # Position the spine along the GC priden
        import exportHelper
        exportHelper.splitSegmentAlongFraction(gcNML,"Seg0_priden2_0","priden2_0",synapse.xg,'Seg0_neck')
        pynml.write_neuroml2_file(gcNMLs[synapse.ggid], "../NeuroML2/GranuleCells/Exported/Granule_0_%i.cell.nml" % synapse.ggid)

        # Add Dendro-dendritic synapses
        # GC -> MC part
        projections += projectionTemplate.text\
            .replace("[ProjectionID]", `sgid`+'_G2M')\
            .replace("[PreCellType]", "Granule")\
            .replace("[PreGID]", `synapse.ggid`)\
            .replace("[PreSegment]", `4`)\
            .replace("[PreAlong]", `0.5`)\
            .replace("[PostCellType]", "Mitral")\
            .replace("[PostGID]", `synapse.mgid`)\
            .replace("[PostSegment]", `postSegmentId`)\
            .replace("[PostAlong]", "0.5")\
            .replace("[Synapse]", "FIsyn")\

        # MC -> GC part
        projections += projectionTemplate.text\
            .replace("[ProjectionID]", `sgid`+'_M2G')\
            .replace("[PreCellType]", "Mitral")\
            .replace("[PreGID]", `synapse.mgid`)\
            .replace("[PreSegment]", `postSegmentId`)\
            .replace("[PreAlong]", `0.5`)\
            .replace("[PostCellType]", "Granule")\
            .replace("[PostGID]", `synapse.ggid`)\
            .replace("[PostSegment]", `4`)\
            .replace("[PostAlong]", "0.5")\
            .replace("[Synapse]", "AmpaNmdaSyn")\

        curSyn += 1


    network = networkTemplate.text\
        .replace("[IncludesPlaceholder]", includes)\
        .replace("[PopulationsPlaceholder]", populations)\
        .replace("[ProjectionsPlaceholder]", projections)

    with open(netFile, "w") as file:
        file.write(network)

    print('Net file saved to: ' + netFile)
def exportToNML(cells):
    '''
    GCs only vary these parameters:
        id
        priden: length (through y position of distal pt), number of subdivitions (nseg)
	    spine neck: location on parent priden2
    '''

    print("Exporting " + str(len(cells)) + "GCs...")

    exported = []

    for gid in cells.keys():
        print("Exporting GC:" + ` gid ` + "...")

        # Obtain the varying values from the network model
        pridenLength = cells[gid].priden.L
        pridenNseg = cells[gid].priden.nseg
        neckLoc = cells[gid].priden2[0].children()[0].parentseg().x

        # Read the cell template
        from pyneuroml import pynml
        nmldoc = pynml.read_neuroml2_file(
            "../NeuroML2/GranuleCells/GranuleCellTemplate.xml")
        cell = nmldoc.cells[0]

        # Replace placeholders
        cell.id = "Granule_0_" + str(gid)
        next(seg for seg in cell.morphology.segments
             if seg.name == 'priden_seg').distal.y = pridenLength
        next(prop
             for prop in next(section
                              for section in cell.morphology.segment_groups
                              if section.id == 'priden').properties
             if prop.tag == 'numberInternalDivisions').value = pridenNseg
        next(seg for seg in cell.morphology.segments
             if seg.name == 'neck_seg').parent.fraction_along = neckLoc

        # Align the GC along the bulb versor
        import granules
        versor = granules.granule_position_orientation(gid)[1]

        for seg in cell.morphology.segments:
            segLength = seg.length  # retain the original length

            if seg.parent is not None:
                parent = next(parent for parent in cell.morphology.segments
                              if parent.id == seg.parent.segments)
                seg.proximal.x = parent.distal.x
                seg.proximal.y = parent.distal.y
                seg.proximal.z = parent.distal.z

            seg.distal = setAlongVersor(seg.distal, versor, seg.proximal,
                                        segLength)

        # Save the file
        cellFile = "../NeuroML2/GranuleCells/Exported/Granule_0_" + str(
            gid) + ".cell.nml"
        pynml.write_neuroml2_file(nmldoc, cellFile)

        exported.append(cellFile)

    return exported