Exemplo n.º 1
0
    def create_variants(self, n, desc, category, constructor):
        def assign_2nd_alg(archipelago, algo):
            if category == 'rings':
                for island in archipelago.topology.every_other_island():
                    island.algorithm = algo
            elif hasattr(archipelago.topology, 'endpoints'):
                for island in archipelago.topology.endpoints:
                    island.algorithm = algo
            elif isinstance(archipelago.topology, FullyConnectedTopology):
                for island in islice(archipelago.topology.islands, None, None, 2):
                    island.algorithm = algo
            return archipelago

        def assign_algs(archipelago, algos):
            '''
            Evenly partitions and assigns algorithms to islands.
            '''
            for island,algo in zip(archipelago.topology.islands, cycle(algos)):
                island.algorithm = algo

        g = self.generations

        self.new_topology(
          desc='{}, de'.format(desc),
          category=category,
          algorithms=['de'],
          archipelago=Archipelago(constructor(de(gen=g),n)))
        self.new_topology(
          desc='{}, de1220'.format(desc),
          category=category,
          algorithms=['de1220'],
          archipelago=Archipelago(constructor(de1220(gen=g),n)))
        self.new_topology(
          desc='{}, sade'.format(desc),
          category=category,
          algorithms=['sade'],
          archipelago=Archipelago(constructor(sade(gen=g),n)))
        self.new_topology(
          desc='{}, bee_colony'.format(desc),
          category=category,
          algorithms=['bee_colony'],
          archipelago=Archipelago(constructor(bee_colony(gen=g),n)))
        # de + nelder mead combo
        self.new_topology(
          desc='{}, de+nelder mead'.format(desc),
          category=category,
          algorithms=['de','neldermead'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), self.make_nelder_mead()))
        # de + praxis combo
        self.new_topology(
          desc='{}, de+praxis'.format(desc),
          category=category,
          algorithms=['de','praxis'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), self.make_praxis()))
        # de + sade combo
        self.new_topology(
          desc='{}, de+sade'.format(desc),
          category=category,
          algorithms=['de','sade'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), sade(gen=g)))
Exemplo n.º 2
0
    def solve_minimization(self):
        if self.optimization_method == OptimizationMethod.SCIPY_DE:
            result = differential_evolution(
                self.objective_function,
                bounds=self.bounds,
                args=self.args,
                strategy=self.solver_args.strategy,
                popsize=self.solver_args.popsize,
                recombination=self.solver_args.recombination,
                mutation=self.solver_args.mutation,
                tol=self.solver_args.tol,
                disp=self.solver_args.disp,
                polish=self.solver_args.polish,
                seed=self.solver_args.seed,
                workers=self.solver_args.workers,
            )
            return result

        elif self.optimization_method == OptimizationMethod.PYGMO_DE1220:
            problem_wrapper = PygmoOptimizationProblemWrapper(
                objective_function=self.objective_function,
                bounds=self.bounds,
                args=self.args)
            pygmo_algorithm = pg.algorithm(
                pg.de1220(
                    gen=self.solver_args.gen,
                    allowed_variants=self.solver_args.allowed_variants,
                    variant_adptv=self.solver_args.variant_adptv,
                    ftol=self.solver_args.ftol,
                    xtol=self.solver_args.xtol,
                    memory=self.solver_args.memory,
                    seed=self.solver_args.seed,
                ))
            pygmo_problem = pg.problem(problem_wrapper)

            if self.solver_args.parallel_execution:
                solution_wrapper = self._run_pygmo_parallel(
                    pygmo_algorithm,
                    pygmo_problem,
                    number_of_islands=self.solver_args.number_of_islands,
                    archipelago_gen=self.solver_args.archipelago_gen,
                )
            else:
                pygmo_solution = self._run_pygmo_serial(
                    pygmo_algorithm, pygmo_problem)
                if self.solver_args.polish:
                    pygmo_solution = self._polish_pygmo_population(
                        pygmo_solution)

                solution_wrapper = PygmoSolutionWrapperSerial(pygmo_solution)

            return solution_wrapper

        else:
            raise NotImplementedError("Unavailable optimization method.")
