Пример #1
0
def main():
    """Main function

    Include the NeuroML model into a LEMS simulation file, run it, plot some
    data.
    """
    # Simulation bits
    sim_id = "HH_single_compartment_example_sim"
    simulation = LEMSSimulation(sim_id=sim_id, duration=300, dt=0.01, simulation_seed=123)
    # Include the NeuroML model file
    simulation.include_neuroml2_file(create_network())
    # Assign target for the simulation
    simulation.assign_simulation_target("single_hh_cell_network")

    # Recording information from the simulation
    simulation.create_output_file(id="output0", file_name=sim_id + ".dat")
    simulation.add_column_to_output_file("output0", column_id="pop0[0]/v", quantity="pop0[0]/v")
    simulation.add_column_to_output_file("output0", column_id="pop0[0]/iChannels", quantity="pop0[0]/iChannels")
    simulation.add_column_to_output_file("output0", column_id="pop0[0]/na/iDensity", quantity="pop0[0]/hh_b_prop/membraneProperties/na_channels/iDensity/")
    simulation.add_column_to_output_file("output0", column_id="pop0[0]/k/iDensity", quantity="pop0[0]/hh_b_prop/membraneProperties/k_channels/iDensity/")

    # Save LEMS simulation to file
    sim_file = simulation.save_to_file()

    # Run the simulation using the default jNeuroML simulator
    pynml.run_lems_with_jneuroml(sim_file, max_memory="2G", nogui=True, plot=False)
    # Plot the data
    plot_data(sim_id)
def run_lems_file(lems_file, verbose):
    results = run_lems_with_jneuroml(lems_file,
                                     nogui=True,
                                     load_saved_data=True,
                                     plot=False,
                                     verbose=verbose)
    return results
def run_lems_file(lems_file,a):
    results = run_lems_with_jneuroml(lems_file, 
                                     nogui=True, 
                                     load_saved_data=True, 
                                     plot=False, 
                                     verbose=a.v)
    return results
Пример #4
0
def simulate_network(lems_file_name,
                     simulator,
                     max_memory='400M',
                     nogui=True,
                     load_saved_data=False,
                     reload_events=False,
                     plot=False,
                     verbose=True,
                     num_processors=1):

    """
    Run a simulation of the LEMS file `lems_file_name` using target platform `simulator`
    """

    if simulator == "jNeuroML":
       results = pynml.run_lems_with_jneuroml(lems_file_name, max_memory=max_memory, nogui=nogui, load_saved_data=load_saved_data, reload_events=reload_events, plot=plot, verbose=verbose)
    elif simulator == "jNeuroML_NEURON":
       results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, max_memory=max_memory, nogui=nogui, load_saved_data=load_saved_data, reload_events=reload_events, plot=plot, verbose=verbose)
    elif simulator == "jNeuroML_NetPyNE":
       results = pynml.run_lems_with_jneuroml_netpyne(lems_file_name, max_memory=max_memory, nogui=nogui, load_saved_data=load_saved_data, reload_events=reload_events, plot=plot, verbose=verbose,num_processors=num_processors)
    else:
        raise Exception("Simulator %s not yet supported"%simulator)

    if load_saved_data:
        return results
Пример #5
0
    def go(self):
        """
        Start the simulation once it's been intialized
        """
        
        cells = [self.target_cell]
        

        self.params.set_bioparameter("unphysiological_offset_current", "0.25nA", "Testing IClamp", "0")
        self.params.set_bioparameter("unphysiological_offset_current_del", "0 ms", "Testing IClamp", "0")
        self.params.set_bioparameter("unphysiological_offset_current_dur", "%f ms"%self.sim_time, "Testing IClamp", "0")
        
        generate(self.reference, 
             self.params, 
             cells=cells, 
             cells_to_stimulate=cells, 
             duration=self.sim_time, 
             dt=self.dt, 
             vmin=-72 if self.params.level=='A' else -52, 
             vmax=-48 if self.params.level=='A' else -28,
             validate=(self.params.level!='B'),
             verbose=False)
             
        self.lems_file = "LEMS_%s.xml"%(self.reference)
        
        print("Running a simulation of %s ms with timestep %s ms"%(self.sim_time, self.dt))
        
        self.go_already = True
        results = pynml.run_lems_with_jneuroml(self.lems_file, nogui=True, load_saved_data=True, plot=False, verbose=False)
        
        self.rec_t = results['t']
        res_template = '%s/0/generic_iaf_cell/v'
        if self.params.level == 'C' or self.params.level == 'D':
            res_template = '%s[0]/v'
        self.rec_v = results[res_template%self.target_cell]
Пример #6
0
 def go(self):
     """
     Start the simulation once it's been intialized
     """
     
     nml_doc = c302.generate(self.reference, 
                             self.params, 
                             cells=self.cells, 
                             cells_to_stimulate=self.cells_to_stimulate, 
                             include_muscles = self.include_muscles,
                             duration=self.sim_time, 
                             dt=self.dt, 
                             validate=(self.params.level!='B'),
                             verbose=False,
                             target_directory = self.generate_dir)
          
     self.lems_file ="LEMS_%s.xml"%(self.reference)
     
     print("Running a simulation of %s ms with timestep %s ms: %s"%(self.sim_time, self.dt, self.lems_file))
     
     self.already_run = True
     
     start = time.time()
     if self.simulator == 'jNeuroML':
         results = pynml.run_lems_with_jneuroml(self.lems_file, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False, 
                                                exec_in_dir = self.generate_dir,
                                                verbose=False)
     elif self.simulator == 'jNeuroML_NEURON':
         results = pynml.run_lems_with_jneuroml_neuron(self.lems_file, 
                                                       nogui=True, 
                                                       load_saved_data=True, 
                                                       plot=False, 
                                                       exec_in_dir = self.generate_dir,
                                                       verbose=False)
     else:
         print('Unsupported simulator: %s'%self.simulator)
         exit()
         
     secs = time.time()-start
 
     print("Ran simulation in %s in %f seconds (%f mins)\n\n"%(self.simulator, secs, secs/60.0))
     
     self.t = [t*1000 for t in results['t']]
     res_template = '%s/0/generic_iaf_cell/v'
     if self.params.level == 'B' or self.params.level == 'C' or self.params.level == 'D':
         res_template = '%s[0]/v'
     self.volts = {}
     
     if self.cells is None:
         self.cells = []
         for pop in nml_doc.networks[0].populations:
             self.cells.append(pop.id)
         
             
     for cell in self.cells:
         self.volts[res_template%cell] = [v*1000 for v in results[res_template%cell]]
Пример #7
0
 def LEMS_run(self, rerun=False, **run_params):
     for key,value in self.run_defaults:
         if key not in run_params:
             run_params[key] = value
     self.results = pynml.run_lems_with_jneuroml(self.lems_file_path, 
                                                 nogui=run_params['nogui'], 
                                                 load_saved_data=True, 
                                                 plot=False, 
                                                 verbose=run_params['v']) 
Пример #8
0
def run_c302(config,
             parameter_set,
             prefix,
             duration,
             dt,
             simulator,
             save=False,
             show_plot_already=True,
             data_reader="SpreadsheetDataReader",
             verbose=False,
             plot_ca=True,
             param_overrides={}):

    print(
        "********************\n\n   Going to generate c302_%s_%s and run for %s on %s\n\n********************"
        % (parameter_set, config, duration, simulator))
    exec('from c302_%s import setup' % config)
    cells, cells_to_stimulate, params, muscles = setup(
        parameter_set,
        data_reader=data_reader,
        generate=True,
        duration=duration,
        dt=dt,
        target_directory='examples',
        verbose=verbose,
        param_overrides=param_overrides)

    os.chdir('examples')

    lems_file = 'LEMS_c302_%s_%s.xml' % (parameter_set, config)

    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file,
                                               nogui=True,
                                               load_saved_data=True,
                                               verbose=verbose)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      verbose=verbose)

    c302.print_("Finished simulation of %s and have reloaded results" %
                lems_file)

    c302_utils.plot_c302_results(results,
                                 config,
                                 parameter_set,
                                 directory=save_fig_dir,
                                 save=save,
                                 show_plot_already=show_plot_already,
                                 data_reader=data_reader,
                                 plot_ca=plot_ca)

    os.chdir('..')

    return cells, cells_to_stimulate, params, muscles
Пример #9
0
    def go(self):

        lems_file_name = 'LEMS_%s.xml' % (self.reference)

        generate_lems_file_for_neuroml(self.reference,
                                       self.neuroml_file,
                                       self.target,
                                       self.sim_time,
                                       self.dt,
                                       lems_file_name=lems_file_name,
                                       target_dir=self.generate_dir,
                                       nml_doc=self.nml_doc)

        pynml.print_comment_v(
            "Running a simulation of %s ms with timestep %s ms: %s" %
            (self.sim_time, self.dt, lems_file_name))

        self.already_run = True

        start = time.time()
        if self.simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(
                lems_file_name,
                nogui=True,
                load_saved_data=True,
                plot=False,
                exec_in_dir=self.generate_dir,
                verbose=False,
                cleanup=self.cleanup)
        elif self.simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(
                lems_file_name,
                nogui=True,
                load_saved_data=True,
                plot=False,
                exec_in_dir=self.generate_dir,
                verbose=False,
                cleanup=self.cleanup)
        else:
            pynml.print_comment_v('Unsupported simulator: %s' % self.simulator)
            exit()

        secs = time.time() - start

        pynml.print_comment_v(
            "Ran simulation in %s in %f seconds (%f mins)\n\n" %
            (self.simulator, secs, secs / 60.0))

        self.t = [t * 1000 for t in results['t']]

        self.volts = {}

        for key in results.keys():
            if key != 't':
                self.volts[key] = [v * 1000 for v in results[key]]
Пример #10
0
def do_lems_sim_g2do():
    """
    Run G2DO simulation from LEMS file.
    :return:  time, V time series
    """
    example_lems_file = os.path.join(_here, 'LEMS_TestG2DO.xml')
    results1 = pynml.run_lems_with_jneuroml(example_lems_file,
                                            nogui=True,
                                            load_saved_data=True)
    t, v = results1['t'], results1['Pop1[0]/V']
    return t, v
Пример #11
0
 def go(self):
     
     
     lems_file_name = 'LEMS_%s.xml'%(self.reference)
     
     generate_lems_file_for_neuroml(self.reference, 
                                    self.neuroml_file, 
                                    self.target, 
                                    self.sim_time, 
                                    self.dt, 
                                    lems_file_name = lems_file_name,
                                    target_dir = self.generate_dir)
     
     pynml.print_comment_v("Running a simulation of %s ms with timestep %s ms: %s"%(self.sim_time, self.dt, lems_file_name))
     
     self.already_run = True
     
     start = time.time()
     if self.simulator == 'jNeuroML':
         results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False, 
                                                exec_in_dir = self.generate_dir,
                                                verbose=False)
     elif self.simulator == 'jNeuroML_NEURON':
         results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                       nogui=True, 
                                                       load_saved_data=True, 
                                                       plot=False, 
                                                       exec_in_dir = self.generate_dir,
                                                       verbose=False)
     else:
         pynml.print_comment_v('Unsupported simulator: %s'%self.simulator)
         exit()
         
     secs = time.time()-start
 
     pynml.print_comment_v("Ran simulation in %s in %f seconds (%f mins)\n\n"%(self.simulator, secs, secs/60.0))
     
     
     self.t = [t*1000 for t in results['t']]
     
     self.volts = {}
     
     for key in results.keys():
         if key != 't':
             self.volts[key] = [v*1000 for v in results[key]]
Пример #12
0
def generate_panel(ref):
    example_lems_file = lems_files[ref]

    results = pynml.run_lems_with_jneuroml(example_lems_file, nogui=True, load_saved_data=True)
    
    if not '-nogui' in sys.argv:
        print("Plotting results of %s"%ref)
        
        plots = len(results.keys())-1
        f, a = plt.subplots(plots, sharex=True, sharey=True)

	#AB on top
        a[0].plot(results['t'], results[[k for k in results if 'AB' in k][0]])
        
        count = 1
        for key in sorted(results):
            if key != 't' and 'AB' not in key:
                a[count].plot(results['t'],results[key], label=""+key)
                count+=1
Пример #13
0
def main(config, parameter_set, prefix, duration, dt, simulator, save=False, show_plot_already=True):
    
    
    exec('from c302_%s import setup'%config)
    cells, cells_to_stimulate, params, muscles = setup(parameter_set, 
                                                       generate=True,
                                                       duration = duration, 
                                                       dt = dt,
                                                       target_directory='examples')
    
    os.chdir('examples')
    
    lems_file = 'LEMS_c302_%s_%s.xml'%(parameter_set,config)
    
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, verbose=True)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, verbose=True)
        
    c302_utils.plot_c302_results(results, config, parameter_set, directory=save_fig_dir,save=save,show_plot_already=show_plot_already)
Пример #14
0
def main(config,
         parameter_set,
         prefix,
         duration,
         dt,
         simulator,
         save=False,
         show_plot_already=True):

    exec('from c302_%s import setup' % config)
    cells, cells_to_stimulate, params, muscles = setup(
        parameter_set,
        generate=True,
        duration=duration,
        dt=dt,
        target_directory='examples')

    os.chdir('examples')

    lems_file = 'LEMS_c302_%s_%s.xml' % (parameter_set, config)

    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file,
                                               nogui=True,
                                               load_saved_data=True,
                                               verbose=True)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      verbose=True)

    c302_utils.plot_c302_results(results,
                                 config,
                                 parameter_set,
                                 directory=save_fig_dir,
                                 save=save,
                                 show_plot_already=show_plot_already)
Пример #15
0
def main(config, parameter_set, prefix, duration, dt, simulator, save=False, show_plot_already=True, data_reader="SpreadsheetDataReader"):
    
    print("********************\n\n   Going to generate c302_%s_%s and run for %s on %s\n\n********************"%(parameter_set,config,duration, simulator))
    exec('from c302_%s import setup'%config)
    cells, cells_to_stimulate, params, muscles = setup(parameter_set, 
                                                       data_reader=data_reader,
                                                       generate=True,
                                                       duration = duration, 
                                                       dt = dt,
                                                       target_directory='examples')
    
    os.chdir('examples')
    
    lems_file = 'LEMS_c302_%s_%s.xml'%(parameter_set,config)
    
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, verbose=True)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, verbose=True)
        
    c302_utils.plot_c302_results(results, config, parameter_set, directory=save_fig_dir,save=save,show_plot_already=show_plot_already, data_reader=data_reader)
    
    os.chdir('..')
Пример #16
0
 def go(self):
     """
     Start the simulation once it's been intialized
     """
     
     
     nml_doc = c302.generate(self.reference, 
                             self.params, 
                             cells=self.cells, 
                             cells_to_stimulate=self.cells_to_stimulate, 
                             duration=self.sim_time, 
                             dt=self.dt, 
                             validate=(self.params.level!='B'),
                             verbose=False)
          
     self.lems_file = "LEMS_%s.xml"%(self.reference)
     
     print("Running a simulation of %s ms with timestep %s ms"%(self.sim_time, self.dt))
     
     self.go_already = True
     results = pynml.run_lems_with_jneuroml(self.lems_file, nogui=True, load_saved_data=True, plot=False, verbose=False)
     #results = pynml.run_lems_with_jneuroml_neuron(self.lems_file, nogui=True, load_saved_data=True, plot=False)
     
     self.t = [t*1000 for t in results['t']]
     res_template = '%s/0/generic_iaf_cell/v'
     if self.params.level == 'B' or self.params.level == 'C' or self.params.level == 'D':
         res_template = '%s[0]/v'
     self.volts = {}
     
     if self.cells is None:
         self.cells = []
         for pop in nml_doc.networks[0].populations:
             self.cells.append(pop.id)
         
             
     for cell in self.cells:
         self.volts[res_template%cell] = [v*1000 for v in results[res_template%cell]]
