Beispiel #1
0
    def run(self, benchmark):
        """Execute the algorithm

        Argument
        --------
        benchmark : str
        """
        if PSO.__flags.seed:
            algorithm = pg.pso(self.__flags.generations,
                               self.__flags.omega,
                               self.__flags.eta1,
                               self.__flags.eta2,
                               self.__flags.max_vel,
                               self.__flags.variant,
                               self.__flags.neighb_type,
                               self.__flags.neighb_param,
                               self.__flags.memory,
                               self.__flags.seed)
        else:
            algorithm = pg.pso(self.__flags.generations,
                               self.__flags.omega,
                               self.__flags.eta1,
                               self.__flags.eta2,
                               self.__flags.max_vel,
                               self.__flags.variant,
                               self.__flags.neighb_type,
                               self.__flags.neighb_param,
                               self.__flags.memory)

        # Execute
        super().exec(algorithm, benchmark)
Beispiel #2
0
    def run(self, converge_info=False, pop_info=False):
        """
        Run the optimisation process using PSO algorithm.
        :param converge_info: optional run the optimisation with convergence information
        :param converge_info: optional run the optimisation with population information
        :return:
        """
        print("Start the optimisation process...")

        if pop_info != False:
            uda = pg.pso(gen=1)
            algo = pg.algorithm(uda)
            algo.set_verbosity(1)
            pop = pg.population(self.problem, self.pop_size)
            self.pop_history = [pop]
            for i in range(int(pop_info)):
                pop = algo.evolve(pop)
                self.pop_history.append(pop)
            self.log = algo.extract(type(uda)).get_log()
            self.pop = pop
        elif converge_info == True:
            uda = pg.pso(gen=self.generation)
            algo = pg.algorithm(uda)
            algo.set_verbosity(1)
            pop = pg.population(self.problem, self.pop_size)
            self.log = algo.extract(type(uda)).get_log()
            self.pop = pop
        else:
            uda = pg.pso(gen=self.generation)
            algo = pg.algorithm(uda)
            pop = pg.population(self.problem, self.pop_size)
            pop = algo.evolve(pop)
        self.champion = pop.champion_x
        return pop.champion_f, pop.champion_x
    def run(self):

        self.algo = pg.algorithm(
            pg.pso(gen=self.param['gen'],
                   eta1=self.param['eta1'],
                   eta2=self.param['eta2']))
        self.algo.set_verbosity(1)

        for i in range(self.param['sessions']):

            print("\n" + str(i + 1) + " out of " +
                  str(self.param['sessions']) + " started. \n")

            self.algo.set_seed(randint(0, 1000))

            self.pop = pg.population(self.problem,
                                     size=self.param['pop_size'],
                                     seed=randint(0, 1000))
            self.pop = self.algo.evolve(self.pop)

            self.process_results()
            self.save_results()

            print(self.pop)
            print("\n" + str(i + 1) + " out of " +
                  str(self.param['sessions']) + " saved.")
Beispiel #4
0
 def run(self):
     algo = pg.algorithm(pg.pso(gen=self.generation))
     pop = pg.population(self.problem, self.pop_size)
     print("Start optimisation process...")
     pop = algo.evolve(pop)
     self.champion = pop.champion_x
     return pop.champion_f, pop.champion_x
Beispiel #5
0
def run_benchmark_coevolution(cp, x_train, y_train, funset):
    ib, params, bounds = define_cgp_system(
        cp.getint('CGPPARAMS', 'n_nodes'),
        x_train.shape[1] if len(x_train.shape) > 1 else 1,
        y_train.shape[1] if len(y_train.shape) > 1 else 1, funset,
        cp.getint('CGPPARAMS', 'max_back'))

    # setup the coevolution elements
    ts = TrainersSet(ib, 16, fitness_function, x_train, y_train)
    predictors = GaPredictors(x_train, y_train, 10, 24)
    predictors.evaluate_fitness(ts)
    x_reduced, y_reduced = predictors.best_predictors_data()

    GENS_STEP = 50

    cf = cost_function(x_reduced, y_reduced, params, bounds)
    prob = pg.problem(cf)
    algo = pg.algorithm(
        pg.pso(gen=GENS_STEP,
               omega=cp.getfloat('OPTIMPARAMS', 'omega'),
               eta1=cp.getfloat('OPTIMPARAMS', 'eta1'),
               eta2=cp.getfloat('OPTIMPARAMS', 'eta2'),
               memory=True))
    algo.set_verbosity(1)
    pop = pg.population(prob, cp.getint('DEFAULT', 'population_size'))
    n_gens = GENS_STEP

    while n_gens < 500:

        pop = algo.evolve(pop)

        # calculate exact fitness of champion and
        # add it to the trainers set
        champion = NPIndividual(pop.champion_x, cf.bounds, cf.params)
        try:
            champion.fitness = fitness_function(champion, x_train, y_train)
            ts.add_trainer(champion)
        except ValueError:
            print('unsuccessful adding of champion')

        # update random population
        ts.update_random_population()

        predictors.predictors_evolution_step(ts)
        print('changing the subset, best predictor: ',
              predictors.best_predictor.fitness)

        x_reduced, y_reduced = predictors.best_predictors_data()
        pop.problem.extract(object).X = x_reduced
        pop.problem.extract(object).Y = y_reduced
        n_gens += GENS_STEP

    uda = algo.extract(pg.pso)

    champion = NPIndividual(pop.champion_x, cf.bounds, cf.params)
    champion.fitness = fitness_function(champion, x_train, y_train)

    fitnesses = [x[2] for x in uda.get_log()]
    fitnesses.append(champion.fitness)
    return fitnesses