Exemplo n.º 3
0
def sade(objective_function,
         gen=100,
         allowed_variants=[2],
         variant_adptv=1,
         ftol=1e-06,
         xtol=1e-06,
         pop_size=15):
    """
    Self-adaptive Differential Evolution, pygmo flavour (pDE)
    Parameters
    - gen (int) – number of generations
    - allowed_variants (array-like object) – allowed mutation variants, each one being a number in [1, 18]
    - variant_adptv (int) – F and CR parameter adaptation scheme to be used (one of 1..2)
    - ftol (float) – stopping criteria on the x tolerance (default is 1e-6)
    - xtol (float) – stopping criteria on the f tolerance (default is 1e-6)
    - memory (bool) – when true the adapted parameters CR anf F are not reset between successive calls to the evolve method
    """
    logs = []
    problem = pg.problem(objective_function)
    algorithm = pg.algorithm(
        pg.de1220(gen=gen,
                  allowed_variants=allowed_variants,
                  variant_adptv=variant_adptv,
                  ftol=ftol,
                  xtol=xtol))
    algorithm.set_verbosity(50)
    population = pg.population(prob=problem, size=pop_size)
    solution = algorithm.evolve(population)
    """
    get_logs output is a list of tuples with the following structure:
    - Gen (int), generation number
    - Fevals (int), number of functions evaluation made
    - Best (float), the best fitness function currently in the population
    - F (float), the value of the adapted paramter F used to create the best so far
    - CR (float), the value of the adapted paramter CR used to create the best so far
    - Variant (int), the mutation variant used to create the best so far
    - dx (float), the norm of the distance to the population mean of the mutant vectors
    - df (float), the population flatness evaluated as the distance between the fitness of the best and of the 
    worst individual
    """

    logs = np.array(algorithm.extract(pg.de1220).get_log())[:, (
        1, 2)]  # taking only function evaluations and best fitness

    algo_ = algorithm.get_name()
    function_ = objective_function.get_name()

    return {
        'champion solution': solution.champion_f,
        'champion coordinates': solution.champion_x,
        'log': logs,
        'algorithm': algo_,
        'problem': function_
    }
Exemplo n.º 4
0
def test_archipelago():
    max_evals = 500000
    popsize = 32
    gen = int(max_evals / popsize + 1)
    algo = pg.algorithm(pg.de1220(gen=gen))
    fac = 1.005
    _test_archipelago(algo, Cassini1(), num=400, stop_val=4.9307 * fac)
    _test_archipelago(algo, Cassini2(), num=600, stop_val=8.383 * fac)
    _test_archipelago(algo, Gtoc1(), num=1000, stop_val=-1581950 / fac)
    _test_archipelago(algo, Messenger(), num=800, stop_val=8.63 * fac)
    _test_archipelago(algo, Rosetta(), num=400, stop_val=1.3433 * fac)
    _test_archipelago(algo, Sagas(), num=400, stop_val=18.187 * fac)
    _test_archipelago(algo, Tandem(5), num=2000, stop_val=-1500.6 / fac)
    _test_archipelago(algo, MessFull(), num=5000, stop_val=1.959 * fac)
Exemplo n.º 5
0
 def minimize(self,
              fun,
              bounds,
              guess=None,
              sdevs=None,
              rg=Generator(MT19937()),
              store=None):
     gen = int(self.max_eval_num(store) / self.popsize + 1)
     algo = pg.algorithm(
         pg.de1220(gen=gen,
                   allowed_variants=[1, 2, 4, 7, 10, 13, 14, 15, 16],
                   variant_adptv=1,
                   seed=int(rg.uniform(0, 2**32 - 1))))
     #         algo = pg.algorithm(pg.sade(gen=gen, variant_adptv = 1, seed = int(rg.uniform(0, 2**32 - 1))))
     udp = pygmo_udp(fun, bounds)
     prob = pg.problem(udp)
     pop = pg.population(prob, self.popsize)
     pop = algo.evolve(pop)
     return pop.champion_x, pop.champion_f, pop.problem.get_fevals()