Пример #17
0
    def go(self):

        pynml.print_comment_v(
            "Running a simulation of %s ms with timestep %s ms: %s" %
            (self.sim_time, self.dt, self.lems_file))

        self.already_run = True

        print self.simulator

        start = time.time()
        if self.simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(
                self.lems_file,  #_name, 
                nogui=True,
                load_saved_data=True,
                plot=False,
                exec_in_dir=self.generate_dir,
                verbose=False)
        elif self.simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(
                self.lems_file,
                nogui=True,
                load_saved_data=False,
                plot=False,
                exec_in_dir=self.generate_dir,
                verbose=False)
        else:
            pynml.print_comment_v('Unsupported simulator: %s' % self.simulator)
            exit()

        secs = time.time() - start

        pynml.print_comment_v(
            "Ran simulation in %s in %f seconds (%f mins)\n\n" %
            (self.simulator, secs, secs / 60.0))
Пример #18
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)
Пример #19
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     
Пример #20
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
Пример #21
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
Пример #22
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
Пример #23
0
# 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")

for i in range(size0):
    quantity = "%s[%i]/v"%(pop0.id, i)
    ls.add_line_to_display(disp0, "%s[%i]: Vm"%(pop0.id,i), quantity, "1mV", pynml.get_next_hex_color())
    ls.add_column_to_output_file(of0, 'v%i'%i, quantity)

# Save to LEMS XML file
lems_file_name = ls.save_to_file()

# Run with jNeuroML
results1 = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=True)
Пример #24
0
def create_plots(lems_file, simulator, directory, save, save_image_full_dir,
                 show_plot_already, plot_ca, plot_connectivity, verbose):
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file,
                                               nogui=True,
                                               load_saved_data=True,
                                               verbose=verbose)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      verbose=verbose)

    print("Finished simulation of %s and have reloaded results" % lems_file)

    #print results

    out = {}
    t = []
    for key, value in results.items():
        if key == 't':
            t = value
        else:
            label = key.split('/')[-1]
            print label
            if label == 'v':
                out[label] = [float(i) * 1e3 for i in value]
            elif label == 'S':
                out[label] = [float(i) * 1e-3 for i in value]
            else:
                out[label] = [float(i) * 1e6 for i in value]

    i = 33330
    print out['S'][i]
    print out['J_SERCA'][i]

    Ca = out['caConc']
    Rmin = min(Ca)
    Rmax = max(Ca)
    Rmin = 4.963093110035229
    Rmax = 32.282101799695049
    print Rmin
    print Rmax
    R0 = Rmax * Ca[0]**(1.7) / (Ca[0]**(1.7) + 2.5**
                                (1.7)) / 100 * (Rmax - Rmin) + Rmin
    #R=Rmax*Ca.^1.7./(Ca.^1.7+2.5^1.7)/100*(Rmax-Rmin)+Rmin;

    FRET = []
    for c in Ca:
        R = Rmax * c**(1.7) / (c**(1.7) + 2.5**
                               (1.7)) / 100 * (Rmax - Rmin) + Rmin
        #R = 5
        y = (R - R0) / R0 * 100
        FRET.append(y)

    fig = plt.figure()
    fig.set_size_inches(12, 8)

    fluxes = fig.add_subplot(221)
    voltage = fig.add_subplot(222)
    concentration = fig.add_subplot(223)
    fret = fig.add_subplot(224)

    fluxes.plot(t,
                out['J_PMCA'],
                label='J_PMCA',
                color='royalblue',
                linestyle='-')
    fluxes.plot(t,
                out['J_SERCA'],
                label='J_SERCA',
                color='chocolate',
                linestyle='--')
    fluxes.plot(t,
                out['J_TRPV'],
                label='J_TRPV',
                color='#F0BE4B',
                linestyle='-.')
    fluxes.plot(t,
                out['J_IPR'],
                label='J_IPR',
                color='darkviolet',
                linestyle=':')
    #fluxes.plot(t, out['J_VGCC'], label='J_VGCC', linestyle='-', marker='o')
    fluxes.plot(t,
                out['J_VGCC'],
                label='J_VGCC',
                color='limegreen',
                linestyle='-')
    fluxes.plot(t,
                out['J_LeakER'],
                label='J_LeakER',
                color='silver',
                linestyle='-')
    fluxes.plot(t,
                out['S'],
                label='Stimulus',
                color='red',
                linestyle='-',
                linewidth=0.6)
    fluxes.legend(loc='upper left', frameon=False, prop={'size': 6})
    fluxes.set_xlim([0, 55])
    fluxes.set_ylim([-0.3, 6])
    fluxes.set_xlabel("Time (s)")
    fluxes.set_ylabel("[Ca2+ flux] (%sM/s)" % u'\u03bc')

    voltage.plot(t, out['v'], label="v")
    voltage.set_xlim([0, 55])
    voltage.set_ylim([-70, 20])
    voltage.set_ylabel('Voltage (mV)')
    voltage.set_xlabel("Time (s)")

    concentration.plot(t, out['caConc'], label="caConc")
    concentration.set_xlim([0, 55])
    concentration.set_ylim([0, 0.5])
    concentration.set_ylabel('[Ca2+] (%sM)' % u'\u03bc')
    concentration.set_xlabel("Time (s)")

    concER = concentration.twinx()
    concER.plot(t, out['concentrationER'], color='grey', linewidth=0.5)
    concER.set_ylim([0, 300])
    concER.set_ylabel('[Ca2+]ER (%sM)' % u'\u03bc', color='grey')
    concER.tick_params('y', colors='grey')

    fret.plot(t, FRET, label="FRET")
    fret.set_xlim([0, 55])
    fret.set_ylim([-1, 10])
    fret.set_ylabel('FRET ratio change (%)')
    fret.set_xlabel("Time (s)")

    plt.subplots_adjust(wspace=0.4)

    plt.show()
import sys

from pyneuroml import pynml


####################################################################
#   Choose a LEMS/NeuroML2 file and run it with jNeuroML

example_lems_file = 'LEMS_NML2_Ex5_DetCell.xml'

results1 = pynml.run_lems_with_jneuroml(example_lems_file, nogui=True, load_saved_data=True)



####################################################################
#   Convert LEMS/NeuroML2 file to NEURON with jNeuroML & run


if not '-noneuron' in sys.argv:  # To allow skipping of this for ease of testing

    results2 = pynml.run_lems_with_jneuroml_neuron(example_lems_file, nogui=True, load_saved_data=True)



####################################################################
#   Reload & plot results

if not '-nogui' in sys.argv:
    
    from matplotlib import pyplot as plt
from pyneuroml import pynml

