Пример #1
0
    def run(self, simulator):

        if simulator == 'jNeuroML':

            from pyneuroml.lems.LEMSSimulation import LEMSSimulation
            ls = LEMSSimulation(self.id, self.duration, self.dt, self.target)
            ls.save_to_file(file_name='LEMS_%s.xml' % self.id)
Пример #2
0
def _get_lems_sim(reference=None, reset=False):
    """Return the main LEMSSimulation object being created"""
    global lems_sim
    global comment
    if reference == None:
        reference = _get_nml_doc().id
    if lems_sim == None or reset:
        # Note: values will be over written
        lems_sim = LEMSSimulation("Sim_%s" % reference,
                                  100,
                                  0.01,
                                  target="network",
                                  comment=comment % 'LEMS')
    return lems_sim
Пример #3
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
Пример #4
0
def generate_lems_file_for_neuroml(sim_id, 
                                   neuroml_file, 
                                   target, 
                                   duration, 
                                   dt, 
                                   lems_file_name,
                                   target_dir,
                                   include_extra_files = [],
                                   gen_plots_for_all_v = True,
                                   plot_all_segments = False,
                                   gen_plots_for_quantities = {},   #  Dict with displays vs lists of quantity paths
                                   gen_plots_for_only_populations = [],   #  List of populations, all pops if = []
                                   gen_saves_for_all_v = True,
                                   save_all_segments = False,
                                   gen_saves_for_only_populations = [],  #  List of populations, all pops if = []
                                   gen_saves_for_quantities = {},   #  Dict with file names vs lists of quantity paths
                                   copy_neuroml = True,
                                   seed=None):
                                       
    
    if seed:
        random.seed(seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input
    
    file_name_full = '%s/%s'%(target_dir,lems_file_name)
    
    print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s'%(file_name_full,neuroml_file))
    
    ls = LEMSSimulation(sim_id, duration, dt, target)
    
    nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=True)
    
    quantities_saved = []
    
    for f in include_extra_files:
        ls.include_neuroml2_file(f, include_included=False)
    
    if not copy_neuroml:
        rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir))
        print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file))
        ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir))
    else:
        print_comment_v("Copying NeuroML file (%s) to: %s (%s)"%(neuroml_file, target_dir, os.path.abspath(target_dir)))
        if os.path.abspath(os.path.dirname(neuroml_file))!=os.path.abspath(target_dir):
            shutil.copy(neuroml_file, target_dir)
        
        neuroml_file_name = os.path.basename(neuroml_file)
        
        ls.include_neuroml2_file(neuroml_file_name, include_included=False)
        
        
        for include in nml_doc.includes:
            incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href)
            print_comment_v(' - Including %s located at %s'%(include.href, incl_curr))
            shutil.copy(incl_curr, target_dir)
            ls.include_neuroml2_file(include.href, include_included=False)
            
            sub_doc = read_neuroml2_file(incl_curr)
        
            for include in sub_doc.includes:
                incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href)
                print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr))
                shutil.copy(incl_curr, target_dir)
                ls.include_neuroml2_file(include.href, include_included=False)
                
                
    if gen_plots_for_all_v or gen_saves_for_all_v or len(gen_plots_for_only_populations)>0 or len(gen_saves_for_only_populations)>0 :
        
        for network in nml_doc.networks:
            for population in network.populations:
                
                quantity_template = "%s[%i]/v"
                component = population.component
                size = population.size
                cell = None
                segment_ids = []
                if plot_all_segments:
                    for c in nml_doc.cells:
                        if c.id == component:
                            cell = c
                            for segment in cell.morphology.segments:
                                segment_ids.append(segment.id)
                            segment_ids.sort()
                        
                if population.type and population.type == 'populationList':
                    quantity_template = "%s/%i/"+component+"/v"
                    size = len(population.instances)
                    
                if gen_plots_for_all_v or population.id in gen_plots_for_only_populations:
                    print_comment('Generating %i plots for %s in population %s'%(size, component, population.id))
   
                    disp0 = 'DispPop__%s'%population.id
                    ls.create_display(disp0, "Membrane potentials of cells in %s"%population.id, "-90", "50")
                    
                    for i in range(size):
                        if cell!=None and plot_all_segments:
                            quantity_template_seg = "%s/%i/"+component+"/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg%(population.id, i, segment_id)
                                ls.add_line_to_display(disp0, "%s[%i] seg %i: v"%(population.id, i, segment_id), quantity, "1mV", get_next_hex_color())
                        else:
                            quantity = quantity_template%(population.id, i)
                            ls.add_line_to_display(disp0, "%s[%i]: v"%(population.id, i), quantity, "1mV", get_next_hex_color())
                
                if gen_saves_for_all_v or population.id in gen_saves_for_only_populations:
                    print_comment('Saving %i values of v for %s in population %s'%(size, component, population.id))
   
                    of0 = 'Volts_file__%s'%population.id
                    ls.create_output_file(of0, "%s.%s.v.dat"%(sim_id,population.id))
                    for i in range(size):
                        if cell!=None and save_all_segments:
                            quantity_template_seg = "%s/%i/"+component+"/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg%(population.id, i, segment_id)
                                ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
                                quantities_saved.append(quantity)
                        else:
                            quantity = quantity_template%(population.id, i)
                            ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
                            quantities_saved.append(quantity)
                        
    for display in gen_plots_for_quantities.keys():
        
        quantities = gen_plots_for_quantities[display]
        ls.create_display(display, "Plots of %s"%display, "-90", "50")
        for q in quantities:
            ls.add_line_to_display(display, safe_variable(q), q, "1", get_next_hex_color())
            
    for file_name in gen_saves_for_quantities.keys():
        
        quantities = gen_saves_for_quantities[file_name]
        ls.create_output_file(file_name, file_name)
        for q in quantities:
            ls.add_column_to_output_file(file_name, safe_variable(q), q)
                        
        
    ls.save_to_file(file_name=file_name_full)
    
    return quantities_saved
