Ejemplo n.º 1
0
def main():
    """Main function

    Include the NeuroML model into a LEMS simulation file, run it, plot some
    data.
    """
    # Simulation bits
    sim_id = "olm_example_sim"
    simulation = LEMSSimulation(sim_id=sim_id,
                                duration=600,
                                dt=0.01,
                                simulation_seed=123)
    # Include the NeuroML model file
    simulation.include_neuroml2_file(create_olm_network())
    # Assign target for the simulation
    simulation.assign_simulation_target("single_olm_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_v_Seg0_soma_0",
                                         quantity="pop0/0/olm/0/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg1_soma_0",
                                         quantity="pop0/0/olm/1/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg0_axon_0",
                                         quantity="pop0/0/olm/2/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg1_axon_0",
                                         quantity="pop0/0/olm/3/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg0_dend_0",
                                         quantity="pop0/0/olm/4/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg1_dend_0",
                                         quantity="pop0/0/olm/6/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg0_dend_1",
                                         quantity="pop0/0/olm/5/v")
    simulation.add_column_to_output_file("output0",
                                         column_id="pop0_0_v_Seg1_dend_1",
                                         quantity="pop0/0/olm/7/v")
    # Save LEMS simulation to file
    sim_file = simulation.save_to_file()

    # Run the simulation using the NEURON simulator
    pynml.run_lems_with_jneuroml_neuron(sim_file,
                                        max_memory="2G",
                                        nogui=True,
                                        plot=False,
                                        skip_run=False)
    # Plot the data
    plot_data(sim_id)
Ejemplo n.º 2
0
def create_test_goc1():
    simid = 'sim_goc2Pools'
    ls = LEMSSimulation(simid, duration=1500, dt=0.025, target='network')

    #Load NeuroML components
    GoC_file_name = 'GoC.cell.nml'
    ls.include_neuroml2_file(GoC_file_name)

    of0 = 'Volts_file'
    ls.create_output_file(of0, "%s.v.dat" % simid)
    ls.add_column_to_output_file(of0, 'v', "Golgi[0]/v")

    eof0 = 'Events_file'
    ls.create_event_output_file(eof0, "%s.v.spikes" % simid, format='ID_TIME')
    ls.add_selection_to_event_output_file(eof0, '0', "Golgi[0]", "spike")

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

    #res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="1G", compile_mods =False, nogui=True, plot=False)
    res = pynml.run_lems_with_jneuroml_neuron(lems_simfile,
                                              max_memory="2G",
                                              nogui=True,
                                              plot=False)

    return res
Ejemplo n.º 3
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
Ejemplo n.º 4
0
def create_test_goc1():
	simid = 'sim_goc1'
	ls = LEMSSimulation( simid, duration=150, dt=0.025, target='net1' )
	
	#Load NeuroML components
	GoC_file_name = 'test_channel.cell.nml'#'Golgi.cell.nml'#'test_channel.cell.nml' #'simple_cell.cell.nml'	#Cell_Golgi.cell.nml
	ls.include_neuroml2_file( GoC_file_name )
	
	disp0 = 'dispaly0'
	ls.create_display(disp0, "Voltage", "-90", "50" )
	ls.add_line_to_display(disp0, "v", "gocpop[0]/v", "1mV", "#ffffff")

	of0 = 'Volts_file'
	ls.create_output_file(of0, "%s.v.dat"%simid)
	ls.add_column_to_output_file(of0, 'v', "gocpop[0]/v")
	
	#of1 = 'Na_file'
	#ls.create_output_file(of1, "%s.na.dat"%simid)
	#ls.add_column_to_output_file(of1, '0', "gocpop[0]/ina")
	
	eof0 = 'Events_file'
	ls.create_event_output_file(eof0, "%s.v.spikes"%simid,format='ID_TIME')
	ls.add_selection_to_event_output_file(eof0, '0', "gocpop[0]", "spike")

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

	#res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="1G", compile_mods =False, nogui=True, plot=False)
	res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="1G", nogui=True, plot=False)
	#res=True
	return res