pynml.run_lems_with_jneuroml('../run_model.xml')
Пример #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 dashboard_cells(net_id,
                    net_file_name,
                    config_array,
                    global_dt,
                    if_params,
                    elec_len_list,
                    dt_list,
                    generate_dashboards=True,
                    compare_to_neuroConstruct=False,
                    regenerate_nml2=False,
                    show_plot_already=False,
                    proj_string_neuroConstruct=None,
                    shell=None,
                    nc_home=None):
            
    ################### check whether use of neuroConstruct python/java interface is needed ########################
    
    if regenerate_nml2:
    
       use_NeuroConstruct(compare_to_neuroConstruct=compare_to_neuroConstruct,
                          regenerate_nml2=regenerate_nml2,
                          proj_string=proj_string_neuroConstruct,
                          global_dt=global_dt,
                          config_array=config_array,
                          elec_len_list=elec_len_list,
                          shell=shell,
                          nc_home=nc_home)
                             
    else:
       
          
       use_NeuroConstruct(compare_to_neuroConstruct=compare_to_neuroConstruct,
                          regenerate_nml2=regenerate_nml2,
                          proj_string=proj_string_neuroConstruct,
                          global_dt=global_dt,
                          config_array=config_array,
                          shell=shell,
                          nc_home=nc_home)     
                             
            
                             
    ############################################################################################################
        
    if generate_dashboards:    
       
       cell_id_list=[]
       
       config_list=[]
       
       analysis_header_list=[]
       
       nC_vs_NML2Curve_list=[]
       
       IFcurve_list=[]
       
       for cellModel in config_array.keys():
       
           cell_id_list.append(cellModel)
           
           config_list.append(config_array[cellModel]['Analysis'])
        
           save_to_path="../"+cellModel
        
           if not os.path.exists(save_to_path):
              print("Creating a new directory %s"%save_to_path)
              os.makedirs(save_to_path)
           else:
              print("A directory %s already exists"%save_to_path)
           
           pathToConfig="../"+config_array[cellModel]['Analysis']
           
           try:
              
              with open(os.path.join(pathToConfig,"compSummary.json"),'r') as f:
              
                   comp_info=json.load(f)
                   
           except IOError:
           
              print "cannot open file %s"%os.path.join(pathToConfig,"compSummary.json")
              
           cell_morph_summary=comp_info[config_array[cellModel]['Analysis']]
           
           src_files = os.listdir(pathToConfig)
           
           num_dx_configs=0
           
           dx_array=[]
           
           found_all_compartmentalizations=False
           
           dx_configs={}
        
           target_v=None
           
           found_default=False
           
           for file_name in src_files:
           
               full_file_path=os.path.join(pathToConfig,file_name)
               
               if (os.path.isdir(full_file_path)) and "_default" in file_name:
               
                  found_default=True
            
                  original_LEMS_target=os.path.join(full_file_path,"LEMS_Target.xml")
            
                  ###################################################################################
                  if -1 in elec_len_list and "-1" in cell_morph_summary.keys():
                  
                      dx_configs[cell_morph_summary["-1"]["IntDivs"]]=original_LEMS_target
                     
                      default_num_of_comps=cell_morph_summary["-1"]["IntDivs"]
                      
                      dx_array.append(int(default_num_of_comps))
                     
                      num_dx_configs+=1
                  ##################################################################################      
                  print("%s is a directory"%full_file_path)
                  print("will generate the IF curve for %s.cell.nml"%cellModel)
                  generate_current_vs_frequency_curve(os.path.join(full_file_path,cellModel+".cell.nml"), 
                                      cellModel, 
                                      start_amp_nA =     if_params['start_amp_nA'], 
                                      end_amp_nA =       if_params['end_amp_nA'], 
                                      step_nA =          if_params['step_nA'], 
                                      analysis_duration =if_params['analysis_duration'], 
                                      analysis_delay =   if_params['analysis_delay'],
                                      dt=                if_params['dt'],
                                      temperature=       if_params['temperature'],
                                      plot_voltage_traces=if_params['plot_voltage_traces'],
                                      plot_if=            if_params['plot_if'],
                                      plot_iv=            if_params['plot_iv'],
                                      show_plot_already=  show_plot_already,
                                      save_if_figure_to='%s/IF_%s.png'%(save_to_path,cellModel),
                                      save_iv_figure_to='%s/IV_%s.png'%(save_to_path,cellModel),
                                      simulator=         if_params['simulator'])
                                        
                  IFcurve="IF_%s"%cellModel
                  
                  IFcurve_list.append(IFcurve)
                  
                  IVcurve="IV_%s"%cellModel
                  
                  nml2_file_path=os.path.join(full_file_path,net_file_name+".net.nml")      
                  
                  net_doc = pynml.read_neuroml2_file(nml2_file_path)
                  net=net_doc.networks[0]
                  pop=net.populations[0]
                  popID=pop.id
                  
                  target_v="%s/0/%s/v"%(popID,cellModel)
               
                  ########################################################################################
               
                  if if_params['simulator'] == 'jNeuroML':
                     results = pynml.run_lems_with_jneuroml(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
                  if if_params['simulator'] == 'jNeuroML_NEURON':
                     results = pynml.run_lems_with_jneuroml_neuron(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
                  
                  t = results['t']
                  v = results[target_v]
                  
                  if compare_to_neuroConstruct:
                  
                     print("will generate the comparison between the nC model and NeuroML2 model")
                     
                     PlotNC_vs_NML2({'NML2':[{'t':t,'v':v}],'nC':[config_array[cellModel]['OriginalTag']],
                                     'subplotTitles':['NeuroML2 versus nC model: simulations in NEURON with dt=%f'%global_dt]},
                                     {'cols':8,'rows':5},
                                     legend=True,
                                     show=False,
                                     save_to_file='%s/nC_vs_NML2_%s.png'%(save_to_path,config_array[cellModel]['Analysis']),
                                     nCcellPath=os.path.join(save_to_path,config_array[cellModel]['Analysis'])   )
                                    
                     analysis_string1="nC_vs_NML2_%s"%config_array[cellModel]['Analysis']
                     
                     analysis_header1="Comparison between the original nC model and NeuroML2 model: simulations in NEURON with dt=%f"%global_dt
                     
                     analysis_header_list.append(analysis_header1)
                     
                     nC_vs_NML2Curve_list.append(analysis_string1)
                              
                  else:
                  
                     print("will generate the plot for the NeuroML2 model")
                     
                     generate_nml2_plot({'NML2':[{'t':t,'v':v}],'subplotTitles':['NeuroML2 model: simulations in NEURON with dt=%f'%global_dt]},
                                        {'cols':8,'rows':5},
                                        show=False,
                                        save_to_file='%s/NML2_%s.png'%(save_to_path,config_array[cellModel]['Analysis']))
                                            
                     analysis_string1="NML2_%s"%config_array[cellModel]['Analysis']
                     
                     analysis_header1="NeuroML2 model: simulations in NEURON with dt=%f"%global_dt    
                     
                     analysis_header_array.append(analysis_header1) 
                     
                     nC_vs_NML2Curve_array.append(analysis_string1)
                     
                  smallest_dt=min(dt_list)  
                              
                  ########################################################################################
                  print("will generate the spike times vs dt curve for %s.cell.nml"%cellModel)
                  analyse_spiketime_vs_dt(nml2_file_path, 
                                          net_id,
                                          get_sim_duration(os.path.join(full_file_path,"LEMS_%s.xml"%net_id)),
                                          if_params['simulator'],
                                          target_v,
                                          dt_list,
                                          verbose=False,
                                          spike_threshold_mV = 0,
                                          show_plot_already=show_plot_already,
                                          save_figure_to="%s/Dt_%s.png"%(save_to_path,cellModel),
                                          num_of_last_spikes=None)
                                          
                  dt_curve="Dt_%s"%cellModel
                  
               if not found_all_compartmentalizations:
                  
                  for elecLen in range(0,len(elec_len_list)):
               
                      elec_len=str(elec_len_list[elecLen]) 
                      
                      if elec_len != "-1":
                  
                         if (elec_len  in file_name) and (elec_len in cell_morph_summary.keys() ):
                      
                            dx_configs[cell_morph_summary[elec_len]["IntDivs"]]=os.path.join(full_file_path,"LEMS_Target.xml")
                      
                            num_dx_configs+=1
                         
                            dx_array.append(int(cell_morph_summary[elec_len]["IntDivs"] ) )
                      
                            break
                         
               if num_dx_configs==len(elec_len_list):
                  
                  found_all_compartmentalizations=True 
                      
           if not found_default:
           
              print("default configuration for %s analysis is not found; execution will terminate; set regenerate_nml2 to True to generate target dirs."%cellModel)
              
              quit()
                      
           if found_all_compartmentalizations:
           
              dx_array=list(np.sort(dx_array) )
                  
              maximum_int_divs=max(dx_array)
           
              print("testing the presence of cell configs with different levels of spatial discretization")
              
              analyse_spiketime_vs_dx(dx_configs, 
                                      if_params['simulator'],
                                      target_v,
                                      verbose=False,
                                      spike_threshold_mV = 0,
                                      show_plot_already=show_plot_already,
                                      save_figure_to="%s/Dx_%s.png"%(save_to_path,cellModel),
                                      num_of_last_spikes=3) 
               
              dx_curve="Dx_%s"%cellModel
                
           else:
              print("not all of the target configurations were recompartmentalized; execution will terminate; set regenerate_nml2 to True to obtain all of the target configurations.")
              quit() 
              
           if config_array[cellModel]['Analysis'] != config_array[cellModel]['SpikeProfile']:    
        
              pathToProfileConfig="../"+config_array[cellModel]['SpikeProfile']+"/"+config_array[cellModel]['SpikeProfile']+"_default"
           
              original_LEMS_target=os.path.join(pathToProfileConfig,"LEMS_Target.xml")
               
              if if_params['simulator'] == 'jNeuroML':
                 results = pynml.run_lems_with_jneuroml(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
              if if_params['simulator'] == 'jNeuroML_NEURON':
                 results = pynml.run_lems_with_jneuroml_neuron(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
                
              if 'SpikeProfileTag' in config_array[cellModel].keys():
                 
                  tag=config_array[cellModel]['SpikeProfileTag']+"_0_wtime"
                 
              else:
                 
                  tag=config_array[cellModel]['OriginalTag']
                  
              if 'SpikeProfileCellTag' in config_array[cellModel].keys() and 'SpikeProfileTag' in config_array[cellModel].keys():
                
                 target_v="%s/0/%s/v"%(config_array[cellModel]['SpikeProfileTag'],config_array[cellModel]['SpikeProfileCellTag'])
                    
              t = results['t']
              v = results[target_v]
        
              if compare_to_neuroConstruct:
               
                 print("will generate the comparison between the nC model and NeuroML2 model")
                 
                 PlotNC_vs_NML2({'NML2':[{'t':t,'v':v}],'nC':[tag],
                                 'subplotTitles':['NML2 versus nC model: simulations in NEURON with dt=%f'%global_dt]},
                                 {'cols':8,'rows':5},
                                 legend=True,
                                 show=show_plot_already,
                                 save_to_file='%s/nC_vs_NML2_%s.png'%(save_to_path,config_array[cellModel]['SpikeProfile']),
                                 nCcellPath=os.path.join(save_to_path,config_array[cellModel]['SpikeProfile'])   )
                               
                 analysis_string2="nC_vs_NML2_%s"%config_array[cellModel]['SpikeProfile']
           
                 analysis_header2="Comparison between the original nC model and NeuroML2 model: simulations in NEURON with dt=%f"%global_dt
           
              else:
        
                 print("will generate the plot for the NeuroML2 model")
                 
                 generate_nml2_plot({'NML2':[{'t':t,'v':v}],'subplotTitles':['NeuroML2 model: simulations in NEURON with dt=%f'%global_dt]},
                                        {'cols':8,'rows':5},
                                        show=False,
                                        save_to_file='%s/NML2_%s.png'%(save_to_path,config_array[cellModel]['SpikeProfile']))
           
                                         
                 analysis_string2="NML2_%s"%config_array[cellModel]['SpikeProfile']
                     
                 analysis_header2="NeuroML2 model: simulations in NEURON with dt=%f"%global_dt
              
              cwd=os.getcwd()
               
              os.chdir(save_to_path)
        
              readme = ''' 
         
## Model: %(CellID)s

### Original neuroConstruct config ID: %(SpikeProfile)s

**%(AnalysisHeader2)s**

![Simulation](%(SpikeProfileCurve)s.png)

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader1)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)

**IV curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IVcurve)s.png)

**Spike times versus time step: the NeuroML2 model simulated in NEURON.
Dashed black lines - spike times at the %(Smallest_dt)s ms time step; Green - spike times at the following time steps (in ms): %(DtArray)s.**

![Simulation](%(DtCurve)s.png)

**Spike times versus spatial discretization: the NeuroML2 model simulated in NEURON.
Default value for the number of internal divs is %(default_divs)s.
Dashed black lines - spike times at the %(MaximumDivs)s internal divisions; Blue - spike times at the following values of internal divisions:
%(IntDivsArray)s.**

![Simulation](%(DxCurve)s.png)'''

              readme_file = open('README.md','w')
              
              readme_final=readme%{"CellID":cellModel,
                                   "IFcurve":IFcurve,
                                   "IVcurve":IVcurve,
                                   "Config":config_array[cellModel]['Analysis'],
                                   "DtCurve":dt_curve,
                                   "DxCurve":dx_curve,
                                   "nC_vs_NML2Curve":analysis_string1,
                                   "AnalysisHeader1":analysis_header1,
                                   "SpikeProfileCurve":analysis_string2,
                                   "AnalysisHeader2":analysis_header2,
                                   "default_divs":default_num_of_comps,
                                   "SpikeProfile":config_array[cellModel]['SpikeProfile'],
                                   "Smallest_dt":smallest_dt,
                                   "DtArray":dt_list,
                                   "IntDivsArray":dx_array,
                                   "MaximumDivs":maximum_int_divs}
                           
              readme_file.write(readme_final)
              
              readme_file.close()

              os.chdir(cwd)
      
           else:  
           
              cwd=os.getcwd()
               
              os.chdir(save_to_path)
        
              readme = ''' 
         
## Model: %(CellID)s

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader1)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)

**IV curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IVcurve)s.png)

**Spike times versus time step: the NeuroML2 model simulated in NEURON.
Dashed black lines - spike times at the %(Smallest_dt)s ms time step; Green - spike times for the following time steps (in ms): %(DtArray)s.**

![Simulation](%(DtCurve)s.png)

**Spike times versus spatial discretization: the NeuroML2 model simulated in NEURON.
Default value for the number of internal divs is %(default_divs)s.
Dashed black lines - spike times at the %(MaximumDivs)s internal divisions; Blue - spike times at the following values of internal divisions:
%(IntDivsArray)s.**

![Simulation](%(DxCurve)s.png)'''

              readme_file = open('README.md','w')
              
              readme_final=readme%{"CellID":cellModel,
                                   "IFcurve":IFcurve,
                                   "IVcurve":IVcurve,
                                   "Config":config_array[cellModel]['Analysis'],
                                   "DtCurve":dt_curve,
                                   "DxCurve":dx_curve,
                                   "nC_vs_NML2Curve":analysis_string1,
                                   "AnalysisHeader1":analysis_header1,
                                   "default_divs":default_num_of_comps,
                                   "Smallest_dt":smallest_dt,
                                   "DtArray":dt_list,
                                   "IntDivsArray":dx_array,
                                   "MaximumDivs":maximum_int_divs}
                           
              readme_file.write(readme_final)
              readme_file.close()
              os.chdir(cwd)                                
              
       cwd=os.getcwd()
               
       os.chdir(os.path.dirname(cwd))
        
       readme = ''' 
      
## Conversion of Thalamocortical cell models to NeuroML2

'''
       readme_file = open('README.md','w')

       for cell_index in range(0,len(cell_id_list)):
       
           readme_cell='''
           
## Model: %(CellID)s

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)'''

           readme_cell=readme_cell%{"CellID":cell_id_list[cell_index],
                                    "Config":config_list[cell_index],
                                    "AnalysisHeader":analysis_header_list[cell_index],
                                    "nC_vs_NML2Curve":os.path.join(cell_id_list[cell_index],nC_vs_NML2Curve_list[cell_index]),
                                    "IFcurve":os.path.join(cell_id_list[cell_index],IFcurve_list[cell_index])}
                                    
           readme=readme+readme_cell
                                
       readme_file.write(readme)
       readme_file.close()
       os.chdir(cwd)     
def analyse_cell(dataset_id, type, nogui=False):

    reference = '%s_%s' % (type, dataset_id)
    cell_file = '%s.cell.nml' % (reference)

    images = 'summary/%s_%s.png'

    generate_current_vs_frequency_curve(
        cell_file,
        reference,
        simulator='jNeuroML_NEURON',
        start_amp_nA=-0.1,
        end_amp_nA=0.4,
        step_nA=0.01,
        analysis_duration=1000,
        analysis_delay=50,
        plot_voltage_traces=False,
        plot_if=not nogui,
        plot_iv=not nogui,
        xlim_if=[-200, 400],
        ylim_if=[-10, 120],
        xlim_iv=[-200, 400],
        ylim_iv=[-120, -40],
        save_if_figure_to=images % (reference, 'if'),
        save_iv_figure_to=images % (reference, 'iv'),
        show_plot_already=False)

    temp_dir = 'temp/'

    shutil.copy(cell_file, temp_dir)

    net_file = generate_network_for_sweeps(type, dataset_id,
                                           '%s.cell.nml' % (reference),
                                           reference, temp_dir)

    lems_file_name = 'LEMS_Test_%s_%s.xml' % (type, dataset_id)

    generate_lems_file_for_neuroml('Test_%s_%s' % (dataset_id, type),
                                   net_file,
                                   'network_%s_%s' % (dataset_id, type),
                                   1500,
                                   0.01,
                                   lems_file_name,
                                   temp_dir,
                                   gen_plots_for_all_v=False,
                                   copy_neuroml=False)

    simulator = "jNeuroML_NEURON"

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

    x = []
    y = []

    print results.keys()

    tt = [t * 1000 for t in results['t']]
    for i in range(len(results) - 1):
        x.append(tt)
        y.append([
            v * 1000
            for v in results['Pop0/%i/%s_%s/v' % (i, type, dataset_id)]
        ])

    pynml.generate_plot(x,
                        y,
                        "Cell: %s" % dataset_id,
                        xaxis="Time (ms)",
                        yaxis="Membrane potential (mV)",
                        show_plot_already=False,
                        ylim=[-120, 60],
                        save_figure_to=images % (reference, 'traces'))
Пример #30
0
def run_c302(config, 
             parameter_set, 
             prefix, 
             duration, 
             dt, 
             simulator, 
             save=False, 
             show_plot_already=True, 
             data_reader="SpreadsheetDataReader",
             verbose=False,
             plot_ca=True,
             plot_connectivity=False,
             param_overrides={},
             config_param_overrides={},
             config_package="",
             target_directory='examples',
             save_fig_to=None):

    if save_fig_to:
        global save_fig_dir
        save_fig_dir = save_fig_to

    print("********************\n\n   Going to generate c302_%s_%s and run for %sms (dt: %sms) on %s\n\n********************"%(parameter_set,config,duration, dt, simulator))
    if config_package:
        exec ('from %s.c302_%s import setup' % (config_package, config), globals())
    else:
        exec ('from c302_%s import setup' % config, globals())

    try:
        os.makedirs(target_directory)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    cells, cells_to_stimulate, params, muscles, nml_doc = setup(parameter_set,
                                                       data_reader=data_reader,
                                                       generate=True,
                                                       duration = duration, 
                                                       dt = dt,
                                                       target_directory=target_directory,
                                                       verbose=verbose,
                                                       param_overrides=param_overrides,
                                                       config_param_overrides=config_param_overrides)

    orig_dir = os.getcwd()

    os.chdir(target_directory)

    try:
        os.makedirs(save_fig_dir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    lems_file = 'LEMS_c302_%s_%s.xml'%(parameter_set,config)
    
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, verbose=verbose)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, verbose=verbose)
        
    c302.print_("Finished simulation of %s and have reloaded results"%lems_file)
        
    c302_utils.plot_c302_results(results, 
                                 config, 
                                 parameter_set, 
                                 directory=save_image_full_dir,
                                 save=save,
                                 show_plot_already=show_plot_already, 
                                 data_reader=data_reader,
                                 plot_ca=plot_ca)

    if plot_connectivity:
        c302_utils.generate_conn_matrix(nml_doc, save_fig_dir=save_image_full_dir)

    os.chdir(orig_dir)

    return cells, cells_to_stimulate, params, muscles
Пример #31
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
def analyse_cell(dataset_id,
                 type,
                 info,
                 nogui=False,
                 densities=False,
                 analysis_dir='../../data/'):

    reference = '%s_%s' % (type, dataset_id)
    cell_file = '%s/%s.cell.nml' % (type, reference)

    print(
        "====================================\n\n   Analysing cell: %s, dataset %s\n"
        % (cell_file, dataset_id))

    nml_doc = pynml.read_neuroml2_file(cell_file)
    notes = nml_doc.cells[0].notes if len(
        nml_doc.cells) > 0 else nml_doc.izhikevich2007_cells[0].notes
    meta_nml = eval(notes[notes.index('{'):])
    summary = "Fitness: %s (max evals: %s, pop: %s)" % (
        meta_nml['fitness'], meta_nml['max_evaluations'],
        meta_nml['population_size'])
    print summary

    images = 'summary/%s_%s.png'
    if_iv_data_files = 'summary/%s_%s.dat'

    data, v_sub, curents_sub, freqs, curents_spike = get_if_iv_for_dataset(
        '%s%s_analysis.json' % (analysis_dir, dataset_id))

    if densities:

        dataset = {}
        seed = meta_nml['seed']
        if isinstance(seed, tuple):
            seed = seed[0]
        layer = str(data['location'].split(',')[-1].strip().replace(' ', ''))
        ref = '%s_%s_%s' % (dataset_id, layer, int(seed))

        dataset['id'] = dataset_id
        dataset['reference'] = ref
        metas = ['aibs_cre_line', 'aibs_dendrite_type', 'location']
        for m in metas:
            dataset[m] = str(data[m])

        metas2 = ['fitness', 'population_size', 'seed']
        for m in metas2:
            dataset[m] = meta_nml[m]

        # Assume images below already generated...
        if type == 'HH':

            cell = nml_doc.cells[0]

            sgv_files, all_info = generate_channel_density_plots(
                cell_file, text_densities=True, passives_erevs=True)
            sgv_file = sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]

            info['datasets'][ref] = dataset

        elif type == 'Izh':

            dataset['tuned_cell_info'] = {}
            izh_cell = nml_doc.izhikevich2007_cells[0]

            for p in ['C', 'a', 'b', 'c', 'd', 'k', 'vpeak', 'vr', 'vt']:

                dataset['tuned_cell_info'][p] = get_value_in_si(
                    getattr(izh_cell, p))
            '''
            sgv_files, all_info = generate_channel_density_plots(cell_file, text_densities=True, passives_erevs=True)
            sgv_file =sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]'''

        info['datasets'][ref] = dataset

    else:

        traces_ax, if_ax, iv_ax = generate_current_vs_frequency_curve(
            cell_file,
            reference,
            simulator='jNeuroML_NEURON',
            start_amp_nA=-0.1,
            end_amp_nA=0.4,
            step_nA=0.01,
            analysis_duration=1000,
            analysis_delay=50,
            plot_voltage_traces=False,
            plot_if=not nogui,
            plot_iv=not nogui,
            xlim_if=[-200, 400],
            ylim_if=[-10, 120],
            xlim_iv=[-200, 400],
            ylim_iv=[-120, -40],
            save_if_figure_to=images % (reference, 'if'),
            save_iv_figure_to=images % (reference, 'iv'),
            save_if_data_to=if_iv_data_files % (reference, 'if'),
            save_iv_data_to=if_iv_data_files % (reference, 'iv'),
            show_plot_already=False,
            return_axes=True)

        iv_ax.plot(curents_sub,
                   v_sub,
                   color='#ff2222',
                   marker='o',
                   linestyle='',
                   zorder=1)
        if_ax.plot(curents_spike,
                   freqs,
                   color='#ff2222',
                   marker='o',
                   linestyle='',
                   zorder=1)

        iv_ax.get_figure().savefig(images % (reference, 'iv'),
                                   bbox_inches='tight')
        if_ax.get_figure().savefig(images % (reference, 'if'),
                                   bbox_inches='tight')

        offset = 100  # mV

        ifv_x = []
        ifv_y = []
        markers = []
        lines = []
        colors = []

        cols = {'Izh': 'r', 'HH': 'g', 'AllenHH': 'b'}

        for ii in ['if', 'iv']:
            for tt in ['Izh', 'HH', 'AllenHH']:
                rr = '%s_%s' % (tt, dataset_id)
                f = if_iv_data_files % (rr, ii)
                if os.path.isfile(f):
                    print("--- Opening: %s" % f)
                    data, indeces = reload_standard_dat_file(f)

                    ifv_x.append(data['t'])

                    if ii == 'if':
                        ifv_y.append([ff - offset for ff in data[0]])
                    else:
                        ifv_y.append([vv for vv in data[0]])

                    markers.append('')
                    colors.append(cols[tt])
                    lines.append('-')

        ifv_x.append(curents_sub)
        vvsub = [vv for vv in v_sub]

        ifv_y.append(vvsub)

        sub_color = '#888888'
        markers.append('D')
        colors.append('k')
        lines.append('')

        ifv_x.append(curents_spike)
        ifv_y.append([ff - offset for ff in freqs])

        markers.append('o')
        colors.append(sub_color)
        lines.append('')

        import matplotlib
        import matplotlib.pyplot as plt

        print ifv_x
        print ifv_y
        ylim = [-105, -20]
        font_size = 18
        ax1 = pynml.generate_plot(ifv_x,
                                  ifv_y,
                                  summary,
                                  markers=markers,
                                  colors=colors,
                                  linestyles=lines,
                                  show_plot_already=False,
                                  xlim=[-100, 400],
                                  font_size=font_size,
                                  ylim=ylim,
                                  title_above_plot=False)

        plt.xlabel('Input current (pA)', fontsize=font_size)
        plt.ylabel("Steady membrane potential (mV)", fontsize=font_size)

        ax2 = ax1.twinx()
        plt.ylim([ylim[0] + offset, ylim[1] + offset])
        plt.ylabel('Firing frequency (Hz)',
                   color=sub_color,
                   fontsize=font_size)
        ax2.tick_params(axis='y', colors=sub_color)

        #plt.axis('off')

        plt.savefig(images % (reference, 'if_iv' + "_FIG"),
                    bbox_inches='tight')

        temp_dir = 'temp/'

        print("Copying %s to %s" % (cell_file, temp_dir))
        shutil.copy(cell_file, temp_dir)

        net_file = generate_network_for_sweeps(type,
                                               dataset_id,
                                               '%s.cell.nml' % (reference),
                                               reference,
                                               temp_dir,
                                               data_dir=analysis_dir)

        lems_file_name = 'LEMS_Test_%s_%s.xml' % (type, dataset_id)

        generate_lems_file_for_neuroml('Test_%s_%s' % (dataset_id, type),
                                       net_file,
                                       'network_%s_%s' % (dataset_id, type),
                                       1500,
                                       0.01,
                                       lems_file_name,
                                       temp_dir,
                                       gen_plots_for_all_v=False,
                                       copy_neuroml=False)

        simulator = "jNeuroML_NEURON"

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

        x = []
        y = []

        print results.keys()

        tt = [t * 1000 for t in results['t']]
        for i in range(len(results) - 1):
            x.append(tt)
            y.append([
                v * 1000
                for v in results['Pop0/%i/%s_%s/v' % (i, type, dataset_id)]
            ])

        pynml.generate_plot(x,
                            y,
                            summary,
                            show_plot_already=False,
                            ylim=[-120, 60],
                            save_figure_to=images % (reference, 'traces'),
                            title_above_plot=True)

        ax = pynml.generate_plot(x,
                                 y,
                                 summary,
                                 show_plot_already=False,
                                 ylim=[-120, 60],
                                 title_above_plot=False)

        ax.set_xlabel(None)
        ax.set_ylabel(None)
        plt.axis('off')

        fig_file = images % (reference, 'traces' + "_FIG")
        plt.savefig(fig_file, bbox_inches='tight', pad_inches=0)
        from PIL import Image
        img = Image.open(fig_file)

        img2 = img.crop((60, 40, 660, 480))
        img2.save(fig_file)
def generate_lems(glif_dir, curr_pA, show_plot=True):

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

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

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

    template_cell = '''<Lems>

      <%s %s/>

    </Lems>
    '''

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

    attributes = ""

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

    file_contents = template_cell%(type, attributes)

    print(file_contents)

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


    import opencortex.build as oc

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

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


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


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



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

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

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

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

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

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


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

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

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


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

### Original model

%(name)s

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

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

#### Original traces:

**Membrane potential**

Current injection of %(curr)s pA

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

**Threshold**

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

### Conversion to NeuroML 2

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

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

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

    jnml LEMS_Test_%(id)s.xml

#### Comparison:

**Membrane potential**

Current injection of %(curr)s pA

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

**Threshold**

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

    os.chdir('..')
    
    return model_metadata, neuron_config, ephys_sweeps
def main(config, parameter_set, prefix, duration, dt, simulator, save_only=False):
    
    
    exec('from c302_%s import setup'%config)
    cells, cells_to_stimulate, params, muscles = setup(parameter_set, 
                                                       generate=True,
                                                       duration = duration, 
                                                       dt = dt,
                                                       target_directory='examples')
    
    os.chdir('examples')
    
    lems_file = 'LEMS_c302_%s_%s.xml'%(parameter_set,config)
    
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, verbose=True)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, verbose=True)
    
    print("Reloaded data: %s"%results.keys())
    cells.sort()
    cells.reverse()
    
    ################################################
    ## Plot voltages cells
    
    print("Plotting neuron voltages")
    template = '%s/0/GenericCell/v'
    if parameter_set=='A' or parameter_set=='B':
        template = '%s/0/generic_iaf_cell/v'
        
    for cell in cells:
        v = results[template%cell]
        if cell==cells[0]:
            volts_n = np.array([v])
        else:
            volts_n = np.append(volts_n,[v],axis=0)
        
    info = 'Membrane potentials of %i cells (%s %s)'%(len(cells),config,parameter_set)
    
    plots(volts_n, info, cells, dt)

    if save_only:
        plt.savefig(save_fig_path%('neurons_%s_%s.png'%(parameter_set,config)),bbox_inches='tight')
    
    ################################################
    ## Plot voltages muscles
    mneurons, all_muscles, muscle_conns = c302.get_cell_muscle_names_and_connection(test=True)
    all_muscles.remove('MANAL')
    all_muscles.remove('MVULVA')
    all_muscles.remove('MVR24')
    all_muscles.sort()
    all_muscles.reverse()

    if muscles:

        print("Plotting muscle voltages")
        for muscle in all_muscles:
            mv = results[template%muscle]
            if muscle==all_muscles[0]:
                mvolts_n = np.array([mv])
            else:
                mvolts_n = np.append(mvolts_n,[mv],axis=0)

        info = 'Membrane potentials of %i muscles (%s %s)'%(len(all_muscles),config,parameter_set)

        plots(mvolts_n, info, cells, dt)
        
        if save_only:
            plt.savefig(save_fig_path%('muscles_%s_%s.png'%(parameter_set,config)),bbox_inches='tight')
    
    ################################################
    ## Plot activity/[Ca2+] in cells
    
    if parameter_set!='A':
        
        print("Plotting neuron activities")
        variable = 'activity'
        description = 'Activity'
        template = '%s/0/GenericCell/%s'
        if parameter_set=='A' or parameter_set=='B':
            template = '%s/0/generic_iaf_cell/%s'
        if parameter_set=='C' or parameter_set=='C1':
            variable = 'caConc'
            description = '[Ca2+]'

        info = '%s of %i cells (%s %s)'%(description, len(cells),config,parameter_set)
        for cell in cells:
            a = results[template%(cell,variable)]
            if cell==cells[0]:
                activities_n = np.array([a])
            else:
                activities_n = np.append(activities_n,[a],axis=0)

        plots(activities_n, info, cells, dt)
        
        if save_only:
            plt.savefig(save_fig_path%('neuron_activity_%s_%s.png'%(parameter_set,config)),bbox_inches='tight')
    
    ################################################
    ## Plot activity/[Ca2+] in muscles
    
    if parameter_set!='A' and muscles:
        
        print("Plotting muscle activities")
        variable = 'activity'
        description = 'Activity'
        template = '%s/0/GenericCell/%s'
        if parameter_set=='A' or parameter_set=='B':
            template = '%s/0/generic_iaf_cell/%s'
        if parameter_set=='C' or parameter_set=='C1':
            variable = 'caConc'
            description = '[Ca2+]'

        info = '%s of %i muscles (%s %s)'%(description, len(all_muscles),config,parameter_set)
        for m in all_muscles:
            a = results[template%(m,variable)]
            if m==all_muscles[0]:
                activities_n = np.array([a])
            else:
                activities_n = np.append(activities_n,[a],axis=0)

        plots(activities_n, info, cells, dt)
    
        if save_only:
            plt.savefig(save_fig_path%('muscle_activity_%s_%s.png'%(parameter_set,config)),bbox_inches='tight')
    
    
    os.chdir('..')

    if not save_only:
        plt.show()