Пример #5
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     
Пример #6
0
def generate_lems_file_for_neuroml(sim_id, 
                                   neuroml_file, 
                                   target, 
                                   duration, 
                                   dt, 
                                   lems_file_name,
                                   target_dir,
                                   nml_doc = None,  # Use this if the nml doc has already been loaded (to avoid delay in reload)
                                   include_extra_files = [],
                                   gen_plots_for_all_v = True,
                                   plot_all_segments = False,
                                   gen_plots_for_quantities = {},   # Dict with displays vs lists of quantity paths
                                   gen_plots_for_only_populations = [],   # List of populations, all pops if = []
                                   gen_saves_for_all_v = True,
                                   save_all_segments = False,
                                   gen_saves_for_only_populations = [],  # List of populations, all pops if = []
                                   gen_saves_for_quantities = {},   # Dict with file names vs lists of quantity paths
                                   gen_spike_saves_for_all_somas = False,
                                   gen_spike_saves_for_only_populations = [],  # List of populations, all pops if = []
                                   gen_spike_saves_for_cells = {},  # Dict with file names vs lists of quantity paths
                                   spike_time_format='ID_TIME',
                                   copy_neuroml = True,
                                   report_file_name = None,
                                   lems_file_generate_seed=None,
                                   verbose=False,
                                   simulation_seed=12345):
                                       
    my_random = random.Random()
    if lems_file_generate_seed:
        my_random.seed(lems_file_generate_seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input
    else:
        my_random.seed(12345) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input
    
    file_name_full = '%s/%s'%(target_dir,lems_file_name)
    
    print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s (copy: %s)'%(file_name_full,neuroml_file,copy_neuroml))
    
    ls = LEMSSimulation(sim_id, duration, dt, target,simulation_seed=simulation_seed)
    
    if nml_doc == None:
        nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=verbose)
        nml_doc_inc_not_included = read_neuroml2_file(neuroml_file, include_includes=False, verbose=False)
    else:
        nml_doc_inc_not_included = nml_doc
        
    ls.set_report_file(report_file_name)
    
    quantities_saved = []
    
    for f in include_extra_files:
        ls.include_neuroml2_file(f, include_included=False)
    
    if not copy_neuroml:
        rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir))
        print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file))
        ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir))
    else:
        print_comment_v("Copying a NeuroML file (%s) to: %s (abs path: %s)"%(neuroml_file, target_dir, os.path.abspath(target_dir)))
        
        if not os.path.isdir(target_dir):
            raise Exception("Target directory %s does not exist!"%target_dir)
        
        if os.path.realpath(os.path.dirname(neuroml_file))!=os.path.realpath(target_dir):
            shutil.copy(neuroml_file, target_dir)
        else:
            print_comment_v("No need, same file...")
        
        neuroml_file_name = os.path.basename(neuroml_file)
        
        ls.include_neuroml2_file(neuroml_file_name, include_included=False)
        
        nml_dir = os.path.dirname(neuroml_file) if len(os.path.dirname(neuroml_file))>0 else '.'

        for include in nml_doc_inc_not_included.includes:
            
            if nml_dir=='.' and os.path.isfile(include.href):
                incl_curr = include.href
            else:
                incl_curr = '%s/%s'%(nml_dir,include.href)
                
            if os.path.isfile(include.href):
                incl_curr = include.href
                
                
            print_comment_v(' - Including %s (located at %s; nml dir: %s), copying to %s'%(include.href, incl_curr, nml_dir, target_dir))
            
            '''
            if not os.path.isfile("%s/%s"%(target_dir, os.path.basename(incl_curr))) and \
               not os.path.isfile("%s/%s"%(target_dir, incl_curr)) and \
               not os.path.isfile(incl_curr):
                shutil.copy(incl_curr, target_dir)
            else:
                print_comment_v("No need to copy...")'''
                
            f1 = "%s/%s"%(target_dir, os.path.basename(incl_curr))
            f2 = "%s/%s"%(target_dir, incl_curr)
            if os.path.isfile(f1):
                print_comment_v("No need to copy, file exists: %s..."%f1)
            elif os.path.isfile(f2):
                print_comment_v("No need to copy, file exists: %s..."%f2)
            else:
                shutil.copy(incl_curr, target_dir)
                
                
            ls.include_neuroml2_file(include.href, include_included=False)
            
            sub_doc = read_neuroml2_file(incl_curr)
            
            sub_dir = os.path.dirname(incl_curr) if len(os.path.dirname(incl_curr))>0 else '.'
        
            for include in sub_doc.includes:
                incl_curr = '%s/%s'%(sub_dir,include.href)
                print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr))
                
                if not os.path.isfile("%s/%s"%(target_dir, os.path.basename(incl_curr))) and \
                   not os.path.isfile("%s/%s"%(target_dir, incl_curr)):
                       
                    shutil.copy(incl_curr, target_dir)
                    ls.include_neuroml2_file(include.href, include_included=False)
                
                
    if gen_plots_for_all_v \
       or gen_saves_for_all_v \
       or len(gen_plots_for_only_populations)>0 \
       or len(gen_saves_for_only_populations)>0 \
       or gen_spike_saves_for_all_somas \
       or len(gen_spike_saves_for_only_populations)>0 :
        
        for network in nml_doc.networks:
            for population in network.populations:
                
                variable = "v" # 
                quantity_template_e = "%s[%i]"

                component = population.component
                size = population.size
                cell = None
                segment_ids = []
                
                for c in nml_doc.spike_generator_poissons:
                    if c.id == component:
                        variable = "tsince"
                for c in nml_doc.SpikeSourcePoisson:
                    if c.id == component:
                        variable = "tsince"
                            
                quantity_template = "%s[%i]/"+variable
                if plot_all_segments or gen_spike_saves_for_all_somas:
                    for c in nml_doc.cells:
                        if c.id == component:
                            cell = c
                            for segment in cell.morphology.segments:
                                segment_ids.append(segment.id)
                            segment_ids.sort()
                        
                
                if population.type and population.type == 'populationList':
                    quantity_template = "%s/%i/"+component+"/"+variable
                    quantity_template_e = "%s/%i/"+component+""
                    # Multicompartmental cell
                    ### Needs to be supported in NeuronWriter
                    ###if len(segment_ids)>1:
                    ###    quantity_template_e = "%s/%i/"+component+"/0"
                    size = len(population.instances)
                    
                if gen_plots_for_all_v or population.id in gen_plots_for_only_populations:
                    print_comment('Generating %i plots for %s in population %s'%(size, component, population.id))
   
                    disp0 = 'DispPop__%s'%population.id
                    ls.create_display(disp0, "Membrane potentials of cells in %s"%population.id, "-90", "50")
                    
                    for i in range(size):
                        if cell!=None and plot_all_segments:
                            quantity_template_seg = "%s/%i/"+component+"/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg%(population.id, i, segment_id)
                                ls.add_line_to_display(disp0, "%s[%i] seg %i: v"%(population.id, i, segment_id), quantity, "1mV", get_next_hex_color(my_random))
                        else:
                            quantity = quantity_template%(population.id, i)
                            ls.add_line_to_display(disp0, "%s[%i]: v"%(population.id, i), quantity, "1mV", get_next_hex_color(my_random))
                
                if gen_saves_for_all_v or population.id in gen_saves_for_only_populations:
                    print_comment('Saving %i values of %s for %s in population %s'%(size, variable, component, population.id))
   
                    of0 = 'Volts_file__%s'%population.id
                    ls.create_output_file(of0, "%s.%s.%s.dat"%(sim_id,population.id,variable))
                    for i in range(size):
                        if cell!=None and save_all_segments:
                            quantity_template_seg = "%s/%i/"+component+"/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg%(population.id, i, segment_id)
                                ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
                                quantities_saved.append(quantity)
                        else:
                            quantity = quantity_template%(population.id, i)
                            ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
                            quantities_saved.append(quantity)
                            
                if gen_spike_saves_for_all_somas or population.id in gen_spike_saves_for_only_populations:
                    print_comment('Saving spikes in %i somas for %s in population %s'%(size, component, population.id))
                    
                    eof0 = 'Spikes_file__%s'%population.id
                    ls.create_event_output_file(eof0, "%s.%s.spikes"%(sim_id,population.id), format=spike_time_format)
                    for i in range(size):
                        quantity = quantity_template_e%(population.id, i)
                        ls.add_selection_to_event_output_file(eof0, i, quantity, "spike")
                        quantities_saved.append(quantity)
                            
    for display in gen_plots_for_quantities.keys():
        
        quantities = gen_plots_for_quantities[display]
        max_ = "1"
        min_ = "-1"
        scale = "1"
        
        # Check for v ...
        if quantities and len(quantities)>0 and quantities[0].endswith('/v'):
            max_ = "40"
            min_ = "-80"
            scale = "1mV"
            
        ls.create_display(display, "Plots of %s"%display, min_, max_)
        for q in quantities:
            ls.add_line_to_display(display, safe_variable(q), q, scale, get_next_hex_color(my_random))
            
    for file_name in gen_saves_for_quantities.keys():
        
        quantities = gen_saves_for_quantities[file_name]
        of_id = safe_variable(file_name)
        ls.create_output_file(of_id, file_name)
        for q in quantities:
            ls.add_column_to_output_file(of_id, safe_variable(q), q)
            quantities_saved.append(q)
            
    for file_name in gen_spike_saves_for_cells.keys():
        
        cells = gen_spike_saves_for_cells[file_name]
        of_id = safe_variable(file_name)
        ls.create_event_output_file(of_id, file_name)
        for i, c in enumerate(cells):
            ls.add_selection_to_event_output_file(of_id, i, c, "spike")
            quantities_saved.append(c)
                                    
        
    ls.save_to_file(file_name=file_name_full)
    
    return quantities_saved, ls
Пример #7
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
Пример #8
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 generatePopulationSimulationLEMS(n_pops, baseline, pops, duration, dt, dl):
    # Create simulation
    # Create LEMS file
    dl_str = 'DL' if dl else ''
    sim_file = 'LEMS_WC_%s%s.xml' % (baseline, dl_str)
    sim_id = 'WC_%s%s' % (baseline, dl_str)

    ls = LEMSSimulation(sim_id, duration, dt, 'net1')
    colours = ['#ff0000', '#0000ff']
    colours2 = ['#ff7777', '#7777ff']

    # Add additional LEMS files
    # Add Wilson and Cowan Components
    ls.include_lems_file('WC_Parameters%s.xml' % dl_str, include_included=True)
    # Add the network definition
    ls.include_lems_file('WC_%s%s.net.nml' % (baseline, dl_str),
                         include_included=True)
    ls.set_report_file('report.txt')

    disp2 = 'd2'
    ls.create_display(disp2, 'Rates', -.1, 1.2)
    for pop_idx, pop in enumerate(pops):
        for n_pop in range(n_pops[pop_idx]):
            ls.add_line_to_display(disp2,
                                   'r_%s' % pop,
                                   '%sPop/%d/%s/%s' %
                                   (pop, n_pop, pop, 'R' if dl else 'r'),
                                   color=colours[pop_idx])

    disp1 = 'd1'
    ls.create_display(disp1, 'iSyn', -2, 8)
    for pop_idx, pop in enumerate(pops):
        for n_pop in range(n_pops[pop_idx]):
            ls.add_line_to_display(disp1,
                                   'iSyn_%s' % pop,
                                   '%sPop/%d/%s/iSyn' % (pop, n_pop, pop),
                                   color=colours[pop_idx],
                                   scale=1 if dl else '1nA')
            ls.add_line_to_display(disp1,
                                   'f_%s' % pop,
                                   '%sPop/%d/%s/f' % (pop, n_pop, pop),
                                   color=colours2[pop_idx])

    of1 = 'of_%s' % pop
    ls.create_output_file(of1, 'WC_%s%s.dat' % (baseline, dl_str))
    for pop_idx, pop in enumerate(pops):
        # save rates in output file
        for n_pop in range(n_pops[pop_idx]):
            ls.add_column_to_output_file(
                of1, 'r_%s' % pop,
                '%sPop/%d/%s/%s' % (pop, n_pop, pop, 'R' if dl else 'r'))

    save_path = os.path.join(sim_file)
    ls.save_to_file(file_name=save_path)
