def run_example3(): import pygmo as pg from pykep.examples import add_gradient, algo_factory # problem udp = add_gradient(mga_lt_EVMe(), with_grad=False) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # algorithm uda = algo_factory("snopt7", False) uda2 = pg.mbh(uda, 5, 0.05) algo = pg.algorithm(uda2) algo.set_verbosity(1) # 3 - Population pop = pg.population(prob, 1) # 4 - Solve the problem (evolve) print("Running Monotonic Basin Hopping ....") pop = algo.evolve(pop) print("Is the solution found a feasible trajectory? " + str(prob.feasibility_x(pop.champion_x))) udp.udp_inner.plot(pop.champion_x)
def run_example4(): import pygmo as pg from pykep.examples import add_gradient, algo_factory N = 20 # problem udp = add_gradient(mga_lt_earth_mars_sundmann(nseg=N), with_grad=False) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # algorithm uda = algo_factory("snopt7", False) uda2 = pg.mbh(uda, 5, 0.05) algo = pg.algorithm(uda2) algo.set_verbosity(1) # 3 - Population pop = pg.population(prob, 1) # 4 - Solve the problem (evolve) print("Running Monotonic Basin Hopping ....") pop = algo.evolve(pop) print("Is the solution found a feasible trajectory? " + str(prob.feasibility_x(pop.champion_x))) udp.udp_inner.plot(pop.champion_x)
def method_b(): algo = pg.algorithm(uda=pg.mbh(pg.nlopt("slsqp"), stop=20, perturb=.2)) print(algo) algo.set_verbosity( 1) # in this case this correspond to logs each 1 call to slsqp pop = pg.population(prob=UdpConstrained(), size=1) pop.problem.c_tol = [1E-6] * 6 pop = algo.evolve(pop)
def run_rui2016(**kwargs): # a new optimisation problem n_rb = kwargs['n_rb'] n_cc = kwargs['n_cc'] n_pairs = kwargs['n_pairs'] prob = Rui2016(**kwargs) # start simulation # prob.gen_cc_ues() # prob.gen_d2d_pairs() # start optimisation nl = pg.nlopt('slsqp') nl.xtol_rel = 1e-3 algo = pg.algorithm(uda=pg.mbh(nl, stop=3)) pop = pg.population(prob=prob, size=1) pop.problem.c_tol = [1e-3] * (n_cc + n_pairs) pop = algo.evolve(pop) return pop
def optimize(self, niter=500, minimizer_kwargs=None, nmin=1000, kforce=100., gradient=False, print_fun=None, popsize=50, stepsize=0.05, optimizer="evolution", seed=None): self.kforce = kforce if type(seed) == type(None): seed = np.random.randint(999999) else: seed = int(seed) np.random.seed(seed) pygmo.set_global_rng_seed(seed=seed) self.set_x0() bounds = gist_bounds(self.xmin, self.xmax, Tconst=True) min_bounds = bounds.get_bounds_for_minimizer() if optimizer == "evolution": ### This works , because pygmo makes deepcopies of this object ### in order to remain "thread safe" during all following operations prob = pygmo.problem(self) if self.decomp: if (popsize % 4) != 0: popsize = (popsize / 4) * 4 if popsize < 5: popsize = 8 pop = pygmo.population(prob=prob, size=popsize) if self.decomp: ### For NSGA2, popsize must be >4 and also ### a multiple of four. algo = pygmo.algorithm(pygmo.nsga2(gen=niter)) #algo = pygmo.algorithm(pygmo.moead(gen=niter)) else: algo = pygmo.algorithm(pygmo.sade(gen=niter)) if self.verbose: algo.set_verbosity(1) pop = algo.evolve(pop) for x in pop.get_x(): print_fun(x) print_fun.flush() elif optimizer == "brute": self.anal_grad = False self.anal_boundary = False N_dim = self._x0.size niter_count = np.zeros(self._x0.size, dtype=int) for i in range(self._x0.size): self._x0[i] = min_bounds[i][0] _diff = min_bounds[i][1] - min_bounds[i][0] niter_count[i] = int(_diff / stepsize) prop = propagator(self._x0, N_dim, stepsize, niter_count) stop = False _stop = False if nmin > 0: self.anal_grad = True self.anal_boundary = False prob = pygmo.problem(self) pop = pygmo.population(prob=prob, size=1) algo = pygmo.algorithm(pygmo.nlopt("slsqp")) algo.maxeval = nmin if self.verbose: algo.set_verbosity(1) while (not stop): if nmin > 0: self.anal_grad = gradient if self.anal_boundary: min_bounds = None bounds = None pop.set_x(0, self._x0) pop = algo.evolve(pop) x = pop.get_x()[0] else: x = self._x0 if print_fun != None: print_fun(x) print_fun.flush() ### propagate self._x0 prop.add() if _stop: stop = True _stop = prop.are_we_done() elif optimizer == "basinhopping": prob = pygmo.problem(self) pop = pygmo.population(prob=prob, size=popsize) algo = pygmo.algorithm(uda=pygmo.mbh( pygmo.nlopt("slsqp"), stop=100, perturb=self.steps * 0.1)) if self.verbose: algo.set_verbosity(1) pop = algo.evolve(pop) for x in pop.get_x(): print_fun(x) print_fun.flush() else: raise ValueError("Optimizer %s is not known." % optimizer)
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)