def task_runner(args):
    pconf = projconf.ProjectConfiguration(sim_path = args["sim_path"],
                                          config_file = projconf.norm_path(args["sim_path"],"full.cfg"))

    item_list = parse_result_candidates(pconf.get_local_path("resultDensityFile"))
    (fitness, candidates) = zip(*item_list)
    if args["best_neurons"] is not None:
        last = min(args["best_neurons"], len(candidates))
        candidates = candidates[:last]
    evals = evaluation.evaluate(pconf.get_logger("start_evaluation"), pconf, candidates, cleanup = args["cleanup"])
    return {"mode" : pconf.get("mode", "Simulation"), "evals" : evals}
    def __init__(self, config, temp):
        self.config_file = projconf.norm_path(config)
        self.temp = temp
        self.pconf = projconf.ProjectConfiguration(config_file = self.config_file)
        
        
        # Create and set sim_path.
        if self.temp:
            temp_path = tempfile.mkdtemp(prefix="neuron_sim-")
            self.pconf.set_sim_path(temp_path)
        else:
            result_directory = self._mk_result_directory()
            self.pconf.set_sim_path(result_directory)
        
        # Copy configurations.
        full_config = projconf.norm_path(self.pconf.sim_path, "full.cfg")
        with open(full_config, "w") as sim_config_file:
            self.pconf.cfg.write(sim_config_file)
        shutil.copy(projconf.norm_path(projconf.DEFAULT_CONFIG), self.pconf.sim_path)
        custom_config = projconf.norm_path(self.pconf.sim_path, "custom.cfg")
        shutil.copyfile(self.config_file, custom_config)
        self.pconf.set_config_file(custom_config)

        # Populate sim folder
        project_name = "Pyr_" + self.pconf.get("mode", "Simulation")
        project_path = projconf.norm_path(self.pconf.get("resources"), project_name)
        shutil.copytree(project_path, projconf.norm_path(self.pconf.sim_path, project_name))
def evaluate(logger, pconf, candidates, cleanup = False):
    """Returns a list containing the neuron itself and its evaluation results."""
    #pconf.invoke_neurosim(logger, type = "current", candidates = candidates, prefix = EVAL_PREFIX)
    try:
        # Get parameters, ignoring the evaluator function.
        parsed_kwargs = {"pconf" : pconf, "mode" : pconf.get("mode", "Simulation")}
        evaluator_section = pconf.get("evaluator", "Simulation")
        parsed_kwargs = callable.get_section_variables(pconf, logger, evaluator_section, parsed_kwargs)
        return fitness.evaluate_channels(candidates, parsed_kwargs)
    finally:
        if cleanup:
            dir = projconf.norm_path(pconf.get_sim_project_path(), "simulations")
            if os.path.isdir(dir):
                shutil.rmtree(dir)
def main():
    parser = argparse.ArgumentParser(description="Plot a neuroConstruct neuron after simulation.")
    parser.add_argument(metavar = "SIM_PATH", dest = "sim_path",
                        help = """Path to the simulation path containing the config files used and the neuroConstruct project.
                        This is also called simulation path and the result of calling "start_sim".""")
    parser.add_argument("-s", "--simulation", required = True, action = "append",
                        help = """Just the name of the simulation as
                        found in the neuroConstruct's neuron simulation.
                        Example: Use "PySim_27" for "Pyr_RS/simulations/PySim_27" """)
    parser.add_argument("-t", "--time", type = float, default = 1.0,
                        help = """The time in seconds that should be displayed.
                        Valid values depend on sampling size and are usually between 0 and 1.0.""")
    parser.add_argument("-f", "--file", action = "store",
                        help = """Don't show image but save the plot in plots/FILE.
                        This name can have a correct file extension to specify the type (*.png or *.eps ..).""")
    options = parser.parse_args()

    configFile = projconf.norm_path(options.sim_path, "full.cfg")
    pconf = projconf.ProjectConfiguration(configFile, options.sim_path)
    if options.file is not None:
        output_file = projconf.norm_path("plots", options.file)
        plot(pconf, options.simulation, options.time, show_plot = False, output_file = output_file)
    else:
        plot(pconf, options.simulation, options.time, show_plot = True)
