Example #1
0
    def handle_single_input(self,
                            inputListId,
                            id,
                            cellId,
                            segId=0,
                            fract=0.5,
                            weight=1.0):

        input_list = self.input_lists[inputListId]
        target_path = "../%s/%i/%s" % (
            input_list.populations, cellId,
            self.populations[input_list.populations].component)

        if self.populations[input_list.populations].type == None:
            target_path = "../%s[%i]" % (input_list.populations, cellId)

        if weight == 1:
            input = neuroml.Input(id=id,
                                  target=target_path,
                                  destination="synapses")
            if segId != 0:
                input.segment_id = "%s" % (segId)
            if fract != 0.5:
                input.fraction_along = "%s" % (fract)
            input_list.input.append(input)
        else:
            input_w = neuroml.InputW(id=id,
                                     target=target_path,
                                     destination="synapses")
            if segId != 0:
                input_w.segment_id = "%s" % (segId)
            if fract != 0.5:
                input_w.fraction_along = "%s" % (fract)
            input_w.weight = weight
            input_list.input_ws.append(input_w)
Example #2
0
def init_voltage(nml_doc, net, dClamps, dNumCells):
    """
    Initialise the voltage of cells with voltageClamps (-> no need to create new cell_type.cell.nml files...)
    :param nml_doc: neuroml.NeuroMLDocument() - to which the voltage clamps will be added
    :param net: neuroml.Network() - to which the inputs will be added
    :param dClamps: dictionary which contains the initial voltages (this in hard coded...)
    :param dNumCells: - dictionary created by create_populations, which specifies how many inputs will be added
    """

    vcDur = 1  # ms
    for cell_type, numCells in dNumCells.iteritems():

        clamp = dClamps[cell_type]
        vc = neuroml.VoltageClamp(id="vc_%s" % cell_type,
                                  delay="0ms",
                                  duration="%gms" % vcDur,
                                  simple_series_resistance="5e4ohm",
                                  target_voltage="%gmV" % clamp)
        nml_doc.voltage_clamps.append(vc)

        input_list = neuroml.InputList(id="input_vc_%s" % cell_type,
                                       populations="pop_%s" % cell_type,
                                       component="vc_%s" % cell_type)

        for i in range(0, numCells):

            inp = neuroml.Input(id=i,
                                target="../pop_%s/%g/%scell" %
                                (cell_type, i, cell_type),
                                destination="synapses")
            input_list.input.append(inp)

        net.input_lists.append(input_list)
Example #3
0
    def handleSingleInput(self, inputListId, id, cellId, segId=0, fract=0.5):

        input_list = self.input_lists[inputListId]
        input = neuroml.Input(
            id=id,
            target="../%s/%i/%s" %
            (input_list.populations, cellId,
             self.populations[input_list.populations].component),
            destination="synapses")
        if segId != 0:
            input.segment_id = "%s" % (segId)
        if fract != 0.5:
            input.fraction_along = "%s" % (fract)
        input_list.input.append(input)