Пример #35
0
def runBrunelNetwork(g=5., 
                     eta=2., 
                     dt = 0.1, 
                     simtime = 1000.0, 
                     delay = 1.5, 
                     epsilon = 0.1, 
                     order = 2500, 
                     N_rec = 50,
                     N_rec_v = 2, 
                     save=False, 
                     simulator_name='nest',
                     jnml_simulator=None,
                     extra = {}):

    exec("from pyNN.%s import *" % simulator_name) in globals()
    
    timer = Timer()

    # === Define parameters ========================================================

    downscale   = 1       # scale number of neurons down by this factor
                          # scale synaptic weights up by this factor to
                          # obtain similar dynamics independent of size
    order       = order   # determines size of network:
                          # 4*order excitatory neurons
                          # 1*order inhibitory neurons
    Nrec        = N_rec   # number of neurons to record from, per population
    epsilon     = epsilon # connectivity: proportion of neurons each neuron projects to

    # Parameters determining model dynamics, cf Brunel (2000), Figs 7, 8 and Table 1
    # here: Case C, asynchronous irregular firing, ~35 Hz
    eta         = eta     # rel rate of external input
    g           = g       # rel strength of inhibitory synapses
    J           = 0.1     # synaptic weight [mV]
    delay       = delay   # synaptic delay, all connections [ms]

    # single neuron parameters
    tauMem      = 20.0    # neuron membrane time constant [ms]
    tauSyn      = 0.1     # synaptic time constant [ms]
    tauRef      = 2.0     # refractory time [ms]
    U0          = 0.0     # resting potential [mV]
    theta       = 20.0    # threshold

    # simulation-related parameters
    simtime     = simtime   # simulation time [ms]
    dt          = dt     # simulation step length [ms]

    # seed for random generator used when building connections
    connectseed = 12345789
    use_RandomArray = True  # use Python rng rather than NEST rng

    # seed for random generator(s) used during simulation
    kernelseed  = 43210987

    # === Calculate derived parameters =============================================

    # scaling: compute effective order and synaptic strength
    order_eff = int(float(order)/downscale)
    J_eff     = J*downscale

    # compute neuron numbers
    NE = int(4*order_eff)  # number of excitatory neurons
    NI = int(1*order_eff)  # number of inhibitory neurons
    N  = NI + NE           # total number of neurons

    # compute synapse numbers
    CE   = int(epsilon*NE)  # number of excitatory synapses on neuron
    CI   = int(epsilon*NI)  # number of inhibitory synapses on neuron
    C    = CE + CI          # total number of internal synapses per n.
    Cext = CE               # number of external synapses on neuron

    # synaptic weights, scaled for alpha functions, such that
    # for constant membrane potential, charge J would be deposited
    fudge = 0.00041363506632638  # ensures dV = J at V=0

    # excitatory weight: JE = J_eff / tauSyn * fudge
    JE = (J_eff/tauSyn)*fudge

    # inhibitory weight: JI = - g * JE
    JI = -g*JE

    # threshold, external, and Poisson generator rates:
    nu_thresh = theta/(J_eff*CE*tauMem)
    nu_ext    = eta*nu_thresh     # external rate per synapse
    p_rate    = 1000*nu_ext*Cext  # external input rate per neuron (Hz)

    # number of synapses---just so we know
    Nsyn = (C+1)*N + 2*Nrec  # number of neurons * (internal synapses + 1 synapse from PoissonGenerator) + 2synapses" to spike detectors
    
    print('Created Brunel network with parameters')
    for p in ['NE','NI','downscale','order','N_rec','epsilon','eta','g','J','delay','tauMem','tauSyn','tauRef','U0','theta','simtime','dt', \
              'order_eff','J_eff','N','CE','CI','C','Cext','fudge','JE','JI','nu_thresh','nu_ext','p_rate','Nsyn']:
        print('  %s%s= %s'%(p, ' '*(12-len(p)), eval(p)))

    # put cell parameters into a dict
    cell_params = {'tau_m'      : tauMem,
                   'tau_syn_E'  : tauSyn,
                   'tau_syn_I'  : tauSyn,
                   'tau_refrac' : tauRef,
                   'v_rest'     : U0,
                   'v_reset'    : U0,
                   'v_thresh'   : theta,
                   'cm'         : 0.001}     # (nF)

    # === Build the network ========================================================

    # clear all existing network elements and set resolution and limits on delays.
    # For NEST, limits must be set BEFORE connecting any elements

    #extra = {'threads' : 2}

    rank = setup(timestep=dt, max_delay=delay, **extra)
    print("rank =", rank)
    np = num_processes()
    print("np =", np)
    import socket
    host_name = socket.gethostname()
    print("Host #%d is on %s" % (rank+1, host_name))

    if 'threads' in extra:
        print("%d Initialising the simulator with %d threads..." % (rank, extra['threads']))
    else:
        print("%d Initialising the simulator with single thread..." % rank)

    # Small function to display information only on node 1
    def nprint(s):
        if rank == 0:
            print(s)

    timer.start()  # start timer on construction

    print("%d Setting up random number generator" % rank)
    rng = NumpyRNG(kernelseed, parallel_safe=True)

    print("%d Creating excitatory population with %d neurons." % (rank, NE))
    celltype = IF_curr_alpha(**cell_params)
    celltype.default_initial_values['v'] = U0 # Setting default init v, useful for NML2 export
    E_net = Population(NE, celltype, label="E_net")

    print("%d Creating inhibitory population with %d neurons." % (rank, NI))
    I_net = Population(NI, celltype, label="I_net")

    print("%d Initialising membrane potential to random values between %g mV and %g mV." % (rank, U0, theta))
    uniformDistr = RandomDistribution('uniform', low=U0, high=theta, rng=rng)
    E_net.initialize(v=uniformDistr)
    I_net.initialize(v=uniformDistr)

    print("%d Creating excitatory Poisson generator with rate %g spikes/s." % (rank, p_rate))
    source_type = SpikeSourcePoisson(rate=p_rate)
    expoisson = Population(NE, source_type, label="expoisson")

    print("%d Creating inhibitory Poisson generator with the same rate." % rank)
    inpoisson = Population(NI, source_type, label="inpoisson")

    # Record spikes
    print("%d Setting up recording in excitatory population." % rank)
    E_net.record('spikes')
    if N_rec_v>0:
        E_net[0:min(NE,N_rec_v)].record('v')

    print("%d Setting up recording in inhibitory population." % rank)
    I_net.record('spikes')
    if N_rec_v>0:
        I_net[0:min(NI,N_rec_v)].record('v')

    progress_bar = ProgressBar(width=20)
    connector = FixedProbabilityConnector(epsilon, rng=rng, callback=progress_bar)
    E_syn = StaticSynapse(weight=JE, delay=delay)
    I_syn = StaticSynapse(weight=JI, delay=delay)
    ext_Connector = OneToOneConnector(callback=progress_bar)
    ext_syn = StaticSynapse(weight=JE, delay=dt)

    print("%d Connecting excitatory population with connection probability %g, weight %g nA and delay %g ms." % (rank, epsilon, JE, delay))
    E_to_E = Projection(E_net, E_net, connector, E_syn, receptor_type="excitatory")
    print("E --> E\t\t", len(E_to_E), "connections")
    I_to_E = Projection(I_net, E_net, connector, I_syn, receptor_type="inhibitory")
    print("I --> E\t\t", len(I_to_E), "connections")
    input_to_E = Projection(expoisson, E_net, ext_Connector, ext_syn, receptor_type="excitatory")
    print("input --> E\t", len(input_to_E), "connections")

    print("%d Connecting inhibitory population with connection probability %g, weight %g nA and delay %g ms." % (rank, epsilon, JI, delay))
    E_to_I = Projection(E_net, I_net, connector, E_syn, receptor_type="excitatory")
    print("E --> I\t\t", len(E_to_I), "connections")
    I_to_I = Projection(I_net, I_net, connector, I_syn, receptor_type="inhibitory")
    print("I --> I\t\t", len(I_to_I), "connections")
    input_to_I = Projection(inpoisson, I_net, ext_Connector, ext_syn, receptor_type="excitatory")
    print("input --> I\t", len(input_to_I), "connections")

    # read out time used for building
    buildCPUTime = timer.elapsedTime()
    # === Run simulation ===========================================================

    # run, measure computer time
    timer.start()  # start timer on construction
    print("%d Running simulation for %g ms (dt=%sms)." % (rank, simtime, dt))
    run(simtime)
    print("Done")
    simCPUTime = timer.elapsedTime()

    # write data to file
    #print("%d Writing data to file." % rank)
    #(E_net + I_net).write_data("Results/brunel_np%d_%s.pkl" % (np, simulator_name))
    if save and not simulator_name=='neuroml':
        for pop in [E_net , I_net]:
            io = PyNNTextIO(filename="brunel-PyNN-%s-%s-%i.gdf"%(simulator_name, pop.label, rank))
            spikes =  pop.get_data('spikes', gather=False)
            for segment in spikes.segments:
                io.write_segment(segment)
                
            io = PyNNTextIO(filename="brunel-PyNN-%s-%s-%i.dat"%(simulator_name, pop.label, rank))
            vs =  pop.get_data('v', gather=False)
            for segment in vs.segments:
                io.write_segment(segment)
            
    spike_data = {}
    spike_data['senders'] = []
    spike_data['times'] = []
    index_offset = 1
    for pop in [E_net , I_net]:
        if rank == 0:
            spikes =  pop.get_data('spikes', gather=False)
            #print(spikes.segments[0].all_data)
            num_rec = len(spikes.segments[0].spiketrains)
            print("Extracting spike info (%i) for %i cells in %s"%(num_rec,pop.size,pop.label))
            #assert(num_rec==len(spikes.segments[0].spiketrains))
            for i in range(num_rec):
                ss = spikes.segments[0].spiketrains[i]
                for s in ss:
                    index = i+index_offset
                    #print("Adding spike at %s in %s[%i] (cell %i)"%(s,pop.label,i,index))
                    spike_data['senders'].append(index)
                    spike_data['times'].append(s)
            index_offset+=pop.size
        
    #from IPython.core.debugger import Tracer
    #Tracer()()

    E_rate = E_net.mean_spike_count()*1000.0/simtime
    I_rate = I_net.mean_spike_count()*1000.0/simtime

    # write a short report
    nprint("\n--- Brunel Network Simulation ---")
    nprint("Nodes              : %d" % np)
    nprint("Number of Neurons  : %d" % N)
    nprint("Number of Synapses : %d" % Nsyn)
    nprint("Input firing rate  : %g" % p_rate)
    nprint("Excitatory weight  : %g" % JE)
    nprint("Inhibitory weight  : %g" % JI)
    nprint("Excitatory rate    : %g Hz" % E_rate)
    nprint("Inhibitory rate    : %g Hz" % I_rate)
    nprint("Build time         : %g s" % buildCPUTime)
    nprint("Simulation time    : %g s" % simCPUTime)

    # === Clean up and quit ========================================================

    end()
    
    
    if simulator_name=='neuroml' and jnml_simulator:
        from pyneuroml import pynml
        lems_file = 'LEMS_Sim_PyNN_NeuroML2_Export.xml'
        
        print('Going to run generated LEMS file: %s on simulator: %s'%(lems_file,jnml_simulator))
        
        if jnml_simulator=='jNeuroML':
            results, events = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, reload_events=True)
        
        elif jnml_simulator=='jNeuroML_NEURON':
            results, events = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, reload_events=True)
            
        spike_data['senders'] = []
        spike_data['times'] = []
        for k in events.keys():
            values = k.split('/') 
            index = int(values[1]) if values[0]=='E_net' else NE+int(values[1])
            n = len(events[k])
            print("Loading spikes for %s (index %i): [%s, ..., %s (n=%s)] sec"%(k,index,events[k][0] if n>0 else '-',events[k][-1] if n>0 else '-',n))
            for t in events[k]:
                spike_data['senders'].append(index)
                spike_data['times'].append(t*1000)
                
    #print spike_data
    return spike_data