def generate_example_network(network_id,
                             numCells_exc,
                             numCells_inh,
                             x_size = 1000,
                             y_size = 100, 
                             z_size = 1000,
                             exc_group_component = "SimpleIaF",
                             inh_group_component = "SimpleIaF_inh",
                             validate = True,
                             random_seed = 1234,
                             generate_lems_simulation = False,
                             connections = True,
                             connection_probability_exc_exc =   0.4,
                             connection_probability_inh_exc =   0.4,
                             connection_probability_exc_inh =   0.4,
                             connection_probability_inh_inh =   0.4,
                             inputs = False,
                             input_firing_rate = 50, # Hz
                             input_offset_min = 0, # nA
                             input_offset_max = 0, # nA
                             num_inputs_per_exc = 4,
                             duration = 500,  # ms
                             dt = 0.05,
                             temperature="32.0 degC"):

    seed(random_seed)

    nml_doc = NeuroMLDocument(id=network_id)

    net = Network(id = network_id, 
                  type = "networkWithTemperature",
                  temperature = temperature)
                  
    net.notes = "Network generated using libNeuroML v%s"%__version__
    nml_doc.networks.append(net)
    
    for cell_comp in set([exc_group_component, inh_group_component]): # removes duplicates
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%cell_comp))

    # The names of the Exc & Inh groups/populations 
    exc_group = "Exc" 
    inh_group = "Inh" 

    # The names of the network connections 
    net_conn_exc_inh = "NetConn_Exc_Inh"
    net_conn_inh_exc = "NetConn_Inh_Exc"
    net_conn_exc_exc = "NetConn_Exc_Exc"
    net_conn_inh_inh = "NetConn_Inh_Inh"

    # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)
    exc_inh_syn = "AMPAR"
    inh_exc_syn = "GABAA"
    exc_exc_syn = "AMPAR"
    inh_inh_syn = "GABAA"

    for syn in [exc_inh_syn, inh_exc_syn]:
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn))


    # Generate excitatory cells 

    exc_pop = Population(id=exc_group, component=exc_group_component, type="populationList", size=numCells_exc)
    net.populations.append(exc_pop)

    for i in range(0, numCells_exc) :
            index = i
            inst = Instance(id=index)
            exc_pop.instances.append(inst)
            inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    # Generate inhibitory cells
    inh_pop = Population(id=inh_group, component=inh_group_component, type="populationList", size=numCells_inh)
    net.populations.append(inh_pop)

    for i in range(0, numCells_inh) :
            index = i
            inst = Instance(id=index)
            inh_pop.instances.append(inst)
            inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    if connections:

        proj_exc_exc = Projection(id=net_conn_exc_exc, presynaptic_population=exc_group, postsynaptic_population=exc_group, synapse=exc_exc_syn)
        net.projections.append(proj_exc_exc)
        
        proj_exc_inh = Projection(id=net_conn_exc_inh, presynaptic_population=exc_group, postsynaptic_population=inh_group, synapse=exc_inh_syn)
        net.projections.append(proj_exc_inh)
        
        proj_inh_exc = Projection(id=net_conn_inh_exc, presynaptic_population=inh_group, postsynaptic_population=exc_group, synapse=inh_exc_syn)
        net.projections.append(proj_inh_exc)
        
        proj_inh_inh = Projection(id=net_conn_inh_inh, presynaptic_population=inh_group, postsynaptic_population=inh_group, synapse=inh_inh_syn)
        net.projections.append(proj_inh_inh)

        count_exc_inh = 0
        count_inh_exc = 0
        count_exc_exc = 0
        count_inh_inh = 0


        for i in range(0, numCells_exc):
            for j in range(0, numCells_inh):
                if i != j:
                    if random()<connection_probability_exc_inh:
                        add_connection(proj_exc_inh, count_exc_inh, exc_group, exc_group_component, i, 0, inh_group, inh_group_component, j, 0)
                        count_exc_inh+=1
                        
                    if random()<connection_probability_inh_exc:

                        add_connection(proj_inh_exc, count_inh_exc, inh_group, inh_group_component, j, 0, exc_group, exc_group_component, i, 0)
                        count_inh_exc+=1
                        
        for i in range(0, numCells_exc):
            for j in range(0, numCells_exc):
                if i != j:
                        
                    if random()<connection_probability_exc_exc:

                        add_connection(proj_exc_exc, count_exc_exc, exc_group, exc_group_component, i, 0, exc_group, exc_group_component, j, 0)
                        count_exc_exc+=1
                    

        for i in range(0, numCells_inh):
            for j in range(0, numCells_inh):
                if i != j:

                    if random()<connection_probability_inh_inh:

                        add_connection(proj_inh_inh, count_inh_inh, inh_group, inh_group_component, j, 0, inh_group, inh_group_component, i, 0)
                        count_inh_inh+=1

    if inputs:
        
        
        if input_firing_rate>0:
            mf_input_syn = "AMPAR"
            if mf_input_syn!=exc_inh_syn and mf_input_syn!=inh_exc_syn:
                nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn))

            rand_spiker_id = "input_%sHz"%input_firing_rate
            
            pfs = PoissonFiringSynapse(id=rand_spiker_id,
                                       average_rate="%s per_s"%input_firing_rate,
                                       synapse=mf_input_syn,
                                       spike_target="./%s"%mf_input_syn)

            nml_doc.poisson_firing_synapses.append(pfs)

            input_list = InputList(id="Input_0",
                                 component=rand_spiker_id,
                                 populations=exc_group)

            count = 0
            for i in range(0, numCells_exc):

                for j in range(num_inputs_per_exc):
                    input = Input(id=count, 
                                  target="../%s/%i/%s"%(exc_group, i, exc_group_component), 
                                  destination="synapses")  
                    input_list.input.append(input)

                count += 1

            net.input_lists.append(input_list)
            
        if input_offset_max != 0 or input_offset_min != 0:
            

            for i in range(0, numCells_exc):

                pg = PulseGenerator(id="PulseGenerator_%i"%i,
                                    delay="0ms",
                                    duration="%sms"%duration,
                                    amplitude="%fnA"%(input_offset_min+(input_offset_max-input_offset_min)*random()))
                nml_doc.pulse_generators.append(pg)

                input_list = InputList(id="Input_Pulse_List_%i"%i,
                                     component=pg.id,
                                     populations=exc_group)

                input = Input(id=0, 
                              target="../%s/%i/%s"%(exc_group, i, exc_group_component), 
                              destination="synapses")  
                input_list.input.append(input)


                net.input_lists.append(input_list)


    #######   Write to file  ######    

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

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


    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file) 
        
    if generate_lems_simulation:
        # Create a LEMSSimulation to manage creation of LEMS file
        
        ls = LEMSSimulation("Sim_%s"%network_id, duration, dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)
        
        # Include generated/existing NeuroML2 files
        ls.include_neuroml2_file('%s.cell.nml'%exc_group_component)
        ls.include_neuroml2_file('%s.cell.nml'%inh_group_component)
        ls.include_neuroml2_file(nml_file)
        

        # Specify Displays and Output Files
        disp_exc = "display_exc"
        ls.create_display(disp_exc, "Voltages Exc cells", "-80", "50")

        of_exc = 'Volts_file_exc'
        ls.create_output_file(of_exc, "v_exc.dat")
        
        disp_inh = "display_inh"
        ls.create_display(disp_inh, "Voltages Inh cells", "-80", "50")

        of_inh = 'Volts_file_inh'
        ls.create_output_file(of_inh, "v_inh.dat")

        for i in range(numCells_exc):
            quantity = "%s/%i/%s/v"%(exc_group, i, exc_group_component)
            ls.add_line_to_display(disp_exc, "Exc %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_exc, "v_%i"%i, quantity)
            
        for i in range(numCells_inh):
            quantity = "%s/%i/%s/v"%(inh_group, i, inh_group_component)
            ls.add_line_to_display(disp_inh, "Inh %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_inh, "v_%i"%i, quantity)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file()
        
    print "-----------------------------------"
Пример #11
0
def generate_lems_file_for_neuroml(sim_id, 
                                   neuroml_file, 
                                   target, 
                                   duration, 
                                   dt, 
                                   lems_file_name,
                                   target_dir,
                                   gen_plots_for_all_v = True,
                                   gen_saves_for_all_v = True,
                                   copy_neuroml = True,
                                   seed=None):
                                       
    
    if seed:
        random.seed(seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input
    
    file_name_full = '%s/%s'%(target_dir,lems_file_name)
    
    print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s'%(file_name_full,neuroml_file))
    
    ls = LEMSSimulation(sim_id, duration, dt, target)
    
    nml_doc = read_neuroml2_file(neuroml_file)
    
    quantities_saved = []
    
    if not copy_neuroml:
        rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir))
        print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file))
        ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir))
    else:
        if os.path.abspath(os.path.dirname(neuroml_file))!=os.path.abspath(target_dir):
            shutil.copy(neuroml_file, target_dir)
        
        neuroml_file_name = os.path.basename(neuroml_file)
        
        ls.include_neuroml2_file(neuroml_file_name, include_included=False)
        
        
        for include in nml_doc.includes:
            incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href)
            print_comment_v(' - Including %s located at %s'%(include.href, incl_curr))
            shutil.copy(incl_curr, target_dir)
            ls.include_neuroml2_file(include.href, include_included=False)
            
            sub_doc = read_neuroml2_file(incl_curr)
        
            for include in sub_doc.includes:
                incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href)
                print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr))
                shutil.copy(incl_curr, target_dir)
                ls.include_neuroml2_file(include.href, include_included=False)
                
                
    if gen_plots_for_all_v or gen_saves_for_all_v:
        
        for network in nml_doc.networks:
            for population in network.populations:
                size = population.size
                component = population.component
                
                quantity_template = "%s[%i]/v"
                if population.type and population.type == 'populationList':
                    quantity_template = "%s/%i/"+component+"/v"
                
                if gen_plots_for_all_v:
                    print_comment('Generating %i plots for %s in population %s'%(size, component, population.id))
   
                    disp0 = 'DispPop__%s'%population.id
                    ls.create_display(disp0, "Voltages of %s"%disp0, "-90", "50")
                    for i in range(size):
                        quantity = quantity_template%(population.id, i)
                        ls.add_line_to_display(disp0, "v %s"%safe_variable(quantity), quantity, "1mV", get_next_hex_color())
                
                if gen_saves_for_all_v:
                    print_comment('Saving %i values of v for %s in population %s'%(size, component, population.id))
   
                    of0 = 'Volts_file__%s'%population.id
                    ls.create_output_file(of0, "%s.%s.v.dat"%(sim_id,population.id))
                    for i in range(size):
                        quantity = quantity_template%(population.id, i)
                        ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
                        quantities_saved.append(quantity)
                        
        
    ls.save_to_file(file_name=file_name_full)
    
    return quantities_saved