Beispiel #6
0
 def island_run(self):
     algo = pg.algorithm(pg.pso(gen=self.generation))
     pop = pg.population(self.problem, self.pop_size)
     island = pg.island(algo=algo, pop=pop, udi=pg.mp_island())
     island.evolve()
     island.wait()
     pop = island.get_population()
     return pop.champion_f, pop.champion_x
Beispiel #7
0
def ref_pygmo(state,comuna,mov=0.2,qp=0,tsim = 300,tci=None,movfunct='sawtooth'):
    # Total number of inhabitants
    endpoint="http://192.168.2.220:8080/covid19/findComunaByIdState?idState="+state+"&&comuna="+comuna    
    r = requests.get(endpoint) #, params = {"w":"774508"})
    mydict = r.json()
    info=pd.DataFrame(mydict)

    # Active infected
    endpoint = "http://192.168.2.223:5006/getActiveNewCasesByComuna?comuna="+comuna
    r = requests.get(endpoint) #, params = {"w":"774508"})
    mydict = r.json()
    data=pd.DataFrame(mydict)
    if not data.actives.any():
        return

    # Build time vector
    tr=np.zeros(len(data))
    for i in range(1,len(data)):
        diff=dt.datetime.strptime(data.dates[i], '%Y-%m-%d')-dt.datetime.strptime(data.dates[i-1], '%Y-%m-%d')
        tr[i]=diff.days+tr[i-1]    

    if(len(tr)==1):
        return    


    # Get actives:
    Ir = list(data.actives)
    
    S0 = info[info['cut']==comuna].numPopulation.iloc[0]
    I0 = Ir[0]
    R0 = 0
    h=0.01
    
    lb=[0.01,0.1,0.05,1.5]
    ub=[3.5,0.3,0.1,5.5]
    bounds = (lb,ub)

    prob = pg.problem(SEIRModel_pygmo(Ir,tr,S0,I0,R0,h,mov,qp,movfunct,bounds))

    algo = pg.algorithm(pg.pso(gen = 50))
    pop = pg.population(prob,50)    
    pop = algo.evolve(pop)        
    print(pop.champion_f)
    print(pop.champion_x)     
    xopt = pop.champion_x
    fopt = pop.champion_f

    print('error '+str(fopt))
    err_rel = fopt/LA.norm(Ir)
    print('relative error '+str(err_rel))
    sim=intger(S0,xopt[3]*I0,I0,R0,min(tr),tsim,h,xopt[0],xopt[1],xopt[2],mov,qp,tr[-1],movfunct)
    b_date=dt.datetime.strptime(data.dates.loc[0], '%Y-%m-%d')

    tout = range(int(tsim))
    sim['t'] = tout
    return({'Ir':Ir,'tr':tr, 'params':xopt, 'err':fopt,'err_rel':err_rel,'sim':sim, 'init_date':b_date})
Beispiel #8
0
 def run(self, params: dict):
     self.params = copy.copy(params)
     self.prob = pg.problem(self.problem)
     num_ind = self.params.pop('num_ind')
     #self.algo = pg.algorithm(pg.sga(**self.params))
     self.algo = pg.algorithm(pg.pso(**self.params))
     self.algo.set_verbosity(1)
     self.pop = pg.population(self.prob, num_ind)
     self.pop = self.algo.evolve(self.pop)
     return self.pop
Beispiel #9
0
def find_intermediate(desired_point):
    # pro = intermediate_pass_problem("intermediate_pass", desired_point)

    algo = pg.algorithm(pg.pso(gen=10))
    prob = pg.problem(intermediate_pass_problem("intermediate_pass", desired_point))
    pop = pg.population(prob, 10)
    pop = algo.evolve(pop)

    print(pop)
    print("Done plotting the best point")
    return [pop.champion_x[0], pop.champion_x[1]]