def plot(pconf, simulations, time = 1.0, show_plot = True, output_file = None):
    dt = pconf.get_float("dt", "Simulation")
    Fs = 1000 / dt
    Ts = 1.0 / Fs; # sampling interval
    duration = pconf.get_float("duration", "Simulation")
    time = min(time, duration / 1000)
    t = numpy.arange(0, time, Ts) # time vector
    D = []
    for simulation in simulations:
        densityFile = projconf.norm_path(pconf.get_sim_project_path(),
                                         "simulations", simulation, "CellGroup_1_0.dat")
        with open(densityFile,'r') as fileDE:
            density = numpy.zeros(len(t))
            densities_list= fileDE.read().split('#\n')      
            densities = densities_list[0].split('\n')
            for i in range(len(density)):
                dens = densities[i].strip()
                density[i] = float(dens)
        fileDE.close()
        y = density
        D.append(y)

        
        plt.plot(t,y)
        xlabel('Zeit [s]')
        ylabel('Membranpotenzial [mV]')
    for z in range(len(simulations)):
        subplot(len(simulations), 1, z + 1)
        plt.plot(t, D[z])
        if(z == len(simulations) // 2):
            ylabel('Membranpotenzial [mV]')
    xlabel('Zeit [s]')
    if show_plot:
        show()
    if output_file is not None:
        savefig(output_file)
    def run(self, quiet = False):
        """Runs the neuron generation and simulation.

        This may take some time, depending on the settings.
        Returns 0 if no error is encountered.
        """
        returncode = 0
        # Initialize logging.
        self.pconf.suppress_logging = quiet
        logger_server = logserver.initFileLogServer(log_file = self.pconf.get_local_path("log_server_file", "Logging"),
                                                    port = self.pconf.get_int("log_server_port", "Logging"),
                                                    file_level = self.pconf.get_int("file_log_level", "Logging"),
                                                    logger_name = "")
        logger_server.start()
        logger = self.pconf.get_logger("simulation", logger_server.port)
        try:
            start_time = time.time()
            logger.info("          =============================================")
            logger.info("          =============================================")
            logger.info("          =======    Starting new Simulation    =======")
            logger.info("          =============================================")
            logger.info("          =============================================")
            version = subprocess.check_output(["git", "describe", "--always"])
            logger.info("Git project version: " + version.strip())
            logger.info
            logger.info("Configuration used:")
            self.pconf.log_configuration(logger)
            if self.config_file == projconf.norm_path(projconf.DEFAULT_CONFIG):
                logger.warning("The specified configuration file is the default configuration."
                               + " Please make any customization in a seperate file.")
            if self.temp:
                self._check_result_dir(logger)
            
            
            
            self.pconf.write_project_data(logger_server.port)

            # Start algorithm
            algorithm = self.pconf.get("algorithm", "Simulation")
            if algorithm == "annealing":
                annealing.start(self.pconf)
            elif algorithm == "genetic":
                evolution.start(self.pconf)
            elif algorithm == "gridsearch":
                gridsearch.start(self.pconf)
            else:
                raise RuntimeError("Unknown algorithm selected: '" + algorithm + "'")

            stop_time = time.time()
            logger.info("Time passed: " + str(stop_time - start_time) + " seconds")
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            logger.exception("Exception encountered, aborting.")
            returncode = 10
        finally:
            try:
                if self.temp:
                    # Log messages after this are likely to be never saved.
                    self._move_to_output(logger)
            except:
                logger.exception("Failed to move simulation folder '"
                                 + self.pconf.sim_path + "'"
                                 + "to the ouput directory '"
                                 + projconf.norm_path(".", self.pconf.get("result_directory")))
                returncode += 20
            finally:
                # Necessary to avoid hanging on open sockets
                logger_server.stop()
        return returncode