def generate_granule_cell_layer(network_id,
                                x_size = 0,     # um
                                y_size = 0,     # um
                                z_size = 0,     # um
                                numCells_grc = 0,
                                numCells_gol = 0,
                                connections = True,
                                connections_method = 'random',
                                connection_probability_grc_gol =   0.2,
                                connection_probability_gol_grc =   0.1,
                                inputs = False,
                                input_firing_rate = 50, # Hz
                                num_inputs_per_grc = 4,
                                validate = True,
                                random_seed = 1234,
                                generate_lems_simulation = False,
                                max_plotted_cells_per_pop = 10,
                                duration = 500,  # ms
                                dt = 0.025,
                                temperature="32.0 degC"):

    seed(random_seed)

    nml_doc = NeuroMLDocument(id=network_id)

    net = Network(id = network_id, 
                  type = "networkWithTemperature",
                  temperature = temperature)
                  
    net.notes = "Network generated using libNeuroML v%s"%__version__
    nml_doc.networks.append(net)

    # The names of the cell type/component used in the populations (Cell Type in neuroConstruct)
    grc_group_component = "Granule_98"
    gol_group_component = "Golgi_98"

    nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component))
    nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component))

    # The names of the Exc & Inh groups/populations (Cell Group in neuroConstruct)
    grc_group = "Grans" 
    gol_group = "Golgis" 

    # The names of the network connections 
    net_conn_grc_gol = "NetConn_Grans_Golgis"
    net_conn_gol_grc = "NetConn_Golgis_Grans"

    # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)
    grc_gol_syn = "AMPA_GranGol"
    gol_grc_syn = "GABAA"

    for syn in [grc_gol_syn, gol_grc_syn]:
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn))

        
    if network_id == 'Solinas2010':
        # Set size and cell numbers for Solinas 2010 network 
        import sys,os
        NEURON_sim_path = '../NEURON'
        sys.path.append(NEURON_sim_path)
        local_path = os.getcwd()
        os.chdir(NEURON_sim_path)
        print os.getcwd()
        import GenerateSolinas2010 as GS2010
        structure = GS2010.GenerateSolinas2010(generate=True)
        os.chdir(local_path)
        goc_data = structure['Golgis']
        grc_data = structure['Granules']
        grc_pos = grc_data['positions']['data']
        goc_pos = goc_data['positions']['data']
        numCells_grc = grc_pos.shape[0]
        numCells_gol = goc_pos.shape[0]
        
    # Generate excitatory cells 

    grc_pop = Population(id=grc_group, component=grc_group_component, type="populationList", size=numCells_grc)
    net.populations.append(grc_pop)

    for i in range(0, numCells_grc) :
            index = i
            inst = Instance(id=index)
            grc_pop.instances.append(inst)
            inst.location = Location(x=str(grc_pos[i,0]), y=str(grc_pos[i,1]), z=str(grc_pos[i,2]))

    # Generate inhibitory cells
    gol_pop = Population(id=gol_group, component=gol_group_component, type="populationList", size=numCells_gol)
    net.populations.append(gol_pop)

    for i in range(0, numCells_gol) :
            index = i
            inst = Instance(id=index)
            gol_pop.instances.append(inst)
            inst.location = Location(x=str(goc_pos[i,0]), y=str(goc_pos[i,1]), z=str(goc_pos[i,2]))
    
    if connections:

        proj_grc_gol = Projection(id=net_conn_grc_gol, presynaptic_population=grc_group, postsynaptic_population=gol_group, synapse=grc_gol_syn)
        net.projections.append(proj_grc_gol)
        proj_gol_grc = Projection(id=net_conn_gol_grc, presynaptic_population=gol_group, postsynaptic_population=grc_group, synapse=gol_grc_syn)
        net.projections.append(proj_gol_grc)

        count_grc_gol = 0
        count_gol_grc = 0

        # Generate exc -> *  connections

        def add_connection(projection, id, pre_pop, pre_component, pre_cell_id, pre_seg_id, post_pop, post_component, post_cell_id, post_seg_id):

            connection = Connection(id=id, \
                                    pre_cell_id="../%s/%i/%s"%(pre_pop, pre_cell_id, pre_component), \
                                    pre_segment_id=pre_seg_id, \
                                    pre_fraction_along=0.5,
                                    post_cell_id="../%s/%i/%s"%(post_pop, post_cell_id, post_component), \
                                    post_segment_id=post_seg_id,
                                    post_fraction_along=0.5)

            projection.connections.append(connection)

        # Connect Granule cells to Golgi cells
        for i in range(0, numCells_grc):
            # get targets for grc[i] from the structure dict
            # print 'Granule ', i , structure['Granules']['divergence_to_goc']['data'][i][1:]
            for j in structure['Granules']['divergence_to_goc']['data'][i][1:]:
                add_connection(proj_grc_gol, count_grc_gol, grc_group, grc_group_component, i, 0, gol_group, gol_group_component, j, 0)
                count_grc_gol+=1

        # Connect Golgi cells to Granule cells
        for i in range(0, numCells_gol):
            # get targets glomeruli for goc[i] from the lol in structure dict
            # print 'Golgi ', i
            # print structure['Golgis']['divergence_to_glom']['data'][i][1:]
            for k in structure['Golgis']['divergence_to_glom']['data'][i][1:]:
                # get target granule cells for glom[k] from the lol in structure dict
                # print 'Glom ', k
                # print structure['Glomeruli']['divergence_to_grc']['data'][k]
                for j in structure['Glomeruli']['divergence_to_grc']['data'][k][1:]:
                    # print 'Granule ', j
                    add_connection(proj_gol_grc, count_gol_grc, gol_group, gol_group_component, i, 0, grc_group, grc_group_component, j, 0)
                    count_gol_grc+=1

    if inputs:
        
        mf_input_syn = "MF_AMPA"
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn))
        
        rand_spiker_id = "input50Hz"
        
        
        #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/>
        pfs = PoissonFiringSynapse(id="input50Hz",
                                   average_rate="%s per_s"%input_firing_rate,
                                   synapse=mf_input_syn,
                                   spike_target="./%s"%mf_input_syn)
                                   
        nml_doc.poisson_firing_synapses.append(pfs)
        
        input_list = InputList(id="Input_0",
                             component=rand_spiker_id,
                             populations=grc_group)
                             
        count = 0
        for i in range(0, numCells_grc):
            
            for j in range(num_inputs_per_grc):
                input = Input(id=count, 
                              target="../%s/%i/%s"%(grc_group, i, grc_group_component), 
                              destination="synapses")  
                input_list.input.append(input)
            
            count += 1
                             
        net.input_lists.append(input_list)


    #######   Write to file  ######    

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

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


    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file) 
        
    if generate_lems_simulation:
        # Create a LEMSSimulation to manage creation of LEMS file
        
        ls = LEMSSimulation("Sim_%s"%network_id, duration, dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)
        
        # Include generated/existing NeuroML2 files
        ls.include_neuroml2_file('%s.cell.nml'%grc_group_component)
        ls.include_neuroml2_file('%s.cell.nml'%gol_group_component)
        ls.include_neuroml2_file(nml_file)
        

        # Specify Displays and Output Files
        disp_grc = "display_grc"
        ls.create_display(disp_grc, "Voltages Granule cells", "-95", "-38")

        of_grc = 'Volts_file_grc'
        ls.create_output_file(of_grc, "v_grc.dat")
        
        disp_gol = "display_gol"
        ls.create_display(disp_gol, "Voltages Golgi cells", "-95", "-38")

        of_gol = 'Volts_file_gol'
        ls.create_output_file(of_gol, "v_gol.dat")

        for i in range(min(numCells_grc,max_plotted_cells_per_pop)):
            quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component)
            ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity)
            
        for i in range(min(numCells_gol,max_plotted_cells_per_pop)):
            quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component)
            ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file()
        
    print "-----------------------------------"
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
Пример #14
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
Пример #15
0
writers.NeuroMLWriter.write(nml_doc, nml_file)


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


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

from neuroml.utils import validate_neuroml2

validate_neuroml2(nml_file)

# Create a LEMSSimulation to manage creation of LEMS file
duration = 1000  # ms
dt = 0.05  # ms
ls = LEMSSimulation(ref, duration, dt)


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

# Include generated/existing NeuroML2 files
ls.include_neuroml2_file(nml_file)

# Specify Displays and Output Files
disp0 = "display_voltages"
ls.create_display(disp0, "Voltages", "-68", "-47")

of0 = 'Volts_file'
ls.create_output_file(of0, "v.dat")
Пример #16
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
Пример #17
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)
Пример #18
0
def generatefISimulationLEMS(population, units):
    # Create LEMS file
    sim_id = 'LEMS_fISim_%s.xml' % population
    ls = LEMSSimulation(sim_id, 200, 0.1, 'net_%s' % population)

    # Add additional LEMS file
    # Add Rate Base Components
    ls.include_lems_file('../RateBased.xml', include_included=True)
    ls.include_lems_file('../CellDefinition.xml', include_included=True)
    # Add specifications for these Rate Based Components
    ls.include_lems_file('../RateBasedSpecifications_high_baseline.xml',
                         include_included=True)
    # Add the network definition
    ls.include_lems_file('fI_%s.nml' % population, include_included=True)

    # Display outputs and check the results plot the lowest, middle and highest values
    middle = math.ceil(units / 2)
    disp0 = 'Rate'
    ls.create_display(disp0, 'Rates', '-2', '45')
    ls.add_line_to_display(disp0,
                           '%s0' % population,
                           '%sPop[0]/r' % population,
                           color='#0000ff')
    ls.add_line_to_display(disp0,
                           '%s%d' % (population, middle),
                           '%sPop[%d]/r' % (population, middle),
                           color='#DDA0DD')
    ls.add_line_to_display(disp0,
                           '%s19' % population,
                           '%sPop[19]/r' % population,
                           color='#00ff00')

    disp1 = 'Voltage'
    ls.create_display(disp1, 'Voltages', '-.072', '-.035')
    ls.add_line_to_display(disp1,
                           '%s0' % population,
                           '%sPop[0]/V' % population,
                           color='#0000ff')
    ls.add_line_to_display(disp1,
                           '%s%d' % (population, middle),
                           '%sPop[%d]/V' % (population, middle),
                           color='#DDA0DD')
    ls.add_line_to_display(disp1,
                           '%s19' % population,
                           '%sPop[19]/V' % population,
                           color='#00ff00')

    # Create output file
    of1 = 'of1'
    ls.create_output_file(of1, 'fI_%s.dat' % population)
    for unit in range(units):
        ls.add_column_to_output_file(of1, 'r%d' % unit,
                                     '%sPop[%d]/r' % (population, unit))
        ls.add_column_to_output_file(of1, 'V%d' % unit,
                                     '%sPop[%d]/V' % (population, unit))

    save_path = os.path.join(sim_id)
    ls.save_to_file(file_name=save_path)
Пример #19
0
def generatePopulationSimulationLEMS(n_pops, baseline, pops, sim_length):
    # Create LEMS file
    sim_id = 'LEMS_PopulationSim%sBaseline.xml' % baseline
    dt = 0.1
    ls = LEMSSimulation(sim_id, sim_length, dt, 'net2')
    colours = ['#0000ff', '#ff0000', '#DDA0DD', '#00ff00']

    # Add additional LEMS files
    # Add Rate Base Components
    ls.include_lems_file('../RateBased.xml', include_included=True)
    ls.include_lems_file('../CellDefinition.xml', include_included=True)
    # Add specifications for the Rate Base Components
    ls.include_lems_file('../RateBasedSpecifications_%s_baseline.xml' %
                         baseline,
                         include_included=True)
    # Add the network definition
    ls.include_lems_file('RandomPopulationRate_%s_baseline.nml' % baseline,
                         include_included=True)

    for pop_idx, pop in enumerate(pops):
        disp1 = '%s' % pop
        ls.create_display(disp1, '%s' % pop, -1, 12)
        for n_pop in range(n_pops[pop_idx]):
            ls.add_line_to_display(disp1,
                                   '%s%d' % (pop, n_pop),
                                   '%sPop/%d/%s/r' % (pop, n_pop, pop.upper()),
                                   color=colours[pop_idx])

    for pop_idx, pop in enumerate(pops):
        # Create output file
        of1 = 'of_%s' % pop
        ls.create_output_file(
            of1, 'Population_%s_%s_baseline.dat' % (pop, baseline))
        for n_pop in range(n_pops[pop_idx]):
            ls.add_column_to_output_file(
                of1, 'r_%s_%d' % (pop, n_pop),
                '%sPop/%d/%s/r' % (pop, n_pop, pop.upper()))

    save_path = os.path.join(sim_id)
    ls.save_to_file(file_name=save_path)