Beispiel #10
0
def find_best():
    print("Finding the best point for this cost function. Please wait...")
    a = best_location_problem("best_location")

    algo = pg.algorithm(pg.pso(gen=10))
    prob = pg.problem(best_location_problem("name is cool"))
    pop = pg.population(prob, 10)
    pop = algo.evolve(pop)

    print(pop)
    print("Done plotting the best point")

    return [pop.champion_x[0], pop.champion_x[1]]
Beispiel #11
0
def get_island(evaluate, params, hooks):
    # config
    # D = 8  decision space dimension
    # N0 = 100  initial population
    # Ng = 100  total generation
    D, Ng, N0 = itemgetter('D', 'Ng', 'N0')(params)

    algo = pg.algorithm(pg.pso(gen=Ng))
    algo.set_verbosity(int(Ng / 10))
    prob = pg.problem(evaluate_wrapper(D, evaluate))
    island = pg.island(algo=algo, prob=prob, size=N0, udi=pg.mp_island())

    return island
Beispiel #12
0
def solver(dimension, lower_bound, upper_bound, optim, bias, popsize):
    global algo
    global pop
    global niter
    global log
    global curve
    prob = pg.problem(ackley_prob(dimension, lower_bound, upper_bound, optim, bias))
    algo = pg.algorithm(pg.pso(gen=8000, omega=0.6, eta1=2, eta2=4, max_vel=0.5, variant=5, neighb_type=2, neighb_param=4))
    algo.set_verbosity(1)
    pop = pg.population(prob, popsize)
    pop = algo.evolve(pop)
    log = algo.extract(pg.pso).get_log()
    curve = [x[2] for x in log]
    niter = log[-1][0]
    return prob, algo, pop, log, niter, curve
Beispiel #13
0
async def optimize(evaluate, configs):
    # config
    # D = 8  decision space dimension
    # N0 = 100  initial population
    # Ng = 100  total generation
    D, Ng, N0 = itemgetter('D', 'Ng', 'N0')(configs)

    algo = pg.algorithm(pg.pso(gen=Ng))
    algo.set_verbosity(int(Ng / 10))
    prob = pg.problem(evaluate_wrapper(D, evaluate))
    pop = pg.population(prob, N0)

    await asyncio.sleep(0)
    pop = algo.evolve(pop)
    gbest = (pop.champion_x, pop.champion_f)

    return gbest
Beispiel #14
0
def run_benchmark(cp, x_train, y_train, funset):
    ib, params, bounds = define_cgp_system(
        cp.getint('CGPPARAMS', 'n_nodes'),
        x_train.shape[1] if len(x_train.shape) > 1 else 1,
        y_train.shape[1] if len(y_train.shape) > 1 else 1, funset,
        cp.getint('CGPPARAMS', 'max_back'))
    cf = cost_function(x_train, y_train, params, bounds)
    prob = pg.problem(cf)
    algo = pg.algorithm(
        pg.pso(gen=cp.getint('DEFAULT', 'gens'),
               omega=cp.getfloat('OPTIMPARAMS', 'omega'),
               eta1=cp.getfloat('OPTIMPARAMS', 'eta1'),
               eta2=cp.getfloat('OPTIMPARAMS', 'eta2')))
    algo.set_verbosity(1)
    pop = pg.population(prob, cp.getint('DEFAULT', 'population_size'))
    pop = algo.evolve(pop)
    uda = algo.extract(pg.pso)

    return [x[2] for x in uda.get_log()]
Beispiel #15
0
    def run(self, pop_size=100, gen=100, **kwargs):
        """
        Run optimization with parameters.
        A range of options can be pass into optimization
        depth_of_discharge=1, discharge_rate=0.005, battery_eff=0.9, discharge_eff=0.8,title=0, azim=0, tracking=0,
        power_coefficient=0.3, cut_in_speed=2, cut_off_speed=15, technology='csi', system_loss=0.10

        :param pop_size: Population size for the optimization
        :param gen: Generations to be run
        :param kwargs:
        :return:
        """
        prob = pg.problem(
            Single_mixed_objective_optimization_function(
                self.route, self.start_time, self.speed, self.demand,
                self.ship, **kwargs))
        algo = pg.algorithm(pg.pso(gen=gen))
        pop = pg.population(prob, pop_size)
        pop = algo.evolve(pop)
        self.champion = pop.champion_x
        return pop.champion_f, pop.champion_x
Beispiel #16
0
import pygmo as po
import numpy as np
import myUDP
import time

band = 3

generations = 500
sizePop = 25
pathsave = '/Users/p277634/python/kaoModel/optimResult/'
#pathsave    = ''
filenameTXT = 'pso_Bandfit_' + str(band) + '.txt'
filenameNPZ = 'pso_Bandfit_' + str(band) + '.npz'