Ejemplo n.º 5
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]]
Ejemplo n.º 6
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
Ejemplo n.º 7
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]]
Ejemplo n.º 8
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]]
Ejemplo n.º 9
0
def main():

    ls, lems_file_name = generate_hippocampal_net(
        network_id="HippocampalNet",
        nrn_runname="TestRun",
        validate=True,
        generate_LEMS_simulation=True)
    import sys
    try:
        run_LEMS_simulation = sys.argv[1]
    except:
        run_LEMS_simulation = False

    if ls and run_LEMS_simulation:
        # run with jNeuroML_NEURON
        print(
            "*** Loading LEMS file: %s and running with jNeuroML_NEURON ***" %
            (lems_file_name))
        sim = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo n.º 12
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('..')
Ejemplo n.º 13
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))
Ejemplo n.º 14
0
def run(a=None,**kwargs): 
    
    try:
        import neuroml
        import pyneuroml
        import xlrd
    except Exception as e:
        print_("Cannot import one of the required packages. Please install!\n"
             "Exception: %s\n"%e)
    
    try:
        if os.environ.has_key('C302_HOME'):
            os.environ['C302_HOME']
            sys.path.append(os.environ['C302_HOME'])
            print_('Python path now: %s'%sys.path)
        import c302
        import c302_utils
    except Exception as e:
        print_("Cannot import c302!\n"
             "Exception: %s\n"%e
             +"Please set environment variable C302_HOME to point to the directory: CElegansNeuroML/CElegans/pythonScripts/c302!\n")
             
        exit()
        
    a = build_namespace(a,**kwargs)
    
    gen_start = time.time()
    
    ref = a.reference
    
    if not os.path.isdir('simulations'):
        os.mkdir('simulations')
    
    sim_ref = "%s_%s_%s"%(a.c302params,ref, time.ctime().replace(' ','_' ).replace(':','.' ))
    sim_dir = "simulations/%s"%(sim_ref)
    os.mkdir(sim_dir)
    
    #exec('from %s import ParameterisedModel'%a.c302params)
    #params = ParameterisedModel()
    
    id = '%s_%s'%(a.c302params,ref)
    
    
    exec('from c302_%s import setup'%ref)
    
    setup(a.c302params, 
          generate=True,
          duration = a.duration,
          dt = a.dt,
          target_directory=sim_dir)
    
             
    lems_file0 = '%s/LEMS_c302_%s.xml'%(sim_dir,id)
    lems_file = '%s/LEMS_c302.xml'%(sim_dir)
    print_("Renaming %s -> %s"%(lems_file0,lems_file))
    os.rename(lems_file0,lems_file)
    
    announce("Generating NEURON files from: %s..."%lems_file)
    
    pynml.run_lems_with_jneuroml_neuron(lems_file,
                                        only_generate_scripts=True,
                                        nogui=True, 
                                        load_saved_data=False, 
                                        verbose=True)
                                        
    main_nrn_py = open('%s/LEMS_c302_nrn.py'%(sim_dir),'r')
    updated =''
    for line in main_nrn_py:
        line = line.replace('GenericCell.hoc','%s/GenericCell.hoc'%sim_dir)
        line = line.replace('GenericNeuronCell.hoc','%s/GenericNeuronCell.hoc'%sim_dir)
        line = line.replace('GenericMuscleCell.hoc','%s/GenericMuscleCell.hoc'%sim_dir)
        line = line.replace("open('time.dat","open('%s/time.dat"%sim_dir)
        line = line.replace("open('c302_","open('%s/c302_"%sim_dir)
        updated += line
    main_nrn_py.close() 
    
    main_nrn_py = open('%s/LEMS_c302_nrn.py'%(sim_dir),'w')
    main_nrn_py.write(updated)
    main_nrn_py.close() 
    
    run_dir = '.'
    command = 'nrnivmodl %s'%sim_dir

    announce("Compiling NMODL files for NEURON...")
    pynml.execute_command_in_dir(command, run_dir, prefix="nrnivmodl: ")

    command = './Release/Sibernetic -c302 -f worm -no_g -l_to lpath=%s timelimit=%s timestep=%s'%(sim_dir,a.duration/1000.0,a.dt/1000)
    env={"PYTHONPATH":"./src:./%s"%sim_dir}
    
    sim_start = time.time()
    
    announce("Executing main Sibernetic simulation of %sms using: \n\n    %s \n\n  in %s with %s"%(a.duration, command, run_dir, env))
    #pynml.execute_command_in_dir('env', run_dir, prefix="Sibernetic: ",env=env,verbose=True)
    pynml.execute_command_in_dir(command, run_dir, prefix="Sibernetic: ",env=env,verbose=True)
    
    sim_end = time.time()
    
    reportj = {}
    
    reportj['duration'] = '%s ms'%a.duration
    reportj['dt'] = '%s ms'%a.dt
    reportj['sim_ref'] = sim_ref
    reportj['reference'] = a.reference
    reportj['c302params'] = a.c302params
    reportj['generation_time'] = '%s s'%(sim_start-gen_start)
    reportj['run_time'] = '%s s'%(sim_end-sim_start)
    reportj['command'] = '%s'%(command)
    
    
    report_file = open("%s/report.json"%sim_dir,'w')
    report_file.write(pp.pformat(reportj))
    report_file.close()
    
    announce("Generating images for neuronal activity...")
    
    results = pynml.reload_saved_data(lems_file, 
                      plot=False, 
                      show_plot_already=False, 
                      simulator=None, 
                      verbose=True)
                      
    c302_utils.plot_c302_results(results,
                                 config=a.reference, 
                                 parameter_set=a.c302params, 
                                 directory=sim_dir,
                                 save=True,
                                 show_plot_already=False)
                                 
    
    pos_file_name = os.path.abspath('%s/position_buffer.txt'%sim_dir)
    announce("Plotting positions of worm body particles in %s..."%pos_file_name)
    
    from plot_positions import plot_positions
    
    if not os.path.isfile(pos_file_name):
        time.sleep(2)
    
    plot_positions(pos_file_name,rate_to_plot = int(a.duration/5))
    
    announce("Finished in %s sec!\n\nSimulation saved in: %s\n\n"%((sim_end-sim_start),sim_dir) + \
             "Report of simulation at: %s/report.json\n\n"%(sim_dir)+ \
             "Rerun simulation with: ./Release/Sibernetic -l_from lpath=%s\n"%(sim_dir))
