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 get_hv_for_algo(algo, max_fevals, pop_size, seed, problem, run): max_gen = math.ceil(max_fevals / pop_size) # same (random) starting population for both algos pop = pg.population(problem, pop_size, seed) f_list, x_list = pop.get_f(), pop.get_x() for i in range(max_gen): pop = algo.evolve(pop) # Get all the f and x values for this generation f_list = numpy.concatenate((f_list, pop.get_f())) x_list = numpy.concatenate((x_list, pop.get_x())) save_values( 'store_x/' + algo.get_name().split(':')[0] + '_x_' + problem.get_name() + '_run' + str(run) + '.txt', x_list.tolist()) save_values( 'store_f/' + algo.get_name().split(':')[0] + '_f_' + problem.get_name() + '_run' + str(run) + '.txt', f_list.tolist()) pop_empty = pg.population(prob=problem, seed=seed) hv_for_run = reconstruct_hv_per_feval(max_fevals, x_list, f_list, pop_empty) save_values( 'store_hv/' + algo.get_name().split(':')[0] + '_hv_ncycle' + '_fevals' + str(max_fevals + 1) + problem.get_name() + '_run' + str(run) + '.txt', hv_for_run) return hv_for_run
def solve(self, otol=1e-5, zguess=None, seperate=False): if seperate: self.segments = self.pool.map(lambda seg: seg.solve(), self.segments) #[seg.solve() for seg in self.segments] else: # set optimisation params self.otol = otol # instantiate optimisation problem prob = pg.problem(self) # instantiate algorithm algo = pg.ipopt() algo.set_numeric_option("tol", self.otol) algo = pg.algorithm(algo) algo.set_verbosity(1) # instantiate and evolve population if zguess is None: pop = pg.population(prob, 1) else: pop = pg.population(prob, 0) pop.push_back(zguess) pop = algo.evolve(pop) # extract soltution self.zopt = pop.champion_x self.fitness(self.zopt) # combine records self.process_records()
def optimise(func, algo_name="sga", population=100, verbosity=100, plot=True, save=True, save_log_x=True, name=None, **kwargs): # Initialise the problem prob = pg.problem(func) # Initialise the algorithms gen = kwargs.get("gen", 10000) if save_log_x: kwargs["gen"] = verbosity iterations = gen / verbosity else: iterations = 1 algorithm = get_algorithm(algo_name, **kwargs) a = pg.algorithm(algorithm) a.set_verbosity(verbosity) # Initialise population if hasattr(func, "x_init"): pop = pg.population(prob, population-1) pop.push_back(func.x_init) else: pop = pg.population(prob, population) print a.get_name() log = np.empty((0, len(get_log(algo_name)))) log_x = np.empty((0, func.ndim)) labels = get_log(algo_name) row_format = "{:>7}" + "{:>15}" * (len(labels)-1) # if save_log_x and verbosity is not None and verbosity > 0: # print row_format.format(*[label.capitalize() + ":" for label in labels]) for it in xrange(iterations): pop = a.evolve(pop) new_log = np.array(a.extract(algorithm.__class__).get_log()) new_log[:, labels.index("gen")] += it * verbosity if save_log_x and verbosity is not None and verbosity > 0: print row_format.format(*["%.4f" % e for e in new_log[0]]) log = np.vstack([log, new_log]) log_x = np.vstack([log_x, pop.champion_x]) f = pop.champion_f x = func.correct_vector(pop.champion_x) if name is None: name = "%s-%s" % (datetime.now().strftime("%Y%m%d"), algo_name) if save: np.savez_compressed(__datadir__ + "%s.npz" % name, x=x, f=f, log=log, log_x=log_x) if plot: plot_log(log, title=name) return x, f, log
def solve(x0, xf, alpha, dv=None, otol=1e-5, iter=200, Tlb=1, Tub=25, lb=100, atol=1e-12, rtol=1e-12): # initialise dynamics dyn = dynamics(x0, xf, alpha, Tlb=Tlb, Tub=Tub, lb=lb, atol=atol, rtol=rtol) # optimisation problem prob = pg.problem(dyn) prob.c_tol = 1e-5 # algorithm algo = pg.ipopt() algo.set_numeric_option("acceptable_tol", otol) algo.set_integer_option("max_iter", iter) algo = pg.algorithm(algo) algo.set_verbosity(1) # guess if dv is None: pop = pg.population(prob, 1) else: pop = pg.population(prob, 0) pop.push_back(dv) # solve dv = algo.evolve(pop).champion_x # feasibility feas = prob.feasibility_x(dv) T = dv[0] l0 = dv[1:] t, y, s, f = dyn.propagate(T, l0) return dv, feas, t, y, dyn.pmp(y.T, alpha)
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.simulated_annealing(Ts=cp.getfloat('OPTIMPARAMS', 'Ts'), Tf=cp.getfloat('OPTIMPARAMS', 'Tf'), n_T_adj=cp.getint('OPTIMPARAMS', 'n_T_adj'), n_range_adj=cp.getint('OPTIMPARAMS', 'n_range_adj'), bin_size=cp.getint('OPTIMPARAMS', 'bin_size'), start_range=cp.getfloat('OPTIMPARAMS', 'start_range'))) algo.set_verbosity(100) pop = pg.population(prob, 1) pop = algo.evolve(pop) uda = algo.extract(pg.simulated_annealing) return [x[2] for x in uda.get_log()]
def find_pulses( cptm: ContinousPulseTransitionsMaker = ContinousPulseTransitionsMaker( 30, (5, 10), 20, 0.3 ), generations: int = DEFAULT_GENERATIONS, population_size: int = DEFAULT_POPULATION_SIZE, seed: int = DEFAULT_SEED, ) -> typing.Tuple[float, ...]: udp = pg.problem(cptm) algorithm = pg.algorithm(pg.gaco(gen=generations, seed=seed)) # algorithm.set_verbosity(1) algorithm.set_verbosity(0) population = pg.population(udp, population_size) resulting_population = algorithm.evolve(population) best_x = resulting_population.champion_x best_fitness = resulting_population.champion_f pulses = cptm._convert_x_to_pulses(best_x) is_valid = best_fitness[1] <= 0 and best_fitness[2] <= 0 if is_valid: print("Found valid solution.") else: msg = "WARNING: FOUND INVALID SOLUTION!" if best_fitness[1] > 0: msg += " Solution is too small." else: msg += " Solution is too big." print(msg) return pulses
def runTest(self): from dcgpy import symbolic_regression, generate_koza_quintic, kernel_set_double, gd4cgp import pygmo as pg import pickle X, Y = generate_koza_quintic() # Interface for the UDPs udp = symbolic_regression(points=X, labels=Y, rows=1, cols=20, levels_back=21, arity=2, kernels=kernel_set_double( ["sum", "diff", "mul", "pdiv"])(), n_eph=2, multi_objective=False, parallel_batches=0) prob = pg.problem(udp) pop = pg.population(prob, 10) # Interface for the UDAs uda = gd4cgp(max_iter=10, lr=0.1, lr_min=1e-6) algo = pg.algorithm(uda) algo.set_verbosity(0) # Testing some evolutions pop = algo.evolve(pop) # In parallel archi = pg.archipelago(prob=prob, algo=algo, n=16, pop_size=4) archi.evolve() archi.wait_check() # Pickling. self.assertTrue(repr(algo) == repr(pickle.loads(pickle.dumps(algo))))
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 optimize(results, dir): pg.mp_bfe.init_pool(50) prob = pg.problem(MotGunOptimizationProblem(dir)) bfe = pg.bfe(pg.mp_bfe()) nsga2 = pg.nsga2() nsga2.set_bfe(bfe) algo = pg.algorithm(nsga2) pop = pg.population(prob=prob, size=256, b=bfe) iteration = 1 while True: print(f"\033[31mITERATION: {iteration}\033[m") plt.title(f'Iteration {iteration}') plt.xlabel('Emittance (nm)') plt.ylabel('Charge (fC)') pg.plot_non_dominated_fronts(pop.get_f()) plt.savefig(results / f'{iteration}.png', dpi=300) plt.clf() assert len(pop.get_x()) == len(pop.get_f()) with open(results / f'iteration_{iteration}.txt', 'w+') as f: f.write( '[Mot Z Offset (mm), Phase (deg)] -> [Emittance 4D sqrt (nm), Charge (fC)]\n' ) for i in range(len(pop.get_x())): f.write('{} -> {}\n'.format(pop.get_x()[i], pop.get_f()[i])) pop = algo.evolve(pop) iteration += 1
def gen_pop(seed, algos, pop_size): prob = pg.problem(sfunc_inst) if nlopt and not seed: algo = pg.algorithm(pg.nlopt(solver="cobyla")) print('[swarms:]'.ljust(15, ' ') + 'On seed ' + str(seed) + ' creating ' + algo.get_name()) algo.extract(pg.nlopt).maxeval = nlopt elif nlopt and seed == 1: algo = pg.algorithm(pg.nlopt(solver="neldermead")) print('[swarms:]'.ljust(15, ' ') + 'On seed ' + str(seed) + ' creating ' + algo.get_name()) algo.extract(pg.nlopt).maxeval = nlopt else: random.seed(seed) algo = random.sample(algos, 1)[0] print('[swarms:]'.ljust(15, ' ') + 'On seed ' + str(seed) + ' creating ' + algo.get_name()) algo.set_seed(seed) pop = pg.population(prob, size=pop_size, seed=seed) ser_pop = dump_pop(pop) ser_algo = cpickle.dumps(algo) return ser_algo, ser_pop
def run(dataset_train, dataset_test, cols, gen): ss = dcgpy.kernel_set_double([ "sum", "diff", "mul", "pdiv", "sin", "cos", "tanh", "log", "exp", "psqrt" ]) Xtrain, ytrain = dataset_train[:, :-1], dataset_train[:, -1] Xtest, ytest = dataset_test[:, :-1], dataset_test[:, -1] udp = dcgpy.symbolic_regression(points=Xtrain, labels=ytrain[:, np.newaxis], kernels=ss(), rows=1, cols=cols, levels_back=21, arity=2, n_eph=3, multi_objective=False, parallel_batches=0) uda = dcgpy.es4cgp(gen=gen) #, mut_n = 1) algo = pg.algorithm(uda) pop = pg.population(udp, 4) pop = algo.evolve(pop) return RMSE(udp.predict(Xtrain, pop.champion_x), ytrain), RMSE(udp.predict(Xtest, pop.champion_x), ytest)
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
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.")
def evaluate_vectors_in_csv(csvpath, codec_arg, rate_control_arg): print("Evaluating vectors of: " + codec_arg + " " + rate_control_arg) cfg.mog_alg = "eval-from-csv" cfg.epoch = 0 cfg.NO_GENERATIONS = 0 cfg.load_params_from_json(codec_arg, rate_control_arg) opt_prob = pyg.problem(sweetspot_problem()) pop = pyg.population(prob=opt_prob) param_sets = [] with open(csvpath) as csv_file: csv_data = csv.reader(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in csv_data: x = row[0] x = x.replace('\n', '').replace('[', '').replace(']', '').replace("'", "").replace('"', "") x = re.sub('\s+', ',', x.strip()) x = x.split(",") x = [elem for elem in x if elem != ""] param_sets.append(x) param_sets = np.asfarray(param_sets,float) cfg.POP_SIZE = len(param_sets) # Evaluate decision vectors for i in trange(len(param_sets)): pset = param_sets[i] pop.push_back(pset)
def main(): # instantiate dynamics dyn = Dynamics() # instantiate leg leg = Leg(dyn, alpha=0, bound=True) # set boudaries t0 = 0 s0 = np.array([1000, 1000, *np.random.randn(4)], dtype=float) l0 = np.random.randn(len(s0)) tf = 1000 sf = np.zeros(len(s0)) leg.set(t0, s0, l0, tf, sf) # define problem udp = Problem(leg, atol=1e-8, rtol=1e-8) prob = pg.problem(udp) # instantiate algorithm uda = pg7.snopt7(True, "/usr/lib/libsnopt7_c.so") uda.set_integer_option("Major iterations limit", 4000) uda.set_integer_option("Iterations limit", 40000) uda.set_numeric_option("Major optimality tolerance", 1e-2) uda.set_numeric_option("Major feasibility tolerance", 1e-4) algo = pg.algorithm(uda) # instantiate population with one chromosome pop = pg.population(prob, 1) #pop = pg.population(prob, 0) #pop.push_back([1000, *l0]) # optimise pop = algo.evolve(pop)
def solve(self, otol=1e-5): # set optimisation params self.otol = otol # instantiate optimisation problem prob = pg.problem(self) # instantiate algorithm algo = pg.ipopt() algo.set_numeric_option("tol", self.otol) algo = pg.algorithm(algo) algo.set_verbosity(1) # instantiate and evolve population pop = pg.population(prob, 1) pop = algo.evolve(pop) # extract soltution self.zopt = pop.champion_x self.fitness(self.zopt) # process records self.process_records() return self
def optimizationSetup(problem): ''' Setup Pygmo for the given problem ''' nl = pg.nlopt('neldermead') pop = pg.population(problem, 1) nl.xtol_rel = 1E-6 nl.maxeval = 10_000 algo = pg.algorithm(nl) algo.set_verbosity(100) pop = pg.population(problem, 1) pop.set_x(0, [0, 0, 0, 0, 0, 0]) initialGuess = pop.get_x()[pop.best_idx()] return pop, algo, initialGuess
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
def full_index_refine(self, rec_basis, num_ap, n_isl=20, pop_size=50, gen_num=2000, pos_tol=(0.007, 0.014, 0.06), rb_tol=0.12): """ Return refinement problems archipelago rec_basis - preliminary reciprocal lattice basis vectors matrix num_ap = [num_ap_x, num_ap_y] - convergent beam numerical apertures in x- and y-axes n_isl - number of islands of one frame pop_size - population size gen_num - maximum generations number of the refinement algorithm pos_tol - relative sample position tolerance rb_tol - lattice basis vectors matrix tolerance """ archi = pygmo.archipelago() for frame_idx, frame_strks in enumerate(iter(self)): frame_basis = rec_basis.dot( self.exp_set.rotation_matrix(frame_idx)) prob = frame_strks.rot_index_refine(rec_basis=frame_basis, num_ap=num_ap, pos_tol=pos_tol, rb_tol=rb_tol) pops = [ pygmo.population(size=pop_size, prob=prob, b=pygmo.mp_bfe()) for _ in range(n_isl) ] for pop in pops: archi.push_back(algo=pygmo.de(gen_num), pop=pop) return archi
def solver(dimension, lower_bound, upper_bound, optim, bias, popsize): global algo global pop global niter global log global curve prob = pg.problem( rastrigin_prob(dimension, lower_bound, upper_bound, optim, bias)) algo = pg.algorithm( pg.sga(gen=2000, cr=0.9, eta_c=2.0, m=0.02, param_m=1.0, param_s=2, crossover='binomial', mutation='gaussian', selection='truncated')) algo.set_verbosity(1) pop = pg.population(prob, popsize) pop = algo.evolve(pop) log = algo.extract(pg.sga).get_log() curve = [x[2] for x in log] niter = log[-1][0] return prob, algo, pop, log, niter, curve
def genetic_algorithm(explr_p): prob = pg.problem(GeneticAlgoProblem()) #sade = pg.sade(gen=1, ftol=1e-20, xtol=1e-20) population_size = 5 if obj_fcn == 'griewank' or dim_x == 3: total_evals = 500 elif obj_fcn == 'shekel' and dim_x == 20: total_evals = 5000 else: total_evals = 1000 generations = total_evals / population_size optimizer = pg.cmaes(gen=generations, ftol=1e-20, xtol=1e-20) algo = pg.algorithm(optimizer) algo.set_verbosity(1) pop = pg.population(prob, size=population_size) pop = algo.evolve(pop) print pop.champion_f champion_x = pop.champion_x uda = algo.extract(pg.cmaes) log = np.array(uda.get_log()) n_fcn_evals = log[:, 1] pop_best_at_generation = -log[:, 2] evaled_x = None evaled_y = pop_best_at_generation max_y = [pop_best_at_generation[0]] for y in pop_best_at_generation[1:]: if y > max_y[-1]: max_y.append(y) else: max_y.append(max_y[-1]) return evaled_x, evaled_y, max_y, 0
def _fit_impl(self, objective, parameters): ndim = len(parameters.infos()) minimums = ndim * [-np.inf] maximums = ndim * [+np.inf] initials = np.empty((ndim, self._size)) # for i, pinfo in enumerate(parameters.infos().values()): for i, name in enumerate(parameters.names()): pinfo = parameters.infos()[name] minimum = pinfo.minimum() maximum = pinfo.maximum() value = pinfo.initial_value() scale = pinfo.initial_scale() has_init = pinfo.has_initial() init_min = value - 0.5 * scale if has_init else minimum init_max = value + 0.5 * scale if has_init else maximum init_min = max(init_min, minimum) init_max = min(init_max, maximum) initials[i, :] = random.uniform(init_min, init_max, self._size) minimums[i] = minimum maximums[i] = maximum # print(parameters.names()) #exit() prb = pg.problem(Problem(objective, parameters, minimums, maximums)) alg = pg.algorithm(self._setup_algorithm(parameters)) alg.set_verbosity(self._verbosity) pop = pg.population(prb, size=self._size, seed=self._seed) for i in range(self._size): pop.set_x(i, initials[:, i]) pop = alg.evolve(pop) solution = dict(mode=pop.champion_x) result = make_fitter_result(objective, parameters, solutions=solution) return result
def main(argv): help_message = 'test.py <inputfile> <outputfile>' if len(argv) < 2: print(help_message) sys.exit(2) else: inputfile = argv[0] outputfile = argv[1] print("Reading data from " + inputfile) # Setting up the user defined problem in pygmo prob = pg.problem(TestOptimizer(inputfile)) solution_size = 8 # Start with an initial set of 100 sets pop = pg.population(prob, size=solution_size) # Set the algorithm to non-dominated sorting GA algo = pg.algorithm(pg.nsga2(gen=40)) # Optimize pop = algo.evolve(pop) # This returns a set of optimal vectors and corresponding fitness values fits, vectors = pop.get_f(), pop.get_x() print("Writing output to " + outputfile) jsonfile = pygeoj.load(filepath=inputfile) num_districts = len(jsonfile) counter = 0 for feature in jsonfile: for sol in range(solution_size): feature.properties = {"sol" + str(sol): str(vectors[sol][counter])} counter += 1 # Save output jsonfile.save(outputfile)
def nsga2(ppn): print('*** NSGA-II ALGORITHM ***') # INSTANCIATE A PYGMO PROBLEM CONSTRUCTING IT FROM A UDP inittime = perf_counter() prob = pg.problem(PPNOProblem(ppn)) generations = trials = nochanges = 0 best_f = best_x = None # INSTANCIATE THE PYGMO ALGORITM NSGA-II algo = pg.algorithm(pg.nsga2(gen=GENERATIONS_PER_TRIAL)) # INSTANCIATE A POPULATION pop = pg.population(prob, size=POPULATION_SIZE) while True: # RUN THE EVOLUION pop = algo.evolve(pop) trials += 1 generations += GENERATIONS_PER_TRIAL # EXTRACT RESULTS AND SEARCH THE BEST fits, vectors = pop.get_f(), pop.get_x() new_f = new_x = None for fit, vector in zip(fits, vectors): # VALID SOLUTION if fit[1] <= 0: if isinstance(new_f, type(None)): new_f = fit new_x = vector elif new_f[0] > fit[0]: new_f = fit new_x = vector if not isinstance(new_f, type(None)): if isinstance(best_f, type(None)): best_f = new_f best_x = new_x else: if best_f[0] > new_f[0]: best_f = new_f best_x = new_x nochanges = 0 else: nochanges += 1 if not isinstance(best_f, type(None)): print('Generations: %i ' % (generations), end='') print('Cost: %.2f Pressure deficit: %0.3f ' % (best_f[0], best_f[1])) if (perf_counter() - inittime) >= MAX_TIME: print('Maximum evolution time was reached.') break elif trials >= MAX_TRIALS: print('Maximum number of trials was reached.') break elif nochanges >= MAX_NO_CHANGES: print('Objective function value was repeated %i times.' % (nochanges)) break return (best_f, best_x)
def runTest(self): from dcgpy import symbolic_regression, generate_koza_quintic, kernel_set_double import pygmo as pg X, Y = generate_koza_quintic() udp = symbolic_regression(points=X, labels=Y, rows=1, cols=20, levels_back=21, arity=2, kernels=kernel_set_double(["sum", "diff"])(), n_eph=2, multi_objective=False, parallel_batches=0) prob = pg.problem(udp) pop = pg.population(prob, 10) udp.pretty(pop.champion_x) udp.prettier(pop.champion_x) # Unconstrained self.assertEqual(prob.get_nc(), 0) self.assertEqual(prob.get_nic(), 0) # Single objective self.assertEqual(prob.get_nobj(), 1) # Dimensions self.assertEqual(prob.get_nix(), 20 * (2 + 1) + 1) self.assertEqual(prob.get_nx(), 2 + prob.get_nix()) # Has gradient and hessians self.assertEqual(prob.has_gradient(), True) self.assertEqual(prob.has_hessians(), True)
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 pygmo_es(): ARCHIPELAGO = True iterations = 10 uda = salimans_nes(iter=iterations) # user defined algorithm udp = saddle_space() # user defined problem prob = pg.problem(udp) # Beautiful white snow if ARCHIPELAGO: archi = pg.archipelago(algo=uda, prob=prob, n=1, pop_size=4) archi.evolve() # print(archi) # prints description of islands contained in archipelago # archi.wait() sols = archi.get_champions_f() idx = sols.index(min(sols)) sols_x = archi.get_champions_x() sol = sols[idx], sols_x[idx] else: pop = pg.population(prob=prob, size=4) pop.set_x(0, [-2.277654673852600, 0.047996554429844, 3.810000000000000]) pop.set_x(1, [-0.138042744751570, -0.144259374836607, 3.127288444444444]) pop.set_x(2, [-2.086814820119193, -0.000122173047640, 3.111181716545691]) uda.evolve(pop) sol = (pop.champion_f, pop.champion_x) print("Done! best solution is:") print(sol) return sol
def get_equilibrium(nn_controller, random_seed=0, mass=0.38905): class controller_equilibrium: def __init__(self, nn_controller): self.nn_controller = nn_controller def fitness(self, state): g0 = 9.81 return [ np.linalg.norm( self.nn_controller.compute_control(state) - np.array([g0 * mass, 0])) ] def get_bounds(self): return ([-1, 0, -1, 0, 0], [1, 0, 1, 0, 0]) # optimisation parameters # increase if necessary to ensure convergence n_generations = 700 n_individuals = 100 prob = pygmo.problem(controller_equilibrium(nn_controller)) algo = pygmo.algorithm( pygmo.de(gen=n_generations, tol=0, ftol=0, seed=random_seed)) pop = pygmo.population(prob, size=n_individuals, seed=random_seed) pop.push_back([0, 0, 0, 0, 0]) algo.set_verbosity(100) pop = algo.evolve(pop) return pop.champion_x
def run_example11(n_seg=30): """ This example demonstrates the use of the class lt_margo developed for the internal ESA CDF study on the interplanetary mission named MARGO. The class was used to produce the preliminary traget selection for the mission resulting in 88 selected possible targets (http://www.esa.int/spaceinimages/Images/2017/11/Deep-space_CubeSat) (http://www.esa.int/gsp/ACT/mad/projects/lt_to_NEA.html) """ import pykep as pk import pygmo as pg import numpy as np from matplotlib import pyplot as plt from pykep.examples import add_gradient, algo_factory # 0 - Target asteroid from MPCORB mpcorbline = "K14Y00D 24.3 0.15 K1794 105.44160 34.12337 117.64264 1.73560 0.0865962 0.88781021 1.0721510 2 MPO369254 104 1 194 days 0.24 M-v 3Eh MPCALB 2803 2014 YD 20150618" # 1 - Algorithm algo = algo_factory("snopt7") # 2 - Problem udp = add_gradient(pk.trajopt.lt_margo( target=pk.planet.mpcorb(mpcorbline), n_seg=n_seg, grid_type="uniform", t0=[pk.epoch(8000), pk.epoch(9000)], tof=[200, 365.25 * 3], m0=20.0, Tmax=0.0017, Isp=3000.0, earth_gravity=False, sep=True, start="earth"), with_grad=False ) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # 3 - Population pop = pg.population(prob, 1) # 4 - Solve the problem (evolve) pop = algo.evolve(pop) # 5 - Inspect the solution print("Feasible?:", prob.feasibility_x(pop.champion_x)) # 6 - plot trajectory axis = udp.udp_inner.plot_traj(pop.champion_x, plot_segments=True) plt.title("The trajectory in the heliocentric frame") # 7 - plot control udp.udp_inner.plot_dists_thrust(pop.champion_x) # 8 - pretty udp.udp_inner.pretty(pop.champion_x) plt.ion() plt.show()
def sade(problem, population_size, params): ''' Execute the Pygmo SADE algorithm on an optimisation problem with the population size and parameters specified. The SADE possible set of parameters are: * variant: mutation variant: 1 -> best/1/exp 10 -> rand/2/bin 2 -> rand/1/exp 11 -> rand/3/exp 3 -> rand-to-best/1/exp 12 -> rand/3/bin 4 -> best/2/exp 13 -> best/3/exp 5 -> rand/2/exp 14 -> best/3/bin 6 -> best/1/bin 15 -> rand-to-current/2/exp 7 -> rand/1/bin 16 -> rand-to-current/2/bin 8 -> rand-to-best/1/bin 17 -> rand-to-best-and-current/2/exp 9 -> best/2/bin 18 -> rand-to-best-and-current/2/bin * variant_adptv: scale factor F and crossover rate CR adaptation scheme to be used * ftol: stopping criteria on the function tolerance * xtol: stopping criteria on the step tolerance Parameters ---------- - problem: the problem to optimise. It must comply to the Pygmo requirements, i.e. being an instance of an UDP class - population_size: The size of the population - params: dictionnary of parameters for the SADE algorithm Return ------ - log: the logs of the execution of the optimisation problem with the population size - duration: the total duration of the resolution of the problem ''' # Extract algorithm parameters nb_generation = params["nb_generation"] variant = params["variant"] variant_adptv = params["variant_adptv"] ftol = params["ftol"] xtol = params["xtol"] algo = pg.algorithm( pg.sade(gen=nb_generation, variant=variant, variant_adptv=variant_adptv, ftol=ftol, xtol=xtol)) algo.set_verbosity(1) solution = pg.population(problem, size=population_size, b=None) startt = datetime.now() solution = algo.evolve(solution) duration = (datetime.now() - startt) uda = algo.extract(pg.sade) log = uda.get_log() return (log, duration, solution.champion_f, solution.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 user_defined_problem(): prob = pg.problem(sphere_function(3)) print(prob) algo = pg.algorithm(pg.bee_colony(gen = 200, limit = 20)) pop = pg.population(prob, 10) pop = algo.evolve(pop) print(pop.champion_f) print(pop)
def run_example8(nseg=40): """ This example demonstrates the direct method (sims-flanagan) on a planet to planet scenario. """ import pykep as pk import pygmo as pg import numpy as np from matplotlib import pyplot as plt from pykep.examples import add_gradient, algo_factory # 1 - Algorithm algo = algo_factory("snopt7") # 2 - Problem udp = add_gradient(pk.trajopt.direct_pl2pl( p0="earth", pf="mars", mass=1000, thrust=0.1, isp=3000, vinf_arr=1e-6, vinf_dep=3.5, hf=False, nseg=nseg, t0=[1100, 1400], tof=[200, 750]), with_grad=False ) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # 3 - Population pop = pg.population(prob, 1) # 4 - Solve the problem (evolve) pop = algo.evolve(pop) # 5 - Inspect the solution if prob.feasibility_x(pop.champion_x): print("Optimal Found!!") else: print("No solution found, try again :)") udp.udp_inner.pretty(pop.champion_x) axis = udp.udp_inner.plot_traj(pop.champion_x) plt.title("The trajectory in the heliocentric frame") axis = udp.udp_inner.plot_control(pop.champion_x) plt.title("The control profile (throttle)") plt.ion() plt.show()
def run_example6(n_seg=5): """ This example demonstrates the optimization of a multiple randezvous mission (low-thrust). Such a mission (including more asteroids) is also called asteroid hopping The spacecraft performances, as well as the three asteroids visited, are taken from the GTOC7 problem description. """ import pygmo as pg from pykep.trajopt import mr_lt_nep from pykep.planet import gtoc7 from pykep.examples import add_gradient, algo_factory from matplotlib import pyplot as plt # If you have no access to snopt7, try slsqp (multiple starts may be # necessary) algo = algo_factory("snopt7") udp = add_gradient( mr_lt_nep( t0=[9600., 9700.], seq=[gtoc7(5318), gtoc7(14254), gtoc7(7422), gtoc7(5028)], n_seg=n_seg, mass=[800., 2000.], leg_tof=[100., 365.25], rest=[30., 365.25], Tmax=0.3, Isp=3000., traj_tof=365.25 * 3., objective='mass', c_tol=1e-05 ), with_grad=False) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() pop = pg.population(prob, 1) pop = algo.evolve(pop) solution = pop.champion_x if prob.feasibility_x(solution): print("FEASIBILE!!!") ax = udp.udp_inner.plot(solution) else: print("INFEASIBLE :(") ax = None plt.ion() plt.show()
def _minimize(self): # Gather the setup islands = self._setup_dict['islands'] pop_size = self._setup_dict['population_size'] evolution_cycles = self._setup_dict['evolution_cycles'] # Print some info print("\nPAGMO setup:") print("------------") print("- Number of islands: %i" % islands) print("- Population size per island: %i" % pop_size) print("- Evolutions cycles per island: %i\n" % evolution_cycles) Npar = len(self._internal_parameters) if is_parallel_computation_active(): wrapper = PAGMOWrapper(function=self.function, parameters=self._internal_parameters, dim=Npar) # use the archipelago, which uses the ipyparallel computation archi = pg.archipelago(udi=pg.ipyparallel_island(), n=islands, algo=self._setup_dict['algorithm'], prob=wrapper, pop_size=pop_size) archi.wait() # Display some info print("\nSetup before parallel execution:") print("--------------------------------\n") print(archi) # Evolve populations on islands print("Evolving... (progress not available for parallel execution)") # For some weird reason, ipyparallel looks for _winreg on Linux (where does # not exist, being a Windows module). Let's mock it with an empty module' mocked = False if os.path.exists("_winreg.py") is False: with open("_winreg.py", "w+") as f: f.write("pass") mocked = True archi.evolve() # Wait for completion (evolve() is async) archi.wait_check() # Now remove _winreg.py if needed if mocked: os.remove("_winreg.py") # Find best and worst islands fOpts = np.array(map(lambda x:x[0], archi.get_champions_f())) xOpts = archi.get_champions_x() else: # do not use ipyparallel. Evolve populations on islands serially wrapper = PAGMOWrapper(function=self.function, parameters=self._internal_parameters, dim=Npar) xOpts = [] fOpts = np.zeros(islands) with progress_bar(iterations=islands, title="pygmo minimization") as p: for island_id in range(islands): pop = pg.population(prob=wrapper, size=pop_size) for i in range(evolution_cycles): pop = self._setup_dict['algorithm'].evolve(pop) # Gather results xOpts.append(pop.champion_x) fOpts[island_id] = pop.champion_f[0] p.increase() # Find best and worst islands min_idx = fOpts.argmin() max_idx = fOpts.argmax() fOpt = fOpts[min_idx] fWorse = fOpts[max_idx] xOpt = np.array(xOpts)[min_idx] # Some information print("\nSummary of evolution:") print("---------------------") print("Best population has minimum %.3f" % (fOpt)) print("Worst population has minimum %.3f" % (fWorse)) print("") # Transform to numpy.array best_fit_values = np.array(xOpt) return best_fit_values, fOpt
def population(self, size, seed=None): return pygmo.population(self._problem, size, seed=seed)
def run_example7(solver="snopt7"): """ This example demonstrates the indirect method (cartesian) on a orbit to orbit scenario. The orbits are those of Earth and Mars. """ import pykep as pk import pygmo as pg import numpy as np from matplotlib import pyplot as plt from pykep.examples import add_gradient, algo_factory # Some pre-computed solutions (obtaining spending some iterations and # restarts from random initial guesses) z_mass_optimal = [397.88267909228767, 2.0719343674552215, 2.7313941033119407, 11.882803539732214, 10.567639551625298, 0.50803671389927796, -11.056641527923768, 12.176151455434058, 4.1269457596809245, 3.4434953247725324] z_quadratic_control = [381.32031472240106, 1.0102363292172423, 1.8134352964367946, 19.522442569527868, - 6.7894353762521105, -3.3749783899165928, 7.0438655057343054, 19.923912672512174, 0.93896446800741751, 3.5483645070393743] z_quadratic_control2 = [459.51623108767666, -1.616057488705803, 0.33049652475302532, -17.735981532357027, - 3.2374905349904912, 2.2249621531880934, 2.9550456430212937, -20.226761256676323, -2.9684113654904061, 3.1471248891703905] z_quadratic_control3 = [519.45371103815569, 0.39617485433378341, 2.7008977766929818, 7.9136210333255468, - 11.03747486077437, -3.0776988186969136, 9.1796869310249747, 6.5013311040515687, -0.2054349910826633, 3.0084671211666865] # A random initial solution z_random = np.hstack( [[np.random.uniform(100, 700)], 2 * np.random.randn(9)]) # We use an initial guess within 10% of a known optima, you can experiment what happens # with a different choice z = z_quadratic_control + z_quadratic_control * np.random.randn(10) * 0.1 #z = z_random # 1 - Algorithm algo = algo_factory(solver) # 2 - Problem. We define a minimum quadratic control problem (alpha=0) with free time # (hamiltonian will be forced to be 0). We provide the option for estimating the gradient numerically for # algorithms that require it. udp = add_gradient(pk.trajopt.indirect_or2or( elem0=[149598261129.93335, 0.016711230601231957, 2.640492490927786e-07, 3.141592653589793, 4.938194050401601, 0], elemf=[227943822376.03537, 0.09339409892101332, 0.032283207367640024, 0.8649771996521327, 5.000312830124232, 0], mass=1000, thrust=0.3, isp=2500, atol=1e-12, rtol=1e-12, tof=[100, 700], freetime=True, alpha=0, bound=True, mu=pk.MU_SUN), with_grad=False) prob = pg.problem(udp) prob.c_tol = [1e-7] * 10 # 3 - Population (i.e. initial guess) pop = pg.population(prob) pop.push_back(z) # 4 - Solve the problem (evolve) pop = algo.evolve(pop) # 5 - Inspect the solution if prob.feasibility_x(pop.champion_x): print("Optimal Found!!") # We call the fitness to set the leg udp.udp_inner.fitness(pop.champion_x) arr = udp.udp_inner.leg.get_states(1e-12, 1e-12) print("Final mass is: ", arr[-1, 7]) else: print("No solution found, try again :)") # plot trajectory axis = udp.udp_inner.plot_traj( pop.champion_x, quiver=True, mark="k", length=1) plt.title("The trajectory in the heliocentric frame") # plot control udp.udp_inner.plot_control(pop.champion_x) plt.title("The control profile (throttle)") plt.ion() plt.show() # Show the trajectory data udp.udp_inner.pretty(pop.champion_x)
def run_example9(): """ This example demonstrates the indirect method (cartesian) on a point to planet variable time scenario. The starting conditions are taken from a run of the indirect method. """ import pykep as pk import pygmo as pg import numpy as np from matplotlib import pyplot as plt from pykep.examples import add_gradient, algo_factory # 1 - Algorithm algo = algo_factory("snopt7") # 2 - Problem udp = add_gradient(pk.trajopt.indirect_pt2pl( x0=[44459220055.461708, -145448367557.6174, 1195278.0377499966, 31208.214734303529, 9931.5012318647168, -437.07278242521573, 1000], t0=1285.6637861007277, pf="mars", thrust=0.1, isp=3000, mu=pk.MU_SUN, tof=[600, 720], alpha=0, # quadratic control bound=True), with_grad=False ) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # 3 - Population pop = pg.population(prob) z = np.hstack(([np.random.uniform(udp.udp_inner.tof[0], udp.udp_inner.tof[1])], 10 * np.random.randn(7))) pop.push_back(z) # 4 - Solve the problem (evolve) pop = algo.evolve(pop) homotopy_path = [0.2, 0.4, 0.6, 0.8, 0.9, 0.98, 0.99, 0.995, 1] for alpha in homotopy_path: z = pop.champion_x print("alpha is: ", alpha) udp = add_gradient(pk.trajopt.indirect_pt2pl( x0=[44459220055.461708, -145448367557.6174, 1195278.0377499966, 31208.214734303529, 9931.5012318647168, -437.07278242521573, 1000], t0=1285.6637861007277, pf="mars", thrust=0.1, isp=3000, mu=pk.MU_SUN, tof=[600, 720], alpha=alpha, # quadratic control bound=True), with_grad=False ) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # 7 - Solve it pop = pg.population(prob) pop.push_back(z) pop = algo.evolve(pop) # 8 - Inspect the solution print("Feasible?:", prob.feasibility_x(pop.champion_x)) # plot trajectory axis = udp.udp_inner.plot_traj(pop.champion_x, quiver=True, mark='k') plt.title("The trajectory in the heliocentric frame") # plot control udp.udp_inner.plot_control(pop.champion_x) plt.title("The control profile (throttle)") plt.ion() plt.show() udp.udp_inner.pretty(pop.champion_x) print("\nDecision vector: ", list(pop.champion_x))
def run_example10(): """ This example demonstrates the indirect method (cartesian) on a point to point fixed time scenario. The boundary conditions are taken from a run of the indirect method. """ import pykep as pk import pygmo as pg import numpy as np from matplotlib import pyplot as plt from pykep.examples import add_gradient, algo_factory # 1 - Algorithm algo = algo_factory("snopt7") # 2 - Problem udp = add_gradient(pk.trajopt.indirect_pt2pt( x0=[44914296854.488266, -145307873786.94177, 1194292.6437741749, 31252.149474878544, 9873.214642584162, -317.08718075574404, 1000], xf=[-30143999066.728119, -218155987244.44385, -3829753551.2279921, 24917.707565772216, -1235.74045124602, -638.05209482866155, 905.47894037275546], thrust=0.1, isp=3000, mu=pk.MU_SUN, tof=[616.77087591237546, 616.77087591237546], freetime=False, alpha=0, # quadratic control bound=True), with_grad=False ) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # 3 - Population pop = pg.population(prob) z = np.hstack(([np.random.uniform(udp.udp_inner.tof[0], udp.udp_inner.tof[1])], 10 * np.random.randn(7))) pop.push_back(z) # 4 - Solve the problem (evolve) pop = algo.evolve(pop) # 5 - Continue the solution to mass optimal homotopy_path = [0.5, 0.75, 0.9, 1] for alpha in homotopy_path: z = pop.champion_x print("alpha: ", alpha) udp = add_gradient(pk.trajopt.indirect_pt2pt( x0=[44914296854.488266, -145307873786.94177, 1194292.6437741749, 31252.149474878544, 9873.214642584162, -317.08718075574404, 1000], xf=[-30143999066.728119, -218155987244.44385, -3829753551.2279921, 24917.707565772216, -1235.74045124602, -638.05209482866155, 905.47894037275546], thrust=0.1, isp=3000, mu=pk.MU_SUN, tof=[616.77087591237546, 616.77087591237546], freetime=False, alpha=alpha, # quadratic control bound=True), with_grad=False ) prob = pg.problem(udp) prob.c_tol = [1e-5] * prob.get_nc() # 7 - Solve it pop = pg.population(prob) pop.push_back(z) pop = algo.evolve(pop) # 8 - Inspect the solution print("Feasible?:", prob.feasibility_x(pop.champion_x)) # plot trajectory axis = udp.udp_inner.plot_traj(pop.champion_x, quiver=True, mark="k") plt.title("The trajectory in the heliocentric frame") # plot control udp.udp_inner.plot_control(pop.champion_x) plt.title("The control profile (throttle)") plt.ion() plt.show() udp.udp_inner.pretty(pop.champion_x) print("\nDecision vector: ", list(pop.champion_x))
udp = mga(seq=seq, t0=[-1000., 0.], tof=[[30, 400], [100, 470], [30, 400], [400, 2000], [1000, 6000]], vinf=3., tof_encoding='direct', orbit_insertion=True, e_target=0.98, rp_target=108950000) udp = mga(seq=seq, t0=[-1000., 0.], tof=7000., vinf=3., tof_encoding='eta', orbit_insertion=True, e_target=0.98, rp_target=108950000) #udp = mga(seq=seq, t0=[-1000., 0.], tof=[[130,200], [430,470], [30, 70], [900, 1200], [4000, 5000]], vinf=0., alpha_encoding=False) prob = pg.problem(udp) uda = pg.cmaes(1500, force_bounds=True, sigma0=0.5, ftol=1e-4) #uda = pg.sade(4500) algo = pg.algorithm(uda) algo.set_verbosity(10) res = list() # for i in range(100): pop = pg.population(prob, 100) pop = algo.evolve(pop) res.append(pop.champion_f)