# algorithm
algo = po.algorithm(po.pso(gen=generations))
algo.set_verbosity(1)
# problem
prob = po.problem(myUDP.KMAOsimpleFitBand(band=band))
# population
pop = po.population(prob=prob, size=sizePop, seed=22)

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

# save TXT fie with general description of the optimization
bestFstr = 'champion fitness: ' + str(
    popE.champion_f[0]) + '; best fit possible: -1'
bestChamp = 'champion decission vector'
Beispiel #17
0
def chi_optimize(method='pso',
                 parallel=False,
                 N_ind=100,
                 N_gen=30,
                 iset=0,
                 show_results=False,
                 dir='../data/',
                 file_name='chi_fit'):
    # Load experimental data
    N_set = 2
    ca_data = svu.loaddata('../data/herzog_data.pkl')[0]
    po_data = svu.loaddata('../data/fit_po.pkl')[0]
    lr_data = svu.loaddata('../data/fit_lra.pkl')[0]

    # Get boundary dictionary
    bounds_dict = models.model_bounds(model='chi')
    # Save effective bounds and scaling
    bounds, scaling = bounds_for_exploration(bounds_dict, normalized=False)

    # Prepare model parameters
    c0 = 5.0
    # c0 = 15.0
    params = np.asarray(np.r_[po_data[[0, 1, 0, 2, 3]], lr_data[[0, 1]], c0,
                              iset])
    args = (params, ca_data)

    #-----------------------------------------------------------------------------------------------------------
    # Effective evolution
    #-----------------------------------------------------------------------------------------------------------
    # Size parameters
    # N_var = problem_dimension(model='lra')
    N_individuals = N_ind
    N_var = problem_dimension(model='chi')
    N_generations = N_gen * N_var

    # Tolerances
    FTOL = 1e-6
    XTOL = 1e-6

    # prob = pg.problem(fit_problem('lra',args))
    prob = pg.problem(fit_problem('chi', args))

    # Optimization
    # NOTE: We keep each algorithm self contained here because different setting of parameters for evolution are
    # needed depending on the chose algorithm
    if method == 'pso':
        algo = pg.algorithm(
            pg.pso(gen=N_generations, variant=5, neighb_type=4, max_vel=0.8))
    elif method == 'bee':
        algo = pg.algorithm(pg.bee_colony(gen=N_generations, limit=2))
    elif method == 'de':
        algo = pg.algorithm(pg.de(gen=N_generations, ftol=FTOL, tol=XTOL))
        # Single-node optimation to run on local machine / laptop
        # N_individuals = 100
        # N_generations = 40 * N_var
        # verbosity = 20

    if not parallel:
        verbosity = 20
        algo.set_verbosity(verbosity)
        pop = pg.population(prob, size=N_individuals)
        pop = algo.evolve(pop)

        best_fitness = pop.get_f()[pop.best_idx()]
        print(best_fitness)

        x_rescaled = rescale_vector(pop.champion_x,
                                    model='chi',
                                    normalized=True,
                                    bounds=bounds,
                                    scaling=scaling)

        # Show results of fit
        if show_results:
            astro = models.Astrocyte(
                model='chi',
                d1=po_data[0],
                d2=po_data[1],
                d3=po_data[0],
                d5=po_data[2],
                a2=po_data[3],
                c0=c0,
                c1=0.5,
                rl=0.1,
                Ker=0.1,
                rc=lr_data[0],
                ver=lr_data[1],
                vbeta=x_rescaled[0],
                vdelta=x_rescaled[1],
                v3k=x_rescaled[2],
                r5p=x_rescaled[3],
                ICs=np.asarray([x_rescaled[6], x_rescaled[4], x_rescaled[5]]))

            options = su.solver_opts(t0=ca_data['time'][iset][0],
                                     tfin=ca_data['time'][iset][-1],
                                     dt=1e-4,
                                     atol=1e-8,
                                     rtol=1e-6,
                                     method="gsl_msadams")
            astro.integrate(algparams=options, normalized=True)

            ca_trace = ca_data['smoothed'][iset]
            plt.plot(ca_data['time'][0], ca_trace, 'k-', astro.sol['ts'],
                     astro.sol['ca'], 'r-')
            plt.show()

    else:
        # Parallel version to run on cluster
        N_evolutions = 100
        N_islands = 10
        # Initiate optimization
        algo = pg.algorithm(
            pg.pso(gen=N_generations, variant=5, neighb_type=4, max_vel=0.8))
        archi = pg.archipelago(n=N_islands,
                               algo=algo,
                               prob=prob,
                               pop_size=N_individuals)
        archi.evolve(N_evolutions)
        archi.wait()
        imin = np.argmin(archi.get_champions_f())
        x_rescaled = rescale_vector(archi.get_champions_x()[imin],
                                    model='chi',
                                    normalized=True,
                                    bounds=bounds,
                                    scaling=scaling)
        print archi.get_champions_f()[imin]
        print x_rescaled

    svu.savedata([x_rescaled], dir + file_name + '.pkl')