def variable_basal_firing_rate(popID, popSize, cellType,
                               input_group_parameters, simulation_duration,
                               seed_number):

    random.seed(seed_number)
    label = input_group_parameters['inputLabel']
    offset_units = input_group_parameters['offsetUnits']
    units = input_group_parameters['ampUnits']
    input_list_array = []
    pulse_generator_array = []
    for cell in range(0, popSize):

        if "gaussian" == input_group_parameters["amplitudeDistribution"]:
            amp = random.gauss(input_group_parameters['averageAmp'],
                               input_group_parameters['stDevAmp'])

        if "uniform" == input_group_parameters["amplitudeDistribution"]:
            amp = random.uniform(input_group_parameters['leftAmpBound'],
                                 input_group_parameters['rightAmpBound'])

        if "constant" == input_group_parameters["amplitudeDistribution"]:
            amp = input_group_parameters['valueAmp']

        if "gaussian" == input_group_parameters["offsetDistribution"]:
            offset = random.gauss(input_group_parameters['averageOffset'],
                                  input_group_parameters['stDevOffset'])

        if "uniform" == input_group_parameters["offsetDistribution"]:
            offset = random.uniform(input_group_parameters['leftOffBound'],
                                    input_group_parameters['rightOffBound'])

        if "constant" == input_group_parameters["offsetDistribution"]:
            offset = input_group_parameters["valueOffset"]

        Pulse_generator_variable=neuroml.PulseGenerator(id="Pulse_%s_%s_%d"%(label,popID,cell),delay="%f%s"%(offset,offset_units),\
        duration="%f%s"%((simulation_duration-offset),offset_units),amplitude="%f%s"%(amp,units))
        pulse_generator_array.append(Pulse_generator_variable)
        Input_list = neuroml.InputList(id="%s_%s_%d" % (label, popID, cell),
                                       component="Pulse_%s_%s_%d" %
                                       (label, popID, cell),
                                       populations="%s" % popID)
        Inp = neuroml.Input(target="../%s/%d/%s" % (popID, cell, cellType),
                            id="%d" % cell,
                            destination="synapses")
        Input_list.input.append(Inp)
        input_list_array.append(Input_list)

    return input_list_array, pulse_generator_array
Example #5
0
 def inject_into(self, cells):
     __doc__ = StandardCurrentSource.inject_into.__doc__
     
     logger.debug("%s injecting into: %s"%(self.__class__.__name__, cells))
     
     self.nml_doc = _get_nml_doc()
     id = self.add_to_nml_doc(self.nml_doc, cells)
     
     
     
     for cell in cells:
         pop_id = cell.parent.label
         index = cell.parent.id_to_index(cell)
         celltype = cell.parent.celltype.__class__.__name__
         logger.debug("Injecting: %s to %s (%s[%s])"%(id, cell, pop_id, index))
         
         input_list = self._get_input_list(id, pop_id)
         
         input = neuroml.Input(id=len(input_list.input), 
                           target="../%s/%i/%s_%s"%(pop_id, index, celltype, pop_id), 
                           destination="synapses")  
         input_list.input.append(input)
    def __getitem__(self, index):

        #print('    Getting instance %s'%(index))
        #print self.array

        id = self.array[index][self._get_index_or_add('id', 0)]
        assert (id == index)

        target_cell_id = int(self.array[index][self._get_index_or_add(
            'target_cell_id', 1)])
        segment_id = int(self.array[index][self._get_index_or_add(
            'segment_id', 1)])
        fraction_along = float(self.array[index][self._get_index_or_add(
            'fraction_along', 1)])

        input = neuroml.Input(id=index,
                              target="../%s/%i/%s" %
                              (self.target_population, target_cell_id, "???"),
                              destination="synapses",
                              segment_id=segment_id,
                              fraction_along=fraction_along)

        return input
def testing(popID, popSize, cellType, input_group_parameters, seed_number,
            saveCellID):

    random.seed(seed_number)
    input_receiving_cells = []
    amp_units = input_group_parameters['ampUnits']
    time_units = input_group_parameters['timeUnits']
    label = input_group_parameters['inputLabel']
    randomly_select_target_cells = random.sample(
        range(popSize),
        int(round(popSize * input_group_parameters['cellFractionToTarget'])))
    pulseGenerator_array = []
    input_list_array = []
    for pulse_x in range(0, len(input_group_parameters['pulseParameters'])):
        Pulse_generator_x=neuroml.PulseGenerator(id="Pulse_%s_%s_%d"%(label,popID,pulse_x),\
        delay="%f%s"%(input_group_parameters['pulseParameters'][pulse_x]['delay'],time_units),\
        duration="%f%s"%(input_group_parameters['pulseParameters'][pulse_x]['duration'],time_units),\
        amplitude="%f%s"%(input_group_parameters['pulseParameters'][pulse_x]['amplitude'],amp_units))
        pulseGenerator_array.append(Pulse_generator_x)

        Input_list = neuroml.InputList(id="%s_%s_%d" % (label, popID, pulse_x),
                                       component="Pulse_%s_%s_%d" %
                                       (label, popID, pulse_x),
                                       populations="%s" % popID)

        for i in randomly_select_target_cells:
            if saveCellID:
                input_receiving_cells.append(i)

            Inp = neuroml.Input(target="../%s/%d/%s" % (popID, i, cellType),
                                id="%d" % i,
                                destination="synapses")
            Input_list.input.append(Inp)

        input_list_array.append(Input_list)

    return input_list_array, pulseGenerator_array, input_receiving_cells