Exemplo n.º 6
0
    def _setOptimizer(self, optimizer):

        if callable(optimizer) == True:

            # User-defined optimizer function

            pass

        elif isinstance(optimizer, str):

            # Pre-defined optimizer

            if optimizer == 'ga':

                gen = self.optimization_configuration['number_of_generations']

                cr = self.optimization_configuration['crossover_rate']

                mr = self.optimization_configuration['mutation_rate']

                elitism = self.optimization_configuration['elitism']

                ind = self.optimization_configuration['number_of_individuals']

                #=================================================================

                crossover_type = self.optimization_configuration[
                    'crossover_type']

                mutation_type = self.optimization_configuration[
                    'mutation_type']

                selection_type = self.optimization_configuration[
                    'selection_type']

                selection_param = self.optimization_configuration[
                    'selection_param']

                #=================================================================

                self._pagmo_selected_algorithm = pg.sga

                self._pagmo_selected_algorithm_log_columns = [
                    'Gen', 'Fevals', 'Best', 'Improvement'
                ]

                algo = pg.algorithm(
                    pg.sga(gen=gen,
                           cr=cr,
                           eta_c=1.,
                           m=mr,
                           param_m=1.,
                           param_s=selection_param,
                           crossover=crossover_type,
                           mutation=mutation_type,
                           selection=selection_type))

                #isl = pg.island(algo, self.optimization_problem, ind)

                self.optimization_mechanism = algo

                return ('ga')

            if optimizer == 'sade':

                gen = self.optimization_configuration['number_of_generations']

                de_ftol = self.optimization_configuration['ftol_de']

                de_xtol = self.optimization_configuration['xtol_de']

                ind = self.optimization_configuration['number_of_individuals']

                #==================================================================

                self._pagmo_selected_algorithm = pg.de1220

                self._pagmo_selected_algorithm_log_columns = [
                    'Gen', 'Fevals', 'Best', 'F', 'CR', 'Variant', 'dx', 'df'
                ]

                algo = pg.algorithm(
                    pg.de1220(gen=gen, ftol=de_ftol, xtol=de_xtol))

                #isl = pg.island(algo, self.optimization_problem, ind)

                self.optimization_mechanism = algo

                return ('sade')

            if optimizer == 'de':

                gen = self.optimization_configuration['number_of_generations']

                cr = self.optimization_configuration['crossover_rate']

                f_w = self.optimization_configuration['scale_factor']

                de_variant = self.optimization_configuration['variant_de']

                de_ftol = self.optimization_configuration['ftol_de']

                de_xtol = self.optimization_configuration['xtol_de']

                ind = self.optimization_configuration['number_of_individuals']

                #==================================================================

                self._pagmo_selected_algorithm = pg.de

                self._pagmo_selected_algorithm_log_columns = [
                    'Gen', 'Fevals', 'Best', 'F', 'CR', 'dx', 'df'
                ]

                algo = pg.algorithm(
                    pg.de(gen=gen,
                          F=f_w,
                          CR=cr,
                          variant=de_variant,
                          ftol=de_ftol,
                          xtol=de_xtol))

                #isl = pg.island(algo, self.optimization_problem, ind)

                self.optimization_mechanism = algo

                return ('de')

            if optimizer == 'pso':

                gen = self.optimization_configuration['number_of_generations']

                omega = self.optimization_configuration['omega_pso']

                eta1 = self.optimization_configuration['eta1_pso']

                eta2 = self.optimization_configuration['eta2_pso']

                vcoeff = self.optimization_configuration['max_v_pso']

                pso_variant = self.optimization_configuration['variant_pso']

                neighb_type = self.optimization_configuration[
                    'neighborhood_type_pso']

                neighb_param = self.optimization_configuration[
                    'neighborhood_param_pso']

                ind = self.optimization_configuration['number_of_individuals']

                #==================================================================

                self._pagmo_selected_algorithm = pg.pso

                self._pagmo_selected_algorithm_log_columns = [
                    'Gen', 'Fevals', 'gbest', 'Mean Vel.', 'Mean lbest',
                    'Avg. Dist.'
                ]

                algo = pg.algorithm(
                    pg.pso(gen=gen,
                           omega=omega,
                           eta1=eta1,
                           eta2=eta2,
                           max_vel=vcoeff,
                           variant=pso_variant))

                #isl = pg.island(algo, self.optimization_problem, ind)

                self.optimization_mechanism = algo

                return ('pso')

        else:

            raise UnexpectedValueError("(decorated function, str)")