class WrapOptimSingleObjectiveUnconstraint(WrapOptim):
    def __init__(self):
        super().__init__()
        self.constraint_penalty = 1000

    def get_nobj(self):
        return 1

    def get_nic(self):
        return 0

    def fitness(self, x):
        old_fitness = super().fitness(x)
        final_fitness = 0
        for idx in range(super().get_nobj()):
            final_fitness += old_fitness[idx] * old_fitness[idx]
        for idx in range(super().get_nic()):
            if old_fitness[idx] > 0:
                final_fitness += old_fitness[idx] * old_fitness[
                    idx] * self.constraint_penalty
        return [final_fitness]


prob = pg.problem(WrapOptimSingleObjectiveUnconstraint())
pop = pg.population(prob, size=nb_population)
algo = pg.algorithm(uda=pg.pso(gen=50))
pop = algo.evolve(pop)
print(pop)
Beispiel #19
0
 def _setup_algorithm(self, parameters):
     alg = pg.pso(**self._alg_attrs)
     return alg
Beispiel #20
0
 def run(self):
     algo = pg.algorithm(pg.pso(gen=self.generation))
     pop = pg.population(self.problem, self.pop_size)
     pop = algo.evolve(pop)
     self.champion = pop.champion_x
     return pop.champion_f, pop.champion_x