Пример #20
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 generate_granule_cell_layer(network_id,
                                x_size,     # um
                                y_size,     # um
                                z_size,     # um
                                numCells_mf,
                                numCells_grc,
                                numCells_gol,
                                mf_group_component = "MossyFiber",
                                grc_group_component = "Granule_98",
                                gol_group_component = "Golgi_98",
                                connections = True,
                                connection_probability_grc_gol =   0.2,
                                connection_probability_gol_grc =   0.1,
                                inputs = False,
                                input_firing_rate = 50, # Hz
                                num_inputs_per_mf = 4,
                                validate = True,
                                random_seed = 1234,
                                generate_lems_simulation = False,
                                duration = 500,  # ms
                                dt = 0.005,
                                temperature="32.0 degC"):

    seed(random_seed)

    nml_doc = NeuroMLDocument(id=network_id)

    net = Network(id = network_id, 
                  type = "networkWithTemperature",
                  temperature = temperature)
                  
    net.notes = "Network generated using libNeuroML v%s"%__version__
    nml_doc.networks.append(net)

    if numCells_mf>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%mf_group_component))
    if numCells_grc>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component))
    if numCells_gol>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component))

    # The names of the groups/populations 
    mf_group = "MossyFibers" 
    grc_group = "Grans" 
    gol_group = "Golgis" 


    # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)=
    mf_grc_syn = "MF_AMPA"
    grc_gol_syn = "AMPA_GranGol"
    gol_grc_syn = "GABAA"

    for syn in [mf_grc_syn, grc_gol_syn, gol_grc_syn]:
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn))


    # Generate Gran cells 
    if numCells_mf>0:
        add_population_in_rectangular_region(net, mf_group, mf_group_component, numCells_mf, 0, 0, 0, x_size, y_size, z_size, color="0 0 1")
        

    # Generate Gran cells 
    if numCells_grc>0:
        add_population_in_rectangular_region(net, grc_group, grc_group_component, numCells_grc, 0, 0, 0, x_size, y_size, z_size, color="1 0 0")
        
        
    # Generate Golgi cells
    if numCells_gol>0:
        add_population_in_rectangular_region(net, gol_group, gol_group_component, numCells_gol, 0, 0, 0, x_size, y_size, z_size, color="0 1 0")

    if connections:

        add_probabilistic_projection(net, mf_group, mf_group_component, grc_group, grc_group_component, 'NetConn', mf_grc_syn, numCells_mf, numCells_grc, 0.01)
    
        add_probabilistic_projection(net, grc_group, grc_group_component, gol_group, gol_group_component, 'NetConn', grc_gol_syn, numCells_grc, numCells_gol, connection_probability_grc_gol)
        
        add_probabilistic_projection(net, gol_group, gol_group_component, grc_group, grc_group_component, 'NetConn', gol_grc_syn, numCells_gol, numCells_grc, connection_probability_gol_grc)
    

    if inputs:
        
        mf_input_syn = "MFSpikeSyn"
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn))
        
        rand_spiker_id = "input%sHz"%input_firing_rate
        
        
        #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/>
        pfs = PoissonFiringSynapse(id=rand_spiker_id,
                                   average_rate="%s per_s"%input_firing_rate,
                                   synapse=mf_input_syn,
                                   spike_target="./%s"%mf_input_syn)
                                   
        nml_doc.poisson_firing_synapses.append(pfs)
        
        input_list = InputList(id="Input_0",
                             component=rand_spiker_id,
                             populations=mf_group)
                             
        count = 0
        for i in range(0, numCells_mf):
            
            for j in range(num_inputs_per_mf):
                input = Input(id=count, 
                              target="../%s/%i/%s"%(mf_group, i, mf_group_component), 
                              destination="synapses")  
                input_list.input.append(input)
            
            count += 1
                             
        net.input_lists.append(input_list)


    #######   Write to file  ######    

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

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


    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file) 
        
    if generate_lems_simulation:
        # Create a LEMSSimulation to manage creation of LEMS file
        
        ls = LEMSSimulation("Sim_%s"%network_id, duration, dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)
        
        # Include generated/existing NeuroML2 files
        ls.include_neuroml2_file('%s.cell.nml'%grc_group_component)
        ls.include_neuroml2_file('%s.cell.nml'%gol_group_component)
        ls.include_neuroml2_file(nml_file)
        

        # Specify Displays and Output Files
        if numCells_mf>0:
            disp_mf = "display_mf"
            ls.create_display(disp_mf, "Voltages Mossy fibers", "-70", "10")

            of_mf = 'Volts_file_mf'
            ls.create_output_file(of_mf, "v_mf.dat")


            for i in range(numCells_mf):
                quantity = "%s/%i/%s/v"%(mf_group, i, mf_group_component)
                ls.add_line_to_display(disp_mf, "MF %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
                ls.add_column_to_output_file(of_mf, "v_%i"%i, quantity)

        # Specify Displays and Output Files
        if numCells_grc>0:
            disp_grc = "display_grc"
            ls.create_display(disp_grc, "Voltages Granule cells", "-75", "30")

            of_grc = 'Volts_file_grc'
            ls.create_output_file(of_grc, "v_grc.dat")


            for i in range(numCells_grc):
                quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component)
                ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
                ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity)
        
        if numCells_gol>0:
            disp_gol = "display_gol"
            ls.create_display(disp_gol, "Voltages Golgi cells", "-75", "30")

            of_gol = 'Volts_file_gol'
            ls.create_output_file(of_gol, "v_gol.dat")

            for i in range(numCells_gol):
                quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component)
                ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
                ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file()
    else:
        
        ls = None
        
    print "-----------------------------------"
    
    return nml_doc, ls