Пример #36
0
def run_c302(config, 
             parameter_set, 
             prefix, 
             duration, 
             dt, 
             simulator, 
             save=False, 
             show_plot_already=True, 
             data_reader="SpreadsheetDataReader",
             verbose=False,
             plot_ca=True,
             plot_connectivity=False,
             param_overrides={},
             config_param_overrides={},
             config_package="",
             target_directory='examples',
             save_fig_to=None):

    if save_fig_to:
        global save_fig_dir
        save_fig_dir = save_fig_to

    c302.print_("********************\n\n   Going to generate c302_%s_%s and run for %sms (dt: %sms) on %s\n\n********************"%(parameter_set,config,duration, dt, simulator))
    if config_package:
        exec ('from %s.c302_%s import setup' % (config_package, config), globals())
    else:
        exec ('from c302_%s import setup' % config, globals())

    try:
        os.makedirs(target_directory)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    cells, cells_to_stimulate, params, muscles, nml_doc = setup(parameter_set,
                                                       data_reader=data_reader,
                                                       generate=True,
                                                       duration = duration, 
                                                       dt = dt,
                                                       target_directory=target_directory,
                                                       verbose=verbose,
                                                       param_overrides=param_overrides,
                                                       config_param_overrides=config_param_overrides)

    orig_dir = os.getcwd()

    os.chdir(target_directory)

    try:
        os.makedirs(save_fig_dir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    lems_file = 'LEMS_c302_%s_%s.xml'%(parameter_set,config)
    
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, verbose=verbose)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, verbose=verbose)
        
    c302.print_("Finished simulation of %s and have reloaded results"%lems_file)
        
    c302_utils.plot_c302_results(results, 
                                 config, 
                                 parameter_set, 
                                 directory=save_image_full_dir,
                                 save=save,
                                 show_plot_already=show_plot_already, 
                                 data_reader=data_reader,
                                 plot_ca=plot_ca)

    if plot_connectivity:
        c302_utils.generate_conn_matrix(nml_doc, save_fig_dir=save_image_full_dir)

    os.chdir(orig_dir)

    return cells, cells_to_stimulate, params, muscles
Пример #37
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
            if ic.id == channel_id:
                for g in ic.gates:
                    gates.append(g.id)

        new_lems_file = "LEMS_Test_%s.xml"%channel_id
    
        lems_helper = generate(nml2_file_path, channel_id, gates, temperature, ion=doc.ion_channel_hhs[0].species)
        
        file_out = open(new_lems_file, 'w')
        file_out.write(lems_helper)
        file_out.close()
        
        success = pynml.run_lems_with_jneuroml("LEMS_Test_%s.xml"%channel_id, 
                           nogui=True, 
                           load_saved_data=False, 
                           plot=False, 
                           exec_in_dir = ".",
                           verbose=True,
                           exit_on_fail = False)
                           
        if success: 
            valid +=1
        else:
            os.rename(nml2_file_path, nml2_file_path+".broken")
        
        max_chans -=1

        
print("\nFound %i models in Channelpedia XML format, converted %i to valid NeuroML2\n"%(count,valid))

unknowns_file = open('unknowns','w')
import sys

from pyneuroml import pynml

####################################################################
#   Choose a LEMS/NeuroML2 file and run it with jNeuroML

example_lems_file = 'LEMS_NML2_Ex5_DetCell.xml'

results1 = pynml.run_lems_with_jneuroml(example_lems_file,
                                        nogui=True,
                                        load_saved_data=True)

####################################################################
#   Convert LEMS/NeuroML2 file to NEURON with jNeuroML & run

if not '-noneuron' in sys.argv:  # To allow skipping of this for ease of testing

    results2 = pynml.run_lems_with_jneuroml_neuron(example_lems_file,
                                                   nogui=True,
                                                   load_saved_data=True)

####################################################################
#   Reload & plot results

if not '-nogui' in sys.argv:

    from matplotlib import pyplot as plt

    for key in results1.keys():
Пример #40
0
    def go(self):
        """
        Start the simulation once it's been intialized
        """

        nml_doc = c302.generate(self.reference,
                                self.params,
                                cells=self.cells,
                                cells_to_stimulate=self.cells_to_stimulate,
                                include_muscles=self.include_muscles,
                                duration=self.sim_time,
                                dt=self.dt,
                                validate=(self.params.level != 'B'),
                                verbose=False,
                                target_directory=self.generate_dir)

        self.lems_file = "LEMS_%s.xml" % (self.reference)

        print("Running a simulation of %s ms with timestep %s ms: %s" %
              (self.sim_time, self.dt, self.lems_file))

        self.already_run = True

        start = time.time()
        if self.simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(
                self.lems_file,
                nogui=True,
                load_saved_data=True,
                plot=False,
                exec_in_dir=self.generate_dir,
                verbose=False)
        elif self.simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(
                self.lems_file,
                nogui=True,
                load_saved_data=True,
                plot=False,
                exec_in_dir=self.generate_dir,
                verbose=False)
        else:
            print('Unsupported simulator: %s' % self.simulator)
            exit()

        secs = time.time() - start

        print("Ran simulation in %s in %f seconds (%f mins)\n\n" %
              (self.simulator, secs, secs / 60.0))

        self.t = [t * 1000 for t in results['t']]
        res_template = '%s/0/generic_iaf_cell/v'
        if self.params.level == 'B' or self.params.level == 'C' or self.params.level == 'D':
            res_template = '%s[0]/v'
        self.volts = {}

        if self.cells is None:
            self.cells = []
            for pop in nml_doc.networks[0].populations:
                self.cells.append(pop.id)

        for cell in self.cells:
            self.volts[res_template % cell] = [
                v * 1000 for v in results[res_template % cell]
            ]
