def run_test_set(test_pso=True, test_mosquito=True, test_bees=True, writer=None):

    if writer is not None:
        writer = csv.writer(writer, delimiter='\t', quoting=csv.QUOTE_ALL)

    functions = [(goldenstein_price, (-2, 2), 2),
                 (ackley, (-40, 40), 2),
                 (xin_sheyang, (-2 * np.pi, 2 * np.pi), 2),
                 (zakharov, (-5, 10), 2),
                 (griewank, (-600, 600), 2),
                 (sphere, (-100, 100), 2),
                 (rosenbrok, (-10, 10), 2),
                 (rastrigin, (-5.12, 5.12), 2),
                ]

    for fun in functions:
        print "Run simulation for function ", fun[0].__name__

        if test_mosquito:
            if writer is not None:
                writer.writerow(("Function", "Initial num swarms", "Final num swarms", "Starvation kt", "Score", "Error", "Position", "Iter", "Fun evals"))
            run_mosquitos(fun, writer=writer)

        if test_pso:
            if writer is not None:
                writer.writerow(("Function", "Topology", "PSO", "Phi", "Score", "Error", "Position", "Iter", "Fun evals"))
            run_pso(fun, writer=writer)

        if test_bees:
            if writer is not None:
                writer.writerow(("Function", "Employed %", "Onlooker %", "Scout Num", "Score", "Error", "Position", "Iter", "Fun evals"))
            run_bees(fun, writer=writer)
Exemplo n.º 2
0
def run_hpsoga(pso_params,
               ga_params,
               eval_func,
               n_particles_part,
               n_vars_part,
               max_iters=100):
    """
    """
    population = None
    global_best = None
    eval_global = float(
        'inf') if pso_params['task'] == 'min' else -float('inf')
    for _ in range(max_iters):
        # Apply the standard PSO to all particles
        population, _, _ = pso.run_pso(
            eval_func=eval_func,
            consts=pso_params['consts'],
            max_iters=pso_params['max_iters'],
            pop_size=pso_params['pop_size'],
            particle_size=pso_params['particle_size'],
            initial_particles=population,
            u_bound=pso_params['u_bound'],
            l_bound=pso_params['l_bound'],
            task=pso_params['task'])
        # Evaluate all candidate solutions
        fitness_vals = np.apply_along_axis(eval_func, 1, population)
        # Apply the selection operator in all solutions
        selected_pop = ga.roulette_selection(population,
                                             pso_params['pop_size'],
                                             fitness_vals, pso_params['task'])
        # Split population in sub-partitions and apply the crossover in each one.
        new_particles = split_and_crossover(selected_pop, n_particles_part,
                                            n_vars_part,
                                            ga_params['prob_cross'],
                                            ga_params['c'])
        if new_particles is not None:
            # Add new candidate solutions to population
            selected_pop = np.append(selected_pop, new_particles, axis=0)
        # Apply mutation
        population = ga.arith_mutation(selected_pop, ga_params['prob_mut'],
                                       pso_params['l_bound'],
                                       pso_params['u_bound'])

        fitness_vals = np.apply_along_axis(eval_func, 1, population)
        global_best, eval_global = pso.update_global_best(
            population, global_best, fitness_vals, eval_global,
            pso_params['task'])
        print(eval_global)
    return population
Exemplo n.º 3
0
    def test_run_pso(self):
        particles = np.array([[1.0, 0.6, -0.2], [0.1, -0.2, -0.7],
                              [0.3, 0.2, 0.1]])
        particles_copy = np.copy(particles)

        eval_func = lambda p: np.sum(p**2)
        max_iter = 10

        consts = [0.7, 0.7, 0.9]

        new_particles, global_solutions, best_evals = pso.run_pso(
            eval_func, consts, max_iter, initial_particles=particles_copy)

        np.testing.assert_allclose(new_particles, np.zeros((3, 3)), atol=1.0)
        np.testing.assert_allclose(global_solutions,
                                   np.zeros((10, 3)),
                                   atol=1.0)

        self.assertListEqual(best_evals, sorted(best_evals, reverse=True))