Пример #22
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
Пример #23
0
def generate_lems_file_for_neuroml(
        sim_id,
        neuroml_file,
        target,
        duration,
        dt,
        lems_file_name,
        target_dir,
        nml_doc=None,  # Use this if the nml doc has already been loaded (to avoid delay in reload)
        include_extra_files=[],
        gen_plots_for_all_v=True,
        plot_all_segments=False,
        gen_plots_for_quantities={},  # Dict with displays vs lists of quantity paths
        gen_plots_for_only_populations=[],  # List of populations, all pops if=[]
        gen_saves_for_all_v=True,
        save_all_segments=False,
        gen_saves_for_only_populations=[],  # List of populations, all pops if=[]
        gen_saves_for_quantities={},  # Dict with file names vs lists of quantity paths
        gen_spike_saves_for_all_somas=False,
        gen_spike_saves_for_only_populations=[],  # List of populations, all pops if=[]
        gen_spike_saves_for_cells={},  # Dict with file names vs lists of quantity paths
        spike_time_format='ID_TIME',
        copy_neuroml=True,
        report_file_name=None,
        lems_file_generate_seed=None,
        verbose=False,
        simulation_seed=12345):

    my_random = random.Random()
    if lems_file_generate_seed:
        my_random.seed(
            lems_file_generate_seed
        )  # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input
    else:
        my_random.seed(
            12345
        )  # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input

    file_name_full = '%s/%s' % (target_dir, lems_file_name)

    print_comment_v(
        'Creating LEMS file at: %s for NeuroML 2 file: %s (copy: %s)' %
        (file_name_full, neuroml_file, copy_neuroml))

    ls = LEMSSimulation(sim_id,
                        duration,
                        dt,
                        target,
                        simulation_seed=simulation_seed)

    if nml_doc is None:
        nml_doc = read_neuroml2_file(neuroml_file,
                                     include_includes=True,
                                     verbose=verbose)
        nml_doc_inc_not_included = read_neuroml2_file(neuroml_file,
                                                      include_includes=False,
                                                      verbose=False)
    else:
        nml_doc_inc_not_included = nml_doc

    ls.set_report_file(report_file_name)

    quantities_saved = []

    for f in include_extra_files:
        ls.include_neuroml2_file(f, include_included=False)

    if not copy_neuroml:
        rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file),
                                       os.path.abspath(target_dir))
        print_comment_v("Including existing NeuroML file (%s) as: %s" %
                        (neuroml_file, rel_nml_file))
        ls.include_neuroml2_file(rel_nml_file,
                                 include_included=True,
                                 relative_to_dir=os.path.abspath(target_dir))
    else:
        print_comment_v(
            "Copying a NeuroML file (%s) to: %s (abs path: %s)" %
            (neuroml_file, target_dir, os.path.abspath(target_dir)))

        if not os.path.isdir(target_dir):
            raise Exception("Target directory %s does not exist!" % target_dir)

        if os.path.realpath(
                os.path.dirname(neuroml_file)) != os.path.realpath(target_dir):
            shutil.copy(neuroml_file, target_dir)
        else:
            print_comment_v("No need, same file...")

        neuroml_file_name = os.path.basename(neuroml_file)

        ls.include_neuroml2_file(neuroml_file_name, include_included=False)

        nml_dir = os.path.dirname(neuroml_file) if len(
            os.path.dirname(neuroml_file)) > 0 else '.'

        for include in nml_doc_inc_not_included.includes:

            if nml_dir == '.' and os.path.isfile(include.href):
                incl_curr = include.href
            else:
                incl_curr = '%s/%s' % (nml_dir, include.href)

            if os.path.isfile(include.href):
                incl_curr = include.href

            print_comment_v(
                ' - Including %s (located at %s; nml dir: %s), copying to %s' %
                (include.href, incl_curr, nml_dir, target_dir))
            '''
            if not os.path.isfile("%s/%s" % (target_dir, os.path.basename(incl_curr))) and \
               not os.path.isfile("%s/%s" % (target_dir, incl_curr)) and \
               not os.path.isfile(incl_curr):
                shutil.copy(incl_curr, target_dir)
            else:
                print_comment_v("No need to copy...")'''

            f1 = "%s/%s" % (target_dir, os.path.basename(incl_curr))
            f2 = "%s/%s" % (target_dir, incl_curr)
            if os.path.isfile(f1):
                print_comment_v("No need to copy, file exists: %s..." % f1)
            elif os.path.isfile(f2):
                print_comment_v("No need to copy, file exists: %s..." % f2)
            else:
                shutil.copy(incl_curr, target_dir)

            ls.include_neuroml2_file(include.href, include_included=False)
            sub_doc = read_neuroml2_file(incl_curr)
            sub_dir = os.path.dirname(incl_curr) if len(
                os.path.dirname(incl_curr)) > 0 else '.'

            if sub_doc.__class__ == neuroml.nml.nml.NeuroMLDocument:
                for include in sub_doc.includes:
                    incl_curr = '%s/%s' % (sub_dir, include.href)
                    print_comment_v(' -- Including %s located at %s' %
                                    (include.href, incl_curr))

                    if not os.path.isfile("%s/%s" % (target_dir, os.path.basename(incl_curr))) and \
                       not os.path.isfile("%s/%s" % (target_dir, incl_curr)):

                        shutil.copy(incl_curr, target_dir)
                        ls.include_neuroml2_file(include.href,
                                                 include_included=False)

    if gen_plots_for_all_v \
       or gen_saves_for_all_v \
       or len(gen_plots_for_only_populations) > 0 \
       or len(gen_saves_for_only_populations) > 0 \
       or gen_spike_saves_for_all_somas \
       or len(gen_spike_saves_for_only_populations) > 0:

        for network in nml_doc.networks:
            for population in network.populations:

                variable = "v"
                quantity_template_e = "%s[%i]"

                component = population.component
                size = population.size
                cell = None
                segment_ids = []

                for c in nml_doc.spike_generator_poissons:
                    if c.id == component:
                        variable = "tsince"
                for c in nml_doc.SpikeSourcePoisson:
                    if c.id == component:
                        variable = "tsince"

                quantity_template = "%s[%i]/" + variable
                if plot_all_segments or gen_spike_saves_for_all_somas:
                    for c in nml_doc.cells:
                        if c.id == component:
                            cell = c
                            for segment in cell.morphology.segments:
                                segment_ids.append(segment.id)
                            segment_ids.sort()

                if population.type and population.type == 'populationList':
                    quantity_template = "%s/%i/" + component + "/" + variable
                    quantity_template_e = "%s/%i/" + component + ""
                    #  Multicompartmental cell
                    #  Needs to be supported in NeuronWriter
                    # if len(segment_ids)>1:
                    #     quantity_template_e = "%s/%i/"+component+"/0"
                    size = len(population.instances)

                if gen_plots_for_all_v or population.id in gen_plots_for_only_populations:
                    print_comment(
                        'Generating %i plots for %s in population %s' %
                        (size, component, population.id))

                    disp0 = 'DispPop__%s' % population.id
                    ls.create_display(
                        disp0,
                        "Membrane potentials of cells in %s" % population.id,
                        "-90", "50")

                    for i in range(size):
                        if cell is not None and plot_all_segments:
                            quantity_template_seg = "%s/%i/" + component + "/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg % (
                                    population.id, i, segment_id)
                                ls.add_line_to_display(
                                    disp0, "%s[%i] seg %i: v" %
                                    (population.id, i, segment_id), quantity,
                                    "1mV", get_next_hex_color(my_random))
                        else:
                            quantity = quantity_template % (population.id, i)
                            ls.add_line_to_display(
                                disp0, "%s[%i]: v" % (population.id, i),
                                quantity, "1mV", get_next_hex_color(my_random))

                if gen_saves_for_all_v or population.id in gen_saves_for_only_populations:
                    print_comment(
                        'Saving %i values of %s for %s in population %s' %
                        (size, variable, component, population.id))

                    of0 = 'Volts_file__%s' % population.id
                    ls.create_output_file(
                        of0,
                        "%s.%s.%s.dat" % (sim_id, population.id, variable))
                    for i in range(size):
                        if cell is not None and save_all_segments:
                            quantity_template_seg = "%s/%i/" + component + "/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg % (
                                    population.id, i, segment_id)
                                ls.add_column_to_output_file(
                                    of0, 'v_%s' % safe_variable(quantity),
                                    quantity)
                                quantities_saved.append(quantity)
                        else:
                            quantity = quantity_template % (population.id, i)
                            ls.add_column_to_output_file(
                                of0, 'v_%s' % safe_variable(quantity),
                                quantity)
                            quantities_saved.append(quantity)

                if gen_spike_saves_for_all_somas or population.id in gen_spike_saves_for_only_populations:
                    print_comment(
                        'Saving spikes in %i somas for %s in population %s' %
                        (size, component, population.id))

                    eof0 = 'Spikes_file__%s' % population.id
                    ls.create_event_output_file(eof0,
                                                "%s.%s.spikes" %
                                                (sim_id, population.id),
                                                format=spike_time_format)
                    for i in range(size):
                        quantity = quantity_template_e % (population.id, i)
                        ls.add_selection_to_event_output_file(
                            eof0, i, quantity, "spike")
                        quantities_saved.append(quantity)

    for display in sorted(gen_plots_for_quantities.keys()):

        quantities = gen_plots_for_quantities[display]
        max_ = "1"
        min_ = "-1"
        scale = "1"

        # Check for v ...
        if quantities and len(quantities) > 0 and quantities[0].endswith('/v'):
            max_ = "40"
            min_ = "-80"
            scale = "1mV"

        ls.create_display(display, "Plots of %s" % display, min_, max_)
        for q in quantities:
            ls.add_line_to_display(display, safe_variable(q), q, scale,
                                   get_next_hex_color(my_random))

    for file_name in sorted(gen_saves_for_quantities.keys()):
        quantities = gen_saves_for_quantities[file_name]
        of_id = safe_variable(file_name)
        ls.create_output_file(of_id, file_name)
        for q in quantities:
            ls.add_column_to_output_file(of_id, safe_variable(q), q)
            quantities_saved.append(q)

    for file_name in sorted(gen_spike_saves_for_cells.keys()):

        quantities = gen_spike_saves_for_cells[file_name]
        of_id = safe_variable(file_name)
        ls.create_event_output_file(of_id, file_name)
        pop_here = None
        for i, quantity in enumerate(quantities):
            pop, index = get_pop_index(quantity)
            if pop_here:
                if pop_here != pop:
                    raise Exception('Problem with generating LEMS for saving spikes for file %s.\n' % file_name + \
                                    'Multiple cells from different populations in one file will cause issues with index/spike id.')
            pop_here = pop
            # print('===== Adding to %s (%s) event %i for %s, pop: %s, i: %s' % (file_name, of_id, i, quantity, pop, index))
            ls.add_selection_to_event_output_file(of_id, index, quantity,
                                                  "spike")
            quantities_saved.append(quantity)

    ls.save_to_file(file_name=file_name_full)
    return quantities_saved, ls
Пример #24
0
def generate_hippocampal_net(network_id,
                             conndata="430",
                             nrn_runname="TestRun",
                             validate=True,
                             randomSeed=12345,
                             generate_LEMS_simulation=False,
                             duration=100,
                             dt=0.01,
                             temperature="34.0 degC"):

    seed(randomSeed)

    cell_types = [
        'axoaxonic', 'bistratified', 'cck', 'cutsuridis', 'ivy', 'ngf', 'olm',
        'poolosyn', 'pvbasket', 'sca'
    ]
    synapse_types = ['exp2Synapses', 'customGABASynapses']

    ###### Create network doc #####

    nml_doc = neuroml.NeuroMLDocument(id=network_id)

    for cell in cell_types:
        nml_doc.includes.append(
            neuroml.IncludeType(href="../cells/%s.cell.nml" % cell))
    for synapse in synapse_types:
        nml_doc.includes.append(
            neuroml.IncludeType(href="../synapses/%s.synapse.nml" % synapse))
    nml_doc.includes.append(neuroml.IncludeType(href="stimulations.nml"))

    # Create network
    net = neuroml.Network(id=network_id,
                          type="networkWithTemperature",
                          temperature=temperature)

    from neuroml import __version__
    net.notes = "Network generated using libNeuroML v%s" % __version__
    nml_doc.networks.append(net)

    # Create populations
    print("Creating populations...")
    dCellIDs, dNumCells = create_populations(net, cell_types, nrn_runname,
                                             randomSeed)

    # Create synapses
    print("Connecting cells...")
    add_synapses(net,
                 conndata,
                 nrn_runname,
                 dCellIDs,
                 dNumCells,
                 write_synapse_file=False)

    # initialise voltage
    print("Initialising cell voltage..")
    # TODO: this shouldn't be hard coded ...
    dClamps = {}
    dClamps["axoaxonic"] = -65.0127
    dClamps["bistratified"] = -67.0184
    dClamps["cck"] = -70.6306
    dClamps["ivy"] = -59.9512
    dClamps["ngf"] = -59.9512
    dClamps["olm"] = -71.1411
    dClamps["poolosyn"] = -62.9601
    dClamps["pvbasket"] = -65.0246
    dClamps["sca"] = -70.5652
    init_voltage(nml_doc, net, dClamps, dNumCells)

    #######   Write to file  ######

    print("Saving to file...")
    nml_file = network_id + '.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)
    print("Written network file to: " + nml_file)

    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file)

    if generate_LEMS_simulation:

        # Create a LEMSSimulation to manage creation of LEMS file
        ls = LEMSSimulation('Sim_' + network_id, duration, dt)

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

        # Incude generated/existing NeuroML2 files
        channel_types = [
            'CavL', 'CavN', 'HCN', 'HCNolm', 'HCNp', 'KCaS', 'Kdrfast',
            'Kdrfastngf', 'Kdrp', 'Kdrslow', 'KvA', 'KvAdistp', 'KvAngf',
            'KvAolm', 'KvAproxp', 'KvCaB', 'KvGroup', 'Nav', 'Navaxonp',
            'Navbis', 'Navcck', 'Navngf', 'Navp', 'leak_chan'
        ]

        for channel in channel_types:
            ls.include_neuroml2_file("../channels/%s.channel.nml" % channel,
                                     include_included=False)
        ls.include_neuroml2_file("../channels/Capool.nml",
                                 include_included=False)
        for cell in cell_types:
            ls.include_neuroml2_file("../cells/%s.cell.nml" % cell,
                                     include_included=False)
        for synapse in synapse_types:
            ls.include_neuroml2_file("../synapses/%s.synapse.nml" % synapse,
                                     include_included=False)
        ls.include_neuroml2_file("stimulations.nml", include_included=False)
        ls.include_neuroml2_file(nml_file, include_included=False)

        ###### Specify Display and output files #####

        max_traces = 9  # the 10th color in NEURON is white ...

        for cell_type, numCells in dNumCells.iteritems():
            PC = False
            if numCells > 0:
                of = "of_%s" % cell_type
                ls.create_output_file(of, "%s.v.dat" % cell_type)
                if cell_type == 'poolosyn' or cell_type == 'cutsuridis':  # TODO: ensure that only one of them is used for modelling pyramidal cells (in a given simulation)
                    PC = True
                    ls.create_event_output_file("spikes_PC", "PC.spikes.dat")
                    ls.create_display("disp_PC", "Voltages Pyramidal cells",
                                      "-80", "50")

                cell_id = "%scell" % cell_type
                pop_id = "pop_%s" % cell_type
                for i in range(numCells):
                    quantity = "%s/%i/%s/v" % (pop_id, i, cell_id)
                    ls.add_column_to_output_file(of, "v_%i" % i, quantity)
                    if PC:
                        ls.add_selection_to_event_output_file(
                            "spikes_PC",
                            i,
                            select='%s/%i/%s' % (pop_id, i, cell_id),
                            event_port='spike')
                        if i < max_traces:
                            ls.add_line_to_display("disp_PC",
                                                   "PC %i: V[mV]" % i,
                                                   quantity, "1mV",
                                                   pynml.get_next_hex_color())

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

    else:

        ls = None
        lems_file_name = ''
        print("-----------------------------------")

    return ls, lems_file_name