Пример #41
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 analyse_cell(dataset_id, type, info, nogui = False, densities=False, analysis_dir='../../data/'):
    
    reference = '%s_%s'%(type,dataset_id)
    cell_file = '%s/%s.cell.nml'%(type,reference)
    
    print("====================================\n\n   Analysing cell: %s, dataset %s\n"%(cell_file,dataset_id))
    
    nml_doc = pynml.read_neuroml2_file(cell_file)
    notes = nml_doc.cells[0].notes if len(nml_doc.cells)>0 else nml_doc.izhikevich2007_cells[0].notes
    meta_nml = eval(notes[notes.index('{'):])
    summary = "Fitness: %s (max evals: %s, pop: %s)"%(meta_nml['fitness'],meta_nml['max_evaluations'],meta_nml['population_size'])
    print summary
    
    images = 'summary/%s_%s.png'
    if_iv_data_files = 'summary/%s_%s.dat'
    

    data, v_sub, curents_sub, freqs, curents_spike = get_if_iv_for_dataset('%s%s_analysis.json'%(analysis_dir,dataset_id))
    
    if densities:

        dataset = {}
        seed = meta_nml['seed']
        if isinstance(seed, tuple):
            seed = seed[0]
        layer = str(data['location'].split(',')[-1].strip().replace(' ',''))
        ref = '%s_%s_%s'%(dataset_id,layer,int(seed))

        dataset['id'] = dataset_id
        dataset['reference'] = ref
        metas = ['aibs_cre_line','aibs_dendrite_type','location']
        for m in metas:
            dataset[m] = str(data[m])

        metas2 = ['fitness','population_size','seed']
        for m in metas2:
            dataset[m] = meta_nml[m]
            
        # Assume images below already generated...
        if type=='HH':
            
            
            cell = nml_doc.cells[0]
            
            sgv_files, all_info = generate_channel_density_plots(cell_file, text_densities=True, passives_erevs=True)
            sgv_file =sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]
        
            info['datasets'][ref] = dataset
            
        elif type=='Izh':
            
            dataset['tuned_cell_info'] = {}
            izh_cell = nml_doc.izhikevich2007_cells[0]
                        
            for p in ['C','a','b','c','d','k','vpeak','vr','vt']:
            
                dataset['tuned_cell_info'][p] = get_value_in_si(getattr(izh_cell, p))
            
            '''
            sgv_files, all_info = generate_channel_density_plots(cell_file, text_densities=True, passives_erevs=True)
            sgv_file =sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]'''
        
        info['datasets'][ref] = dataset
        
    else:

        traces_ax, if_ax, iv_ax = generate_current_vs_frequency_curve(cell_file, 
                                            reference, 
                                            simulator = 'jNeuroML_NEURON',
                                            start_amp_nA =         -0.1, 
                                            end_amp_nA =           0.4, 
                                            step_nA =              0.01, 
                                            analysis_duration =    1000, 
                                            analysis_delay =       50,
                                            plot_voltage_traces =  False,
                                            plot_if =              not nogui,
                                            plot_iv =              not nogui, 
                                            xlim_if =              [-200, 400],
                                            ylim_if =              [-10, 120],
                                            xlim_iv =              [-200, 400],
                                            ylim_iv =              [-120, -40],
                                            save_if_figure_to =    images%(reference, 'if'), 
                                            save_iv_figure_to =    images%(reference, 'iv'),
                                            save_if_data_to =      if_iv_data_files%(reference, 'if'), 
                                            save_iv_data_to =      if_iv_data_files%(reference, 'iv'), 
                                            show_plot_already = False,
                                            return_axes = True)


        iv_ax.plot(curents_sub, v_sub,   color='#ff2222',marker='o', linestyle='',zorder=1)   
        if_ax.plot(curents_spike, freqs ,color='#ff2222',marker='o', linestyle='',zorder=1)

        iv_ax.get_figure().savefig(images%(reference, 'iv'),bbox_inches='tight')
        if_ax.get_figure().savefig(images%(reference, 'if'),bbox_inches='tight')
        
        
        offset = 100 # mV 
        
        ifv_x = []
        ifv_y = []
        markers = []
        lines = []
        colors = []
        
        cols = {'Izh':'r','HH':'g','AllenHH':'b'}
        
        for ii in ['if','iv']:
            for tt in ['Izh','HH','AllenHH']:
                rr = '%s_%s'%(tt,dataset_id)
                f = if_iv_data_files%(rr, ii)
                if os.path.isfile(f):
                    print("--- Opening: %s"%f)
                    data, indeces = reload_standard_dat_file(f)
                    
                    ifv_x.append(data['t'])
                    
                    if ii=='if':
                        ifv_y.append([ff-offset for ff in data[0]])
                    else:
                        ifv_y.append([vv for vv in data[0]])
                        
                    
                    markers.append('')
                    colors.append(cols[tt])
                    lines.append('-')
                    
        ifv_x.append(curents_sub)
        vvsub = [vv for vv in v_sub]
        
        ifv_y.append(vvsub)
        
        sub_color = '#888888'
        markers.append('D')
        colors.append('k')
        lines.append('')
        
        ifv_x.append(curents_spike)
        ifv_y.append([ff-offset for ff in freqs])
        
        markers.append('o')
        colors.append(sub_color)
        lines.append('')
        
        import matplotlib
        import matplotlib.pyplot as plt

        print ifv_x
        print ifv_y
        ylim = [-105, -20]
        font_size = 18
        ax1 = pynml.generate_plot(ifv_x,
                    ifv_y, 
                    summary, 
                    markers=markers,
                    colors=colors,
                    linestyles=lines,
                    show_plot_already=False,
                    xlim = [-100, 400],
                    font_size = font_size,
                    ylim = ylim,
                    title_above_plot=False)
                    
        plt.xlabel('Input current (pA)', fontsize = font_size)
        plt.ylabel("Steady membrane potential (mV)", fontsize = font_size)
        
        ax2 = ax1.twinx()
        plt.ylim([ylim[0]+offset,ylim[1]+offset])
        plt.ylabel('Firing frequency (Hz)', color=sub_color, fontsize = font_size)
        ax2.tick_params(axis='y', colors=sub_color)
        
        
        #plt.axis('off')
        
        plt.savefig(images%(reference, 'if_iv'+"_FIG"),bbox_inches='tight')
        

        temp_dir = 'temp/'

        print("Copying %s to %s"%(cell_file, temp_dir))
        shutil.copy(cell_file, temp_dir)

        net_file = generate_network_for_sweeps(type, dataset_id, '%s.cell.nml'%(reference), reference, temp_dir, data_dir=analysis_dir)

        lems_file_name = 'LEMS_Test_%s_%s.xml'%(type,dataset_id)

        generate_lems_file_for_neuroml('Test_%s_%s'%(dataset_id,type),
                                       net_file,
                                       'network_%s_%s'%(dataset_id,type), 
                                       1500, 
                                       0.01, 
                                       lems_file_name,
                                       temp_dir,
                                       gen_plots_for_all_v=False,
                                       copy_neuroml = False)

        simulator = "jNeuroML_NEURON"

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

        x = []
        y = []

        print results.keys()

        tt = [t*1000 for t in results['t']]
        for i in range(len(results)-1):
            x.append(tt)
            y.append([v*1000 for v in results['Pop0/%i/%s_%s/v'%(i,type,dataset_id)]])

        pynml.generate_plot(x,
                    y, 
                    summary, 
                    show_plot_already=False,
                    ylim = [-120, 60],
                    save_figure_to = images%(reference, 'traces'),
                    title_above_plot=True)
                 
        ax = pynml.generate_plot(x,
                    y, 
                    summary, 
                    show_plot_already=False,
                    ylim = [-120, 60],
                    title_above_plot=False)
                    
        ax.set_xlabel(None)
        ax.set_ylabel(None)
        plt.axis('off')
        
        fig_file = images%(reference, 'traces'+"_FIG")
        plt.savefig(fig_file, bbox_inches='tight', pad_inches=0)
        from PIL import Image
        img = Image.open(fig_file)

        img2 = img.crop((60, 40, 660, 480))
        img2.save(fig_file)
Пример #43
0
def analyse_spiketime_vs_dt(nml2_file,
                            target,
                            duration,
                            simulator,
                            cell_v_path,
                            dts,
                            verbose=False,
                            spike_threshold_mV=0,
                            show_plot_already=True,
                            save_figure_to=None,
                            num_of_last_spikes=None):

    from pyelectro.analysis import max_min
    import numpy as np

    all_results = {}

    dts = list(np.sort(dts))

    for dt in dts:
        if verbose:
            print_comment_v(" == Generating simulation for dt = %s ms" % dt)
        ref = str("Sim_dt_%s" % dt).replace('.', '_')
        lems_file_name = "LEMS_%s.xml" % ref
        generate_lems_file_for_neuroml(ref,
                                       nml2_file,
                                       target,
                                       duration,
                                       dt,
                                       lems_file_name,
                                       '.',
                                       gen_plots_for_all_v=True,
                                       gen_saves_for_all_v=True,
                                       copy_neuroml=False)

        if simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(lems_file_name,
                                                   nogui=True,
                                                   load_saved_data=True,
                                                   plot=False,
                                                   verbose=verbose)
        if simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(lems_file_name,
                                                          nogui=True,
                                                          load_saved_data=True,
                                                          plot=False,
                                                          verbose=verbose)

        print("Results reloaded: %s" % results.keys())

        all_results[dt] = results

    xs = []
    ys = []
    labels = []

    spxs = []
    spys = []
    linestyles = []
    markers = []
    colors = []
    spike_times_final = []
    array_of_num_of_spikes = []

    for dt in dts:
        t = all_results[dt]['t']
        v = all_results[dt][cell_v_path]
        xs.append(t)
        ys.append(v)
        labels.append(dt)

        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)

        spike_times = mm['maxima_times']

        spike_times_final.append(spike_times)

        array_of_num_of_spikes.append(len(spike_times))

    max_num_of_spikes = max(array_of_num_of_spikes)

    min_dt_spikes = spike_times_final[0]

    bound_dts = [math.log(dts[0]), math.log(dts[-1])]

    if num_of_last_spikes == None:

        num_of_spikes = len(min_dt_spikes)

    else:

        if len(min_dt_spikes) >= num_of_last_spikes:

            num_of_spikes = num_of_last_spikes

        else:

            num_of_spikes = len(min_dt_spikes)

    spike_indices = [(-1) * ind for ind in range(1, num_of_spikes + 1)]

    if len(min_dt_spikes) > abs(spike_indices[-1]):

        earliest_spike_time = min_dt_spikes[spike_indices[-1] - 1]

    else:

        earliest_spike_time = min_dt_spikes[spike_indices[-1]]

    for spike_ind in range(0, max_num_of_spikes):

        spike_time_values = []

        dt_values = []

        for dt in range(0, len(dts)):

            if spike_times_final[dt] != []:

                if len(spike_times_final[dt]) >= spike_ind + 1:

                    if spike_times_final[dt][spike_ind] >= earliest_spike_time:

                        spike_time_values.append(
                            spike_times_final[dt][spike_ind])

                        dt_values.append(math.log(dts[dt]))

        linestyles.append('')

        markers.append('o')

        colors.append('g')

        spxs.append(dt_values)

        spys.append(spike_time_values)

    for last_spike_index in spike_indices:

        vertical_line = [
            min_dt_spikes[last_spike_index], min_dt_spikes[last_spike_index]
        ]

        spxs.append(bound_dts)

        spys.append(vertical_line)

        linestyles.append('--')

        markers.append('')

        colors.append('k')

    pynml.generate_plot(spxs,
                        spys,
                        "Spike times vs dt",
                        colors=colors,
                        linestyles=linestyles,
                        markers=markers,
                        xaxis='ln ( dt (ms) )',
                        yaxis='Spike times (s)',
                        show_plot_already=show_plot_already,
                        save_figure_to=save_figure_to)

    if verbose:
        pynml.generate_plot(xs,
                            ys,
                            "Membrane potentials in %s for %s" %
                            (simulator, dts),
                            labels=labels,
                            show_plot_already=show_plot_already,
                            save_figure_to=save_figure_to)
Пример #44
0
        new_lems_file = "test/LEMS_Test_%s.xml" % channel_id

        lems_helper = generate(nml2_file_name,
                               channel_id,
                               gates,
                               temperature,
                               ion=doc.ion_channel_hhs[0].species)

        file_out = open(new_lems_file, 'w')
        file_out.write(lems_helper)
        file_out.close()

        success = pynml.run_lems_with_jneuroml("LEMS_Test_%s.xml" % channel_id,
                                               nogui=True,
                                               load_saved_data=False,
                                               plot=False,
                                               exec_in_dir="test/",
                                               verbose=True,
                                               exit_on_fail=False)

        if success:
            valid += 1
        else:
            os.rename(nml2_file_path, nml2_file_path + ".broken")

        max_chans -= 1

print(
    "\nFound %i models in Channelpedia XML format, converted %i to valid NeuroML2\n"
    % (count, valid))
import sys
from pyneuroml import pynml


lems_file = 'LEMS_test_Ca.xml'

results = pynml.run_lems_with_jneuroml(lems_file, max_memory='2G', nogui=True, load_saved_data=True)

if not '-nogui' in sys.argv:
    
    from pylab import plot, show, figure, title

    for key in results.keys():
        if key != 't':
            figure()
            plot(results['t'], results[key], label="jNeuroML: "+key, color="g")
            title(key)

    show()
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
Пример #47
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     
Пример #48
0
def analyse_spiketime_vs_dt(nml2_file, 
                            target,
                            duration,
                            simulator,
                            cell_v_path,
                            dts,
                            verbose=False,
                            spike_threshold_mV = 0,
                            show_plot_already=True,
                            save_figure_to=None,
                            num_of_last_spikes=None):
                                
    from pyelectro.analysis import max_min
    import numpy as np
    
    all_results = {}
    
    dts=list(np.sort(dts))
    
    for dt in dts:
        if verbose:
            print_comment_v(" == Generating simulation for dt = %s ms"%dt)
        ref = str("Sim_dt_%s"%dt).replace('.','_')
        lems_file_name = "LEMS_%s.xml"%ref
        generate_lems_file_for_neuroml(ref, 
                                   nml2_file, 
                                   target, 
                                   duration, 
                                   dt, 
                                   lems_file_name,
                                   '.',
                                   gen_plots_for_all_v = True,
                                   gen_saves_for_all_v = True,
                                   copy_neuroml = False,
                                   seed=None)
                                   
        if simulator == 'jNeuroML':
             results = pynml.run_lems_with_jneuroml(lems_file_name, nogui=True, load_saved_data=True, plot=False, verbose=verbose)
        if simulator == 'jNeuroML_NEURON':
             results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True, load_saved_data=True, plot=False, verbose=verbose)
             
        print("Results reloaded: %s"%results.keys())
             
        all_results[dt] = results
        
    xs = []
    ys = []
    labels = []
    
    spxs = []
    spys = []
    linestyles = []
    markers = []
    colors=[]
    spike_times_final=[]
    array_of_num_of_spikes=[]
    
    for dt in dts:
        t = all_results[dt]['t']
        v = all_results[dt][cell_v_path]
        xs.append(t)
        ys.append(v)
        labels.append(dt)
        
        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        
        spike_times = mm['maxima_times']
        
        spike_times_final.append(spike_times)
        
        array_of_num_of_spikes.append(len(spike_times))
        
    max_num_of_spikes=max(array_of_num_of_spikes)
    
    min_dt_spikes=spike_times_final[0]
    
    bound_dts=[math.log(dts[0]),math.log(dts[-1])]
    
    if num_of_last_spikes == None:
    
       num_of_spikes=len(min_dt_spikes)
       
    else:
       
       if len(min_dt_spikes) >=num_of_last_spikes:
       
          num_of_spikes=num_of_last_spikes
          
       else:
       
          num_of_spikes=len(min_dt_spikes)
    
    spike_indices=[(-1)*ind for ind in range(1,num_of_spikes+1) ]
    
    if len(min_dt_spikes) > abs(spike_indices[-1]):
    
       earliest_spike_time=min_dt_spikes[spike_indices[-1]-1]
       
    else:
     
       earliest_spike_time=min_dt_spikes[spike_indices[-1]]
       
    for spike_ind in range(0,max_num_of_spikes):
    
        spike_time_values=[]
        
        dt_values=[]
        
        for dt in range(0,len(dts)):
        
            if spike_times_final[dt] !=[]:
           
               if len(spike_times_final[dt]) >= spike_ind+1:
               
                  if spike_times_final[dt][spike_ind] >= earliest_spike_time:
             
                     spike_time_values.append(spike_times_final[dt][spike_ind])
               
                     dt_values.append(math.log(dts[dt]))       
        
        linestyles.append('')
               
        markers.append('o')
       
        colors.append('g')
       
        spxs.append(dt_values)
       
        spys.append(spike_time_values)
    
    for last_spike_index in spike_indices:
       
       vertical_line=[min_dt_spikes[last_spike_index],min_dt_spikes[last_spike_index] ]
          
       spxs.append(bound_dts)
          
       spys.append(vertical_line)
          
       linestyles.append('--')
          
       markers.append('')
       
       colors.append('k')
    
    pynml.generate_plot(spxs, 
          spys, 
          "Spike times vs dt",
          colors=colors,
          linestyles = linestyles,
          markers = markers,
          xaxis = 'ln ( dt (ms) )', 
          yaxis = 'Spike times (s)',
          show_plot_already=show_plot_already,
          save_figure_to=save_figure_to) 
    
    if verbose:
        pynml.generate_plot(xs, 
                  ys, 
                  "Membrane potentials in %s for %s"%(simulator,dts),
                  labels = labels,
                  show_plot_already=show_plot_already,
                  save_figure_to=save_figure_to)
