def solve(problem, state0, homotopy=0, algo=None, x=None, display=True): # algo = algorithm.scipy_slsqp(max_iter=30, acc=1E-4, epsilon=1e-6, # screen_output=False) if not algo: # Use SNOPT if possible algo = algorithm.snopt(400, opt_tol=1e-4, feas_tol=1e-4) # Alternatively the scipy SQP solver can be used # algo = algorithm.scipy_slsqp(max_iter = 1000,acc = 1E-8, # epsilon = 1.49e-08, screen_output = True) # algo.screen_output = True prob = problem( state0=state0, homotopy=homotopy, pinpoint=True, ) if display: print('state: ', state0) print('homot: ', homotopy) print('algo : ', algo) print('x : ', x) if x is None: pop = population(prob, 1) else: pop = population(prob) pop.push_back(x) print(pop[0].cur_x) try: pop = algo.evolve(pop) x = pop[0].cur_x feasible = prob.feasibility_x(x) if not feasible and (norm(x) < 1e-2): pop = algo.evolve(pop) pop = algo.evolve(pop) # x = pop.champion.x x = pop[0].cur_x feasible = prob.feasibility_x(x) except ValueError: feasible = False if display: print('evx : ', x) print(feasible) # if display: # print( (u'\u2713' if feasible else u'\u2717') + # ' (homotopy: {0})'.format(homotopy)) return {'x': pop.champion.x, 'prob': prob, 'feasible': feasible}
def solve(problem, state0, homotopy=0, algo=None, x=None, display=True): # algo = algorithm.scipy_slsqp(max_iter=30, acc=1E-4, epsilon=1e-6, # screen_output=False) if not algo: # Use SNOPT if possible algo = algorithm.snopt(400, opt_tol=1e-4, feas_tol=1e-4) # Alternatively the scipy SQP solver can be used # algo = algorithm.scipy_slsqp(max_iter = 1000,acc = 1E-8, # epsilon = 1.49e-08, screen_output = True) # algo.screen_output = True prob = problem(state0=state0, homotopy=homotopy, pinpoint=True,) if display: print('state: ', state0) print('homot: ', homotopy) print('algo : ', algo) print('x : ', x) if x is None: pop = population(prob, 1) else: pop = population(prob) pop.push_back(x) print(pop[0].cur_x) try: pop = algo.evolve(pop) x = pop[0].cur_x feasible = prob.feasibility_x(x) if not feasible and (norm(x) < 1e-2): pop = algo.evolve(pop) pop = algo.evolve(pop) # x = pop.champion.x x = pop[0].cur_x feasible = prob.feasibility_x(x) except ValueError: feasible=False if display: print('evx : ', x) print(feasible) # if display: # print( (u'\u2713' if feasible else u'\u2717') + # ' (homotopy: {0})'.format(homotopy)) return {'x': pop.champion.x, 'prob': prob, 'feasible': feasible}
def run(n_restarts=5): from PyGMO import algorithm, island, population prob = earthToMars() algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5) # algo.screen_output = True algo2 = algorithm.mbh(algo, n_restarts, 0.005) algo2.screen_output = True pop = population(prob) pop.push_back((-3.810404036178629e-05, 8.036667366434322e-05, 0, -0.00011631957922519811, -0.0003960700040113729, 0, 0.00014343900668268246, -0.00039460589468829016, 0, 0.0004133243825183847, -0.0002676479632615287, 0, -6.353773946676955e-05, -0.0004027302771161609, 0, -0.00019483461157664088, -0.0003938299142410649, 0, 0.0003740376551173652, -0.00045439735580127933, 0, 0.00026271994456226056, -4.17413726080276e-05, 0, 0.0004025294016016401, 9.22186764465555e-05, 0, 0.0004379362102351141, -8.202101747983173e-05, 0, 2.0842990495214604e-05, -1.927554372930426e-05, 0, -2.392388475139966e-05, -6.3420840462436174e-06, 0)) pop.push_back((0.00018354551497353738, 0.0002897005581203533, 0, 9.385407683672441e-05, -0.0004375546286935724, 0, -0.00017406053466786356, -0.0004055793819144533, 0, 7.811816626063441e-05, -0.00028869842254392053, 0, 0.000280132941671916, -0.00045467528344872834, 0, 0.00031161406626870487, -0.0004418005074233615, 0, 0.00016912620000403375, -0.00045156036938030775, 0, 0.00043500734938167605, -4.4611940286304056e-05, 0, 0.00023373694896547512, 4.622353180355802e-06, 0, 0.00043504614537196785, -0.00042017445674379463, 0, 0.00016822207354911628, 0.00010574669088542543, 0, 2.1129649656070842e-05, 0.00020199652091584146, 0)) # pop.push_back((301.93091863294785, 0.0016076262089444425, 0.0015896115913838728, 0.0)) # pop.push_back((420.2372419060117, 0.010494326408284994, 0.0044382506954818565, 0.0)) # pop.push_back((411.21323621411335, 0.008748839048462907, 0.0033290148214346503, 0.0)) # pop.push_back((395.8283718212657, 0.006450877568564355, 0.002069880891910152, 0.0)) # pop.push_back((319.95400029222867, 0.0016702166037494744, 0.0013676901851197968, 0.0)) # pop.push_back((319.5113399461457, 0.00166499548529299, 0.0013736935829129556, 0.0)) # pop.push_back((320.0969905134936, 0.001671977113629641, 0.001365741362825864, 0.0)) # pop.push_back((324.8947207784664, 0.0017420256877963634, 0.0013024051696600683, 0.0)) isl = island(algo2,pop) print("Running Monotonic Basin Hopping .... this will take a while.") isl.evolve(1) isl.join() print("Is the solution found a feasible trajectory? " + str(prob.feasibility_x(isl.population.champion.x))) return isl.population.champion.x
def run(n_restarts=5): from PyGMO import algorithm, island, population prob = earthToMars() algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5) # algo.screen_output = True algo2 = algorithm.mbh(algo, n_restarts, 0.005) algo2.screen_output = True pop = population(prob) pop.push_back((320.33563525584435, 0.0016748335274261476, 0.0013627675495311467, 0.0)) pop.push_back((301.93091863294785, 0.0016076262089444425, 0.0015896115913838728, 0.0)) pop.push_back((301.93091863294785, 0.0016076262089444425, 0.0015896115913838728, 0.0)) pop.push_back((420.2372419060117, 0.010494326408284994, 0.0044382506954818565, 0.0)) pop.push_back((411.21323621411335, 0.008748839048462907, 0.0033290148214346503, 0.0)) pop.push_back((395.8283718212657, 0.006450877568564355, 0.002069880891910152, 0.0)) pop.push_back((319.95400029222867, 0.0016702166037494744, 0.0013676901851197968, 0.0)) pop.push_back((319.5113399461457, 0.00166499548529299, 0.0013736935829129556, 0.0)) pop.push_back((320.0969905134936, 0.001671977113629641, 0.001365741362825864, 0.0)) pop.push_back((324.8947207784664, 0.0017420256877963634, 0.0013024051696600683, 0.0)) isl = island(algo2,pop) print("Running Monotonic Basin Hopping .... this will take a while.") isl.evolve(1) isl.join() print("Is the solution found a feasible trajectory? " + str(prob.feasibility_x(isl.population.champion.x))) return isl.population.champion.x
def do_test_migr_setup(self, pop_xs, out_pop_xs, top, n_evolves): """ Generic procedure for testing whether the state of populations in 'pop_xs', after performing 'n_evolve' migration steps is equal to the expected 'out_pop_xs', given topology 'top'. """ prob = problem.identity() alg = algorithm.null() pops = [] for xs in pop_xs: pop = population(prob) for x in xs: pop.push_back(x) pops.append(pop) archi = archipelago( distribution_type=distribution_type.broadcast, migration_direction=migration_direction.destination) for pop in pops: archi.push_back( island(alg, pop, s_policy=migration.best_s_policy(), r_policy=migration.fair_r_policy())) archi.topology = top archi.evolve_batch(n_evolves, 1, False) out_xs = [] for ii, isl in enumerate(archi, 1): out_xs.append(tuple(sorted([i.cur_f for i in isl.population]))) out_xs = tuple(out_xs) self.assertEqual(out_xs, out_pop_xs)
def check_low_thrustable(inci, verbose=False): """ Given a incipit_stats object, checks each leg on los_thrustabality. It will return a list of tuple, one tuple for each leg. Each tuple contains (feasibility, famous coefficient).""" if os.name == 'posix': alg = algorithm.snopt(500, feas_tol=1e-9, opt_tol=1e-2, screen_output=False) else: alg = algorithm.scipy_slsqp(screen_output=False) prob = one_lt_leg(t = inci.initial[0], r=inci.initial[1], v=inci.initial[2], high_fidelity=True) pop = population(prob, 1) pop = alg.evolve(pop) feasible = prob.feasibility_x(pop.champion.x) feas_list = [ feasible] fam_coeff_list = [ (inci.DV[0] / (inci.T[0]*DAY2SEC)) / (0.1 / 2000.0) ] if verbose: print '+++ Checking feasibility of: ' + inci.filename + ' +++' print 'Initial leg feasible? --> ' + str(prob.feasibility_x(pop.champion.x)) for i in xrange(1, inci.n_legs): prob = one_lt_leg(t = [inci.t_P[i-1], inci.t_P[i]], r=[inci.r_P[i-1], inci.r_P[i]], v=[inci.v_sc[i-1][0], inci.v_sc[i-1][1]], high_fidelity=True) pop = population(prob, 1) pop = alg.evolve(pop) feasible = feasible and prob.feasibility_x(pop.champion.x) if verbose: print 'Leg no. ' + str(i) + ' feasible? --> ' + str(prob.feasibility_x(pop.champion.x)) # compute famous coefficient fam_coeff_list.append( (inci.DV[i] / (inci.T[i]*DAY2SEC)) / (0.1 / 2000.0) ) feas_list.append(prob.feasibility_x(pop.champion.x)) if verbose: if feasible: print 'Feasible!' else: print 'infeasible...' return zip(feas_list, fam_coeff_list)
def test_pop_ctor(self): # constructs the hypervolume object from a population object, expects # to not raise any error prob = problem.zdt(2) pop = population(prob, 100) # construction from a population object hypervolume(pop) # setting verification flag to False hypervolume(pop, False) # setting verification flag to True hypervolume(pop, True)
def Archive(pop, pop_new, prob): algo = algorithm.moead(gen=1) pop_next = population(prob, 1) idx = pop.compute_pareto_fronts()[0] for i in idx: pop_new.push_back(pop[i].cur_x) pop_new = algo.evolve(pop_new) idx = pop_new.get_best_idx(n_individus) pop_next.set_x(0, pop_new[idx[0]].cur_x) for i in idx[1:]: pop_next.push_back(pop_new[i].cur_x) return pop_next
def trajectory_file_load(fpath, verbose=False): """ used to load a trajectory file dump from tree search module """ # get trajectory try: best, x = load_trajectory( fpath ) except: raise Exception('ERROR: could not load trajectory') # reconstruct a problem instance try: prob = mga_incipit( seq=[fb.moon for fb in best.traj]+[best.next_moon.moon], tof = [ [0,300] ]*(len(x)/4) ) except: raise Exception('ERROR: could not instantiate problem') pop = population(prob) pop.push_back(x) return incipit_stats(pop.champion, fpath.split('/')[-1], 0, *lambertization(prob, x))
def jde_mga_1dsm(seq, t0, tof, slack=5, pop_size=50, n_evolve=10, dv_launch=6127., verbose=False): """Runs jDE with mga_1dsm problem.""" from PyGMO.problem import mga_1dsm_tof from PyGMO.algorithm import jde from PyGMO import population prob = mga_1dsm_tof(seq=[kep.planet_ss(name) for name in seq], t0=[kep.epoch(t0-slack), kep.epoch(t0+slack)], tof=[[t-slack, t+slack] for t in tof], vinf=[0., dv_launch/1000.], add_vinf_arr=False) algo = jde(gen=500, memory=True) pop = population(prob, pop_size) if verbose: print pop.champion.f[0] for i in xrange(n_evolve): pop = algo.evolve(pop) if verbose: print pop.champion.f
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. """ from PyGMO import algorithm, population from PyKEP.trajopt import mr_lt_nep from PyKEP import planet_gtoc7 algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5, screen_output=True) prob = mr_lt_nep(t0=[9600., 9700.], seq=[ planet_gtoc7(5318), planet_gtoc7(14254), planet_gtoc7(7422), planet_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) pop = population(prob, 1) pop = algo.evolve(pop) solution = pop.champion.x if prob.feasibility_x(solution): print "FEASIBILE!!!" ax = prob.plot(solution) else: print "INFEASIBLE :(" ax = None return prob, solution, ax
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. """ from PyGMO import algorithm, population from PyKEP.trajopt import mr_lt_nep from PyKEP.planet import gtoc7 algo = algorithm.scipy_slsqp(max_iter=500, acc=1e-5, screen_output=True) prob = 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 ) pop = population(prob, 1) pop = algo.evolve(pop) solution = pop.champion.x if prob.feasibility_x(solution): print("FEASIBILE!!!") ax = prob.plot(solution) else: print("INFEASIBLE :(") ax = None return prob, solution, ax
def do_test_migr_setup(self, pop_xs, out_pop_xs, top, n_evolves): """ Generic procedure for testing whether the state of populations in 'pop_xs', after performing 'n_evolve' migration steps is equal to the expected 'out_pop_xs', given topology 'top'. """ prob = problem.identity() alg = algorithm.null() pops = [] for xs in pop_xs: pop = population(prob) for x in xs: pop.push_back(x) pops.append(pop) archi = archipelago(distribution_type=distribution_type.broadcast, migration_direction=migration_direction.destination) for pop in pops: archi.push_back(island(alg, pop, s_policy=migration.best_s_policy(), r_policy=migration.fair_r_policy())) archi.topology = top archi.evolve_batch(n_evolves, 1, False) out_xs = [] for ii, isl in enumerate(archi, 1): out_xs.append(tuple(sorted([i.cur_f for i in isl.population]))) out_xs = tuple(out_xs) self.assertEqual(out_xs, out_pop_xs)
def get_bounds(self): return ([-4] * 2, [4] * 2) def get_nic(self): return 6 def get_nix(self): return 2 from PyGMO import population d = EPANetSimulation('/home/varsha/Documents/Project.inp') prob = problem(my_udp()) print(prob) algo = pg.algorithm.sms_emoa( gen=2000) # 2000 generations of SMS-EMOA should solve it pop = population(prob, 500) pop = algo.evolve(pop) print(prob.objfun(pop.champion.x)) import matplotlib.pyplot as plt import numpy as np F = np.array([ind.cur_f for ind in pop]).T plt.scatter(F[0], F[1]) plt.xlabel("Objective 1") plt.ylabel("Objective 2") plt.show()
def _get_lt_problem(self, x, n_seg=[10, 10], high_fidelity=True): """ This method returns the equivalent low-thrust problem of an incipit """ from PyKEP import epoch, lambert_problem, DAY2SEC, fb_prop, propagate_lagrangian from PyGMO import population from math import pi, acos, cos, sin, sqrt, exp from scipy.linalg import norm retval = [] #1 - we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience T = x[3::4] n_legs = len(x) / 4 seq = self.get_sequence() common_mu = seq[0].mu_central_body #2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (n_legs)) r_P = list([None] * (n_legs)) v_P = list([None] * (n_legs)) DV = list([None] * (n_legs)) for i, planet in enumerate(seq): t_P[i] = epoch(x[0] + sum(T[:i + 1])) r_P[i], v_P[i] = seq[i].eph(t_P[i]) #3 - We start with the first leg: a lambert arc theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 r = [cos(phi) * sin(theta), cos(phi) * cos(theta), sin(phi)] #phi close to zero is in the moon orbit plane injection r = [JR * 1000 * d for d in r] l = lambert_problem(r, r_P[0], T[0] * DAY2SEC, common_mu, False, False) #Lambert arc to reach seq[1] v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] #We start appending in the lt chromosome (see mga_incipit_lt) retval.append(theta) retval.append(phi) #First DSM occuring at the very beginning (will be cancelled by the optimizer) DV[0] = abs(norm(v_beg_l) - 3400) #Start of the first lt leg encoding retval.append(T[0]) retval.append(exp(-DV[0] / 9.80665 / 2000) * 2000) #Tsiolkowsky retval.extend(v_beg_l) retval.extend([a - b for a, b in zip(v_end_l, v_P[0])]) #4 - And we proceed with each successive leg for i in xrange(1, n_legs): #Fly-by v_out = fb_prop(v_end_l, v_P[i - 1], x[1 + 4 * i] * seq[i - 1].radius, x[4 * i], seq[i - 1].mu_self) #s/c propagation before the DSM r, v = propagate_lagrangian(r_P[i - 1], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) #Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1 - x[4 * i + 2]) * T[i] * DAY2SEC l = lambert_problem(r, r_P[i], dt, common_mu, False, False) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] #DSM occuring at time nu2*T2 DV[i] = norm([a - b for a, b in zip(v_beg_l, v)]) #lt encoding of all legs retval.append(T[i]) retval.append(exp(-sum(DV[:i + 1]) / 9.80665 / 2000) * 2000) #Tsiolkowsky retval.extend([a - b for a, b in zip(v_out, v_P[i - 1])]) if i != n_legs - 1: retval.extend([a - b for a, b in zip(v_end_l, v_P[i])]) retval = retval + [0] * sum(n_seg) * 3 prob = mga_incipit_lt(high_fidelity=high_fidelity, seq=seq, n_seg=n_seg, tf=epoch(x[0] + sum(T)), vf=[a - b for a, b in zip(v_end_l, v_P[i])]) # solves the problem of chemical trajectories wanting higher launch dv ub = list(prob.ub) lb = list(prob.lb) ub[4:7] = [5000, 5000, 5000] lb[4:7] = [-5000, -5000, -5000] prob.set_bounds(lb, ub) pop = population(prob) pop.push_back(retval) return (prob, pop)
def _get_lt_problem(self,x,n_seg=[10,10], high_fidelity=True): """ This method returns the equivalent low-thrust problem of an incipit """ from PyKEP import epoch, lambert_problem, DAY2SEC, fb_prop, propagate_lagrangian from PyGMO import population from math import pi, acos,cos,sin,sqrt, exp from scipy.linalg import norm retval = [] #1 - we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience T = x[3::4] n_legs = len(x)/4 seq = self.get_sequence() common_mu = seq[0].mu_central_body #2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (n_legs)) r_P = list([None] * (n_legs)) v_P = list([None] * (n_legs)) DV = list([None] * (n_legs)) for i,planet in enumerate(seq): t_P[i] = epoch(x[0]+sum(T[:i+1])) r_P[i],v_P[i] = seq[i].eph(t_P[i]) #3 - We start with the first leg: a lambert arc theta = 2*pi*x[1] phi = acos(2*x[2]-1)-pi/2 r = [cos(phi)*sin(theta), cos(phi)*cos(theta), sin(phi)] #phi close to zero is in the moon orbit plane injection r = [JR*1000*d for d in r] l = lambert_problem(r,r_P[0],T[0]*DAY2SEC,common_mu, False, False) #Lambert arc to reach seq[1] v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] #We start appending in the lt chromosome (see mga_incipit_lt) retval.append(theta) retval.append(phi) #First DSM occuring at the very beginning (will be cancelled by the optimizer) DV[0] = abs(norm(v_beg_l) - 3400) #Start of the first lt leg encoding retval.append(T[0]) retval.append(exp(-DV[0]/9.80665/2000)*2000) #Tsiolkowsky retval.extend(v_beg_l) retval.extend([a-b for a,b in zip(v_end_l,v_P[0])]) #4 - And we proceed with each successive leg for i in xrange(1,n_legs): #Fly-by v_out = fb_prop(v_end_l,v_P[i-1],x[1+4*i]*seq[i-1].radius,x[4*i],seq[i-1].mu_self) #s/c propagation before the DSM r,v = propagate_lagrangian(r_P[i-1],v_out,x[4*i+2]*T[i]*DAY2SEC,common_mu) #Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1-x[4*i+2])*T[i]*DAY2SEC l = lambert_problem(r,r_P[i],dt,common_mu, False, False) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] #DSM occuring at time nu2*T2 DV[i] = norm([a-b for a,b in zip(v_beg_l,v)]) #lt encoding of all legs retval.append(T[i]) retval.append(exp(-sum(DV[:i+1])/9.80665/2000)*2000) #Tsiolkowsky retval.extend([a-b for a,b in zip(v_out,v_P[i-1])]) if i != n_legs-1: retval.extend([a-b for a,b in zip(v_end_l,v_P[i])]) retval = retval + [0]*sum(n_seg)*3 prob = mga_incipit_lt(high_fidelity=high_fidelity,seq=seq, n_seg = n_seg,tf = epoch(x[0]+sum(T)), vf = [a-b for a,b in zip(v_end_l,v_P[i])]) # solves the problem of chemical trajectories wanting higher launch dv ub = list(prob.ub) lb = list(prob.lb) ub[4:7] = [5000,5000,5000] lb[4:7] = [-5000,-5000,-5000] prob.set_bounds(lb, ub) pop = population(prob) pop.push_back(retval) return (prob,pop)
def human_readable_extra(self): text = """\tProblem dimension: %s Implemented function: f1 = x1, f2 = g * ( 1 - math.sqrt(x1/g) ) (ZDT1)""" % str(self.__dim) return text # <codecell> if __name__ == '__main__': print("############### NSGA-II ##########################") algo = algorithm.nsga_II(gen = 250) prob1 = schaffer_function() print(prob1) pop = population(prob1,100) isl = island(algo,pop) isl.evolve(1) isl.population.plot_pareto_fronts() # <codecell> prob2 = zdt_1() print(prob2) pop2 = population(prob2,100) isl2 = island(algo,pop2) isl2.evolve(1) isl2.population.plot_pareto_fronts()