Пример #25
0
    def createModel(self):

        # File names of all components
        pyr_file_name = "../ACnet2_NML2/Cells/pyr_4_sym.cell.nml"
        bask_file_name = "../ACnet2_NML2/Cells/bask.cell.nml"

        exc_exc_syn_names = '../ACnet2_NML2/Synapses/AMPA_syn.synapse.nml'
        exc_inh_syn_names = '../ACnet2_NML2/Synapses/AMPA_syn_inh.synapse.nml'
        inh_exc_syn_names = '../ACnet2_NML2/Synapses/GABA_syn.synapse.nml'
        inh_inh_syn_names = '../ACnet2_NML2/Synapses/GABA_syn_inh.synapse.nml'
        bg_exc_syn_names = '../ACnet2_NML2/Synapses/bg_AMPA_syn.synapse.nml'

        nml_doc = NeuroMLDocument(id=self.filename + '_doc')
        net = Network(id=self.filename + '_net')
        nml_doc.networks.append(net)

        nml_doc.includes.append(IncludeType(pyr_file_name))
        nml_doc.includes.append(IncludeType(bask_file_name))
        nml_doc.includes.append(IncludeType(exc_exc_syn_names))
        nml_doc.includes.append(IncludeType(exc_inh_syn_names))
        nml_doc.includes.append(IncludeType(inh_exc_syn_names))
        nml_doc.includes.append(IncludeType(inh_inh_syn_names))
        nml_doc.includes.append(IncludeType(bg_exc_syn_names))

        # Create a LEMSSimulation to manage creation of LEMS file
        ls = LEMSSimulation(self.filename, self.sim_time, self.dt)

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

        # The names of the cell type/component used in the Exc & Inh populations
        exc_group_component = "pyr_4_sym"
        inh_group_component = "bask"

        # The names of the Exc & Inh groups/populations
        exc_group = "pyramidals"  #"pyramidals48x48"
        inh_group = "baskets"  #"baskets24x24"

        # The names of the network connections
        net_conn_exc_exc = "pyr_pyr"
        net_conn_exc_inh = "pyr_bask"
        net_conn_inh_exc = "bask_pyr"
        net_conn_inh_inh = "bask_bask"

        # The names of the synapse types
        exc_exc_syn = "AMPA_syn"
        exc_exc_syn_seg_id = 3  # Middle apical dendrite
        exc_inh_syn = "AMPA_syn_inh"
        exc_inh_syn_seg_id = 1  # Dendrite
        inh_exc_syn = "GABA_syn"
        inh_exc_syn_seg_id = 6  # Basal dendrite
        inh_inh_syn = "GABA_syn_inh"
        inh_inh_syn_seg_id = 0  # Soma

        aff_exc_syn = "AMPA_aff_syn"
        aff_exc_syn_seg_id = 5  # proximal apical dendrite

        bg_exc_syn = "bg_AMPA_syn"
        bg_exc_syn_seg_id = 7  # Basal dendrite

        # Excitatory Parameters
        XSCALE_ex = 24  #48
        ZSCALE_ex = 24  #48
        xSpacing_ex = 40  # 10^-6m
        zSpacing_ex = 40  # 10^-6m

        # Inhibitory Parameters
        XSCALE_inh = 12  #24
        ZSCALE_inh = 12  #24
        xSpacing_inh = 80  # 10^-6m
        zSpacing_inh = 80  # 10^-6m

        numCells_ex = XSCALE_ex * ZSCALE_ex
        numCells_inh = XSCALE_inh * ZSCALE_inh

        # Connection probabilities (initial value)
        connection_probability_ex_ex = 0.15
        connection_probability_ex_inh = 0.45
        connection_probability_inh_ex = 0.6
        connection_probability_inh_inh = 0.6

        # Generate excitatory cells

        exc_pop = Population(id=exc_group,
                             component=exc_group_component,
                             type="populationList",
                             size=XSCALE_ex * ZSCALE_ex)
        net.populations.append(exc_pop)

        exc_pos = np.zeros((XSCALE_ex * ZSCALE_ex, 2))

        for i in range(0, XSCALE_ex):
            for j in range(0, ZSCALE_ex):
                # create cells
                x = i * xSpacing_ex
                z = j * zSpacing_ex
                index = i * ZSCALE_ex + j

                inst = Instance(id=index)
                exc_pop.instances.append(inst)

                inst.location = Location(x=x, y=0, z=z)

                exc_pos[index, 0] = x
                exc_pos[index, 1] = z

        # Generate inhibitory cells

        inh_pop = Population(id=inh_group,
                             component=inh_group_component,
                             type="populationList",
                             size=XSCALE_inh * ZSCALE_inh)
        net.populations.append(inh_pop)

        inh_pos = np.zeros((XSCALE_inh * ZSCALE_inh, 2))

        for i in range(0, XSCALE_inh):
            for j in range(0, ZSCALE_inh):
                # create cells
                x = i * xSpacing_inh
                z = j * zSpacing_inh
                index = i * ZSCALE_inh + j

                inst = Instance(id=index)
                inh_pop.instances.append(inst)

                inst.location = Location(x=x, y=0, z=z)

                inh_pos[index, 0] = x
                inh_pos[index, 1] = z

        proj_exc_exc = Projection(id=net_conn_exc_exc,
                                  presynaptic_population=exc_group,
                                  postsynaptic_population=exc_group,
                                  synapse=exc_exc_syn)
        net.projections.append(proj_exc_exc)
        proj_exc_inh = Projection(id=net_conn_exc_inh,
                                  presynaptic_population=exc_group,
                                  postsynaptic_population=inh_group,
                                  synapse=exc_inh_syn)
        net.projections.append(proj_exc_inh)
        proj_inh_exc = Projection(id=net_conn_inh_exc,
                                  presynaptic_population=inh_group,
                                  postsynaptic_population=exc_group,
                                  synapse=inh_exc_syn)
        net.projections.append(proj_inh_exc)
        proj_inh_inh = Projection(id=net_conn_inh_inh,
                                  presynaptic_population=inh_group,
                                  postsynaptic_population=inh_group,
                                  synapse=inh_inh_syn)
        net.projections.append(proj_inh_inh)

        # Generate exc -> *  connections

        exc_exc_conn = np.zeros((numCells_ex, numCells_ex))
        exc_inh_conn = np.zeros((numCells_ex, numCells_inh))

        count_exc_exc = 0
        count_exc_inh = 0
        for i in range(0, XSCALE_ex):
            for j in range(0, ZSCALE_ex):
                x = i * xSpacing_ex
                y = j * zSpacing_ex
                index = i * ZSCALE_ex + j
                #print("Looking at connections for exc cell at (%i, %i)"%(i,j))

                # exc -> exc  connections
                conn_type = net_conn_exc_exc
                for k in range(0, XSCALE_ex):
                    for l in range(0, ZSCALE_ex):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_ex
                        yk = l * zSpacing_ex
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_ex_ex * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_ex + l
                            count_exc_exc += 1

                            add_connection(proj_exc_exc, count_exc_exc,
                                           exc_group, exc_group_component,
                                           index, 0, exc_group,
                                           exc_group_component, index2,
                                           exc_exc_syn_seg_id)

                            exc_exc_conn[index, index2] = 1

                # exc -> inh  connections
                conn_type = net_conn_exc_inh
                for k in range(0, XSCALE_inh):
                    for l in range(0, ZSCALE_inh):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_inh
                        yk = l * zSpacing_inh
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_ex_inh * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_inh + l
                            count_exc_inh += 1

                            add_connection(proj_exc_inh, count_exc_inh,
                                           exc_group, exc_group_component,
                                           index, 0, inh_group,
                                           inh_group_component, index2,
                                           exc_inh_syn_seg_id)

                            exc_inh_conn[index, index2] = 1

        inh_exc_conn = np.zeros((numCells_inh, numCells_ex))
        inh_inh_conn = np.zeros((numCells_inh, numCells_inh))

        count_inh_exc = 0
        count_inh_inh = 0
        for i in range(0, XSCALE_inh):
            for j in range(0, ZSCALE_inh):

                x = i * xSpacing_inh
                y = j * zSpacing_inh
                index = i * ZSCALE_inh + j
                #print("Looking at connections for inh cell at (%i, %i)"%(i,j))

                # inh -> exc  connections
                conn_type = net_conn_inh_exc
                for k in range(0, XSCALE_ex):
                    for l in range(0, ZSCALE_ex):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_ex
                        yk = l * zSpacing_ex
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_inh_ex * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_ex + l
                            count_inh_exc += 1

                            add_connection(proj_inh_exc, count_inh_exc,
                                           inh_group, inh_group_component,
                                           index, 0, exc_group,
                                           exc_group_component, index2,
                                           inh_exc_syn_seg_id)

                            inh_exc_conn[index, index2] = 1

                # inh -> inh  connections
                conn_type = net_conn_inh_inh
                for k in range(0, XSCALE_inh):
                    for l in range(0, ZSCALE_inh):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_inh
                        yk = l * zSpacing_inh
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_inh_inh * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_inh + l
                            count_inh_inh += 1

                            add_connection(proj_inh_inh, count_inh_inh,
                                           inh_group, inh_group_component,
                                           index, 0, inh_group,
                                           inh_group_component, index2,
                                           inh_inh_syn_seg_id)

                            inh_inh_conn[index, index2] = 1

        print(
            "Generated network with %i exc_exc, %i exc_inh, %i inh_exc, %i inh_inh connections"
            % (count_exc_exc, count_exc_inh, count_inh_exc, count_inh_inh))

        #######   Create Input   ######
        # Create a sine generator
        sgE = SineGenerator(id="sineGen_0",
                            phase="0",
                            delay="0ms",
                            duration=str(self.sim_time) + "ms",
                            amplitude=str(self.Edrive_weight) + "nA",
                            period=str(self.Drive_period) + "ms")
        sgI = SineGenerator(id="sineGen_1",
                            phase="0",
                            delay="0ms",
                            duration=str(self.sim_time) + "ms",
                            amplitude=str(self.Idrive_weight) + "nA",
                            period=str(self.Drive_period) + "ms")

        nml_doc.sine_generators.append(sgE)
        nml_doc.sine_generators.append(sgI)
        # Create an input object for each excitatory cell
        for i in range(0, XSCALE_ex):
            exp_input = ExplicitInput(target="%s[%i]" % (exc_pop.id, i),
                                      input=sgE.id)
            net.explicit_inputs.append(exp_input)

        # Create an input object for a percentage of inhibitory cells
        input_probability = 0.65
        for i in range(0, XSCALE_inh):
            ran = random.random()
            if 0 < ran <= input_probability:
                inh_input = ExplicitInput(target="%s[%i]" % (inh_pop.id, i),
                                          input=sgI.id)
                net.explicit_inputs.append(inh_input)

        # Define Poisson noise input

        # Ex

        #nml_doc.includes.append(IncludeType('Synapses/bg_AMPA_syn.synapse.nml'))

        pfs1 = PoissonFiringSynapse(id="poissonFiringSyn1",
                                    average_rate=str(self.bg_noise_frequency) +
                                    "Hz",
                                    synapse=bg_exc_syn,
                                    spike_target="./%s" % bg_exc_syn)
        nml_doc.poisson_firing_synapses.append(pfs1)

        pfs_input_list1 = InputList(id="pfsInput1",
                                    component=pfs1.id,
                                    populations=exc_pop.id)
        net.input_lists.append(pfs_input_list1)
        for i in range(0, numCells_ex):
            pfs_input_list1.input.append(
                Input(id=i,
                      target='../%s/%i/%s' %
                      (exc_pop.id, i, exc_group_component),
                      segment_id=bg_exc_syn_seg_id,
                      destination="synapses"))

        #######   Write to file  ######

        print("Saving to file...")
        nml_file = '../ACnet2_NML2/' + self.filename + '_doc' + '.net.nml'
        writers.NeuroMLWriter.write(nml_doc, nml_file)

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

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file)
        print "-----------------------------------"

        ###### Output #######

        # Output membrane potential
        # Ex population
        Ex_potentials = 'V_Ex'
        ls.create_output_file(Ex_potentials,
                              "../ACnet2_NML2/Results/v_exc.dat")
        for j in range(numCells_ex):
            quantity = "%s[%i]/v" % (exc_pop.id, j)
            v = 'v' + str(j)
            ls.add_column_to_output_file(Ex_potentials, v, quantity)

        # Inh population
        #Inh_potentials = 'V_Inh'
        #ls.create_output_file(Inh_potentials, "../ACnet2_NML2/Results/v_inh.dat")
        #for j in range(numCells_inh):
        #	quantity = "%s[%i]/v"%(inh_pop.id, j)
        #	v = 'v'+str(j)
        #	ls.add_column_to_output_file(Inh_potentials,v, quantity)

        # include generated network
        ls.include_neuroml2_file(nml_file)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file(file_name='../ACnet2_NML2/LEMS_' +
                                         self.filename + '.xml')