Example #8
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
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 #10
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
Example #11
0
def add_targeted_inputs_to_population(net,
                                      id,
                                      population,
                                      input_comp_id,
                                      segment_group,
                                      number_per_cell=1,
                                      all_cells=False,
                                      only_cells=None):
    """
    Add current input to the specified population. Attributes:
    
    `net`
        reference to the network object previously created

    `id` 
        id of the <inputList> to be created
        
    `population` 
        the <population> to be targeted
        
    `input_comp_id` 
        id of the component to be used for the input (e.g. added with add_pulse_generator())
        
    `segment_group`
        which segment group on the target cells to limit input locations to 

        
    `number_per_cell`
        How many inputs to apply to each cell of the population. Default 1
        
    `all_cells`
        whether to target all cells. Default False
        
    `only_cells`
        which specific cells to target. List of ids. Default None
        
        
    """

    if all_cells and only_cells is not None:
        error = "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" % sys._getframe(
        ).f_code.co_name
        opencortex.print_comment_v(error)
        raise Exception(error)

    cell_ids = []

    target_cell = oc_build.cell_ids_vs_nml_docs[
        population.component].get_by_id(population.component)

    target_segs = oc_build.extract_seg_ids(target_cell, [segment_group],
                                           "segGroups")

    seg_target_dict = oc_build.make_target_dict(target_cell, target_segs)

    subset_dict = {segment_group: number_per_cell}

    if all_cells:
        cell_ids = range(population.size)
    if only_cells is not None:
        if only_cells == []:
            return
        cell_ids = only_cells

    input_list = neuroml.InputList(id=id,
                                   component=input_comp_id,
                                   populations=population.id)
    count = 0
    for cell_id in cell_ids:

        target_seg_array, target_fractions = oc_build.get_target_segments(
            seg_target_dict, subset_dict)

        for i in range(number_per_cell):
            input = neuroml.Input(
                id=count,
                target="../%s/%i/%s" %
                (population.id, cell_id, population.component),
                segment_id=target_seg_array[i],
                fraction_along=target_fractions[i],
                destination="synapses")
            input_list.input.append(input)
            count += 1

    if count > 0:
        net.input_lists.append(input_list)

    return input_list