import numpy as np
import myUDP
import time

generations = 400
sizePop = 15
#pathsave    = '/home/oscar/Documents/PythonProjects/kuramotoAO/optimizationResults/'
pathsave = '/Users/p277634/python/kaoModel/optimResult/'
filenameTXT = 'DE1220_i_cabral.txt'
filenameNPZ = 'DE1220_i_cabral.npz'

# algorithm
algo = po.algorithm(
    po.de1220(gen=generations,
              allowed_variants=np.arange(1, 19, dtype=np.uint32),
              variant_adptv=2,
              ftol=1e-4,
              xtol=1e-4,
              memory=False))
algo.set_verbosity(1)

# problem
prob = po.problem(myUDP.kMcabral())
# population
pop = po.population(prob=prob, size=sizePop)

# evolution
start = time.time()
popE = algo.evolve(pop)
print('time evolution: ', time.time() - start)

# save TXT fie with general description of the optimization
Exemplo n.º 8
0
    archi.evolve()
    archi.wait()
    archi.wait_check()
    print(archi)

import pygmo as pg
# The user-defined problem
udp = pg.schwefel(dim=20)
# The pygmo problem
prob = pg.problem(udp)

# For a number of generation based algorithms we can use a similar script to run and average over 25 runs.
udas = [
    pg.sade(gen=500),
    pg.de(gen=500),
    pg.de1220(gen=500),
    pg.pso(gen=500),
    pg.bee_colony(gen=250, limit=20)
]
for uda in udas:
    logs = []
    for i in range(25):
        algo = pg.algorithm(uda)
        algo.set_verbosity(1)  # regulates both screen and log verbosity
        pop = pg.population(prob, 20)
        pop = algo.evolve(pop)
        logs.append(algo.extract(type(uda)).get_log())
    logs = np.array(logs)
    avg_log = np.average(logs, 0)
    plt.plot(avg_log[:, 1],
             avg_log[:, 2] - 418.9829 * 20,
Exemplo n.º 9
0
 def _setup_algorithm(self, parameters):
     alg = pg.de1220(**self._alg_attrs)
     return alg
Exemplo n.º 10
0
    def __call__(self, function):

        scanner_options = {
            'sade':
            dict(gen=self.gen,
                 variant=self.variant,
                 variant_adptv=self.variant_adptv,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 seed=self.seed),
            'gaco':
            dict(gen=self.gen,
                 ker=self.ker,
                 q=self.q,
                 oracle=self.oracle,
                 acc=self.acc,
                 threshold=self.threshold,
                 n_gen_mark=self.n_gen_mark,
                 impstop=self.impstop,
                 evalstop=self.evalstop,
                 focus=self.focus,
                 memory=self.memory,
                 seed=self.seed),
            'maco':
            dict(gen=self.gen,
                 ker=self.ker,
                 q=self.q,
                 threshold=self.threshold,
                 n_gen_mark=self.n_gen_mark,
                 evalstop=self.evalstop,
                 focus=self.focus,
                 memory=self.memory,
                 seed=self.seed),
            'gwo':
            dict(gen=self.gen, seed=self.seed),
            'bee_colony':
            dict(gen=self.gen, limit=self.limit, seed=self.seed),
            'de':
            dict(gen=self.gen,
                 F=self.F,
                 CR=self.CR,
                 variant=self.variant,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 seed=self.seed),
            'sea':
            dict(gen=self.gen, seed=self.seed),
            'sga':
            dict(gen=self.gen,
                 cr=self.cr,
                 eta_c=self.eta_c,
                 m=self.m,
                 param_m=self.param_m,
                 param_s=self.param_s,
                 crossover=self.crossover,
                 mutation=self.mutation,
                 selection=self.selection,
                 seed=self.seed),
            'de1220':
            dict(gen=self.gen,
                 allowed_variants=self.allowed_variants,
                 variant_adptv=self.variant_adptv,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 seed=self.seed),
            'cmaes':
            dict(gen=self.gen,
                 cc=self.cc,
                 cs=self.cs,
                 c1=self.c1,
                 cmu=self.cmu,
                 sigma0=self.sigma0,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 force_bounds=self.force_bounds,
                 seed=self.seed),
            'moead':
            dict(gen=self.gen,
                 weight_generation=self.weight_generation,
                 decomposition=self.decomposition,
                 neighbours=self.neighbours,
                 CR=self.CR,
                 F=self.F,
                 eta_m=self.eta_m,
                 realb=self.realb,
                 limit=self.limit,
                 preserve_diversity=self.preserve_diversity,
                 seed=self.seed),
            'compass_search':
            dict(max_fevals=self.max_fevals,
                 start_range=self.start_range,
                 stop_range=self.stop_range,
                 reduction_coeff=self.reduction_coeff),
            'simulated_annealing':
            dict(Ts=self.Ts,
                 Tf=self.Tf,
                 n_T_adj=self.n_T_adj,
                 n_range_adj=self.n_range_adj,
                 bin_size=self.bin_size,
                 start_range=self.start_range,
                 seed=self.seed),
            'pso':
            dict(gen=self.gen,
                 omega=self.omega,
                 eta1=self.eta1,
                 eta2=self.eta2,
                 max_vel=self.max_vel,
                 variant=self.variant,
                 neighb_type=self.neighb_type,
                 neighb_param=self.neighb_param,
                 memory=self.memory,
                 seed=self.seed),
            'pso_gen':
            dict(gen=self.gen,
                 omega=self.omega,
                 eta1=self.eta1,
                 eta2=self.eta2,
                 max_vel=self.max_vel,
                 variant=self.variant,
                 neighb_type=self.neighb_type,
                 neighb_param=self.neighb_param,
                 memory=self.memory,
                 seed=self.seed),
            'nsga2':
            dict(gen=self.gen,
                 cr=self.cr,
                 eta_c=self.eta_c,
                 m=self.m,
                 eta_m=self.eta_m,
                 seed=self.seed),
            'nspso':
            dict(gen=self.gen,
                 omega=self.omega,
                 c1=self.c1,
                 c2=self.c2,
                 chi=self.chi,
                 v_coeff=self.v_coeff,
                 leader_selection_range=self.leader_selection_range,
                 diversity_mechanism=self.diversity_mechanism,
                 memory=self.memory,
                 seed=self.seed),
            'mbh':
            dict(algo=self.algo,
                 stop=self.stop,
                 perturb=self.perturb,
                 seed=self.seed),
            'cstrs_self_adaptive':
            dict(iters=self.iters, algo=self.algo, seed=self.seed),
            'ihs':
            dict(gen=self.gen,
                 phmcr=self.phmcr,
                 ppar_min=self.ppar_min,
                 ppar_max=self.ppar_max,
                 bw_min=self.bw_min,
                 bw_max=self.bw_max,
                 seed=self.seed),
            'xnes':
            dict(gen=self.gen,
                 eta_mu=self.eta_mu,
                 eta_sigma=self.eta_sigma,
                 eta_b=self.eta_b,
                 sigma0=self.sigma0,
                 ftol=self.ftol,
                 xtol=self.xtol,
                 memory=self.memory,
                 force_bounds=self.force_bounds,
                 seed=self.seed)
        }

        if self.log_data:
            xl = []
            yl = []

        log_data = self.log_data

        #
        class interf_function:
            def __init__(self, dim):
                self.dim = dim

            def fitness(self, x):
                x = np.expand_dims(x, axis=0)
                y = function(x)
                # x = x[0]
                y = y.tolist()
                if log_data:
                    xl.append(x)
                    yl.append(y)
                # print (x, y[0])
                return y[0]

            if function.is_differentiable():

                def gradient(self, x):
                    x = np.expand_dims(x, axis=0)
                    g = function(x)
                    g = g.tolist()
                    return g[0]

            def get_bounds(self):
                lb = []
                ub = []
                bounds = function.get_ranges()
                # warning
                # check for infinities
                for i in range(len(bounds)):
                    lb.append(bounds[i, 0])
                    ub.append(bounds[i, 1])
                r = (np.array(lb), np.array(ub))
                return r

        # I need to call pygmo functions directly
        prob = pg.problem(interf_function(function))

        # print (prob.get_thread_safety())

        if self.scanner == "sade":
            # I need a dictionary with algorithms and options
            algo = pg.algorithm(pg.sade(**scanner_options[self.scanner]))
        elif self.scanner == "gaco":
            algo = pg.algorithm(pg.gaco(**scanner_options[self.scanner]))
        # elif self.scanner == "maco": # is not implemented though in webpage
        #                               looks it is
        # algo = pg.algorithm(pg.maco(**scanner_options[self.scanner]))
        elif self.scanner == "gwo":
            algo = pg.algorithm(pg.gwo(**scanner_options[self.scanner]))
        elif self.scanner == "bee_colony":
            algo = pg.algorithm(pg.bee_colony(**scanner_options[self.scanner]))
        elif self.scanner == "de":
            algo = pg.algorithm(pg.de(**scanner_options[self.scanner]))
        elif self.scanner == "sea":
            algo = pg.algorithm(pg.sea(**scanner_options[self.scanner]))
        elif self.scanner == "sga":
            algo = pg.algorithm(pg.sga(**scanner_options[self.scanner]))
        elif self.scanner == "de1220":
            algo = pg.algorithm(pg.de1220(**scanner_options[self.scanner]))
        elif self.scanner == "cmaes":
            algo = pg.algorithm(pg.cmaes(**scanner_options[self.scanner]))
        # elif self.scanner == "moead": #multiobjective algorithm
        #  algo = pg.algorithm(pg.moead(**scanner_options[self.scanner]))
        elif self.scanner == "compass_search":
            algo = pg.algorithm(
                pg.compass_search(**scanner_options[self.scanner]))
        elif self.scanner == 'simulated_annealing':
            algo = pg.algorithm(
                pg.simulated_annealing(**scanner_options[self.scanner]))
        elif self.scanner == 'pso':
            algo = pg.algorithm(pg.pso(**scanner_options[self.scanner]))
        elif self.scanner == 'pso_gen':
            algo = pg.algorithm(pg.pso_gen(**scanner_options[self.scanner]))
        # elif self.scanner == 'nsga2': #multiobjective algorithm
        #  algo = pg.algorithm(pg.nsga2(**scanner_options[self.scanner]))
        # elif self.scanner == 'nspso': is not implemented though in webpage
        #                               looks it is
        #  algo = pg.algorithm(pg.nspso(**scanner_options[self.scanner]))
        elif self.scanner == 'mbh':
            if scanner_options[self.scanner]['algo'] == 'de':
                algo = pg.algorithm(
                    pg.mbh(pg.algorithm(pg.de(**scanner_options['de']))))
        # elif self.scanner == 'ihs': #does not work
        #  algo = pg.algorithm(ihs(**scanner_options[self.scanner]))
        # elif self.scanner == 'xnes': #does not work
        #  algo = pg.algorithm(xnes(**scanner_options[self.scanner]))
        # uda = algo.extract(xnes)
        else:
            print(
                'The ' + self.scanner + ' algorithm is not implemented. The '
                'list of algorithms available is', algorithms)
            sys.exit()

        # add verbosing flag
        if self.verbose > 1:
            algo.set_verbosity(self.verbose)

        pop = pg.population(prob, self.size)

        if self.verbose > 9:
            print('prob', prob)

        opt = algo.evolve(pop)

        if self.verbose > 9:
            print('algo', algo)

        # best_x = np.expand_dims(opt.champion_x, axis=0)
        # best_fitness = np.expand_dims(opt.get_f()[opt.best_idx()], axis=0)
        best_x = np.expand_dims(opt.champion_x, axis=0)
        best_fitness = np.expand_dims(opt.champion_f, axis=0)

        if self.verbose > 0:
            print('best fit:', best_x, best_fitness)

        if self.log_data:
            x = np.squeeze(xl, axis=(1, ))
            y = np.squeeze(yl, axis=(2, ))

        if self.log_data:
            return (x, y)
        else:
            return (best_x, best_fitness)
Exemplo n.º 11
0
    def create_variants(self, n, desc, category, constructor):
        def assign_2nd_alg(archipelago, algo):
            if category == 'rings':
                for island in archipelago.topology.every_other_island():
                    island.algorithm = algo
            elif hasattr(archipelago.topology, 'endpoints'):
                for island in archipelago.topology.endpoints:
                    island.algorithm = algo
            elif isinstance(archipelago.topology, FullyConnectedTopology):
                for island in islice(archipelago.topology.islands, None, None, 2):
                    island.algorithm = algo
            return archipelago

        def assign_algs(archipelago, algos):
            '''
            Evenly partitions and assigns algorithms to islands.
            '''
            for island,algo in zip(archipelago.topology.islands, cycle(algos)):
                island.algorithm = algo

        g = self.generations

        self.new_topology(
          desc='{}, de'.format(desc),
          category=category,
          algorithms=['de'],
          archipelago=Archipelago(constructor(de(gen=g),n)))
        self.new_topology(
          desc='{}, de1220'.format(desc),
          category=category,
          algorithms=['de1220'],
          archipelago=Archipelago(constructor(de1220(gen=g),n)))
        self.new_topology(
          desc='{}, sade'.format(desc),
          category=category,
          algorithms=['sade'],
          archipelago=Archipelago(constructor(sade(gen=g),n)))
        self.new_topology(
          desc='{}, ihs'.format(desc),
          category=category,
          algorithms=['ihs'],
          archipelago=Archipelago(constructor(ihs(gen=g),n)))
        self.new_topology(
          desc='{}, pso'.format(desc),
          category=category,
          algorithms=['pso'],
          archipelago=Archipelago(constructor(pso(gen=g),n)))
        self.new_topology(
          desc='{}, pso_gen'.format(desc),
          category=category,
          algorithms=['pso_gen'],
          archipelago=Archipelago(constructor(pso_gen(gen=g),n)))
        # self.new_topology(
        #   desc='{}, simulated_annealing'.format(desc),
        #   category=category,
        #   algorithms=['simulated_annealing'],
        #   archipelago=Archipelago(constructor(simulated_annealing(),n)))
        self.new_topology(
          desc='{}, bee_colony'.format(desc),
          category=category,
          algorithms=['bee_colony'],
          archipelago=Archipelago(constructor(bee_colony(gen=g),n)))
        self.new_topology(
          desc='{}, cmaes'.format(desc),
          category=category,
          algorithms=['cmaes'],
          archipelago=Archipelago(constructor(cmaes(gen=g),n)))
        self.new_topology(
          desc='{}, nsga2'.format(desc),
          category=category,
          algorithms=['nsga2'],
          archipelago=Archipelago(constructor(nsga2(gen=g),n)))
        self.new_topology(
          desc='{}, xnes'.format(desc),
          category=category,
          algorithms=['xnes'],
          archipelago=Archipelago(constructor(xnes(gen=g),n)))
        # de + nelder mead combo
        self.new_topology(
          desc='{}, de+nelder mead'.format(desc),
          category=category,
          algorithms=['de','neldermead'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), self.make_nelder_mead()))
        # de + praxis combo
        self.new_topology(
          desc='{}, de+praxis'.format(desc),
          category=category,
          algorithms=['de','praxis'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), self.make_praxis()))
        # de + nsga2 combo
        self.new_topology(
          desc='{}, de+nsga2'.format(desc),
          category=category,
          algorithms=['de','nsga2'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), nsga2(gen=g)))
        # de + de1220 combo
        self.new_topology(
          desc='{}, de+de1220'.format(desc),
          category=category,
          algorithms=['de','de1220'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), de1220(gen=g)))
        # de + sade combo
        self.new_topology(
          desc='{}, de+sade'.format(desc),
          category=category,
          algorithms=['de','sade'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), sade(gen=g)))
        # de + pso combo
        self.new_topology(
          desc='{}, de+pso'.format(desc),
          category=category,
          algorithms=['de','pso'],
          archipelago=assign_2nd_alg(Archipelago(constructor(de(gen=g),n)), pso(gen=g)))


      # extra configurations for fully connected topology
        if constructor is self.factory.createFullyConnected:
            self.new_topology(
                desc='{}, de+pso+praxis'.format(desc),
                category=category,
                algorithms=['de','pso','praxis'],
                archipelago=assign_algs(Archipelago(constructor(de(gen=g),n)), (de(gen=g), pso(gen=g), self.make_praxis())))
            self.new_topology(
                desc='{}, de+pso+praxis+nsga2'.format(desc),
                category=category,
                algorithms=['de','pso','praxis','nsga2'],
                archipelago=assign_algs(Archipelago(constructor(de(gen=g),n)), (de(gen=g), pso(gen=g), self.make_praxis(), nsga2(gen=g))))
            self.new_topology(
                desc='{}, de+pso+praxis+cmaes'.format(desc),
                category=category,
                algorithms=['de','pso','praxis','cmaes'],
                archipelago=assign_algs(Archipelago(constructor(de(gen=g),n)), (de(gen=g), pso(gen=g), self.make_praxis(), cmaes(gen=g))))
            self.new_topology(
                desc='{}, de+pso+praxis+xnes'.format(desc),
                category=category,
                algorithms=['de','pso','praxis','xnes'],
                archipelago=assign_algs(Archipelago(constructor(de(gen=g),n)), (de(gen=g), pso(gen=g), self.make_praxis(), xnes(gen=g))))
Exemplo n.º 12
0
class my_udp:
    def fitness(self, x):
        return (np.sin(x[0]+x[1]-x[2]), x[0] + np.cos(x[2]*x[1]), x[2])
    def get_bounds(self):
        return ([-1,-1,-1],[1,1,1])
    def get_nec(self):
        return 1
    def get_nic(self):
        return 1


prob = problem(my_udp())
pop = pg.population(prob, 16, seed=1337)
#algo = pg.algorithm(pg.scipy_optimize(method="SLSQP"))
algo = pg.algorithm(pg.de1220())
algo.set_verbosity(10)
# Solve the problem
new_pop = algo.evolve(pop) 
# Collect information
print(new_pop.champion_f) 
print(new_pop.problem.get_fevals())
print(new_pop.problem.get_gevals())

print("---------")

#prob = sphere_1d()
#algo = algorithm(de(500))
algo = algorithm(de1220(gen = 500))
pop = population(prob, 20)
new_pop = algo.evolve(pop)