Пример #26
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     
Пример #27
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
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.001):
    
    nml_doc = neuroml.NeuroMLDocument(id=network_id)
    nml_doc.includes.append(neuroml.IncludeType(href='WangBuzsakiCell.xml'))
    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 = '%sNet.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('WangBuzsakiCell.xml', 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
Пример #29
0
def generate_lems_file_for_neuroml(
        sim_id,
        neuroml_file,
        target,
        duration,
        dt,
        lems_file_name,
        target_dir,
        gen_plots_for_all_v=True,
        plot_all_segments=False,
        gen_plots_for_only=[],  #  List of populations
        gen_plots_for_quantities={},  #  Dict with displays vs lists of quantity paths
        gen_saves_for_all_v=True,
        save_all_segments=False,
        gen_saves_for_only=[],  #  List of populations
        gen_saves_for_quantities={},  #  Dict with file names vs lists of quantity paths
        copy_neuroml=True,
        seed=None):

    if seed:
        random.seed(
            seed
        )  # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input

    file_name_full = '%s/%s' % (target_dir, lems_file_name)

    print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s' %
                    (file_name_full, neuroml_file))

    ls = LEMSSimulation(sim_id, duration, dt, target)

    nml_doc = read_neuroml2_file(neuroml_file,
                                 include_includes=True,
                                 verbose=True)

    quantities_saved = []

    if not copy_neuroml:
        rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file),
                                       os.path.abspath(target_dir))
        print_comment_v("Including existing NeuroML file (%s) as: %s" %
                        (neuroml_file, rel_nml_file))
        ls.include_neuroml2_file(rel_nml_file,
                                 include_included=True,
                                 relative_to_dir=os.path.abspath(target_dir))
    else:
        print_comment_v(
            "Copying NeuroML file (%s) to: %s (%s)" %
            (neuroml_file, target_dir, os.path.abspath(target_dir)))
        if os.path.abspath(
                os.path.dirname(neuroml_file)) != os.path.abspath(target_dir):
            shutil.copy(neuroml_file, target_dir)

        neuroml_file_name = os.path.basename(neuroml_file)

        ls.include_neuroml2_file(neuroml_file_name, include_included=False)

        for include in nml_doc.includes:
            incl_curr = '%s/%s' % (os.path.dirname(neuroml_file), include.href)
            print_comment_v(' - Including %s located at %s' %
                            (include.href, incl_curr))
            shutil.copy(incl_curr, target_dir)
            ls.include_neuroml2_file(include.href, include_included=False)

            sub_doc = read_neuroml2_file(incl_curr)

            for include in sub_doc.includes:
                incl_curr = '%s/%s' % (os.path.dirname(neuroml_file),
                                       include.href)
                print_comment_v(' -- Including %s located at %s' %
                                (include.href, incl_curr))
                shutil.copy(incl_curr, target_dir)
                ls.include_neuroml2_file(include.href, include_included=False)

    if gen_plots_for_all_v or gen_saves_for_all_v or len(
            gen_plots_for_only) > 0 or len(gen_saves_for_only) > 0:

        for network in nml_doc.networks:
            for population in network.populations:

                quantity_template = "%s[%i]/v"
                component = population.component
                size = population.size
                cell = None
                segment_ids = []
                if plot_all_segments:
                    for c in nml_doc.cells:
                        if c.id == component:
                            cell = c
                    for segment in cell.morphology.segments:
                        segment_ids.append(segment.id)
                    segment_ids.sort()

                if population.type and population.type == 'populationList':
                    quantity_template = "%s/%i/" + component + "/v"
                    size = len(population.instances)

                if gen_plots_for_all_v or population.id in gen_plots_for_only:
                    print_comment(
                        'Generating %i plots for %s in population %s' %
                        (size, component, population.id))

                    disp0 = 'DispPop__%s' % population.id
                    ls.create_display(disp0, "Voltages of %s" % disp0, "-90",
                                      "50")

                    for i in range(size):
                        if plot_all_segments:
                            quantity_template_seg = "%s/%i/" + component + "/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg % (
                                    population.id, i, segment_id)
                                ls.add_line_to_display(
                                    disp0, "v in seg %i %s" %
                                    (segment_id, safe_variable(quantity)),
                                    quantity, "1mV", get_next_hex_color())
                        else:
                            quantity = quantity_template % (population.id, i)
                            ls.add_line_to_display(
                                disp0, "v %s" % safe_variable(quantity),
                                quantity, "1mV", get_next_hex_color())

                if gen_saves_for_all_v or population.id in gen_saves_for_only:
                    print_comment(
                        'Saving %i values of v for %s in population %s' %
                        (size, component, population.id))

                    of0 = 'Volts_file__%s' % population.id
                    ls.create_output_file(
                        of0, "%s.%s.v.dat" % (sim_id, population.id))
                    for i in range(size):
                        if save_all_segments:
                            quantity_template_seg = "%s/%i/" + component + "/%i/v"
                            for segment_id in segment_ids:
                                quantity = quantity_template_seg % (
                                    population.id, i, segment_id)
                                ls.add_column_to_output_file(
                                    of0, 'v_%s' % safe_variable(quantity),
                                    quantity)
                                quantities_saved.append(quantity)
                        else:
                            quantity = quantity_template % (population.id, i)
                            ls.add_column_to_output_file(
                                of0, 'v_%s' % safe_variable(quantity),
                                quantity)
                            quantities_saved.append(quantity)

    for display in gen_plots_for_quantities.keys():

        quantities = gen_plots_for_quantities[display]
        ls.create_display(display, "Plots of %s" % display, "-90", "50")
        for q in quantities:
            ls.add_line_to_display(display, safe_variable(q), q, "1",
                                   get_next_hex_color())

    for file_name in gen_saves_for_quantities.keys():

        quantities = gen_saves_for_quantities[file_name]
        ls.create_output_file(file_name, file_name)
        for q in quantities:
            ls.add_column_to_output_file(file_name, safe_variable(q), q)

    ls.save_to_file(file_name=file_name_full)

    return quantities_saved