Ejemplo n.º 15
0
def create_GoC_network( duration, dt, seed, runid, run=False):

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

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

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

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

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


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

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

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

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

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

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

	if run:
		res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", nogui=True, plot=False)
	else:
		res = pynml.run_lems_with_jneuroml_neuron( lems_simfile, max_memory="2G", only_generate_scripts = True, compile_mods = False, nogui=True, plot=False)
	
	
	return res
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
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)
####################################################################
#   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():

        plt.xlabel('Time (ms)')
        plt.ylabel('...')
        plt.grid('on')
Ejemplo n.º 20
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)
def create_GoC_network(duration, dt, seed, runid, run=False):

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

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

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

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

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

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

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

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

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

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

    ### 2. Electrical coupling between GoCs

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

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

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

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

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

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

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

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

    return res
def create_GoC_network(duration=2000,
                       dt=0.025,
                       seed=123,
                       runid=0,
                       run=False,
                       minI=-75,
                       maxI=200,
                       iStep=25,
                       iDur=400,
                       iRest=500):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return res
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 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)     
Ejemplo n.º 25
0
def create_GoC_network(duration,
                       dt,
                       seed,
                       N_goc=0,
                       N_mf=15,
                       run=False,
                       prob_type='Boltzmann',
                       GJw_type='Vervaeke2010'):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ### Electrical coupling between GoCs

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

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

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

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

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

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

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

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

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

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

    return res