Пример #49
0
def main(config, parameter_set, prefix, duration, dt, simulator):
    
    
    exec('from c302_%s import setup'%config)
    cells, cells_to_stimulate, params, muscles = setup(parameter_set, 
                                                       generate=True,
                                                       duration = duration, 
                                                       dt = dt,
                                                       target_directory='examples')
    
    os.chdir('examples')
    
    lems_file = 'LEMS_c302_%s_%s.xml'%(parameter_set,config)
    
    if simulator == 'jNeuroML':
        results = pynml.run_lems_with_jneuroml(lems_file, nogui=True, load_saved_data=True, verbose=True)
    elif simulator == 'jNeuroML_NEURON':
        results = pynml.run_lems_with_jneuroml_neuron(lems_file, nogui=True, load_saved_data=True, verbose=True)
    
    print("Reloaded data: %s"%results.keys())
    cells.sort()
    cells.reverse()
    
    ################################################
    ## Plot voltages cells
    
    print("Plotting neuron voltages")
    template = '%s/0/GenericCell/v'
    if parameter_set=='A' or parameter_set=='B':
        template = '%s/0/generic_iaf_cell/v'
        
    for cell in cells:
        v = results[template%cell]
        if cell==cells[0]:
            volts_n = np.array([v])
        else:
            volts_n = np.append(volts_n,[v],axis=0)
        
    info = 'Membrane potentials of %i cells'%(len(cells))
    fig, ax = plt.subplots()
    plot0 = ax.pcolor(volts_n)
    ax.set_yticks(np.arange(volts_n.shape[0]) + 0.5, minor=False)
    ax.set_yticklabels(cells)
    
    fig.colorbar(plot0)
    
    fig.canvas.set_window_title(info)
    plt.title(info)
    plt.xlabel('Time (ms)')
 
    fig.canvas.draw()
    labels = [float(item.get_text())*dt for item in ax.get_xticklabels()]

    ax.set_xticklabels(labels)
    
    ################################################
    ## Plot voltages muscles
    mneurons, all_muscles, muscle_conns = c302.get_cell_muscle_names_and_connection(test=True)
    all_muscles.remove('MANAL')
    all_muscles.remove('MVULVA')
    all_muscles.remove('MVR24')
    all_muscles.sort()
    all_muscles.reverse()

    if muscles:

        print("Plotting muscle voltages")
        for muscle in all_muscles:
            mv = results[template%muscle]
            if muscle==all_muscles[0]:
                mvolts_n = np.array([mv])
            else:
                mvolts_n = np.append(mvolts_n,[mv],axis=0)

        info = 'Membrane potentials of %i muscles'%(len(all_muscles))
        fig, ax = plt.subplots()
        plot0 = ax.pcolor(mvolts_n)
        ax.set_yticks(np.arange(mvolts_n.shape[0]) + 0.5, minor=False)
        ax.set_yticklabels(all_muscles)

        fig.colorbar(plot0)

        fig.canvas.set_window_title(info)
        plt.title(info)
        plt.xlabel('Time (ms)')

        fig.canvas.draw()
        labels = [float(item.get_text())*dt for item in ax.get_xticklabels()]

        ax.set_xticklabels(labels)
    
    ################################################
    ## Plot activity/[Ca2+] in cells
    
    if parameter_set!='A':
        
        print("Plotting neuron activities")
        variable = 'activity'
        description = 'Activity'
        template = '%s/0/GenericCell/%s'
        if parameter_set=='A' or parameter_set=='B':
            template = '%s/0/generic_iaf_cell/%s'
        if parameter_set=='C' or parameter_set=='C1':
            variable = 'caConc'
            description = '[Ca2+]'

        info = '%s of %i cells'%(description, len(cells))
        for cell in cells:
            a = results[template%(cell,variable)]
            if cell==cells[0]:
                activities_n = np.array([a])
            else:
                activities_n = np.append(activities_n,[a],axis=0)

        fig, ax = plt.subplots()
        plot0 = ax.pcolor(activities_n)
        ax.set_yticks(np.arange(activities_n.shape[0]) + 0.5, minor=False)
        ax.set_yticklabels(cells)

        fig.colorbar(plot0)
        fig.canvas.set_window_title(info)
        plt.title(info)
        plt.xlabel('Time (ms)')

        fig.canvas.draw()
        labels = [float(item.get_text())*dt for item in ax.get_xticklabels()]

        ax.set_xticklabels(labels)
    
    ################################################
    ## Plot activity/[Ca2+] in muscles
    
    if parameter_set!='A' and muscles:
        
        print("Plotting muscle activities")
        variable = 'activity'
        description = 'Activity'
        template = '%s/0/GenericCell/%s'
        if parameter_set=='A' or parameter_set=='B':
            template = '%s/0/generic_iaf_cell/%s'
        if parameter_set=='C' or parameter_set=='C1':
            variable = 'caConc'
            description = '[Ca2+]'

        info = '%s of %i muscles'%(description, len(all_muscles))
        for m in all_muscles:
            a = results[template%(m,variable)]
            if m==all_muscles[0]:
                activities_n = np.array([a])
            else:
                activities_n = np.append(activities_n,[a],axis=0)

        fig, ax = plt.subplots()
        plot0 = ax.pcolor(activities_n)
        ax.set_yticks(np.arange(activities_n.shape[0]) + 0.5, minor=False)
        ax.set_yticklabels(all_muscles)

        fig.colorbar(plot0)
        fig.canvas.set_window_title(info)
        plt.title(info)
        plt.xlabel('Time (ms)')

        fig.canvas.draw()
        labels = [float(item.get_text())*dt for item in ax.get_xticklabels()]

        ax.set_xticklabels(labels)
    
    

    plt.show()
Пример #50
0
def main():

    args = process_args()
        
    verbose = args.v
    
    ## Get name of channel mechanism to test

    if verbose: print("Going to test channel from file: "+ args.channelFile)
    
    step_target_voltage = args.stepTargetVoltage
    clamp_delay = args.clampDelay 
    clamp_duration = args.clampDuration
    clamp_base_voltage = args.clampBaseVoltage
    duration = args.duration
    erev = args.erev
    
    info = {}
    chan_list = []
    info["channels"] = chan_list
    
    for channel_file in args.channelFiles:

        if not os.path.isfile(channel_file):
            print("File could not be found: %s!\n"%channel_file)
            exit(1)
        doc = loaders.NeuroMLLoader.load(channel_file)

        channels = []
        for c in doc.ion_channel_hhs: channels.append(c)
        for c in doc.ion_channel: channels.append(c)

        for ic in channels:    
            channel_id = ic.id
            gates = []

            for g in ic.gates:
                gates.append(g.id)
            for g in ic.gate_hh_rates:
                gates.append(g.id)
            for g in ic.gate_hh_tau_infs:
                gates.append(g.id)

            if len(gates) == 0:
                print("No gates found in a channel with ID %s"%channel_id)
            else:
                
                if args.html:
                    if not os.path.isdir('html'):
                        os.mkdir('html')
                    channel_info = {}
                    chan_list.append(channel_info)
                    channel_info['id'] = channel_id
                    channel_info['file'] = channel_file
                    if ic.notes:
                        #print ic.notes
                        channel_info['notes'] = ic.notes
                        
                lems_content = generate_lems_channel_analyser(channel_file, channel_id, args.minV, \
                                  step_target_voltage, args.maxV, clamp_delay, \
                                  clamp_duration, clamp_base_voltage, duration, erev, gates, \
                                  args.temperature, args.caConc)

                new_lems_file = "LEMS_Test_%s.xml"%channel_id


                lf = open(new_lems_file, 'w')
                lf.write(lems_content)
                lf.close()

                print("Written generated LEMS file to %s\n"%new_lems_file)

                if not args.norun:
                    results = pynml.run_lems_with_jneuroml(new_lems_file, nogui=True, load_saved_data=True, plot=False)

                    if not args.nogui:
                        v = "rampCellPop0[0]/v"

                        fig = pylab.figure()
                        fig.canvas.set_window_title("Time Course(s) of activation variables of %s from %s at %sdegC"%(channel_id, channel_file, args.temperature))

                        pylab.xlabel('Membrane potential (V)')
                        pylab.ylabel('Time Course - tau (s)')
                        pylab.grid('on')
                        for g in gates:
                            g_tau = "rampCellPop0[0]/test/%s/%s/tau"%(channel_id, g)
                            col=get_state_color(g)
                            pylab.plot(results[v], results[g_tau], color=col, linestyle='-', label="%s %s tau"%(channel_id, g))
                            pylab.gca().autoscale(enable=True, axis='x', tight=True)

                        pylab.legend()

                        if args.html:
                            pylab.savefig('html/%s.tau.png'%channel_id)

                        fig = pylab.figure()
                        fig.canvas.set_window_title("Steady state(s) of activation variables of %s from %s at %sdegC"%(channel_id, channel_file, args.temperature))
                        pylab.xlabel('Membrane potential (V)')
                        pylab.ylabel('Steady state - inf')
                        pylab.grid('on')
                        for g in gates:
                            g_inf = "rampCellPop0[0]/test/%s/%s/inf"%(channel_id, g)
                            #print("Plotting %s"%(g_inf))
                            col=get_state_color(g)
                            pylab.plot(results[v], results[g_inf], color=col, linestyle='-', label="%s %s inf"%(channel_id, g))
                            pylab.gca().autoscale(enable=True, axis='x', tight=True)
                        pylab.legend()

                        if args.html:
                            pylab.savefig('html/%s.inf.png'%channel_id)


        
    if not args.html:
        pylab.show()
    else:
        pp = pprint.PrettyPrinter(depth=4)
        pp.pprint(info)
        merged = merge_with_template(info, HTML_TEMPLATE_FILE)
        print(merged)
        new_html_file = "html/ChannelInfo.html"
        lf = open(new_html_file, 'w')
        lf.write(merged)
        lf.close()
        print('Written HTML info to: %s'%new_html_file)