Exemplo n.º 4
0
def minimize(obj_function,
             method,
             population_size=config.population_size,
             stopping_criterion=StoppingCriterion.default(),
             interval=(config.coord_min, config.coord_max),
             params=None):
    """
    Minimize the given function.
    Minimization uses metaheuristics like Particle Swarm Optimization and Differential Evolution,
    utilizing swarm intelligence to come up with a (nearly) optimal solution.
    :param obj_function: Function to minimize. This has to be an instance of `problem.ObjFunc`.
    :param method: Method to use during optimization. Right now this can be either PSO or DE.
    :param population_size: Size of the population to use for the algorithm.
    :param stopping_criterion: Stopping criterion for the algorithm,
    this has to be an instance of `problem.StoppingCriterion`.
    :param interval: interval on which the function should be optimized will be a square:
    interval^dim (^ meaning the power using cartesian product).
    :param params: method-specific parameters in form of a dictionary.
    See the documentation for `de.run_de` and `pso.run_pso` for more detailed explanation.
    :return: Depending on the stopping criterion this can be either the best solution achieved by the method
    or number of steps required to get to this solution.
    """
    if method == 'pso':
        return pso.run_pso(fit_func=obj_function.func,
                           dimensionality=obj_function.dim,
                           population_size=population_size,
                           interval=interval,
                           stopping_criterion=stopping_criterion,
                           method_params=params,
                           chart=False)

    if method == 'de':
        return de.run_de(fit_func=obj_function.func,
                         dimensionality=obj_function.dim,
                         population_size=population_size,
                         interval=interval,
                         stopping_criterion=stopping_criterion,
                         method_params=params,
                         chart=False)

    print 'Method "{0}" currently not supported, sorry.'.format(method)
Exemplo n.º 5
0
def run_experiment(algorithm,
                   parameters,
                   func_name,
                   n_runs,
                   df_results,
                   dataset_name=None,
                   n_attrib=1):
    """
    Run single experiment.

    Parameters
    ----------
    algorithm: string
        Name of algorithm.
    parameters: dict
        Parameters for the algorithm in the current experiment.
    func_name: string
    n_runs: int
    df_results: DataFrame
        Dataframe for saving the experiments results.
    dataset_name: string
        Takes the value 'None' if it's not a clustering optimisation problem.
    n_attrib: int
        Number of attributes for the dataset (Default value = 1).

    Returns
    -------
    df_results: DataFrame
        DataFrame containing the results of experiments.
    """
    if dataset_name is not None:
        eval_func, task = functions.get_cluster_index(func_name, dataset_name)
        l_bound, u_bound = -1.0, 1.0
        print(
            f'======== Clust eval index: {func_name}: {dataset_name} ========')
    else:
        eval_func, l_bound, u_bound, task = functions.get_function(func_name)
        print(f'======== Benchmark function: {func_name} ========')

    func_params = {
        "eval_func": eval_func,
        "l_bound": l_bound,
        "u_bound": u_bound,
        "task": task
    }
    # create all permutations of parameters
    grid_params = create_grid_params(parameters)

    n_params = len(grid_params)
    index_params = 1

    for p in grid_params:
        print(f'======== Parameters {index_params} of {n_params} ========')
        for run in range(n_runs):
            print(f'-------- {algorithm} - run {run+1} --------')
            inicio = time.time()
            if algorithm == 'pso':
                _, _, best_evals = pso.run_pso(
                    eval_func=eval_func,
                    consts=p['consts'],
                    max_iters=p['max_iters'],
                    pop_size=p['pop_size'],
                    particle_size=p['particle_size'],
                    l_bound=l_bound,
                    u_bound=u_bound,
                    task=task)
            elif algorithm == 'hgapso':
                _, _, best_evals = hgapso.run_hgapso(alg_params=p,
                                                     func_params=func_params)
            else:  # logapso
                _, _, best_evals = logapso.run_logapso(
                    alg_params=p,
                    func_params=func_params,
                    prob_run_ga=p['prob_run_ga'],
                    step_size=p['step_size'])
            print(time.time() - inicio)
            n_iters = len(best_evals)
            # This is a clustering optimization problem
            if dataset_name is not None:
                # Each particle has C X F dimensions, where C is the number
                # of clusters and F is the number of features for the dataset.
                n_clusters = int(p['particle_size'] / n_attrib)
                df_results = add_results_to_df(p, df_results, n_iters,
                                               best_evals, run, algorithm,
                                               n_clusters)

            else:  # This is problem of benchmark function optimization
                df_results = add_results_to_df(p, df_results, n_iters,
                                               best_evals, run, algorithm)
        index_params += 1
    return df_results