Ejemplo n.º 26
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()
####################################################################
#   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():

        plt.xlabel('Time (ms)')
        plt.ylabel('...')
        plt.grid('on')
Ejemplo n.º 28
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     
Ejemplo n.º 29
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
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()
Ejemplo n.º 31
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
Ejemplo n.º 32
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 =
Ejemplo n.º 33
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
Ejemplo n.º 34
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
Ejemplo n.º 35
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
Ejemplo n.º 36
0
def create_GoC_network(duration=2000, dt=0.025, seed=123, runid=0, run=False):

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

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

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

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

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

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

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

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

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

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

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

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

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

    return res
Ejemplo n.º 37
0
def run(a=None, **kwargs):

    try:
        import neuroml
        import pyneuroml
        import xlrd
    except Exception as e:
        print_("Cannot import one of the required packages. Please install!\n"
               "Exception: %s\n" % e)

    try:
        if os.environ.has_key('C302_HOME'):
            os.environ['C302_HOME']
            sys.path.append(os.environ['C302_HOME'])
            print_('Python path now: %s' % sys.path)
        import c302
        import c302_utils
    except Exception as e:
        print_(
            "Cannot import c302!\n"
            "Exception: %s\n" % e +
            "Please set environment variable C302_HOME to point to the directory: CElegansNeuroML/CElegans/pythonScripts/c302!\n"
        )

        exit()

    a = build_namespace(a, **kwargs)

    gen_start = time.time()

    ref = a.reference

    if not os.path.isdir('simulations'):
        os.mkdir('simulations')

    sim_ref = "%s_%s_%s" % (a.c302params, ref, time.ctime().replace(
        ' ', '_').replace(':', '.'))
    sim_dir = "simulations/%s" % (sim_ref)
    os.mkdir(sim_dir)

    #exec('from %s import ParameterisedModel'%a.c302params)
    #params = ParameterisedModel()

    id = '%s_%s' % (a.c302params, ref)

    exec('from c302_%s import setup' % ref)

    setup(a.c302params,
          generate=True,
          duration=a.duration,
          dt=a.dt,
          target_directory=sim_dir)

    lems_file0 = '%s/LEMS_c302_%s.xml' % (sim_dir, id)
    lems_file = '%s/LEMS_c302.xml' % (sim_dir)
    print_("Renaming %s -> %s" % (lems_file0, lems_file))
    os.rename(lems_file0, lems_file)

    announce("Generating NEURON files from: %s..." % lems_file)

    pynml.run_lems_with_jneuroml_neuron(lems_file,
                                        only_generate_scripts=True,
                                        nogui=True,
                                        load_saved_data=False,
                                        verbose=True)

    main_nrn_py = open('%s/LEMS_c302_nrn.py' % (sim_dir), 'r')
    updated = ''
    for line in main_nrn_py:
        line = line.replace('GenericCell.hoc', '%s/GenericCell.hoc' % sim_dir)
        line = line.replace('GenericNeuronCell.hoc',
                            '%s/GenericNeuronCell.hoc' % sim_dir)
        line = line.replace('GenericMuscleCell.hoc',
                            '%s/GenericMuscleCell.hoc' % sim_dir)
        line = line.replace("open('time.dat", "open('%s/time.dat" % sim_dir)
        line = line.replace("open('c302_", "open('%s/c302_" % sim_dir)
        updated += line
    main_nrn_py.close()

    main_nrn_py = open('%s/LEMS_c302_nrn.py' % (sim_dir), 'w')
    main_nrn_py.write(updated)
    main_nrn_py.close()

    run_dir = '.'
    command = 'nrnivmodl %s' % sim_dir

    announce("Compiling NMODL files for NEURON...")
    pynml.execute_command_in_dir(command, run_dir, prefix="nrnivmodl: ")

    command = './Release/Sibernetic -c302 -f worm -no_g -l_to lpath=%s timelimit=%s timestep=%s' % (
        sim_dir, a.duration / 1000.0, a.dt / 1000)
    env = {"PYTHONPATH": "./src:./%s" % sim_dir}

    sim_start = time.time()

    announce(
        "Executing main Sibernetic simulation of %sms using: \n\n    %s \n\n  in %s with %s"
        % (a.duration, command, run_dir, env))
    #pynml.execute_command_in_dir('env', run_dir, prefix="Sibernetic: ",env=env,verbose=True)
    pynml.execute_command_in_dir(command,
                                 run_dir,
                                 prefix="Sibernetic: ",
                                 env=env,
                                 verbose=True)

    sim_end = time.time()

    reportj = {}

    reportj['duration'] = '%s ms' % a.duration
    reportj['dt'] = '%s ms' % a.dt
    reportj['sim_ref'] = sim_ref
    reportj['reference'] = a.reference
    reportj['c302params'] = a.c302params
    reportj['generation_time'] = '%s s' % (sim_start - gen_start)
    reportj['run_time'] = '%s s' % (sim_end - sim_start)
    reportj['command'] = '%s' % (command)

    report_file = open("%s/report.json" % sim_dir, 'w')
    report_file.write(pp.pformat(reportj))
    report_file.close()

    announce("Generating images for neuronal activity...")

    results = pynml.reload_saved_data(lems_file,
                                      plot=False,
                                      show_plot_already=False,
                                      simulator=None,
                                      verbose=True)

    c302_utils.plot_c302_results(results,
                                 config=a.reference,
                                 parameter_set=a.c302params,
                                 directory=sim_dir,
                                 save=True,
                                 show_plot_already=False)

    pos_file_name = os.path.abspath('%s/position_buffer.txt' % sim_dir)
    announce("Plotting positions of worm body particles in %s..." %
             pos_file_name)

    from plot_positions import plot_positions

    if not os.path.isfile(pos_file_name):
        time.sleep(2)

    plot_positions(pos_file_name, rate_to_plot=int(a.duration / 5))

    announce("Finished in %s sec!\n\nSimulation saved in: %s\n\n"%((sim_end-sim_start),sim_dir) + \
             "Report of simulation at: %s/report.json\n\n"%(sim_dir)+ \
             "Rerun simulation with: ./Release/Sibernetic -l_from lpath=%s\n"%(sim_dir))