def XF_input_models_3D_region_specific(popID,
                                       cellType,
                                       cellNML2Type,
                                       input_group_parameters,
                                       cell_positions,
                                       seed_number,
                                       saveCellID,
                                       parentDir=None):

    random.seed(seed_number)
    input_receiving_cells = []
    if parentDir != None:
        cellTypeFile = parentDir + "/NeuroML2" + "/" + cellType
    else:
        cellTypeFile = cellType

    fraction_to_target_per_pop = input_group_parameters['fractionToTarget']

    dim_array = np.shape(cell_positions)
    region_specific_targets_per_cell_group = []
    for region in range(0, len(input_group_parameters['regionList'])):
        for cell in range(0, dim_array[0]):
            if (
                    input_group_parameters['regionList'][region]['xVector'][0]
                    < cell_positions[cell, 0]
            ) and (cell_positions[cell, 0] <
                   input_group_parameters['regionList'][region]['xVector'][1]):
                if (input_group_parameters['regionList'][region]['yVector'][0]
                        < cell_positions[cell, 1]) and (
                            cell_positions[cell, 1] <
                            input_group_parameters['regionList'][region]
                            ['yVector'][1]):
                    if (input_group_parameters['regionList'][region]['zVector']
                        [0] < cell_positions[cell, 2]) and (
                            cell_positions[cell, 2] <
                            input_group_parameters['regionList'][region]
                            ['zVector'][1]):
                        region_specific_targets_per_cell_group.append(cell)

    target_cells = random.sample(
        region_specific_targets_per_cell_group,
        int(
            round(fraction_to_target_per_pop *
                  len(region_specific_targets_per_cell_group))))

    label = input_group_parameters['inputLabel']
    synapse_list = input_group_parameters['synapseList']
    synapse_name_array = []
    poisson_synapse_array = []
    input_list_array = []
    for synapse_index in range(0, len(synapse_list)):
        synapse_name = synapse_list[synapse_index]['synapseType']
        synapse_name_array.append(synapse_name)
        synapse_dict = {}
        if synapse_list[synapse_index][
                'targetingModel'] == "segments and subsegments":
            segment_target_array=extract_morphology_information([cellTypeFile],{cellTypeFile:cellNML2Type},\
                 ["segments",synapse_list[synapse_index]['segmentList']])

        if synapse_list[synapse_index][
                'targetingModel'] == "segment groups and segments":
            segment_target_array =extract_morphology_information([cellTypeFile],{cellTypeFile:cellNML2Type},\
         ["segment groups",synapse_list[synapse_index]['segmentGroupList']])

        if synapse_list[synapse_index]['synapseMode'] == "persistent":
            poisson_syn=neuroml.PoissonFiringSynapse(id="%s_%s_%s_syn%d"%(label,synapse_name,popID,synapse_index),\
                           average_rate="%f per_s"%synapse_list[synapse_index]['averageRate'],\
                           synapse=synapse_list[synapse_index]['synapseType'],\
                           spike_target="./%s"%synapse_list[synapse_index]['synapseType'])
            synapse_dict['synapseMode'] = "persistent"

        if synapse_list[synapse_index]['synapseMode'] == "transient":
            poisson_syn=neuroml.TransientPoissonFiringSynapse(id="%s_%s_%s_syn%d"%(label,synapse_name,popID,synapse_index),\
            average_rate="%f per_s"%synapse_list[synapse_index]['averageRate'],\
            synapse=synapse_list[synapse_index]['synapseType'] ,\
            spike_target="./%s"%synapse_list[synapse_index]['synapseType'],\
            delay="%f%s"%(synapse_list[synapse_index]['delay'],synapse_list[synapse_index]['units']),\
            duration="%f%s"%(synapse_list[synapse_index]['duration'],synapse_list[synapse_index]['units'] )  )
            synapse_dict['synapseMode'] = "transient"

        synapse_dict['synapse_object'] = poisson_syn

        poisson_synapse_array.append(synapse_dict)

        input_list = neuroml.InputList(
            id="List_%s_%s_%s_syn%d" %
            (label, synapse_name, popID, synapse_index),
            component=poisson_syn.id,
            populations="%s" % popID)

        count = 0
        for target_cell in target_cells:
            if saveCellID:
                input_receiving_cells.append(target_cell)
            if synapse_list[synapse_index][
                    'numberModel'] == "constant number of inputs per cell":
                no_of_inputs = synapse_list[synapse_index]['noInputs']
            if synapse_list[synapse_index][
                    'numberModel'] == "variable number of inputs per cell":
                if synapse_list[synapse_index]['distribution'] == "binomial":
                    no_of_inputs=np.random.binomial(synapse_list[synapse_index]['maxNoInputs'],\
                    synapse_list[synapse_index]['averageNoInputs']/synapse_list[synapse_index]['maxNoInputs'])
                ### other options can be added
            if synapse_list[synapse_index][
                    'targetingModel'] == "segment groups and segments":
                target_points=get_unique_target_points(segment_target_array,"segment groups and segments",\
                [synapse_list[synapse_index]['segmentGroupList'],synapse_list[synapse_index]['segmentGroupProbabilities']],no_of_inputs)
            if synapse_list[synapse_index][
                    'targetingModel'] == "segments and subsegments":
                target_points=get_unique_target_points(segment_target_array,"segments and subsegments",\
                [synapse_list[synapse_index]['segmentList'],synapse_list[synapse_index]['segmentProbabilities'],\
                synapse_list[synapse_index]['fractionAlongANDsubsegProbabilities']],no_of_inputs)
            for target_point in range(0, len(target_points)):
                syn_input = neuroml.Input(id="%d"%(count),target="../%s/%i/%s"%(popID,target_cell,cellType),\
                destination="synapses",segment_id="%d"%target_points[target_point,0],fraction_along="%f"%target_points[target_point,1])

                input_list.input.append(syn_input)
                count = count + 1

        input_list_array.append(input_list)
    return input_list_array, poisson_synapse_array, synapse_name_array, input_receiving_cells
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
Example #14
0
def generate_WB_network(cell_id,
                        synapse_id,
                        numCells_bc,
                        connection_probability,
                        I_mean,
                        I_sigma,
                        generate_LEMS_simulation,
                        duration,
                        x_size=100,
                        y_size=100,
                        z_size=100,
                        network_id=ref + 'Network',
                        color='0 0 1',
                        connection=True,
                        temperature='37 degC',
                        validate=True,
                        dt=0.01):

    nml_doc = neuroml.NeuroMLDocument(id=network_id)
    nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsaki.cell.nml'))
    nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiSynapse.xml'))

    # Create network
    net = neuroml.Network(id=network_id,
                          type='networkWithTemperature',
                          temperature=temperature)
    net.notes = 'Network generated using libNeuroML v%s' % __version__
    nml_doc.networks.append(net)

    # Create population
    pop = neuroml.Population(id=ref + 'pop',
                             component=cell_id,
                             type='populationList',
                             size=numCells_bc)
    if color is not None:
        pop.properties.append(neuroml.Property('color', color))
    net.populations.append(pop)

    for i in range(0, numCells_bc):
        inst = neuroml.Instance(id=i)
        pop.instances.append(inst)
        inst.location = neuroml.Location(x=str(x_size * rnd.random()),
                                         y=str(y_size * rnd.random()),
                                         z=str(z_size * rnd.random()))

    # Add connections
    proj = neuroml.ContinuousProjection(id=ref + 'proj',
                                        presynaptic_population=pop.id,
                                        postsynaptic_population=pop.id)

    conn_count = 0
    for i in range(0, numCells_bc):
        for j in range(0, numCells_bc):
            if i != j and rnd.random() < connection_probability:
                connection = neuroml.ContinuousConnectionInstance(
                    id=conn_count,
                    pre_cell='../%s/%i/%s' % (pop.id, i, cell_id),
                    pre_component='silent',
                    post_cell='../%s/%i/%s' % (pop.id, j, cell_id),
                    post_component=synapse_id)
                proj.continuous_connection_instances.append(connection)
                conn_count += 1

    net.continuous_projections.append(proj)

    # make cell pop inhomogenouos (different V_init-s with voltage-clamp)
    vc_dur = 2  # ms
    for i in range(0, numCells_bc):
        tmp = -75 + (rnd.random() * 15)
        vc = neuroml.VoltageClamp(id='VClamp%i' % i,
                                  delay='0ms',
                                  duration='%ims' % vc_dur,
                                  simple_series_resistance='1e6ohm',
                                  target_voltage='%imV' % tmp)

        nml_doc.voltage_clamps.append(vc)

        input_list = neuroml.InputList(id='input_%i' % i,
                                       component='VClamp%i' % i,
                                       populations=pop.id)
        input = neuroml.Input(id=i,
                              target='../%s/%i/%s' % (pop.id, i, cell_id),
                              destination='synapses')
        input_list.input.append(input)

        net.input_lists.append(input_list)

    # Add outer input (IClamp)
    tmp = rnd.normal(I_mean, I_sigma**2,
                     numCells_bc)  # random numbers from Gaussian distribution
    for i in range(0, numCells_bc):
        pg = neuroml.PulseGenerator(id='IClamp%i' % i,
                                    delay='%ims' % vc_dur,
                                    duration='%ims' % (duration - vc_dur),
                                    amplitude='%fpA' % (tmp[i]))

        nml_doc.pulse_generators.append(pg)

        input_list = neuroml.InputList(id='input%i' % i,
                                       component='IClamp%i' % i,
                                       populations=pop.id)
        input = neuroml.Input(id=i,
                              target='../%s/%i/%s' % (pop.id, i, cell_id),
                              destination='synapses')
        input_list.input.append(input)

        net.input_lists.append(input_list)

    # Write to file
    nml_file = '%s100Cells.net.nml' % ref
    print 'Writing network file to:', nml_file, '...'
    neuroml.writers.NeuroMLWriter.write(nml_doc, nml_file)

    if validate:

        # Validate the NeuroML
        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file)

    if generate_LEMS_simulation:

        # Vreate a LEMSSimulation to manage creation of LEMS file
        ls = LEMSSimulation(sim_id='%sNetSim' % ref, duration=duration, dt=dt)

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

        # Incude generated/existing NeuroML2 files
        ls.include_neuroml2_file('WangBuzsaki.cell.nml',
                                 include_included=False)
        ls.include_neuroml2_file('WangBuzsakiSynapse.xml',
                                 include_included=False)
        ls.include_neuroml2_file(nml_file, include_included=False)

        # Specify Display and output files
        disp_bc = 'display_bc'
        ls.create_display(disp_bc, 'Basket Cell Voltage trace', '-80', '40')

        of_bc = 'volts_file_bc'
        ls.create_output_file(of_bc, 'wangbuzsaki_network.dat')

        of_spikes_bc = 'spikes_bc'
        ls.create_event_output_file(of_spikes_bc,
                                    'wangbuzsaki_network_spikes.dat')

        max_traces = 9  # the 10th color in NEURON is white ...
        for i in range(numCells_bc):
            quantity = '%s/%i/%s/v' % (pop.id, i, cell_id)
            if i < max_traces:
                ls.add_line_to_display(disp_bc, 'BC %i: Vm' % i, quantity,
                                       '1mV', pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_bc, 'v_%i' % i, quantity)
            ls.add_selection_to_event_output_file(of_spikes_bc,
                                                  i,
                                                  select='%s/%i/%s' %
                                                  (pop.id, i, cell_id),
                                                  event_port='spike')

        # Save to LEMS file
        print 'Writing LEMS file...'
        lems_file_name = ls.save_to_file()

    else:

        ls = None
        lems_file_name = ''

    return ls, lems_file_name
