Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
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
def run_optimisation(prefix,
                     config,
                     level,
                     parameters,
                     max_constraints,
                     min_constraints,
                     weights,
                     target_data,
                     sim_time=500,
                     dt=0.05,
                     analysis_start_time=0,
                     population_size=20,
                     max_evaluations=20,
                     num_selected=10,
                     num_offspring=20,
                     mutation_rate=0.9,
                     num_elites=1,
                     seed=12345,
                     simulator='jNeuroML',
                     nogui=False,
                     num_local_procesors_to_use=4):

    print("Running optimisation...")
    print("parameters: %s" % parameters)
    print("max_constraints: %s" % max_constraints)
    print("min_constraints: %s" % min_constraints)
    print("simulator: %s" % simulator)
    ref = prefix + config

    run_dir = "NT_%s_%s" % (ref, time.ctime().replace(' ', '_').replace(
        ':', '.'))
    os.mkdir(run_dir)

    my_controller = C302Controller(
        ref,
        level,
        config,
        sim_time,
        dt,
        simulator=simulator,
        generate_dir=run_dir,
        num_local_procesors_to_use=num_local_procesors_to_use)

    peak_threshold = -31 if level.startswith('A') or level.startswith(
        'B') else (-40)

    analysis_var = {
        'peak_delta': 0,
        'baseline': 0,
        'dvdt_threshold': 0,
        'peak_threshold': peak_threshold
    }

    data = ref + '.dat'

    sim_var = OrderedDict()
    for i in range(len(parameters)):
        sim_var[
            parameters[i]] = max_constraints[i] / 2 + min_constraints[i] / 2

    #make an evaluator, using automatic target evaluation:
    my_evaluator = c302Evaluators.EnhancedNetworkEvaluator(
        controller=my_controller,
        analysis_start_time=analysis_start_time,
        analysis_end_time=sim_time,
        parameters=parameters,
        analysis_var=analysis_var,
        weights=weights,
        targets=target_data)

    #make an optimizer
    my_optimizer = optimizers.CustomOptimizerA(max_constraints,
                                               min_constraints,
                                               my_evaluator,
                                               population_size=population_size,
                                               max_evaluations=max_evaluations,
                                               num_selected=num_selected,
                                               num_offspring=num_offspring,
                                               num_elites=num_elites,
                                               mutation_rate=mutation_rate,
                                               seeds=None,
                                               verbose=False)

    start = time.time()
    #run the optimizer
    best_candidate, fitness = my_optimizer.optimize(do_plot=False,
                                                    seed=seed,
                                                    summary_dir=run_dir)

    secs = time.time() - start

    reportj = {}
    info = "Ran %s evaluations (pop: %s) in %f seconds (%f mins total; %fs per eval)\n\n" % (
        max_evaluations, population_size, secs, secs / 60.0,
        (secs / max_evaluations))
    report = "----------------------------------------------------\n\n" + info

    reportj['comment'] = info
    reportj['time'] = secs

    for key, value in zip(parameters, best_candidate):
        sim_var[key] = value

    best_candidate_t, best_candidate_v = my_controller.run_individual(
        sim_var, show=False)

    best_candidate_results = my_controller.last_results

    best_candidate_analysis = c302Analysis.Data_Analyser(
        best_candidate_v,
        best_candidate_t,
        analysis_var,
        start_analysis=analysis_start_time,
        end_analysis=sim_time)

    best_cand_analysis_full = best_candidate_analysis.analyse()
    best_cand_analysis = best_candidate_analysis.analyse(target_data)

    report += "---------- Best candidate ------------------------------------------\n"

    report += pp.pformat(best_candidate) + "\n\n"
    report += pp.pformat(best_cand_analysis_full) + "\n"
    report += pp.pformat(best_cand_analysis) + "\n\n"
    report += "FITNESS: %f\n\n" % fitness

    print(report)

    reportj['fitness'] = fitness
    reportj['fittest vars'] = dict(sim_var)
    reportj['best_cand_details'] = best_candidate
    reportj['best_cand_analysis_full'] = best_cand_analysis_full
    reportj['best_cand_analysis'] = best_cand_analysis
    reportj['parameters'] = parameters
    reportj['analysis_var'] = analysis_var
    reportj['target_data'] = target_data
    reportj['weights'] = weights

    reportj['analysis_start_time'] = analysis_start_time

    reportj['population_size'] = population_size
    reportj['max_evaluations'] = max_evaluations
    reportj['num_selected'] = num_selected
    reportj['num_offspring'] = num_offspring
    reportj['mutation_rate'] = mutation_rate
    reportj['num_elites'] = num_elites
    reportj['seed'] = seed
    reportj['simulator'] = simulator

    reportj['sim_time'] = sim_time
    reportj['dt'] = dt

    reportj['run_directory'] = run_dir
    reportj['reference'] = ref

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

    plot_file = open("%s/plotgens.py" % run_dir, 'w')
    plot_file.write(
        'from neurotune.utils import plot_generation_evolution\nimport os\n')
    plot_file.write('\n')
    plot_file.write('parameters = %s\n' % parameters)
    plot_file.write('\n')
    plot_file.write(
        "curr_dir = os.path.dirname(__file__) if len(os.path.dirname(__file__))>0 else '.'\n"
    )
    plot_file.write(
        "plot_generation_evolution(parameters, individuals_file_name = '%s/ga_individuals.csv'%curr_dir)\n"
    )
    plot_file.close()

    if not nogui:
        added = []
        for wref in weights.keys():
            ref = wref.split(':')[0]
            if not ref in added and not "phase_offset" in ref:
                added.append(ref)
                best_candidate_plot = plt.plot(best_candidate_t,
                                               best_candidate_v[ref],
                                               label="%s - %i evaluations" %
                                               (ref, max_evaluations))

        plt.legend()

        plt.ylim(-80.0, 80.0)
        plt.xlim(0.0, sim_time)
        plt.title("Models")
        plt.xlabel("Time (ms)")
        plt.ylabel("Membrane potential(mV)")

        utils.plot_generation_evolution(
            sim_var.keys(),
            individuals_file_name='%s/ga_individuals.csv' % run_dir)

        c302_utils.plot_c302_results(best_candidate_results,
                                     config,
                                     level,
                                     directory=run_dir,
                                     save=True)