Ejemplo n.º 38
0
        lems_file_name = ''

    return ls, lems_file_name


if __name__ == '__main__':

    generate_LEMS_simulation = True
    save_plots = True

    numCells_bc = 100
    duration = 500  # [ms]
    ls, lems_file_name = generate_WB_network('wb1', 'wbsNet', numCells_bc, 1,
                                             1, 0.1, generate_LEMS_simulation,
                                             duration)

    if generate_LEMS_simulation:

        # run with jNeuroML_NEURON
        print 'Loading LEMS file: %s and running with jNeuroML_NEURON' % (
            lems_file_name)
        sim = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True)

    if save_plots:

        raster_plot('wangbuzsaki_network_spikes.dat', duration, numCells_bc)
        print 'Raster plot saved'

        voltage_plots('wangbuzsaki_network.dat', [15, 83])
        print 'Voltage plot saved'
Ejemplo n.º 39
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
Ejemplo n.º 40
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()
Ejemplo n.º 41
0
if __name__ == '__main__':
    
    generate_LEMS_simulation = True
    save_plots = True
    
    numCells_bc = 100
    duration = 500  # [ms]
    ls, lems_file_name = generate_WB_network('wb1', 'wbsNet', numCells_bc, 1, 1, 0.1, generate_LEMS_simulation, duration)


    if generate_LEMS_simulation:
        
        # run with jNeuroML_NEURON
        print 'Loading LEMS file: %s and running with jNeuroML_NEURON'%(lems_file_name)
        sim = pynml.run_lems_with_jneuroml_neuron(lems_file_name, nogui=True)

    if save_plots:
        
        raster_plot('wangbuzsaki_network_spikes.dat', duration, numCells_bc)
        print 'Raster plot saved'
        
        voltage_plots('wangbuzsaki_network.dat', [15, 83])
        print 'Voltage plot saved'
        
        
        
        

  
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'))
Ejemplo n.º 43
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     
Ejemplo n.º 44
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]
            ]