Beispiel #21
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)
Beispiel #22
0
def mySADE(n_trials, n_gen, p_size, new_parameters, n_servers, offset):
    # uda = pg.sade(gen=n_gen, variant=7, variant_adptv=1, memory=False, seed=1234, ftol=1e-3, xtol=1e-3)
    # pso from pygmo
    udas = []
    udas.append(
        pg.pso(gen=n_gen, omega=0.7298, eta1=2.05, eta2=2.05, max_vel=0.5, variant=5, neighb_type=2, memory=True,
               seed=1234))

    # pso from slides
    # udas.append(
    #     pg.pso(gen=n_gen, omega=0.7298, eta1=1.49618, eta2=1.49618, memory=True, seed=1234, max_vel=0.5, variant=5,
    #            neighb_type=2))
    #
    # udas.append(pg.sade(gen=n_gen, variant=7, variant_adptv=1, memory=False, seed=1234, ftol=1e-3, xtol=1e-3))
    # udas.append(pg.sade(gen=n_gen, variant=8, variant_adptv=1, memory=False, seed=1234, ftol=1e-3, xtol=1e-3))
    # udas.append(pg.sade(gen=n_gen, variant=18, variant_adptv=1, memory=False, seed=1234, ftol=1e-3, xtol=1e-3))

    # algo = pg.algorithm(pg.gaco(10, 13, 1.0, 1e9, 0.0, 1, 7, 100000, 100000, 0.0, 10, 0.9, False, 23))

    # #MULTIOBJ UDAS
    # udas.append(
    #     pg.moead(gen=n_gen, weight_generation="grid", decomposition="tchebycheff", neighbours=20, CR=1, F=.9, eta_m=20))
    # udas.append(
    #     pg.moead(gen=n_gen, weight_generation="low discrepancy", decomposition="tchebycheff", neighbours=20, CR=1,
    #              F=.9, eta_m=20,))
    # udas.append(
    #     pg.moead(gen=n_gen, weight_generation="grid", decomposition="weighted", neighbours=20, CR=1, F=.9, eta_m=20))
    # udas.append(
    #     pg.moead(gen=n_gen, weight_generation="low discrepancy", decomposition="weighted", neighbours=20, CR=1,
    #              F=.9, eta_m=20))

    plotting = []
    P = used_parameters
    global_results = []
    print namestr(P, globals())
    par_name = namestr(P, globals())[0]
    today = datetime.datetime.now().day

    print "Starting servers"
    servers = []
    for i in range(n_servers):
        servers.append(ServerTorcs.ServerTorcs(port=3001 + i + offset))
        servers[i].start()
        time.sleep(.5)
    print "Servers started"

    for index, uda in enumerate(udas):
        logs = []
        algo = pg.algorithm(uda)
        new_algo_name = algo.get_name().replace(" ", "").replace(":", "")
        results_trial = []

        time.sleep(1)
        print ('uda:', index)

        for j in range(0, n_trials):
            # prob1 = pg.problem(myProblem(n_servers, index))
            prob1 = pg.problem(
                myProblem(n_servers, index + j, par_name, n_gen, p_size, today, new_algo_name,
                          new_parameters, offset))
            # prob1 = pg.problem(myProblemMultiobj(n_servers, index))

            log_trial = []
            algo.set_verbosity(1)
            pop = pg.population(prob1, p_size, seed=j + index)
            # pop_inj = [3.15392734e+01, 4.06351818e+03, 4.97105933e+03, 1.21724869e-02,
            #            8.46515570e+03, 4.20830027e+03, 3.36044504e+01, 8.29855857e+02,
            #            7.34442849e+03, 2.31965057e-01, 1.12100314e+02, 8.61982701e-04,
            #            7.69219306e+03, 1.64014121e+00, 9.21010307e+00, 3.05622329e+00,
            #            4.25427737e-02, 5.29581177e+03, 4.43502782e-01, 3.48692685e+01,
            #            6.78188600e+03, 7.64180124e+01, 4.51893080e-01, 1.00028542e-04,
            #            2.55765200e+01, 2.55946953e+00, 1.06115486e-01, 8.31605221e-02,
            #            3.73600771e-01, 5.80222129e-01, 9.95582187e-01, 8.34279341e+03,
            #            1.96224119e+02, 2.47433910e-02, 9.08202495e+00, 2.34373462e+00,
            #            1.72508422e-01, 2.45826790e-01, 1.25945279e+01, 7.14638162e-01,
            #            4.51873959e-01, -3.13286844e-01, 2.71382726e+00, 4.68865255e+02,
            #            2.15839339e+00, 2.91927274e+00, 2.22224571e+00, 1.57180463e+00,
            #            7.34361953e-01, 3.11895138e+03]
            # pop.push_back(pop_inj)
            algo.evolve(pop)
            log_trial.append(algo.extract(type(uda)).get_log())
            log_trial = np.array(log_trial)
            results_trial.append(np.min(log_trial[:, log_trial.shape[1] - 1, 2]))
            # print "trial", j, "--", results_trial
            plotting.append(log_trial)

        logs.append(algo.extract(type(uda)).get_log())
        logs = np.array(logs)
        # print "logs", logs
        avg_log = np.average(logs, 0)
        # print "avg_log", avg_log
        global_results.append(np.min(results_trial, 0))
        plt.plot(avg_log[:, 1], avg_log[:, 2], label=algo.get_name() + str(index))
        if n_trials > 1:
            for j, elem in enumerate(plotting):
                plt.plot(elem[0][:, 1], elem[0][:, 2], label=str(j))

        # print "plotting", plotting
        # print "-------------------"
        # for elem in plotting:
        #     print elem
        #     for ele in elem:
        #         print ele
        #         for el in ele:
        #             print el

        for i, key in enumerate(P):
            P[key] = pop.champion_x[i]

        with open(new_parameters + "_BEST_" + par_name + "_nGen" + str(n_gen) + "_pSize" + str(p_size) + "_circ" + str(
                n_servers) + "_" + new_algo_name + str(index + j) + "_today" + str(today) + ".txt",
                  'w') as outfile:
            json.dump(P, outfile)

        with open(
                new_parameters + "_GenBest_" + par_name + "_nGen" + str(n_gen) + "_pSize" + str(p_size) + "_circ" + str(
                    n_servers) + "_" + new_algo_name + str(index + j) + "_today" + str(
                    today) + ".txt", 'w') as outfile:
            outfile.write(str(algo.extract(type(uda)).get_log()))

    print("global results: ", global_results)

    for i, key in enumerate(P):
        P[key] = pop.champion_x[i]
    os.chdir(r"C:\Users\Vincenzo\Documents\GitHub\ComputazioneNaturale\snakeoil2015")
    print "champion_x", pop.champion_x
    print "champion_f", pop.champion_f
    with open("def_param.py", 'a') as outfile:
        outfile.write("\n")
        outfile.write(new_parameters + " = " + str(P))
    with open(new_parameters + ".txt", 'w') as outfile:
        json.dump(P, outfile)
    # We then add details to the plot
    if n_trials < 2:
        plt.legend()
    plt.grid()
    plt.show()