Example #15
0
conn_count = 0
for pre in range(0, size0):
    # Create a number of random amplitude current pulses
    pg = neuroml.PulseGenerator(id="input%i" % pre,
                                delay="0ms",
                                duration="500ms",
                                amplitude="%fnA" % (0.5 + random.random()))
    nml_doc.pulse_generators.append(pg)

    # Add these to cells
    input_list = neuroml.InputList(id="il%i" % pre,
                                   component=pg.id,
                                   populations=pop0.id)
    input = neuroml.Input(id=pre,
                          target="../%s[%i]" % (pop0.id, pre),
                          destination="synapses")
    input_list.input.append(input)
    net.input_lists.append(input_list)

    # Connect cells with defined probability
    prob_connection = 0.5
    for post in range(0, size1):
        if random.random() <= prob_connection:
            conn = \
                neuroml.Connection(id=conn_count, \
                                   pre_cell_id="../%s[%i]" % (pop0.id, pre),
                                   post_cell_id="../%s[%i]" % (pop1.id, post))
            proj1.connections.append(conn)
            conn_count += 1
Example #16
0
    net.populations.append(pop)

    pg = neuroml.PulseGenerator(id="pulseGen0",
                                delay="100ms",
                                duration="800ms",
                                amplitude="28 pA")

    nml_doc.pulse_generators.append(pg)

    input_list = neuroml.InputList(id='il',
                                   component=pg.id,
                                   populations=pop.id)

    input = neuroml.Input(
        id=0,
        target="../%s/%i/%s" % (pop.id, 0, cell_comp),
        segment_id=3,  # dend tip...
        destination="synapses")

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

    nml_file = '%s/%s.net.nml' % (root_dir, reference)
    writers.NeuroMLWriter.write(nml_doc, nml_file)

    print("Written network file to: " + nml_file)

    ############################################
    #  Create the LEMS file with helper method
    sim_id = 'Sim%s' % reference
    target = net.id