Ejemplo n.º 7
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.º 8
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.º 9
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.º 10
0
def run_optimisation(prefix,
                     config,
                     level,
                     parameters,
                     max_constraints,
                     min_constraints,
                     weights,
                     target_data,
                     sim_time =            500,
                     dt =                  0.05,
                     analysis_start_time = 0,
                     population_size =     20,
                     max_evaluations =     20,
                     num_selected =        10,
                     num_offspring =       20,
                     mutation_rate =       0.9,
                     num_elites =          1,
                     seed =                12345,
                     simulator =           'jNeuroML',
                     nogui =               False,
                     num_local_procesors_to_use = 4):  
                         
    print("Running optimisation...")
    print("parameters: %s"%parameters)
    print("max_constraints: %s"%max_constraints)
    print("min_constraints: %s"%min_constraints)
    print("simulator: %s"%simulator)
    ref = prefix+config
    
    run_dir = "NT_%s_%s"%(ref, time.ctime().replace(' ','_' ).replace(':','.' ))
    os.mkdir(run_dir)

    my_controller = C302Controller(ref, 
                                   level, 
                                   config, 
                                   sim_time, 
                                   dt, 
                                   simulator = simulator, 
                                   generate_dir=run_dir,
                                   num_local_procesors_to_use = num_local_procesors_to_use)

    peak_threshold = -31 if level.startswith('A') or level.startswith('B') else (-20)

    analysis_var = {'peak_delta':     0,
                    'baseline':       0,
                    'dvdt_threshold': 0, 
                    'peak_threshold': peak_threshold}

    data = ref+'.dat'

    sim_var = OrderedDict()
    for i in range(len(parameters)):
        sim_var[parameters[i]] = max_constraints[i]/2 + min_constraints[i]/2



    #make an evaluator, using automatic target evaluation:
    my_evaluator = c302Evaluators.EnhancedNetworkEvaluator(controller=my_controller,
                                                analysis_start_time=analysis_start_time,
                                                analysis_end_time=sim_time,
                                                parameters=parameters,
                                                analysis_var=analysis_var,
                                                weights=weights,
                                                targets=target_data)


    #make an optimizer
    my_optimizer = optimizers.CustomOptimizerA(max_constraints,
                                             min_constraints,
                                             my_evaluator,
                                             population_size=population_size,
                                             max_evaluations=max_evaluations,
                                             num_selected=num_selected,
                                             num_offspring=num_offspring,
                                             num_elites=num_elites,
                                             mutation_rate=mutation_rate,
                                             seeds=None,
                                             verbose=False)

    start = time.time()
    #run the optimizer
    best_candidate, fitness = my_optimizer.optimize(do_plot=False, 
                                                    seed=seed,
                                                    summary_dir = run_dir)

    secs = time.time()-start
    
    reportj = {}
    info = "Ran %s evaluations (pop: %s) in %f seconds (%f mins total; %fs per eval)\n\n"%(max_evaluations, population_size, secs, secs/60.0, (secs/max_evaluations))
    report = "----------------------------------------------------\n\n"+ info
             
             
    reportj['comment'] = info
    reportj['time'] = secs

    for key,value in zip(parameters,best_candidate):
        sim_var[key]=value


    best_candidate_t, best_candidate_v = my_controller.run_individual(sim_var,show=False)
    
    best_candidate_results = my_controller.last_results

    best_candidate_analysis = c302Analysis.Data_Analyser(best_candidate_v,
                                               best_candidate_t,
                                               analysis_var,
                                               start_analysis=analysis_start_time,
                                               end_analysis=sim_time)

    best_cand_analysis_full = best_candidate_analysis.analyse()
    best_cand_analysis = best_candidate_analysis.analyse(target_data)

    report+="---------- Best candidate ------------------------------------------\n"
    
    report+=pp.pformat(best_candidate)+"\n\n"
    report+=pp.pformat(best_cand_analysis_full)+"\n"
    report+=pp.pformat(best_cand_analysis)+"\n\n"
    report+="FITNESS: %f\n\n"%fitness
    
    print(report)
    
    reportj['fitness']=fitness
    reportj['fittest vars']=dict(sim_var)
    reportj['best_cand_details']=best_candidate
    reportj['best_cand_analysis_full']=best_cand_analysis_full
    reportj['best_cand_analysis']=best_cand_analysis
    reportj['parameters']=parameters
    reportj['analysis_var']=analysis_var
    reportj['target_data']=target_data
    reportj['weights']=weights
    
    reportj['analysis_start_time']=analysis_start_time
    
    reportj['population_size']=population_size
    reportj['max_evaluations']=max_evaluations
    reportj['num_selected']=num_selected
    reportj['num_offspring']=num_offspring
    reportj['mutation_rate']=mutation_rate
    reportj['num_elites']=num_elites
    reportj['seed']=seed
    reportj['simulator']=simulator
    
    reportj['sim_time']=sim_time
    reportj['dt']=dt
    
    reportj['run_directory'] = run_dir
    reportj['reference'] = ref
    
    report_file = open("%s/report.json"%run_dir,'w')
    report_file.write(pp.pformat(reportj))
    report_file.close()
    
    plot_file = open("%s/plotgens.py"%run_dir,'w')
    plot_file.write('from neurotune.utils import plot_generation_evolution\nimport os\n')
    plot_file.write('\n')
    plot_file.write('parameters = %s\n'%parameters)
    plot_file.write('\n')
    plot_file.write("curr_dir = os.path.dirname(__file__) if len(os.path.dirname(__file__))>0 else '.'\n")
    plot_file.write("plot_generation_evolution(parameters, individuals_file_name = '%s/ga_individuals.csv'%curr_dir)\n")
    plot_file.close()
    
    

    if not nogui:
        added =[]
        for wref in weights.keys():
            ref = wref.split(':')[0]
            if not ref in added and not "phase_offset" in ref:
                added.append(ref)
                best_candidate_plot = plt.plot(best_candidate_t,best_candidate_v[ref], label="%s - %i evaluations"%(ref,max_evaluations))

        plt.legend()

        plt.ylim(-80.0,80.0)
        plt.xlim(0.0,sim_time)
        plt.title("Models")
        plt.xlabel("Time (ms)")
        plt.ylabel("Membrane potential(mV)")


        utils.plot_generation_evolution(sim_var.keys(), individuals_file_name = '%s/ga_individuals.csv'%run_dir)

        
        c302_utils.plot_c302_results(best_candidate_results, config, level, directory=run_dir,save=True)