Beispiel #23
0
def main():
    #Hyperparameters
    #---------------

    ind_best_weight = 1.19314
    neigh_best_weight = 1.19314
    intertia_weigth = 0.72134

    #1 - gbest
    #2 - lbest
    #3 - Von Neumann
    #4 - Adaptive random
    neighb_topology = 4

    #Number of K informants for the Adaptative Random neighborhood
    neighb_param = 3

    #1 - Canonical (with inertia weight)
    #2 - Same social and cognitive rand.
    #3 - Same rand. for all components
    #4 - Only one rand.
    #5 - Canonical (with constriction fact.)
    #6 - Fully Informed (FIPS)
    pso_variant = 1

    #Number of particles in the swarm
    swarm_size = 40

    #Select problem and dimensions
    #application_window = tk.Tk()
    f_problem = int(
        input("What problem (F) do you want to optimize? (1 to 6): "))
    dimensions = int(input("For how many dimensions? (1 to 500): "))
    generations = int(input("Maximum number of iterations? (1 to 500): "))

    sel_func = functions(f=f_problem, dim=dimensions)

    print('\n----------------------------------------------')
    print('\nFunction: ', sel_func.f.f_name)
    print('\nDimensions: ', dimensions)
    print('\nGenerations: ', generations)

    #Solver
    #------
    print('\n----------------------------------------------')
    print('\nOptimization Running...')
    start = time.time()

    prob = pg.problem(sel_func)
    print('\n{}', prob)
    pop = pg.population(prob, size=swarm_size)
    algo = pg.algorithm(
        pg.pso(gen=generations,
               omega=intertia_weigth,
               eta1=neigh_best_weight,
               eta2=ind_best_weight,
               max_vel=1,
               variant=pso_variant,
               neighb_type=neighb_topology,
               neighb_param=neighb_param,
               memory=False,
               seed=123))
    algo.set_verbosity(1)
    pop = algo.evolve(pop)
    log = algo.extract(pg.pso).get_log()

    best_fitness = pop.get_f()[
        pop.best_idx()]  # Getting the best individual in the population
    print('\n----------------------------------------------')
    print('\nResult:')
    print('\nBest fitness: ', best_fitness)  # Get the best parameter set
    best_parameterset = pop.get_x()[pop.best_idx()]
    print('\nBest parameter set: ', best_parameterset)
    print('\nTime elapsed for optimization: ',
          time.time() - start, ' seconds\n')

    #Plot convergence curve (Iterations)
    x = [x[0] for x in log]
    y = [y[2] for y in log]
    z = [z[1] for z in log]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x, y, color='lightblue', linewidth=1)
    ax.set_xlim(1, generations)
    plt.suptitle("Convergence curve by generation")
    plt.show()

    #For 2D
    if (dimensions == 2) and (f_problem != 5):
        #Plot last swarm and best particle in contour plot
        f1 = functions(f=f_problem, dim=dimensions)
        x = np.arange(f1.bounds[0][0], f1.bounds[1][1], 1)
        y = np.arange(f1.bounds[0][0], f1.bounds[1][1], 1)
        z = f1.contour
        h = plt.contourf(x, y, z)
        plt.plot(pop.get_x()[:, 0], pop.get_x()[:, 1], 'b+')
        plt.plot(pop.get_x()[pop.best_idx()][0],
                 pop.get_x()[pop.best_idx()][1], 'r+')
        plt.show()
def ref_sim_pygmo(state,
                  comuna,
                  mov=0.2,
                  qp=0,
                  tsim=300,
                  tci=None,
                  movfunct='sawtooth'):
    # Region, comuna, movilidad durante cuarentena, periodo cuarenetena, tiempo simulacion, tiempo inicial cuarentena

    # Total number of inhabitants
    endpoint = "http://192.168.2.220:8080/covid19/findComunaByIdState?idState=" + state + "&&comuna=" + comuna
    r = requests.get(endpoint)  #, params = {"w":"774508"})
    mydict = r.json()
    info = pd.DataFrame(mydict)

    # Total number of infected people
    endpoint = "http://192.168.2.220:8080/covid19/getDatosMinSalSummary?state=" + state + "&comuna=" + comuna
    r = requests.get(endpoint)  #, params = {"w":"774508"})
    mydict = r.json()
    data = pd.DataFrame(mydict)
    data = data[data.data != 0]
    data = data.reset_index()
    #if not data.data.any():
    #    return

    tr = np.zeros(len(data.data))
    for i in range(1, len(data.data), 1):
        diff = dt.datetime.strptime(data.labels[i],
                                    '%d/%m') - dt.datetime.strptime(
                                        data.labels[i - 1], '%d/%m')
        tr[i] = diff.days + tr[i - 1]

    #if(len(tr)==1):
    #    return

    Cn = np.zeros(data.data.shape[0])
    Cn[0] = data.data.iloc[0]
    for i in range(1, len(Cn), 1):
        Cn[i] = data.data[i] - data.data[i - 1]

    Ir = np.zeros(data.data.shape[0])
    Ir[np.where(tr - 14 <= 0)] = data.data.iloc[np.where(tr - 14 <= 0)]
    for i in np.where(tr - 14 > 0)[0]:
        ind = np.where(tr - tr[i] + 14 < 0)[0]
        Ir[i] = data.data[i] - sum(Cn[0:ind[-1]])

    S0 = info[info['cut'] == comuna].numPopulation.iloc[0]
    I0 = Ir[0]
    R0 = 0
    h = 0.01

    lb = [0.01, 0.1, 0.05, 1.5]
    ub = [3.5, 0.3, 0.1, 5.5]
    bounds = [lb, ub]

    # Create pygmo problem
    seirmodel = SEIRModel(Ir, tr, S0, I0, R0, h, mov, qp, movfunct, bounds)
    prob = pg.problem(seirmodel)
    print(prob)

    # Choose pygmo algorithm
    #algo = pg.algorithm(pg.bee_colony(gen = 20, limit = 20))
    algo = pg.algorithm(pg.pso(gen=20))

    # Create population: Number of particules in swarm
    pop = pg.population(prob, 10)
    pop = algo.evolve(pop)
    #print(pop.champion_f)
    err = pop.champion_f[0]

    xopt = pop.champion_x
    print('error ' + str(err))
    print('rel_error ' + str(err / LA.norm(Ir)))
    sim = edosolve(S0, xopt[3] * I0, I0, R0, min(tr), tsim, h, xopt[0],
                   xopt[1], xopt[2], mov, qp, tr[-1], movfunct)
    b_date = dt.datetime.strptime(data.labels.loc[0], '%d/%m')

    tout = range(int(tsim))
    #idx=np.searchsorted(tr,tout)
    #sim['S'] = sim['S'][idx]
    #sim['E'] = sim['E'][idx]
    #sim['I'] = sim['I'][idx]
    #sim['R'] = sim['R'][idx]
    sim['t'] = tout
    return ({
        'Ir': Ir,
        'tr': tr,
        'params': xopt,
        'err': err,
        'sim': sim,
        'init_date': b_date
    })