Example #17
0
sgp_pop = neuroml.Population(id="SpikeGeneratorPoissons",
                             size=1,
                             component=sgp.id)
net.populations.append(sgp_pop)

# Add inputs

pfs_input_list = neuroml.InputList(id="pfsInput",
                                   component=pfs.id,
                                   populations=pyr_cells_pop0.id)
net.input_lists.append(pfs_input_list)

pfs_input_list.input.append(
    neuroml.Input(id=0,
                  target='../%s/0/%s' % (pyr_cells_pop0.id, cell_id),
                  destination="synapses"))
pfs_input_list.input.append(
    neuroml.Input(id=1,
                  target='../%s/1/%s' % (pyr_cells_pop0.id, cell_id),
                  segment_id="2",
                  destination="synapses"))
pfs_input_list.input.append(
    neuroml.Input(id=2,
                  target='../%s/2/%s' % (pyr_cells_pop0.id, cell_id),
                  segment_id="4",
                  destination="synapses"))

tsi_input_list = neuroml.InputList(id="tsiInput",
                                   component=tsi.id,
                                   populations=pyr_cells_pop3.id)
Example #18
0
    new_net.populations[0].id = pop_id
    new_net.populations[0].component = pop_comp

    stim_ref = "stim"
    stim = neuroml.PulseGenerator(id=stim_ref, 
                                  delay="1020ms", 
                                  duration="1000ms", 
                                  amplitude="%spA"%get_test_current(model_id))
    new_net_doc.pulse_generators.append(stim)
    
    input_list = neuroml.InputList(id="%s_input"%stim_ref,
                         component=stim_ref,
                         populations=pop_id)

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

    input_list.input.append(input)
    new_net.input_lists.append(input_list)
    
    pynml.write_neuroml2_file(new_net_doc, new_net_loc)

    generate_lems_file_for_neuroml(model_id,
                                   new_net_loc,
                                   "network",
                                   pref_duration_ms,
                                   pref_dt_ms, # used in Allen Neuron runs
                                   "LEMS_%s.xml"%model_id,
                                   nml2_cell_dir,
                                   copy_neuroml = False,
Example #19
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 #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 add_inputs_to_population(net,
                             id,
                             population,
                             input_comp_id,
                             number_per_cell=1,
                             all_cells=False,
                             only_cells=None,
                             segment_ids=[0],
                             fraction_alongs=[0.5]):
    """
    Add current input to the specified population. Attributes:
    
    `net`
        reference to the network object previously created

    `id` 
        id of the <inputList> to be created
        
    `population` 
        the <population> to be targeted
        
    `input_comp_id` 
        id of the component to be used for the input (e.g. added with add_pulse_generator())
        
    `number_per_cell`
        how many inputs to apply to each cell of the population. Default 1
        
    `all_cells`
        Whether to target all cells. Default False
        
    `only_cells`
        Which specific cells to target. List of ids. Default None
        
    `segment_ids`
        List of segment ids to place inputs onto on each cell. Either list of 1 value or list of number_per_cell entries. Default [0]
        
    `fraction_alongs`
        List of fractions along the specified segments to place inputs onto on each cell. Either list of 1 value or list of number_per_cell entries. Default [0.5]
        
        
    """

    if all_cells and only_cells is not None:
        error = "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" % sys._getframe(
        ).f_code.co_name
        opencortex.print_comment_v(error)
        raise Exception(error)

    if len(segment_ids) != 1 or len(segment_ids) != number_per_cell:

        error = "Error! Attribute segment_ids in method opencortex.build.%s()"% sys._getframe().f_code.co_name+\
        " should be a list of one integer (id of the segment all inputs to each cell go into) or a "+ \
        "list of the same length as number_per_cell!"
        opencortex.print_comment_v(error)
        raise Exception(error)

    if len(fraction_alongs) != 1 or len(fraction_alongs) != number_per_cell:

        error = "Error! Attribute fraction_alongs in method opencortex.build.%s()"% sys._getframe().f_code.co_name+\
        " should be a list of one float (fraction along the segment all inputs to each cell go into) or a "+ \
        "list of the same length as number_per_cell!"
        opencortex.print_comment_v(error)
        raise Exception(error)

    cell_ids = []

    if all_cells:
        cell_ids = range(population.size)
    if only_cells is not None:
        if only_cells == []:
            return
        cell_ids = only_cells

    input_list = neuroml.InputList(id=id,
                                   component=input_comp_id,
                                   populations=population.id)
    count = 0
    for cell_id in cell_ids:
        for i in range(number_per_cell):

            segment_id = -1
            if len(segment_ids) == 1:
                segment_id = segment_ids[0]
            else:
                segment_id = segment_ids[i]

            fraction_along = -1
            if len(fraction_alongs) == 1:
                fraction_along = fraction_alongs[0]
            else:
                fraction_along = fraction_alongs[i]

            if fraction_along < 0 or fraction_along > 1:
                error = "Error! Attribute fraction_along should be >=0 and <=1"
                opencortex.print_comment_v(error)
                raise Exception(error)

            input = neuroml.Input(
                id=count,
                target="../%s/%i/%s" %
                (population.id, cell_id, population.component),
                segment_id=segment_id,
                fraction_along=fraction_along,
                destination="synapses")
            input_list.input.append(input)
            count += 1

    if count > 0:
        net.input_lists.append(input_list)

    return input_list
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
inst.location = neuroml.Location(x=0, y=0, z=0)
net.populations.append(pop)