Ejemplo n.º 45
0
def _generate_neuron_files_from_neuroml(network,
                                        verbose=False,
                                        dir_for_mod_files=None):
    """
    Generate NEURON hoc/mod files from the NeuroML files which are marked as 
    included in the NeuroMLlite description; also compiles the mod files
    """

    print_v(
        "-------------   Generating NEURON files from NeuroML for %s (default dir: %s)..."
        % (network.id, dir_for_mod_files))
    nml_src_files = []

    from neuroml import NeuroMLDocument
    import neuroml.writers as writers
    temp_nml_doc = NeuroMLDocument(id="temp")

    dirs_for_mod_files = []
    if dir_for_mod_files != None:
        dirs_for_mod_files.append(os.path.abspath(dir_for_mod_files))

    for c in network.cells:
        if c.neuroml2_source_file:
            nml_src_files.append(c.neuroml2_source_file)
            dir_for_mod = os.path.dirname(
                os.path.abspath(c.neuroml2_source_file))
            if not dir_for_mod in dirs_for_mod_files:
                dirs_for_mod_files.append(dir_for_mod)

    for s in network.synapses:
        if s.neuroml2_source_file:
            nml_src_files.append(s.neuroml2_source_file)
            dir_for_mod = os.path.dirname(
                os.path.abspath(s.neuroml2_source_file))
            if not dir_for_mod in dirs_for_mod_files:
                dirs_for_mod_files.append(dir_for_mod)

    for i in network.input_sources:
        if i.neuroml2_source_file:
            nml_src_files.append(i.neuroml2_source_file)
            dir_for_mod = os.path.dirname(
                os.path.abspath(i.neuroml2_source_file))
            if not dir_for_mod in dirs_for_mod_files:
                dirs_for_mod_files.append(dir_for_mod)

    temp_nml_doc = _extract_pynn_components_to_neuroml(network)

    summary = temp_nml_doc.summary()

    if 'IF_' in summary:
        import tempfile
        temp_nml_file = tempfile.NamedTemporaryFile(delete=False,
                                                    suffix='.nml',
                                                    dir=dir_for_mod_files)
        print_v("Writing temporary NML file to: %s, summary: " %
                temp_nml_file.name)
        print_v(summary)

        writers.NeuroMLWriter.write(temp_nml_doc, temp_nml_file.name)
        nml_src_files.append(temp_nml_file.name)

    for f in nml_src_files:
        from pyneuroml import pynml
        print_v("Generating/compiling hoc/mod files for: %s" % f)
        pynml.run_lems_with_jneuroml_neuron(f,
                                            nogui=True,
                                            only_generate_scripts=True,
                                            compile_mods=True,
                                            verbose=False)

    for dir_for_mod_files in dirs_for_mod_files:
        if not dir_for_mod_files in locations_mods_loaded_from:
            print_v(
                "Generated NEURON code; loading mechanisms from %s (cwd: %s; already loaded: %s)"
                % (dir_for_mod_files, os.getcwd(), locations_mods_loaded_from))
            try:

                from neuron import load_mechanisms
                if os.getcwd() == dir_for_mod_files:
                    print_v(
                        "That's current dir => importing neuron module loads mods here..."
                    )
                else:
                    load_mechanisms(dir_for_mod_files)
                locations_mods_loaded_from.append(dir_for_mod_files)
            except:
                print_v("Failed to load mod file mechanisms...")
        else:
            print_v("Already loaded mechanisms from %s (all loaded: %s)" %
                    (dir_for_mod_files, locations_mods_loaded_from))
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)
Ejemplo n.º 47
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
Ejemplo n.º 48
0
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)