Beispiel #25
0
    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,
             label=algo.get_name())
Beispiel #26
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))))
Beispiel #27
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)")
Beispiel #28
0
        res = LA.norm(self.Ir - sol.I[idx])
        return ([res])

    def get_bounds(self):
        return (self.bounds)

    def set_bounds(self, bounds):
        self.bounds = bounds
        return (self.bounds)

    def get_name(self):
        return "SEIR Unsectorial"


# PSO Normal
algo = pg.algorithm(pg.pso(gen=20))
pop = pg.population(prob, 50)
t0 = time()
pop = algo.evolve(pop)
t1 = time()
print('Optimization takes %f seconds' % (t1 - t0))
print(pop.champion_f)
print(pop.champion_x)

# PSO Mejorada
algo = pg.algorithm(pg.pso_gen(gen=50, memory=True, variant=6))
pop = pg.population(prob, 50)
t0 = time()
pop = algo.evolve(pop)
t1 = time()
print('Optimization takes %f seconds' % (t1 - t0))
            #to then remove the worst individual
            #pop.erase(pop.get_worst_idx())
            #at the end of it all we return the 'evolved' population
            return pop

    def get_name(self):
        return "Monte Carlo (Python)"

    def human_readable_extra(self):
        return "n_iter=" + str(self.__n_iter)


if __name__ == '__main__':
    gp = GrowthOptimization()
    prob = pg.problem(gp)
    algo = pg.algorithm(pg.pso(gen=300))
    #algo = MonteCarlo(100)
    try:
        if not runParallel:
            pop = pg.population(prob, 40)
            print(dir(pop))
            pop = algo.evolve(pop)

            print(pop.champion_f)
        else:
            archi = pg.archipelago(n=16,
                                   algo=algo,
                                   prob=prob,
                                   pop_size=20,
                                   seed=32)
            archi.evolve()
Beispiel #30
0
                      grid,
                      targetSpeed_mps=targetSpeed_mps,
                      waypoints=numWaypoints,
                      bounds=bounds,
                      weights=weights,
                      currentsGrid_u=currentsGrid_u,
                      currentsGrid_v=currentsGrid_v,
                      currentsTransform=currentsTransform_u,
                      regionTransform=regionTransform,
                      rewardGrid=rewardGrid,
                      timeIn=timeOffset_s,
                      interval=timeInterval_s,
                      pixelsize_m=pixelsize_m))
        algo = pg.algorithm(
            pg.pso(gen=generations,
                   omega=hyperparams[1],
                   eta1=hyperparams[2],
                   eta2=hyperparams[3]))
        algo.set_verbosity(10)

        # Generate initial population
        if initPopFile is not None:
            # Load initial population from file
            pop = pg.population(
                prob, 0)  # Ignore pool_size; filling population from file

            # Read file
            with open(initPopFile) as f:
                lines = [line.rstrip() for line in f]
                lines.reverse()

            # Process each line