stim = neuroml.PulseGenerator(id='stim0',
                              delay='50ms',
                              duration='200ms',
                              amplitude='0.5nA')

net_doc.pulse_generators.append(stim)

input_list = neuroml.InputList(id="%s_input" % stim.id,
                               component=stim.id,
                               populations=pop.id)

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

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

nml_file = net.id + '.net.nml'

writers.NeuroMLWriter.write(net_doc, nml_file)

print("Saved network file to: " + nml_file)

###### Validate the NeuroML ######

from neuroml.utils import validate_neuroml2
                              synapse="ampa")

    conn = neuroml.Connection(id=0,
                                    pre_cell_id="../%s/%i/%s"%(pc0.id,0,pc0.component), \
                                    pre_segment_id=2, \
                                    pre_fraction_along=0.1,
                                    post_cell_id="../%s/%i/%s"%(pc.id,2,pc.id))
    prc.connections.append(conn)
    nc.projections.append(prc)

    ilc = InputListContainer(id="iii", component="CCC", populations=pc.id)
    nc.input_lists.append(ilc)
    ilc.input.append(
        neuroml.Input(id=0,
                      target="../pyramidals_48/37/pyr_4_sym",
                      destination="synapses",
                      segment_id="2",
                      fraction_along="0.3"))

    nc2 = NetworkContainer(id="testnet2")

    pc2 = PopulationContainer(id="fake2", component="iaf", size=4)
    nc2.populations.append(pc2)

    print(pc)

    nets = [nc, nc2, net0]
    nets = [nc]

    for n in nets:
        print('\n--------------------------------')