Пример #51
0
def generate_and_run(simulation,
                     simulator,
                     network=None,
                     return_results=False,
                     base_dir=None,
                     target_dir=None,
                     num_processors=1):
    """
    Generates the network in the specified simulator and runs, if appropriate
    """

    if network == None:
        network = load_network_json(simulation.network)

    print_v("Generating network %s and running in simulator: %s..." %
            (network.id, simulator))

    if simulator == 'NEURON':

        _generate_neuron_files_from_neuroml(network,
                                            dir_for_mod_files=target_dir)

        from neuromllite.NeuronHandler import NeuronHandler

        nrn_handler = NeuronHandler()

        for c in network.cells:
            if c.neuroml2_source_file:
                src_dir = os.path.dirname(
                    os.path.abspath(c.neuroml2_source_file))
                nrn_handler.executeHoc('load_file("%s/%s.hoc")' %
                                       (src_dir, c.id))

        generate_network(network, nrn_handler, generate_network, base_dir)
        if return_results:
            raise NotImplementedError(
                "Reloading results not supported in Neuron yet...")

    elif simulator.lower() == 'sonata':  # Will not "run" obviously...

        from neuromllite.SonataHandler import SonataHandler

        sonata_handler = SonataHandler()

        generate_network(network,
                         sonata_handler,
                         always_include_props=True,
                         base_dir=base_dir)

        print_v("Done with Sonata...")

    elif simulator.lower().startswith('graph'):  # Will not "run" obviously...

        from neuromllite.GraphVizHandler import GraphVizHandler, engines

        try:
            if simulator[-1].isalpha():
                engine = engines[simulator[-1]]
                level = int(simulator[5:-1])
            else:
                engine = 'dot'
                level = int(simulator[5:])

        except Exception as e:
            print_v("Error parsing: %s: %s" % (simulator, e))
            print_v(
                "Graphs of the network structure can be generated at many levels of detail (1-6, required) and laid out using GraphViz engines (d - dot (default); c - circo; n - neato; f - fdp), so use: -graph3c, -graph2, -graph4f etc."
            )
            return

        handler = GraphVizHandler(level, engine=engine, nl_network=network)

        generate_network(network,
                         handler,
                         always_include_props=True,
                         base_dir=base_dir)

        print_v("Done with GraphViz...")

    elif simulator.lower().startswith('matrix'):  # Will not "run" obviously...

        from neuromllite.MatrixHandler import MatrixHandler

        try:
            level = int(simulator[6:])
        except:
            print_v("Error parsing: %s" % simulator)
            print_v(
                "Matrices of the network structure can be generated at many levels of detail (1-n, required), so use: -matrix1, -matrix2, etc."
            )
            return

        handler = MatrixHandler(level, nl_network=network)

        generate_network(network,
                         handler,
                         always_include_props=True,
                         base_dir=base_dir)

        print_v("Done with MatrixHandler...")

    elif simulator.startswith('PyNN'):

        #_generate_neuron_files_from_neuroml(network)
        simulator_name = simulator.split('_')[1].lower()

        from neuromllite.PyNNHandler import PyNNHandler

        pynn_handler = PyNNHandler(simulator_name, simulation.dt, network.id)

        syn_cell_params = {}
        for proj in network.projections:

            synapse = network.get_child(proj.synapse, 'synapses')
            post_pop = network.get_child(proj.postsynaptic, 'populations')

            if not post_pop.component in syn_cell_params:
                syn_cell_params[post_pop.component] = {}
            for p in synapse.parameters:
                post = ''
                if synapse.pynn_receptor_type == "excitatory":
                    post = '_E'
                elif synapse.pynn_receptor_type == "inhibitory":
                    post = '_I'
                syn_cell_params[post_pop.component][
                    '%s%s' % (p, post)] = synapse.parameters[p]

        cells = {}
        for c in network.cells:
            if c.pynn_cell:
                cell_params = {}
                if c.parameters:
                    for p in c.parameters:
                        cell_params[p] = evaluate(c.parameters[p],
                                                  network.parameters)

                dont_set_here = [
                    'tau_syn_E', 'e_rev_E', 'tau_syn_I', 'e_rev_I'
                ]
                for d in dont_set_here:
                    if d in c.parameters:
                        raise Exception(
                            'Synaptic parameters like %s should be set ' +
                            'in individual synapses, not in the list of parameters associated with the cell'
                            % d)
                if c.id in syn_cell_params:
                    cell_params.update(syn_cell_params[c.id])
                print_v("Creating cell with params: %s" % cell_params)
                exec('cells["%s"] = pynn_handler.sim.%s(**cell_params)' %
                     (c.id, c.pynn_cell))

                if c.pynn_cell != 'SpikeSourcePoisson':
                    exec(
                        "cells['%s'].default_initial_values['v'] = cells['%s'].parameter_space['v_rest'].base_value"
                        % (c.id, c.id))

        pynn_handler.set_cells(cells)

        receptor_types = {}
        for s in network.synapses:
            if s.pynn_receptor_type:
                receptor_types[s.id] = s.pynn_receptor_type

        pynn_handler.set_receptor_types(receptor_types)

        for input_source in network.input_sources:
            if input_source.pynn_input:
                pynn_handler.add_input_source(input_source)

        generate_network(network,
                         pynn_handler,
                         always_include_props=True,
                         base_dir=base_dir)

        for pid in pynn_handler.populations:
            pop = pynn_handler.populations[pid]
            if 'all' in simulation.recordTraces or pop.label in simulation.recordTraces:
                if pop.can_record('v'):
                    pop.record('v')

        pynn_handler.sim.run(simulation.duration)
        pynn_handler.sim.end()

        traces = {}
        events = {}

        if not 'NeuroML' in simulator:
            from neo.io import PyNNTextIO

            for pid in pynn_handler.populations:
                pop = pynn_handler.populations[pid]

                if 'all' in simulation.recordTraces or pop.label in simulation.recordTraces:

                    filename = "%s.%s.v.dat" % (simulation.id, pop.label)
                    all_columns = []
                    print_v("Writing data for %s to %s" %
                            (pop.label, filename))
                    for i in range(len(pop)):
                        if pop.can_record('v'):
                            ref = '%s[%i]' % (pop.label, i)
                            traces[ref] = []
                            data = pop.get_data('v', gather=False)
                            for segment in data.segments:
                                vm = segment.analogsignals[0].transpose()[i]

                                if len(all_columns) == 0:
                                    tt = np.array([
                                        t * simulation.dt / 1000.
                                        for t in range(len(vm))
                                    ])
                                    all_columns.append(tt)
                                vm_si = [float(v / 1000.) for v in vm]
                                traces[ref] = vm_si
                                all_columns.append(vm_si)

                            times_vm = np.array(all_columns).transpose()

                    np.savetxt(filename, times_vm, delimiter='\t', fmt='%s')

        if return_results:
            _print_result_info(traces, events)
            return traces, events

    elif simulator == 'NetPyNE':

        if target_dir == None:
            target_dir = './'

        _generate_neuron_files_from_neuroml(network,
                                            dir_for_mod_files=target_dir)

        from netpyne import specs
        from netpyne import sim
        # Note NetPyNE from this branch is required: https://github.com/Neurosim-lab/netpyne/tree/neuroml_updates
        from netpyne.conversion.neuromlFormat import NetPyNEBuilder

        import pprint
        pp = pprint.PrettyPrinter(depth=6)

        netParams = specs.NetParams()
        simConfig = specs.SimConfig()
        netpyne_handler = NetPyNEBuilder(netParams,
                                         simConfig=simConfig,
                                         verbose=True)

        generate_network(network, netpyne_handler, base_dir=base_dir)

        netpyne_handler.finalise()

        simConfig = specs.SimConfig()
        simConfig.tstop = simulation.duration
        simConfig.duration = simulation.duration
        simConfig.dt = simulation.dt
        simConfig.seed = simulation.seed
        simConfig.recordStep = simulation.dt

        simConfig.recordCells = ['all']
        simConfig.recordTraces = {}

        for pop in netpyne_handler.popParams.values():
            if 'all' in simulation.recordTraces or pop.id in simulation.recordTraces:
                for i in pop['cellsList']:
                    id = pop['pop']
                    index = i['cellLabel']
                    simConfig.recordTraces['v_%s_%s' % (id, index)] = {
                        'sec': 'soma',
                        'loc': 0.5,
                        'var': 'v',
                        'conds': {
                            'pop': id,
                            'cellLabel': index
                        }
                    }

        simConfig.saveDat = True

        print_v("NetPyNE netParams: ")
        pp.pprint(netParams.todict())
        #print_v("NetPyNE simConfig: ")
        #pp.pprint(simConfig.todict())

        sim.initialize(
            netParams,
            simConfig)  # create network object and set cfg and net params

        sim.net.createPops()
        cells = sim.net.createCells(
        )  # instantiate network cells based on defined populations

        for proj_id in netpyne_handler.projection_infos.keys():
            projName, prePop, postPop, synapse, ptype = netpyne_handler.projection_infos[
                proj_id]
            print_v("Creating connections for %s (%s): %s->%s via %s" %
                    (projName, ptype, prePop, postPop, synapse))

            preComp = netpyne_handler.pop_ids_vs_components[prePop]

            for conn in netpyne_handler.connections[projName]:

                pre_id, pre_seg, pre_fract, post_id, post_seg, post_fract, delay, weight = conn

                #connParam = {'delay':delay,'weight':weight,'synsPerConn':1, 'sec':post_seg, 'loc':post_fract, 'threshold':threshold}
                connParam = {
                    'delay': delay,
                    'weight': weight,
                    'synsPerConn': 1,
                    'sec': post_seg,
                    'loc': post_fract
                }

                if ptype == 'electricalProjection':

                    if weight != 1:
                        raise Exception(
                            'Cannot yet support inputs where weight !=1!')
                    connParam = {
                        'synsPerConn': 1,
                        'sec': post_seg,
                        'loc': post_fract,
                        'gapJunction': True,
                        'weight': weight
                    }
                else:
                    connParam = {
                        'delay': delay,
                        'weight': weight,
                        'synsPerConn': 1,
                        'sec': post_seg,
                        'loc': post_fract
                    }
                    #'threshold': threshold}

                connParam['synMech'] = synapse

                if post_id in sim.net.gid2lid:  # check if postsyn is in this node's list of gids
                    sim.net._addCellConn(connParam, pre_id, post_id)

        stims = sim.net.addStims(
        )  # add external stimulation to cells (IClamps etc)
        simData = sim.setupRecording(
        )  # setup variables to record for each cell (spikes, V traces, etc)
        sim.runSim()  # run parallel Neuron simulation
        sim.gatherData()  # gather spiking data and cell info from each node
        sim.saveData(
        )  # save params, cell info and sim output to file (pickle,mat,txt,etc)

        if return_results:
            raise NotImplementedError(
                "Reloading results not supported in NetPyNE yet...")

    elif simulator == 'jNeuroML' or simulator == 'jNeuroML_NEURON' or simulator == 'jNeuroML_NetPyNE':

        from pyneuroml.lems import generate_lems_file_for_neuroml
        from pyneuroml import pynml

        lems_file_name = 'LEMS_%s.xml' % simulation.id

        nml_file_name, nml_doc = generate_neuroml2_from_network(
            network, base_dir=base_dir, target_dir=target_dir)
        included_files = ['PyNN.xml']

        for c in network.cells:
            if c.lems_source_file:
                included_files.append(c.lems_source_file)
        '''
        if network.cells:
            for c in network.cells:
                included_files.append(c.neuroml2_source_file)
        '''
        if network.synapses:
            for s in network.synapses:
                if s.lems_source_file:
                    included_files.append(s.lems_source_file)

        print_v("Generating LEMS file prior to running in %s" % simulator)

        pops_plot_save = []
        pops_spike_save = []
        gen_plots_for_quantities = {}
        gen_saves_for_quantities = {}

        for p in network.populations:

            if simulation.recordTraces and ('all' in simulation.recordTraces or
                                            p.id in simulation.recordTraces):
                pops_plot_save.append(p.id)

            if simulation.recordSpikes and ('all' in simulation.recordSpikes or
                                            p.id in simulation.recordSpikes):
                pops_spike_save.append(p.id)

            if simulation.recordRates and ('all' in simulation.recordRates
                                           or p.id in simulation.recordRates):
                size = evaluate(p.size, network.parameters)
                for i in range(size):
                    quantity = '%s/%i/%s/r' % (p.id, i, p.component)
                    gen_plots_for_quantities['%s_%i_r' %
                                             (p.id, i)] = [quantity]
                    gen_saves_for_quantities['%s_%i.r.dat' %
                                             (p.id, i)] = [quantity]

            if simulation.recordVariables:
                for var in simulation.recordVariables:
                    to_rec = simulation.recordVariables[var]
                    if ('all' in to_rec or p.id in to_rec):
                        size = evaluate(p.size, network.parameters)
                        for i in range(size):
                            quantity = '%s/%i/%s/%s' % (p.id, i, p.component,
                                                        var)
                            gen_plots_for_quantities['%s_%i_%s' %
                                                     (p.id, i, var)] = [
                                                         quantity
                                                     ]
                            gen_saves_for_quantities['%s_%i.%s.dat' %
                                                     (p.id, i, var)] = [
                                                         quantity
                                                     ]

        generate_lems_file_for_neuroml(
            simulation.id,
            nml_file_name,
            network.id,
            simulation.duration,
            simulation.dt,
            lems_file_name,
            target_dir=target_dir if target_dir else '.',
            nml_doc=
            nml_doc,  # Use this if the nml doc has already been loaded (to avoid delay in reload)
            include_extra_files=included_files,
            gen_plots_for_all_v=False,
            plot_all_segments=False,
            gen_plots_for_quantities=
            gen_plots_for_quantities,  # Dict with displays vs lists of quantity paths
            gen_plots_for_only_populations=
            pops_plot_save,  # List of populations, all pops if = []
            gen_saves_for_all_v=False,
            save_all_segments=False,
            gen_saves_for_only_populations=
            pops_plot_save,  # List of populations, all pops if = []
            gen_saves_for_quantities=
            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=
            pops_spike_save,  # 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,
            lems_file_generate_seed=12345,
            report_file_name='report.%s.txt' % simulation.id,
            simulation_seed=simulation.seed if simulation.seed else 12345,
            verbose=True)

        lems_file_name = _locate_file(lems_file_name, target_dir)

        if simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(
                lems_file_name,
                nogui=True,
                load_saved_data=return_results,
                reload_events=return_results)
        elif simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(
                lems_file_name,
                nogui=True,
                load_saved_data=return_results,
                reload_events=return_results)
        elif simulator == 'jNeuroML_NetPyNE':
            results = pynml.run_lems_with_jneuroml_netpyne(
                lems_file_name,
                nogui=True,
                verbose=True,
                load_saved_data=return_results,
                reload_events=return_results,
                num_processors=num_processors)

        print_v("Finished running LEMS file %s in %s (returning results: %s)" %
                (lems_file_name, simulator, return_results))

        if return_results:
            traces, events = results
            _print_result_info(traces, events)
            return results  # traces, events =
def analyse_cell(dataset_id, type, nogui = False):
    
    
    reference = '%s_%s'%(type,dataset_id)
    cell_file = '%s.cell.nml'%(reference)
    
    images = 'summary/%s_%s.png'
    
    generate_current_vs_frequency_curve(cell_file, 
                                        reference, 
                                        simulator = 'jNeuroML_NEURON',
                                        start_amp_nA =         -0.1, 
                                        end_amp_nA =           0.4, 
                                        step_nA =              0.01, 
                                        analysis_duration =    1000, 
                                        analysis_delay =       50,
                                        plot_voltage_traces =  False,
                                        plot_if =              not nogui,
                                        plot_iv =              not nogui, 
                                        xlim_if =              [-200, 400],
                                        ylim_if =              [-10, 120],
                                        xlim_iv =              [-200, 400],
                                        ylim_iv =              [-120, -40],
                                        save_if_figure_to=images%(reference, 'if'), 
                                        save_iv_figure_to=images%(reference, 'iv'),
                                        show_plot_already = False)
               
    temp_dir = 'temp/'
    
    shutil.copy(cell_file, temp_dir)
    
    net_file = generate_network_for_sweeps(type, dataset_id, '%s.cell.nml'%(reference), reference, temp_dir)
    
    lems_file_name = 'LEMS_Test_%s_%s.xml'%(type,dataset_id)
    
    generate_lems_file_for_neuroml('Test_%s_%s'%(dataset_id,type),
                                   net_file,
                                   'network_%s_%s'%(dataset_id,type), 
                                   1500, 
                                   0.01, 
                                   lems_file_name,
                                   temp_dir,
                                   gen_plots_for_all_v=False,
                                   copy_neuroml = False)
    
    simulator = "jNeuroML_NEURON"
    
    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(temp_dir+lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(temp_dir+lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False)
                                                
    x = []
    y = []
    
    print results.keys()
    
    tt = [t*1000 for t in results['t']]
    for i in range(len(results)-1):
        x.append(tt)
        y.append([v*1000 for v in results['Pop0/%i/%s_%s/v'%(i,type,dataset_id)]])
        
    pynml.generate_plot(x,
                y, 
                "Cell: %s"%dataset_id, 
                xaxis = "Time (ms)", 
                yaxis = "Membrane potential (mV)",
                show_plot_already=False,
                ylim = [-120, 60],
                save_figure_to = images%(reference, 'traces'))
def analyse_spiketime_vs_dx(lems_path_dict, 
                            simulator,
                            cell_v_path,
                            verbose=False,
                            spike_threshold_mV = 0,
                            show_plot_already=True,
                            save_figure_to=None,
                            num_of_last_spikes=None):
                                
    from pyelectro.analysis import max_min
    
    all_results = {}
    comp_values=[]
    for num_of_comps in lems_path_dict.keys():
        comp_values.append(int(num_of_comps))
        if verbose:
            print_comment_v(" == Generating simulation for electrotonic length = %s"%(dx))
                                   
        if simulator == 'jNeuroML':
             results = pynml.run_lems_with_jneuroml(lems_path_dict[num_of_comps], nogui=True, load_saved_data=True, plot=False, verbose=verbose)
        if simulator == 'jNeuroML_NEURON':
             results = pynml.run_lems_with_jneuroml_neuron(lems_path_dict[num_of_comps], nogui=True, load_saved_data=True, plot=False, verbose=verbose)
             
        print("Results reloaded: %s"%results.keys())
             
        all_results[int(num_of_comps)] = results
        
    xs = []
    ys = []
    labels = []
    
    spxs = []
    spys = []
    linestyles = []
    markers = []
    colors=[]
    spike_times_final=[]
    array_of_num_of_spikes=[]
    
    comp_values=list(np.sort(comp_values))
    
    for num_of_comps in comp_values:
        t = all_results[num_of_comps]['t']
        v = all_results[num_of_comps][cell_v_path]
        xs.append(t)
        ys.append(v)
        labels.append(num_of_comps)
        
        mm = max_min(v, t, delta=0, peak_threshold=spike_threshold_mV)
        
        spike_times = mm['maxima_times']
        
        spike_times_final.append(spike_times)
        
        array_of_num_of_spikes.append(len(spike_times))
        
    max_num_of_spikes=max(array_of_num_of_spikes)
    
    max_comps_spikes=spike_times_final[-1]
    
    bound_comps=[comp_values[0],comp_values[-1]]
    
    if num_of_last_spikes == None:
    
       num_of_spikes=len(max_comps_spikes)
       
    else:
       
       if len(max_comps_spikes) >=num_of_last_spikes:
       
          num_of_spikes=num_of_last_spikes
          
       else:
       
          num_of_spikes=len(max_comps_spikes)
          
    spike_indices=[(-1)*ind for ind in range(1,num_of_spikes+1) ]
    
    if len(max_comps_spikes) > abs(spike_indices[-1]):
    
       earliest_spike_time=max_comps_spikes[spike_indices[-1]-1]
       
    else:
     
       earliest_spike_time=max_comps_spikes[spike_indices[-1]]
       
    for spike_ind in range(0,max_num_of_spikes):
   
        spike_time_values=[]
        
        compartments=[]
        
        for comp_value in range(0,len(comp_values)):
        
            if spike_times_final[comp_value] !=[]:
           
              if len(spike_times_final[comp_value]) >= spike_ind+1 :
              
                 if spike_times_final[comp_value][spike_ind] >= earliest_spike_time:
             
                    spike_time_values.append(spike_times_final[comp_value][spike_ind])
               
                    compartments.append(comp_values[comp_value])       
        
        linestyles.append('')
               
        markers.append('o')
       
        colors.append('b')
       
        spxs.append(compartments)
       
        spys.append(spike_time_values)
    
    for last_spike_index in spike_indices:
       
        vertical_line=[max_comps_spikes[last_spike_index],max_comps_spikes[last_spike_index] ]
          
        spxs.append(bound_comps)
          
        spys.append(vertical_line)
          
        linestyles.append('--')
          
        markers.append('')
       
        colors.append('k')
             
    pynml.generate_plot(spxs, 
          spys, 
          "Spike times vs spatial discretization",
          colors=colors,
          linestyles = linestyles,
          markers = markers,
          xaxis = 'Number of internal divisions',
          yaxis = 'Spike times (s)',
          show_plot_already=show_plot_already,
          save_figure_to=save_figure_to)       
    
    if verbose:
        pynml.generate_plot(xs, 
                  ys, 
                  "Membrane potentials in %s for %s"%(simulator,dts),
                  labels = labels,
                  show_plot_already=show_plot_already,
                  save_figure_to=save_figure_to)      
Пример #54
0
def generate_lems(glif_dir, curr_pA, show_plot=True):

    os.chdir(glif_dir)

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

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

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

    template_cell = '''<Lems>

      <%s %s/>

    </Lems>
    '''

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

    cell_id = 'GLIF_%s' % glif_dir

    attributes = ""

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

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

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

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

    file_contents = template_cell % (type, attributes)

    print(file_contents)

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

    import opencortex.build as oc

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### Original model

%(name)s

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

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

#### Original traces:

**Membrane potential**

Current injection of %(curr)s pA

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

**Threshold**

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

### Conversion to NeuroML 2

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

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

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

    jnml LEMS_Test_%(id)s.xml

#### Comparison:

**Membrane potential**

Current injection of %(curr)s pA

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

**Threshold**

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

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

    os.chdir('..')

    return model_metadata, neuron_config, ephys_sweeps