def _compute_constraints_impl(self, x): from PyKEP import epoch, AU, EARTH_VELOCITY, DAY2SEC from PyKEP.sims_flanagan import sc_state start = epoch(x[0]) end = epoch(x[0] + x[1]) r, v = self.__earth.eph(start) v = [a + b for a, b in zip(v, x[4:7])] x0 = sc_state(r, v, self.__sc.mass) r, v = self.__mars.eph(end) xe = sc_state(r, v, x[3]) self.__leg.set(start, x0, x[-3 * self.__nseg :], end, xe, x[2] * DAY2SEC) v_inf_con = (x[4] * x[4] + x[5] * x[5] + x[6] * x[6] - self.__Vinf * self.__Vinf) / ( EARTH_VELOCITY * EARTH_VELOCITY ) try: retval = list(self.__leg.mismatch_constraints() + self.__leg.throttles_constraints()) + [v_inf_con] except: print "warning: CANNOT EVALUATE constraints .... possible problem in the taylor integration in the Sundmann variable" return (1e14,) * (8 + 1 + self.__nseg + 2) # We then scale all constraints to non-dimensional values retval[0] /= AU retval[1] /= AU retval[2] /= AU retval[3] /= EARTH_VELOCITY retval[4] /= EARTH_VELOCITY retval[5] /= EARTH_VELOCITY retval[6] /= self.__sc.mass retval[7] /= 365.25 * DAY2SEC return retval
def _mga_incipit_cstrs_ctor( self, seq=[ planet_js('io'), planet_js('io'), planet_js('europa')], t0=[ epoch(7305.0), epoch(11323.0)], tof=[ [ 100, 200], [ 3, 200], [ 4, 100]], Tmax=300.00, Dmin=2.0): """ USAGE: mga_incipit_cstrs(seq = [planet_js('io'),planet_js('io'),planet_js('europa')], t0 = [epoch(6905.0),epoch(11323.0)], tof = [[100,200],[3,200],[4,100]], Tmax = 365.25, Dmin = 0.2) * seq: list of jupiter moons defining the trajectory incipit * t0: list of two epochs defining the launch window * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof) arg_list.append(Tmax) arg_list.append(Dmin) self._orig_init(*arg_list)
def opt_dt(tt1, tt2): t1 = epoch(tt1) t2 = epoch(tt2) dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC rE, vE = plEarth.eph(t1) vE = array(vE) rM, vM = plMars.eph(t2) vM = array(vM) l = lambert_problem(rE, rM, dt, MU_SUN) vEl = array(l.get_v1()[0]) dvE = vEl - vE vMl = array(l.get_v2()[0]) dvM = vMl - vM """ print "" print " detlal-V at Earth: " print " Earth: ",vE print " Ship: ",vEl print " delta ", dvE, linalg.norm(dvE) print "" print " detlal-V at Mars : " print " Mars: ", vM print " Ship: ", vMl dvM = (vM - vMl) print " delta ", dvM, linalg.norm(dvM) print " total delta-v ", linalg.norm(dvM)+linalg.norm(dvE) """ print " dt ", (tt2 - tt1), " dv ", linalg.norm(dvM) + linalg.norm(dvE) plot_planet(ax, plMars, t0=t2, color=(0.8, 0.8, 1), units=AU) plot_lambert(ax, l, color=(1, 0, 0), units=AU)
def point_planet(plnt, t0='PyKEP.epoch(0)', N=60, units=1.0): from PyKEP import MU_SUN, SEC2DAY, epoch, AU from math import pi, sqrt import numpy as np if t0 == 'PyKEP.epoch(0)': t0 = epoch(0) # orbit period at epoch T = plnt.compute_period(t0) * SEC2DAY # points where the orbit will be plotted when = np.linspace(0, T, N) # Ephemerides Calculation for the given planet x = np.array([0.0] * N) y = np.array([0.0] * N) z = np.array([0.0] * N) for i, day in enumerate(when): r, v = plnt.eph(epoch(t0.mjd2000 + day)) x[i] = r[0] / units y[i] = r[1] / units z[i] = r[2] / units return x,y,z
def plot(self,x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_sf_leg mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(0,0,0, color='y') # 1 - We decode the chromosome extracting the time of flights T = list([0]*(self.__n_legs)) for i in range(self.__n_legs): T[i] = x[2+i*8] #2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (self.__n_legs+1)) r_P = list([None] * (self.__n_legs+1)) v_P = list([None] * (self.__n_legs+1)) for i,planet in enumerate(self.seq): t_P[i+1] = epoch(self.tf - sum(T[i+1:])) r_P[i+1],v_P[i+1] = self.seq[i].eph(t_P[i+1]) plot_planet(ax, self.seq[i], t_P[i+1], units=JR, legend = True,color='k') #And we insert a fake planet simulating the starting position t_P[0] = epoch(self.tf - sum(T)) theta = x[0] phi = x[1] 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] r_P[0] = r v_P[0] = x[4:7] #3 - We iterate through legs to compute mismatches and throttles constraints ceq = list() cineq = list() m0 = self.__sc.mass for i in range(self.__n_legs): if i!=0: #First Leg v = [a+b for a,b in zip(v_P[i],x[(4 + i * 8):(7 + i * 8)])] else: v = v_P[i] x0 = sc_state(r_P[i],v,m0) v = [a+b for a,b in zip(v_P[i+1],x[(7 + i * 8):(10 + i * 8)])] if (i==self.__n_legs-1): #Last leg v = [a+b for a,b in zip(v_P[i+1],self.vf)] xe = sc_state(r_P[i+1], v ,x[3+8*i]) throttles = x[(8*self.__n_legs-1 + 3*sum(self.__n_seg[:i])):(8*self.__n_legs-1 + 3*sum(self.__n_seg[:i])+3*self.__n_seg[i])] self.__leg.set(t_P[i],x0,throttles,t_P[i+1],xe) plot_sf_leg(ax, self.__leg, units=JR,N=50) #update mass! m0 = x[3+8*i] ceq.extend(self.__leg.mismatch_constraints()) cineq.extend(self.__leg.throttles_constraints()) #raise Exception plt.show() return ax
def _mga_1dsm_tof_ctor( self, seq=[ planet_ss('earth'), planet_ss('venus'), planet_ss('earth')], t0=[ epoch(0), epoch(1000)], tof=[ [ 50, 900], [ 50, 900]], vinf=[ 0.5, 2.5], multi_objective=False, add_vinf_dep=False, add_vinf_arr=True): """ Constructs an mga_1dsm problem (tof-encoding) USAGE: problem.mga_1dsm(seq = [planet_ss('earth'),planet_ss('venus'),planet_ss('earth')], t0 = [epoch(0),epoch(1000)], tof = [ [50, 900], [50, 900] ], vinf = [0.5, 2.5], multi_objective = False, add_vinf_dep = False, add_vinf_arr = True) * seq: list of PyKEP planets defining the encounter sequence (including the starting planet) * t0: list of two epochs defining the launch window * tof: list of intervals defining the times of flight (days) * vinf: list of two floats defining the minimum and maximum allowed initial hyperbolic velocity at launch (km/sec) * multi_objective: when True constructs a multiobjective problem (dv, T) * add_vinf_dep: when True the computed Dv includes the initial hyperbolic velocity (at launch) * add_vinf_arr: when True the computed Dv includes the final hyperbolic velocity (at arrival) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof) arg_list.append(vinf[0]) arg_list.append(vinf[1]) arg_list.append(multi_objective) arg_list.append(add_vinf_dep) arg_list.append(add_vinf_arr) self._orig_init(*arg_list)
def run_example2(): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, DAY2SEC, planet_ss, AU, MU_SUN, lambert_problem from PyKEP.orbit_plots import plot_planet, plot_lambert mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') t1 = epoch(0) t2 = epoch(640) dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC ax.scatter([0],[0],[0], color='y') pl = planet_ss('earth') plot_planet(ax,pl, t0=t1, color=(0.8,0.8,1), legend=True, units = AU) rE,vE = pl.eph(t1) pl = planet_ss('mars') plot_planet(ax,pl, t0=t2, color=(0.8,0.8,1), legend=True, units = AU) rM, vM = pl.eph(t2) l = lambert_problem(rE,rM,dt,MU_SUN) plot_lambert(ax,l, color='b', legend=True, units = AU) plot_lambert(ax,l,sol=1, color='g', legend=True, units = AU) plot_lambert(ax,l,sol=2, color='g', legend=True, units = AU) plt.show()
def opt_dt(tt1, tt2): t1 = epoch(tt1) t2 = epoch(tt2) dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC rE, vE = plEarth.eph(t1) vE = array(vE) rM, vM = plMars.eph(t2) vM = array(vM) l = lambert_problem(rE, rM, dt, MU_SUN) vEl = array(l.get_v1()[0]) dvE = (vEl - vE) vMl = array(l.get_v2()[0]) dvM = (vMl - vM) ''' print "" print " detlal-V at Earth: " print " Earth: ",vE print " Ship: ",vEl print " delta ", dvE, linalg.norm(dvE) print "" print " detlal-V at Mars : " print " Mars: ", vM print " Ship: ", vMl dvM = (vM - vMl) print " delta ", dvM, linalg.norm(dvM) print " total delta-v ", linalg.norm(dvM)+linalg.norm(dvE) ''' print " dt ", (tt2 - tt1), " dv ", linalg.norm(dvM) + linalg.norm(dvE) plot_planet(ax, plMars, t0=t2, color=(0.8, 0.8, 1), units=AU) plot_lambert(ax, l, color=(1, 0, 0), units=AU)
def _compute_constraints_impl(self,x): from PyKEP import epoch, AU, EARTH_VELOCITY, fb_con from PyKEP.sims_flanagan import leg, sc_state from numpy.linalg import norm from math import sqrt, asin, acos #Ephemerides t_E = epoch(x[0]) t_V = epoch(x[0] + x[1]) t_M = epoch(x[0] + x[1] + x[9]) rE, vE = self.__earth.eph(t_E) rV, vV = self.__venus.eph(t_V) rM, vM = self.__mercury.eph(t_M) #First Leg v = [a+b for a,b in zip(vE,x[3:6])] x0 = sc_state(rE,v,self.__sc.mass) v = [a+b for a,b in zip(vV,x[6:9])] xe = sc_state(rV, v ,x[2]) self.__leg1.set(t_E,x0,x[-3 * (self.__nseg1 + self.__nseg2):-self.__nseg2 * 3],t_V,xe) #Second leg v = [a+b for a,b in zip(vV,x[11:14])] x0 = sc_state(rV,v,x[2]) v = [a+b for a,b in zip(vM,x[14:17])] xe = sc_state(rM, v ,x[10]) self.__leg2.set(t_E,x0,x[(-3 * self.__nseg2):],t_V,xe) #Defining the costraints #departure v_dep_con = (x[3] * x[3] + x[4] * x[4] + x[5] * x[5] - self.__Vinf_dep * self.__Vinf_dep) / (EARTH_VELOCITY * EARTH_VELOCITY) #arrival v_arr_con = (x[14] * x[14] + x[15] * x[15] + x[16] * x[16] - self.__Vinf_arr * self.__Vinf_arr) / (EARTH_VELOCITY * EARTH_VELOCITY) #fly-by at Venus DV_eq, alpha_ineq = fb_con(x[6:9],x[11:14],self.__venus) #Assembling the constraints retval = list(self.__leg1.mismatch_constraints() + self.__leg2.mismatch_constraints()) + [DV_eq] + list(self.__leg1.throttles_constraints() + self.__leg2.throttles_constraints()) + [v_dep_con] + [v_arr_con] + [alpha_ineq] #We then scale all constraints to non dimensional values #leg 1 retval[0] /= AU retval[1] /= AU retval[2] /= AU retval[3] /= EARTH_VELOCITY retval[4] /= EARTH_VELOCITY retval[5] /= EARTH_VELOCITY retval[6] /= self.__sc.mass #leg 2 retval[7] /= AU retval[8] /= AU retval[9] /= AU retval[10] /= EARTH_VELOCITY retval[11] /= EARTH_VELOCITY retval[12] /= EARTH_VELOCITY retval[13] /= self.__sc.mass #fly-by at Venus retval[14] /= (EARTH_VELOCITY*EARTH_VELOCITY) return retval
def run_example5(): from PyGMO import archipelago, problem from PyGMO.algorithm import jde from PyGMO.topology import ring from PyKEP import planet_ss,epoch from PyKEP.interplanetary import mga_1dsm #We define an Earth-Venus-Earth problem (single-objective) seq = [planet_ss('earth'),planet_ss('venus'),planet_ss('earth')] prob = mga_1dsm(seq=seq) prob.set_tof(0.7,3) prob.set_vinf(2.5) prob.set_launch_window(epoch(5844),epoch(6209)) prob.set_tof(0.7,3) print prob #We solve it!! algo = jde(100) topo = ring() archi = archipelago(algo,prob,8,20, topology=topo) print "Running a Self-Adaptive Differential Evolution Algorithm .... on 8 parallel islands" archi.evolve(10); archi.join() isl = min(archi, key=lambda x:x.population.champion.f[0]) print "Done!! Best solution found is: " + str(isl.population.champion.f[0]/1000) + " km / sec" prob.pretty(isl.population.champion.x) prob.plot(isl.population.champion.x)
def _compute_constraints_impl(self,x): from PyKEP import epoch, AU, EARTH_VELOCITY, DAY2SEC from PyKEP.sims_flanagan import sc_state start = epoch(x[0]) end = epoch(x[0] + x[1]) r,v = self.__earth.eph(start) v = [a+b for a,b in zip(v,x[4:7])] x0 = sc_state(r,v,self.__sc.mass) r,v = self.__mars.eph(end) xe = sc_state(r, v ,x[3]) self.__leg.set(start,x0,x[-3 * self.__nseg:],end,xe, x[2] * DAY2SEC) v_inf_con = (x[4] * x[4] + x[5] * x[5] + x[6] * x[6] - self.__Vinf * self.__Vinf) / (EARTH_VELOCITY * EARTH_VELOCITY) try: retval = list(self.__leg.mismatch_constraints() + self.__leg.throttles_constraints()) + [v_inf_con] except: print "warning: CANNOT EVALUATE constraints .... possible problem in the Taylor integration in the Sundmann variable" return (1e14,)*(8+1+self.__nseg+2) #We then scale all constraints to non-dimensional values retval[0] /= AU retval[1] /= AU retval[2] /= AU retval[3] /= EARTH_VELOCITY retval[4] /= EARTH_VELOCITY retval[5] /= EARTH_VELOCITY retval[6] /= self.__sc.mass retval[7] /= 365.25 * DAY2SEC return retval
def plot(self,x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg start = epoch(x[0]) end = epoch(x[0] + x[1]) r,v = self.__earth.eph(start) v = [a+b for a,b in zip(v,x[3:6])] x0 = sc_state(r,v,self.__sc.mass) r,v = self.__mars.eph(end) xe = sc_state(r, v ,x[2]) self.__leg.set(start,x0,x[-3 * self.__nseg:],end,xe) fig = plt.figure() ax = fig.gca(projection='3d') #The Sun ax.scatter([0],[0],[0], color='y') #The leg plot_sf_leg(ax, self.__leg, units=AU,N=10) #The planets plot_planet(ax, self.__earth, start, units=AU, legend = True,color=(0.8,0.8,1)) plot_planet(ax, self.__mars, end, units=AU, legend = True,color=(0.8,0.8,1)) plt.show()
def run_example2(): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, DAY2SEC, planet_ss, AU, MU_SUN, lambert_problem from PyKEP.orbit_plots import plot_planet, plot_lambert mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') t1 = epoch(0) t2 = epoch(640) dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC ax.scatter([0], [0], [0], color='y') pl = planet_ss('earth') plot_planet(ax, pl, t0=t1, color=(0.8, 0.8, 1), legend=True, units=AU) rE, vE = pl.eph(t1) pl = planet_ss('mars') plot_planet(ax, pl, t0=t2, color=(0.8, 0.8, 1), legend=True, units=AU) rM, vM = pl.eph(t2) l = lambert_problem(rE, rM, dt, MU_SUN) plot_lambert(ax, l, color='b', legend=True, units=AU) plot_lambert(ax, l, sol=1, color='g', legend=True, units=AU) plot_lambert(ax, l, sol=2, color='g', legend=True, units=AU) plt.show()
def plot(self, x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg # Making sure the leg corresponds to the requested chromosome self._compute_constraints_impl(x) start = epoch(x[0]) end = epoch(x[0] + x[1]) # Plotting commands fig = plt.figure() axis = fig.gca(projection='3d') # The Sun axis.scatter([0], [0], [0], color='y') # The leg plot_sf_leg(self.__leg, units=AU, N=10, ax=axis) # The planets plot_planet( self.__earth, start, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis) plot_planet( self.__mars, end, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis) plt.show()
def run_example5(): from PyGMO import archipelago, problem from PyGMO.algorithm import jde from PyGMO.topology import ring from PyKEP import epoch from PyKEP.planet import jpl_lp from PyKEP.trajopt import mga_1dsm # We define an Earth-Venus-Earth problem (single-objective) seq = [jpl_lp('earth'), jpl_lp('venus'), jpl_lp('earth')] prob = mga_1dsm(seq=seq) prob.set_tof(0.7, 3) prob.set_vinf(2.5) prob.set_launch_window(epoch(5844), epoch(6209)) prob.set_tof(0.7, 3) # We solve it!! algo = jde(100) topo = ring() archi = archipelago(algo, prob, 8, 20, topology=topo) print( "Running a Self-Adaptive Differential Evolution Algorithm .... on 8 parallel islands" ) archi.evolve(10) archi.join() isl = min(archi, key=lambda x: x.population.champion.f[0]) print("Done!! Best solution found is: " + str(isl.population.champion.f[0] / 1000) + " km / sec") prob.pretty(isl.population.champion.x) prob.plot(isl.population.champion.x)
def _compute_constraints_impl(self, x): start = epoch(x[0]) end = epoch(x[0] + x[1]) r, v = self.earth.eph(start) v = [a + b for a, b in zip(v, x[3:6])] x0 = sc_state(r, v, self.sc.mass) r, v = self.mars.eph(end) xe = sc_state(r, v, x[2]) self.leg.set(start, x0, x[-3 * self.nseg:], end, xe) v_inf_con = (x[3] * x[3] + x[4] * x[4] + x[5] * x[5] - self.Vinf * self.Vinf) / (EARTH_VELOCITY * EARTH_VELOCITY) retval = list(self.leg.mismatch_constraints() + self.leg.throttles_constraints()) + [v_inf_con] # We then scale all constraints to non-dimensional values retval[0] /= AU retval[1] /= AU retval[2] /= AU retval[3] /= EARTH_VELOCITY retval[4] /= EARTH_VELOCITY retval[5] /= EARTH_VELOCITY retval[6] /= self.sc.mass return retval
def _compute_constraints_impl(self, x): from PyKEP import epoch, AU, EARTH_VELOCITY from PyKEP.sims_flanagan import leg, sc_state start = epoch(x[0]) end = epoch(x[0] + x[1]) r, v = self.__earth.eph(start) v = [a + b for a, b in zip(v, x[3:6])] x0 = sc_state(r, v, self.__sc.mass) r, v = self.__mars.eph(end) xe = sc_state(r, v, x[2]) self.__leg.set(start, x0, x[-3 * self.__nseg:], end, xe) v_inf_con = (x[3] * x[3] + x[4] * x[4] + x[5] * x[5] - self.__Vinf * self.__Vinf) / (EARTH_VELOCITY * EARTH_VELOCITY) retval = list(self.__leg.mismatch_constraints() + self.__leg.throttles_constraints()) + [v_inf_con] #We then scale all constraints to non dimensiona values retval[0] /= AU retval[1] /= AU retval[2] /= AU retval[3] /= EARTH_VELOCITY retval[4] /= EARTH_VELOCITY retval[5] /= EARTH_VELOCITY retval[6] /= self.__sc.mass return retval
def plot_planet(ax,plnt,t0='PyKEP.epoch(0)', N=60, units = 1.0, color = 'k', s=80, legend = False): """ Plots the planet position and its orbit USAGE: plot_planet(ax,plnt,t0='PyKEP.epoch(0)', N=60, units=AU, legend = False): * ax: 3D axis object created using fig.gca(projection='3d') * plnt: PyKEP.planet object we want to plot * t0: PyKEP.epoch object indicating when we want to plot the planet position * units: the length unit to be used in the plot * color: matplotlib color to use to plot the line * s: planet size (pixel^2) * legend when True it plots also the legend with the planet name EXAMPLE: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') pl = planet_ss('earth') plot_planet(ax,pl) plt.show() """ from PyKEP import MU_SUN, SEC2DAY, epoch, AU from math import pi,sqrt import numpy as np if t0 == 'PyKEP.epoch(0)': t0 = epoch(0) #orbit semi-major axis a = plnt.orbital_elements[0] #orbital period in days T = 2*pi*sqrt(a**3/plnt.mu_central_body) * SEC2DAY #points where the orbit will be plotted when = np.linspace(0,T,N) #Ephemerides Calculation for the given planet x = np.array([0.0]*N) y = np.array([0.0]*N) z = np.array([0.0]*N) for i,day in enumerate(when): r,v = plnt.eph(epoch(t0.mjd2000 + day)) x[i] = r[0]/units y[i] = r[1]/units z[i] = r[2]/units #Actual plot commands if legend: label=plnt.name + " " + t0.__repr__()[0:11] else: label=None ax.plot(x, y, z, label=label, c=color) ax.scatter([x[0]],[y[0]],[z[0]], s=s, marker='o', alpha=0.8, c = color) if legend: ax.legend()
def _mga_incipit_cstrs_ctor( self, seq=[planet_js('io'), planet_js('io'), planet_js('europa')], t0=[epoch(7305.0), epoch(11323.0)], tof=[[100, 200], [3, 200], [4, 100]], Tmax=365.25, Dmin=0.2): """ USAGE: mga_incipit_cstrs(seq = [planet_js('io'),planet_js('io'),planet_js('europa')], t0 = [epoch(6905.0),epoch(11323.0)], tof = [[100,200],[3,200],[4,100]], Tmax = 365.25, Dmin = 0.2) * seq: list of jupiter moons defining the trajectory incipit * t0: list of two epochs defining the launch window * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) """ # We construct the arg list for the original constructor exposed by boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof) arg_list.append(Tmax) arg_list.append(Dmin) self._orig_init(*arg_list)
def planets_pos(self): from jplephem import Ephemeris import de421 from PyKEP import epoch self.eph = Ephemeris(de421) earthpos = [] marspos = [] venuspos = [] for ep in self.sc_state[3]: posSun, __ = self.eph.position_and_velocity('sun', epoch(ep, epoch.epoch_type.MJD2000).jd) positione, __ = self.eph.position_and_velocity('earthmoon', epoch(ep, epoch.epoch_type.MJD2000).jd) positione = self.eq2eclipt(positione - posSun) earthpos.append(positione) positionm, __ = self.eph.position_and_velocity('mars', epoch(ep, epoch.epoch_type.MJD2000).jd) positionm = self.eq2eclipt(positionm - posSun) marspos.append(positionm) positionv, __ = self.eph.position_and_velocity('venus', epoch(ep, epoch.epoch_type.MJD2000).jd) positionv = self.eq2eclipt(positionv - posSun) venuspos.append(positionv) self.earthpos_km = [earthpos[i].reshape((1,3)).tolist()[0] for i in range(len(earthpos))] self.marspos_km = [marspos[i].reshape((1,3)).tolist()[0] for i in range(len(earthpos))] self.venuspos_km = [venuspos[i].reshape((1,3)).tolist()[0] for i in range(len(earthpos))]
def plot(self,x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU, DAY2SEC from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg start = epoch(x[0]) end = epoch(x[0] + x[1]) r,v = self.__earth.eph(start) v = [a+b for a,b in zip(v,x[4:7])] x0 = sc_state(r,v,self.__sc.mass) r,v = self.__mars.eph(end) xe = sc_state(r, v ,x[3]) self.__leg.set(start,x0,x[-3 * self.__nseg:],end,xe, x[2] * DAY2SEC) fig = plt.figure() axis = fig.gca(projection='3d') #The Sun axis.scatter([0],[0],[0], color='y') #The leg plot_sf_leg(self.__leg, units=AU,N=10, ax = axis) #The planets plot_planet(self.__earth, start, units=AU, legend = True,color=(0.8,0.8,1), ax = axis) plot_planet(self.__mars, end, units=AU, legend = True,color=(0.8,0.8,1), ax = axis) plt.show()
def _compute_constraints_impl(self,x): from PyKEP import epoch, AU, EARTH_VELOCITY from PyKEP.sims_flanagan import leg, sc_state start = epoch(x[0]) end = epoch(x[0] + x[1]) r,v = self.__earth.eph(start) v = [a+b for a,b in zip(v,x[3:6])] x0 = sc_state(r,v,self.__sc.mass) r,v = self.__mars.eph(end) xe = sc_state(r, v ,x[2]) self.__leg.set(start,x0,x[-3 * self.__nseg:],end,xe) v_inf_con = (x[3] * x[3] + x[4] * x[4] + x[5] * x[5] - self.__Vinf * self.__Vinf) / (EARTH_VELOCITY * EARTH_VELOCITY) retval = list(self.__leg.mismatch_constraints() + self.__leg.throttles_constraints()) + [v_inf_con] #We then scale all constraints to non dimensiona values retval[0] /= AU retval[1] /= AU retval[2] /= AU retval[3] /= EARTH_VELOCITY retval[4] /= EARTH_VELOCITY retval[5] /= EARTH_VELOCITY retval[6] /= self.__sc.mass return retval
def plot(self, x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg t_E = epoch(x[0]) t_V = epoch(x[0] + x[1]) t_M = epoch(x[0] + x[1] + x[9]) rE, vE = self.__earth.eph(t_E) rV, vV = self.__venus.eph(t_V) rM, vM = self.__mercury.eph(t_M) #First Leg v = [a + b for a, b in zip(vE, x[3:6])] x0 = sc_state(rE, v, self.__sc.mass) v = [a + b for a, b in zip(vV, x[6:9])] xe = sc_state(rV, v, x[2]) self.__leg1.set( t_E, x0, x[-3 * (self.__nseg1 + self.__nseg2):-self.__nseg2 * 3], t_V, xe) #Second leg v = [a + b for a, b in zip(vV, x[11:14])] x0 = sc_state(rV, v, x[2]) v = [a + b for a, b in zip(vM, x[14:17])] xe = sc_state(rM, v, x[10]) self.__leg2.set(t_E, x0, x[(-3 * self.__nseg2):], t_V, xe) fig = plt.figure() axis = fig.gca(projection='3d') #The Sun axis.scatter([0], [0], [0], color='y') #The legs plot_sf_leg(self.__leg1, units=AU, N=10, ax=axis) plot_sf_leg(self.__leg2, units=AU, N=10, ax=axis) #The planets plot_planet(self.__earth, t_E, units=AU, legend=True, color=(0.7, 0.7, 1), ax=axis) plot_planet(self.__venus, t_V, units=AU, legend=True, color=(0.7, 0.7, 1), ax=axis) plot_planet(self.__mercury, t_M, units=AU, legend=True, color=(0.7, 0.7, 1), ax=axis) plt.show()
def get_score_data(self,x): """ This method returns the data needed to compute the score of a trajectory. This is tuples of (epoch, moon, v_inf, rp, beta) """ from _feasible_faces import vinfs_to_beta, get_fb_axis # moons nlegs = self.__n_legs # time of flights T = x[2::8][:nlegs] # epochs and ephemerides of the planetary encounters # ep_list = list([None] * nlegs) ep_list = list([None] * (nlegs+1)) t_P = list([None] * (nlegs+1)) r_P = list([None] * (nlegs+1)) v_P = list([None] * (nlegs+1)) for i,planet in enumerate(self.seq): ep_list[i+1] = self.tf - sum(T[i+1:]) t_P[i+1] = epoch(ep_list[i+1]) r_P[i+1],v_P[i+1] = self.seq[i].eph(t_P[i+1]) #And we insert a fake planet simulating the starting position ep_list[0] = self.tf - sum(T) t_P[0] = epoch(ep_list[0]) theta = x[0] phi = x[1] 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] r_P[0] = r v_P[0] = x[4:7] #getting vinfs_out vinf_in_list = list([None] * (nlegs)) for i, planet in enumerate(self.seq): vinf_in_list[i] = x[7+(i*8):10+(i*8)] #getting vinfs_in vinf_out_list = list([None] * (nlegs+1)) for i in xrange(len(self.seq) + 1): vinf_out_list[i] = x[4+(i*8):7+(i*8)] #getting rp beta_list = [] rp_list = [] for moon, vinf_in, vinf_out, v_planet in zip(self.seq[:-1], vinf_in_list[:-1], vinf_out_list[1:-1], v_P[1:]): alpha = acos(np.dot(vinf_in, vinf_out)/np.linalg.norm(vinf_in)/np.linalg.norm(vinf_out)) rp_list.append(moon.mu_self/np.dot(vinf_in,vinf_in)*(1.0/sin(alpha/2.0)-1.0)) beta_list.append(vinfs_to_beta(vinf_in, vinf_out, v_planet)) # last flyby is not yet determined rp_list.append(None) beta_list.append(None) return zip(ep_list[1:], self.seq, vinf_in_list, rp_list, beta_list)
def __init__( self, seq=[planet_ss('earth'), planet_ss('venus'), planet_ss('earth')], t0=[epoch(0), epoch(1000)], tof=[1.0, 5.0], vinf=[0.5, 2.5], add_vinf_dep=False, add_vinf_arr=True, multi_objective=False): """ Constructs an mga_1dsm problem USAGE: traj.mga_1dsm(seq = [planet_ss('earth'),planet_ss('venus'),planet_ss('earth')], t0 = [epoch(0),epoch(1000)], tof = [1.0,5.0], vinf = [0.5, 2.5], multi_objective = False, add_vinf_dep = False, add_vinf_arr=True) * seq: list of PyKEP planets defining the encounter sequence (including the starting launch) * t0: list of two epochs defining the launch window * tof: list of two floats defining the minimum and maximum allowed mission lenght (years) * vinf: list of two floats defining the minimum and maximum allowed initial hyperbolic velocity (at launch), in km/sec * multi_objective: when True constructs a multiobjective problem (dv, T) * add_vinf_dep: when True the computed Dv includes the initial hyperbolic velocity (at launch) * add_vinf_arr: when True the computed Dv includes the final hyperbolic velocity (at the last planet) """ #Sanity checks ...... all planets need to have the same mu_central_body if ([r.mu_central_body for r in seq].count(seq[0].mu_central_body) != len(seq)): raise ValueError( 'All planets in the sequence need to have exactly the same mu_central_body' ) self.__add_vinf_dep = add_vinf_dep self.__add_vinf_arr = add_vinf_arr self.__n_legs = len(seq) - 1 dim = 6 + (self.__n_legs - 1) * 4 obj_dim = multi_objective + 1 #First we call the constructor for the base PyGMO problem #As our problem is n dimensional, box-bounded (may be multi-objective), we write #(dim, integer dim, number of obj, number of con, number of inequality con, tolerance on con violation) super(mga_1dsm, self).__init__(dim, 0, obj_dim, 0, 0, 0) #We then define all planets in the sequence and the common central body gravity as data members self.seq = seq self.common_mu = seq[0].mu_central_body #And we compute the bounds lb = [t0[0].mjd2000, 0.0, 0.0, vinf[0] * 1000, 1e-5, tof[0] * 365.25 ] + [-2 * pi, 1.1, 1e-5, 1e-5] * (self.__n_legs - 1) ub = [ t0[1].mjd2000, 1.0, 1.0, vinf[1] * 1000, 1.0 - 1e-5, tof[1] * 365.25 ] + [2 * pi, 30.0, 1.0 - 1e-5, 1.0 - 1e-5] * (self.__n_legs - 1) #Accounting that each planet has a different safe radius...... for i, pl in enumerate(seq[1:-1]): lb[7 + 4 * i] = pl.safe_radius / pl.radius #And we set them self.set_bounds(lb, ub)
def __init__( self, t=[epoch(8.233141758995751e+003), epoch(8.289990617468195e+003)], r=[[-660821073.83843112, -85286653.193055451, -3513417.5052384529], [-660832082.91625774, -85197143.615338504, -3513971.6825616611]], v=[[7873.9701471924709, -16990.277371090539, -58.967610944493998], [7869.0526122101373, -16988.601525093596, -58.937906751346844]], m0=2000, Tmax=0.1, Isp=2000, mu=MU_JUPITER, n_seg=10, high_fidelity=False, optimize_mass=False): """ USAGE: one_lt_leg(t = [epoch(8.233141758995751e+003), epoch(8.289990617468195e+003)], r = [[-660821073.83843112, -85286653.193055451, -3513417.5052384529], [-660832082.91625774, -85197143.615338504, -3513971.6825616611]], v = [[7873.9701471924709, -16990.277371090539, -58.967610944493998], [7869.0526122101373, -16988.601525093596, -58.937906751346844]], m0 = 2000, Tmax = 0.1, Isp = 2000, mu = MU_JUPITER, n_seg = 10, high_fidelity = False) * t: starting and final epochs * r: starting and final position (m) * v: starting and final velocity (m/s) * m0: starting mass (k) * Tmax: maximum allowed thrust (N) * Isp: specific impulse (s) * mu = central body gravity parameter (m^3/s^2) * n_seg = number of segments, * high_fidelity = compute the trajectory in high fidelity mode * optimize_mass = when False the problem is built as a constraint satisfaction problem. When True mass gets optimized """ self.__t = t self.__r = r self.__v = v self.__opt_mass = optimize_mass self.__sc = spacecraft(m0, Tmax, Isp) self.__leg = leg() self.__leg.set_mu(mu) self.__leg.set_spacecraft(self.__sc) self.__leg.high_fidelity = high_fidelity dim = 1 + n_seg * 3 c_dim = n_seg + 7 #First we call the constructor for the base PyGMO problem #As our problem is n dimensional, box-bounded (may be multi-objective), we write #(dim, integer dim, number of obj, number of con, number of inequality con, tolerance on con violation) super(one_lt_leg, self).__init__(dim, 0, 1, c_dim, n_seg, 1e-4) #And we compute the bounds lb = [m0 / 2] + [-1.0] * n_seg * 3 ub = [m0] + [1.0] * n_seg * 3 self.set_bounds(lb, ub)
def plot(self, x, ax=None): """ ax = prob.plot(x, ax=None) - x: encoded trajectory - ax: matplotlib axis where to plot. If None figure and axis will be created - [out] ax: matplotlib axis where to plot Plots the trajectory represented by a decision vector x on the 3d axis ax Example:: ax = prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg # Creating the axis if necessary if ax is None: mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() axis = fig.gca(projection='3d') else: axis = ax # Plotting the Sun ........ axis.scatter([0], [0], [0], color='y') # Computing the legs self._compute_constraints_impl(x) # Plotting the legs for leg in self.__legs: plot_sf_leg(leg, units=AU, N=10, ax=axis) # Plotting the PyKEP.planets both at departure and arrival dates for i in range(self.__num_legs): idx = i * self.__dim_leg plot_planet(self.__seq[i], epoch(x[idx]), units=AU, legend=True, color=(0.7, 0.7, 1), s=30, ax=axis) plot_planet(self.__seq[i + 1], epoch(x[idx] + x[idx + 1]), units=AU, legend=False, color=(0.7, 0.7, 1), s=30, ax=axis) plt.show() return axis
def planet_planet(start_planet, arrive_planet, tlaunch, tarrive, rev, N): # Create PyKEP epoch objects and calculate flight time t1 = epoch(tlaunch) t2 = epoch(tarrive) dt = (tarrive - tlaunch) * DAY2SEC OBJ1 = planet_ss(start_planet) OBJ2 = planet_ss( arrive_planet) # Calculate location of objects in flight path r1, v1 = OBJ1.eph(t1) r2, v2 = OBJ2.eph(t2) # Find trajectory l = lambert_problem(r1, r2, dt, MU_SUN) #extract relevant information from solution r = l.get_r1() v = l.get_v1()[0] mu = l.get_mu() #define the integration time dtn = dt / (N - 1) dtn_days = dtn * SEC2DAY #alocate the cartesian components for r t = np.array([0.0] * N) x = np.array([0.0] * N) y = np.array([0.0] * N) z = np.array([0.0] * N) #calculate the spacecraft position at each dt for i in range(N): t[i] = tlaunch + dtn_days * i x[i] = r[0] / AU y[i] = r[1] / AU z[i] = r[2] / AU r, v = propagate_lagrangian(r, v, dtn, mu) #traj = [t, x, y, z] vin = l.get_v1()[rev] vout = l.get_v2()[rev] #dV=fb_vel(vin,vout,planet_ss(arrive_planet)) #dV=np.sqrt( np.square(vin[0]/vout[0])+np.square(vin[1]/vout[1])+np.square(vin[2]/vout[2])) #dV=np.sqrt( np.square(vin[0]-v1[0])+np.square(v1[1]-vin[1])+np.square(v1[2]-vin[2])) #dV=np.sqrt( np.square(v2[0]-vout[0])+np.square(v2[1]-vout[1])+np.square(v2[2]-vout[2])) #dV=np.sqrt( np.square(v1[0]/vin[0])+np.square(v1[1]/vin[1])+np.square(v1[2]/vin[2])) C3_launch = (np.sqrt( np.square(vin[0] - v1[0]) + np.square(vin[1] - v1[1]) + np.square(vin[2] - v1[2])))**2 C3_arrive = (np.sqrt( np.square(vout[0] - v2[0]) + np.square(vout[1] - v2[1]) + np.square(vout[2] - v2[2])))**2 C3 = np.sqrt((C3_arrive**2) + (C3_launch**2)) return C3
def _mga_1dsm_tof_plot(self, x): """ Plots the trajectory represented by the decision vector x """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(0, 0, 0, color='y') seq = self.get_sequence() # 2 - We plot the first leg r_P0, v_P0 = seq[0].eph(epoch(x[0])) plot_planet(ax, seq[0], t0=epoch(x[0]), color=(0.8, 0.6, 0.8), legend=True, units=AU) r_P1, v_P1 = seq[1].eph(epoch(x[0] + x[5])) theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 Vinfx = x[3] * cos(phi) * cos(theta) Vinfy = x[3] * cos(phi) * sin(theta) Vinfz = x[3] * sin(phi) v0 = [a + b for a, b in zip(v_P0, [Vinfx, Vinfy, Vinfz])] r, v = propagate_lagrangian(r_P0, v0, x[4] * x[5] * DAY2SEC, seq[0].mu_central_body) plot_kepler(ax, r_P0, v0, x[4] * x[5] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU) # Lambert arc to reach seq[1] dt = (1 - x[4]) * x[5] * DAY2SEC l = lambert_problem(r, r_P1, dt, seq[0].mu_central_body) plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU) v_end_l = l.get_v2()[0] vinf_in = [a - b for a, b in zip(v_end_l, v_P1)] _part_plot(x[6:], AU, ax, seq[1:], x[0] + x[5], vinf_in) return ax
def _mga_1dsm_tof_plot(self, x): """ Plots the trajectory represented by the decision vector x """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(0, 0, 0, color='y') seq = self.get_sequence() # 2 - We plot the first leg r_P0, v_P0 = seq[0].eph(epoch(x[0])) plot_planet(ax, seq[0], t0=epoch(x[0]), color=( 0.8, 0.6, 0.8), legend=True, units = AU) r_P1, v_P1 = seq[1].eph(epoch(x[0] + x[5])) theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 Vinfx = x[3] * cos(phi) * cos(theta) Vinfy = x[3] * cos(phi) * sin(theta) Vinfz = x[3] * sin(phi) v0 = [a + b for a, b in zip(v_P0, [Vinfx, Vinfy, Vinfz])] r, v = propagate_lagrangian( r_P0, v0, x[4] * x[5] * DAY2SEC, seq[0].mu_central_body) plot_kepler( ax, r_P0, v0, x[4] * x[5] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU) # Lambert arc to reach seq[1] dt = (1 - x[4]) * x[5] * DAY2SEC l = lambert_problem(r, r_P1, dt, seq[0].mu_central_body) plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU) v_end_l = l.get_v2()[0] vinf_in = [a - b for a, b in zip(v_end_l, v_P1)] _part_plot(x[6:], AU, ax, seq[1:], x[0] + x[5], vinf_in) return ax
def __init__(self, seq = [planet_ss('earth'),planet_ss('venus'),planet_ss('earth')], t0 = [epoch(0),epoch(1000)], tof = [[100, 200],[200, 300]], vinf = [3,5], add_vinf_dep=False, add_vinf_arr=True, multi_objective = False): """ Constructs an mga_1dsm_tof problem USAGE: traj.mga_1dsm(seq = [planet_ss('earth'),planet_ss('venus'),planet_ss('earth')], t0 = [epoch(0),epoch(1000)], tof = [[100, 200],[200, 300]], vinf = [0.5, 2.5], multi_objective = False, add_vinf_dep = False, add_vinf_arr=True) * seq: list of PyKEP planets defining the encounter sequence (including the starting launch) * t0: list of two epochs defining the launch window * tof: containing a list of intervals for the time of flight of each leg (days) * vinf: list of two floats defining the minimum and maximum allowed initial hyperbolic velocity (at launch), in km/sec * multi_objective: when True constructs a multiobjective problem (dv, T) * add_vinf_dep: when True the computed Dv includes the initial hyperbolic velocity (at launch) * add_vinf_arr: when True the computed Dv includes the final hyperbolic velocity (at the last planet) """ #Sanity checks ...... all planets need to have the same mu_central_body if ( [r.mu_central_body for r in seq].count(seq[0].mu_central_body)!=len(seq) ): raise ValueError('All planets in the sequence need to have exactly the same mu_central_body') self.__add_vinf_dep = add_vinf_dep self.__add_vinf_arr = add_vinf_arr self.__n_legs = len(seq) - 1 dim = 5 + (self.__n_legs-1) * 3 + (self.__n_legs)* 1 obj_dim = multi_objective + 1 #First we call the constructor for the base PyGMO problem #As our problem is n dimensional, box-bounded (may be multi-objective), we write #(dim, integer dim, number of obj, number of con, number of inequality con, tolerance on con violation) super(mga_1dsm_tof,self).__init__(dim,0,obj_dim,0,0,0) #We then define all planets in the sequence and the common central body gravity as data members self.seq = seq self.common_mu = seq[0].mu_central_body #And we compute the bounds lb = [t0[0].mjd2000,0.0,0.0,vinf[0]*1000,1e-5] + [-2*pi, 1.1,1e-5 ] * (self.__n_legs-1) + [1]*self.__n_legs ub = [t0[1].mjd2000,1.0,1.0,vinf[1]*1000,1.0-1e-5] + [2*pi, 30.0,1.0-1e-5] * (self.__n_legs-1) + [700]*self.__n_legs for i in range(0, self.__n_legs): lb[4+3*(self.__n_legs-1) + i+1] = tof[i][0] ub[4+3*(self.__n_legs-1) + i+1] = tof[i][1] #Accounting that each planet has a different safe radius...... for i,pl in enumerate(seq[1:-1]): lb[6+3*i] = pl.safe_radius / pl.radius #And we set them self.set_bounds(lb,ub)
def __init__(self, t = [epoch(8.233141758995751e+003), epoch(8.289990617468195e+003)], r = [[-660821073.83843112, -85286653.193055451, -3513417.5052384529], [-660832082.91625774, -85197143.615338504, -3513971.6825616611]], v = [[7873.9701471924709, -16990.277371090539, -58.967610944493998], [7869.0526122101373, -16988.601525093596, -58.937906751346844]], m0 = 2000, Tmax = 0.1, Isp = 2000, mu = MU_JUPITER, n_seg = 10, high_fidelity = False, optimize_mass = False ): """ USAGE: one_lt_leg(t = [epoch(8.233141758995751e+003), epoch(8.289990617468195e+003)], r = [[-660821073.83843112, -85286653.193055451, -3513417.5052384529], [-660832082.91625774, -85197143.615338504, -3513971.6825616611]], v = [[7873.9701471924709, -16990.277371090539, -58.967610944493998], [7869.0526122101373, -16988.601525093596, -58.937906751346844]], m0 = 2000, Tmax = 0.1, Isp = 2000, mu = MU_JUPITER, n_seg = 10, high_fidelity = False) * t: starting and final epochs * r: starting and final position (m) * v: starting and final velocity (m/s) * m0: starting mass (k) * Tmax: maximum allowed thrust (N) * Isp: specific impulse (s) * mu = central body gravity parameter (m^3/s^2) * n_seg = number of segments, * high_fidelity = compute the trajectory in high fidelity mode * optimize_mass = when False the problem is built as a constraint satisfaction problem. When True mass gets optimized """ self.__t = t self.__r = r self.__v = v self.__opt_mass = optimize_mass self.__sc = spacecraft(m0,Tmax,Isp) self.__leg = leg() self.__leg.set_mu(mu) self.__leg.set_spacecraft(self.__sc) self.__leg.high_fidelity = high_fidelity dim = 1 + n_seg * 3 c_dim = n_seg + 7 #First we call the constructor for the base PyGMO problem #As our problem is n dimensional, box-bounded (may be multi-objective), we write #(dim, integer dim, number of obj, number of con, number of inequality con, tolerance on con violation) super(one_lt_leg,self).__init__(dim,0,1,c_dim,n_seg,1e-4) #And we compute the bounds lb = [m0/2] + [-1.0] * n_seg * 3 ub = [m0] + [1.0] * n_seg * 3 self.set_bounds(lb,ub)
def planet_planet(start_planet, arrive_planet, tlaunch, tarrive, rev, N): # Create PyKEP epoch objects and calculate flight time t1 = epoch(tlaunch) t2 = epoch(tarrive) dt = (tarrive - tlaunch) * DAY2SEC OBJ1 = planet_ss(start_planet) OBJ2 = planet_ss(arrive_planet) # Calculate location of objects in flight path r1, v1 = OBJ1.eph(t1) r2, v2 = OBJ2.eph(t2) # Find trajectory l = lambert_problem(r1, r2, dt, MU_SUN) #extract relevant information from solution r = l.get_r1() v = l.get_v1()[0] mu = l.get_mu() #define the integration time dtn = dt / (N - 1) dtn_days = dtn * SEC2DAY #alocate the cartesian components for r t = np.array([0.0] * N) x = np.array([0.0] * N) y = np.array([0.0] * N) z = np.array([0.0] * N) #calculate the spacecraft position at each dt for i in range(N): t[i] = tlaunch + dtn_days * i x[i] = r[0] / AU y[i] = r[1] / AU z[i] = r[2] / AU r, v = propagate_lagrangian(r, v, dtn, mu) #traj = [t, x, y, z] vin = l.get_v1()[rev] vout = l.get_v2()[rev] #dV=fb_vel(vin,vout,planet_ss(arrive_planet)) #dV=np.sqrt( np.square(vin[0]/vout[0])+np.square(vin[1]/vout[1])+np.square(vin[2]/vout[2])) #dV=np.sqrt( np.square(vin[0]-v1[0])+np.square(v1[1]-vin[1])+np.square(v1[2]-vin[2])) #dV=np.sqrt( np.square(v2[0]-vout[0])+np.square(v2[1]-vout[1])+np.square(v2[2]-vout[2])) #dV=np.sqrt( np.square(v1[0]/vin[0])+np.square(v1[1]/vin[1])+np.square(v1[2]/vin[2])) C3_launch = (np.sqrt(np.square(vin[0] - v1[0]) + np.square(vin[1] - v1[1]) + np.square(vin[2] - v1[2]))) ** 2 C3_arrive = (np.sqrt(np.square(vout[0] - v2[0]) + np.square(vout[1] - v2[1]) + np.square(vout[2] - v2[2]))) ** 2 C3 = np.sqrt((C3_arrive ** 2) + (C3_launch ** 2)) return C3
def plot_cluster_evolution(self, cluster_id=None, only_core=False, epochs=range(7500, 8400, 100), skip=100, alpha=0.3): """ Plots a cluster evolution at 9 prefixed epochs. """ if self.n_clusters < 1: print("No clusters have been found yet") return if cluster_id >= self.n_clusters or cluster_id < 0: print( "cluster_id should be larger then 0 and smaller than the number of clusters (-1)" ) return if len(epochs) != 9: print( "The epochs requested must be exactly 9 as to assemble 3x3 subplots" ) return import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D from PyKEP.orbit_plots import plot_planet from PyKEP import epoch if only_core: ids = self.core_members[cluster_id] else: ids = self.members[cluster_id] fig = plt.figure() for i, ep in enumerate(epochs): axis = fig.add_subplot(3, 3, i + 1, projection='3d') plt.axis('off') plt.title(epoch(ep).__repr__()[:11]) for pl in self._asteroids[::skip]: axis = plot_planet(pl, ax=axis, alpha=0.05, s=0) for cluster_member in ids: r, v = self._asteroids[cluster_member].eph(epoch(ep)) axis.scatter([r[0]], [r[1]], [r[2]], marker='o', alpha=alpha) plt.draw() plt.show() return fig
def plot_initial_geometry(ni=0.0, mu=0.5): """ Visualizes the initial spaceraft conditions for the gtoc6 problem. Given a point on the initial spheres, \ it assumes a velocity (almost) pointing toward Jupiter. THIS IS ONLY A VISUALIZATION, the initial velocityshould not be taken as realistic. """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from math import sin,cos,acos,pi from PyKEP.orbit_plots import plot_kepler, plot_planet from PyKEP import DAY2SEC, propagate_lagrangian, epoch from scipy.linalg import norm ep=epoch(0.0) days=300.0 r = [JR*1000*cos(ni)*cos(mu), JR*1000*cos(ni)*sin(mu),JR*1000*sin(ni)] VINF = 3400.0 v = [-d/norm(r)*3400 for d in r] v = [d+200 for d in v] fig = plt.figure() ax = fig.gca(projection='3d', aspect='equal') plot_planet(ax,io,color = 'r', units = JR, t0 = ep, legend=True) plot_planet(ax,europa,color = 'b', units = JR, t0 = ep, legend=True) plot_planet(ax,ganymede,color = 'k', units = JR, t0 = ep, legend=True) plot_planet(ax,callisto,color = 'y', units = JR, t0 = ep, legend=True) plot_kepler(ax,r,v,days*DAY2SEC,MU_JUPITER, N=200, units = JR, color = 'b') plt.plot([r[0]/JR],[r[1]/JR],[r[2]/JR],'o') plt.show()
def opt_dt(tt1,tt2): t1 = epoch(tt1) t2 = epoch(tt2) #print t1 dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC rE, vE = plEarth.eph(t1); vE=array(vE) rM, vM = plMars .eph(t2); vM=array(vM) l = lambert_problem(rE,rM,dt,MU_SUN) vEl = array(l.get_v1()[0]); dvE = (vEl - vE) vMl = array(l.get_v2()[0]); dvM = (vMl - vM) dvMTot = linalg.norm(dvM); dvETot= linalg.norm(dvE) dvTot = dvMTot+dvETot print " t1 " ,tt1," t2 ", tt2," dt ",(tt2-tt1)," dv ", dvTot return vE, vM, vEl, vMl
def plot(self, x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg t_E = epoch(x[0]) t_V = epoch(x[0] + x[1]) t_M = epoch(x[0] + x[1] + x[9]) rE, vE = self.__earth.eph(t_E) rV, vV = self.__venus.eph(t_V) rM, vM = self.__mercury.eph(t_M) # First Leg v = [a + b for a, b in zip(vE, x[3:6])] x0 = sc_state(rE, v, self.__sc.mass) v = [a + b for a, b in zip(vV, x[6:9])] xe = sc_state(rV, v, x[2]) self.__leg1.set( t_E, x0, x[-3 * (self.__nseg1 + self.__nseg2):-self.__nseg2 * 3], t_V, xe) # Second leg v = [a + b for a, b in zip(vV, x[11:14])] x0 = sc_state(rV, v, x[2]) v = [a + b for a, b in zip(vM, x[14:17])] xe = sc_state(rM, v, x[10]) self.__leg2.set(t_E, x0, x[(-3 * self.__nseg2):], t_V, xe) fig = plt.figure() axis = fig.gca(projection='3d') # The Sun axis.scatter([0], [0], [0], color='y') # The legs plot_sf_leg(self.__leg1, units=AU, N=10, ax=axis) plot_sf_leg(self.__leg2, units=AU, N=10, ax=axis) # The planets plot_planet( self.__earth, t_E, units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis) plot_planet( self.__venus, t_V, units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis) plot_planet( self.__mercury, t_M, units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis) plt.show()
def plot(self,x): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg fig = plt.figure() ax = fig.gca(projection='3d') #Plotting the Sun ........ ax.scatter([0],[0],[0], color='y') #Plotting the legs ....... # 1 - We decode the chromosome extracting the time of flights T = list([0]*(self.__n_legs)) for i in range(self.__n_legs): T[i] = x[1+i*8] #2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (self.__n_legs+1)) r_P = list([None] * (self.__n_legs+1)) v_P = list([None] * (self.__n_legs+1)) for i,planet in enumerate(self.seq): t_P[i] = epoch(x[0] + sum(T[0:i])) r_P[i],v_P[i] = self.seq[i].eph(t_P[i]) #3 - We iterate through legs to compute mismatches and throttles constraints ceq = list() cineq = list() m0 = self.__sc.mass for i in range(self.__n_legs): #First Leg v = [a+b for a,b in zip(v_P[i],x[(3 + i * 8):(6 + i * 8)])] x0 = sc_state(r_P[i],v,m0) v = [a+b for a,b in zip(v_P[i+1],x[(6 + i * 8):(11 + i * 8)])] xe = sc_state(r_P[i+1], v ,x[2 + i * 8]) throttles = x[(1 +8 * self.__n_legs + 3*sum(self.__n_seg[:i])):(1 +8 * self.__n_legs + 3*sum(self.__n_seg[:i])+3*self.__n_seg[i])] self.__leg.set(t_P[i],x0,throttles,t_P[i+1],xe) #update mass! m0 = x[2+8*i] plot_sf_leg(ax, self.__leg, units=AU,N=10) #Plotting planets for i,planet in enumerate(self.seq): plot_planet(ax, planet, t_P[i], units=AU, legend = True,color=(0.7,0.7,1)) plt.show()
def _get_score_data_part(self, x): from PyKEP import epoch, lambert_problem, DAY2SEC, fb_prop, propagate_lagrangian from math import pi, acos, cos, sin, sqrt from scipy.linalg import norm from copy import deepcopy """ This method returns the data needed to compute the score of a trajectory. """ #1 - we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience T = x[3::4] nlegs = len(x) / 4 seq = self.get_sequence() common_mu = seq[0].mu_central_body t0 = self.t0.mjd2000 vinf_in = deepcopy(self.vinf_in) #2 - We compute the epochs and ephemerides of the planetary encounters ep_list = list([None] * (nlegs + 1)) t_P = list([None] * (nlegs + 1)) r_P = list([None] * (nlegs + 1)) v_P = list([None] * (nlegs + 1)) DV = list([None] * nlegs) for i, planet in enumerate(seq): ep_list[i] = t0 + sum(T[:i]) t_P[i] = epoch(t0 + sum(T[:i])) r_P[i], v_P[i] = seq[i].eph(t_P[i]) #init lists for fly-by parameters vinf_list = [] rp_list = [] beta_list = [] v_end_l = [a + b for a, b in zip(vinf_in, v_P[0])] #3 - And we proceed with each successive leg for i in xrange(nlegs): #Fly-by v_out = fb_prop(v_end_l, v_P[i], x[1 + 4 * i] * seq[i].radius, x[4 * i], seq[i].mu_self) vinf_list.append([a - b for a, b in zip(v_end_l, v_P[i])]) rp_list.append(x[1 + 4 * i] * seq[i].radius) beta_list.append(x[4 * i]) #s/c propagation before the DSM r, v = propagate_lagrangian(r_P[i], 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 + 1], dt, common_mu, False, False) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] vinf_list.append([a - b for a, b in zip(v_end_l, v_P[-1])]) rp_list.append(None) beta_list.append(None) return zip(ep_list, seq, vinf_list, rp_list, beta_list)
def _mga_part_plot(self, x): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams["legend.fontsize"] = 10 fig = plt.figure() ax = fig.gca(projection="3d", aspect="equal") ax.scatter(0, 0, 0, color="y") JR = 71492000.0 legs = len(x) / 4 seq = self.get_sequence() common_mu = seq[0].mu_central_body start_mjd2000 = self.t0.mjd2000 # 1 - we 'decode' the chromosome recording the various times of flight (days) in the list T T = x[3::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (legs + 1)) r_P = list([None] * (legs + 1)) v_P = list([None] * (legs + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(start_mjd2000 + sum(T[:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(ax, planet, t0=t_P[i], color=(0.8, 0.6, 0.8), legend=True, units=JR) v_end_l = [a + b for a, b in zip(v_P[0], self.vinf_in)] # 4 - And we iterate on the legs for i in xrange(0, legs): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[1 + 4 * i] * seq[i - 1].radius, x[4 * i], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian(r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) plot_kepler( ax, r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu, N=500, color="b", legend=False, units=JR ) # 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 + 1], dt, common_mu, False, False) plot_lambert(ax, l, sol=0, color="r", legend=False, units=JR, N=500) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] plt.show() return ax
def _compute_DV_DT_incipit(self,x): """ This method computes, for each leg, all the velocity increments coming from deep space manoeuvres and all the transfer times. Use: DV,DT = prob.compute_DV_DT(x) * x: trajectory encoding """ from PyKEP import epoch, lambert_problem, DAY2SEC, fb_prop, propagate_lagrangian from math import pi, acos,cos,sin,sqrt from scipy.linalg import norm #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] #First DSM occuring at the very beginning (will be cancelled by the optimizer) DV[0] = abs(norm(v_beg_l) - 3400) #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)]) return (DV,T)
def _get_score_data_part(self,x): from PyKEP import epoch, lambert_problem, DAY2SEC, fb_prop, propagate_lagrangian from math import pi, acos,cos,sin,sqrt from scipy.linalg import norm from copy import deepcopy """ This method returns the data needed to compute the score of a trajectory. """ #1 - we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience T = x[3::4] nlegs = len(x)/4 seq = self.get_sequence() common_mu = seq[0].mu_central_body t0 = self.t0.mjd2000 vinf_in = deepcopy(self.vinf_in) #2 - We compute the epochs and ephemerides of the planetary encounters ep_list = list([None] * (nlegs+1)) t_P = list([None] * (nlegs+1)) r_P = list([None] * (nlegs+1)) v_P = list([None] * (nlegs+1)) DV = list([None] * nlegs) for i,planet in enumerate(seq): ep_list[i] = t0+sum(T[:i]) t_P[i] = epoch(t0+sum(T[:i])) r_P[i],v_P[i] = seq[i].eph(t_P[i]) #init lists for fly-by parameters vinf_list = [] rp_list = [] beta_list = [] v_end_l = [a+b for a,b in zip(vinf_in, v_P[0])] #3 - And we proceed with each successive leg for i in xrange(nlegs): #Fly-by v_out = fb_prop(v_end_l,v_P[i],x[1+4*i]*seq[i].radius,x[4*i],seq[i].mu_self) vinf_list.append( [a-b for a,b in zip(v_end_l,v_P[i])] ) rp_list.append(x[1+4*i]*seq[i].radius) beta_list.append(x[4*i]) #s/c propagation before the DSM r,v = propagate_lagrangian(r_P[i],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+1],dt,common_mu, False, False) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] vinf_list.append([a-b for a,b in zip(v_end_l,v_P[-1])]) rp_list.append(None) beta_list.append(None) return zip(ep_list, seq, vinf_list, rp_list, beta_list)
def _part_plot(x, units, ax, seq, start_mjd2000, vinf_in): """ Plots the trajectory represented by a decision vector x = [beta,rp,eta,T] * N associated to a sequence seq, a start_mjd2000 and an incoming vinf_in """ from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm legs = len(x) / 4 common_mu = seq[0].mu_central_body # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = x[3::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (legs + 1)) r_P = list([None] * (legs + 1)) v_P = list([None] * (legs + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(start_mjd2000 + sum(T[:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(ax, planet, t0=t_P[i], color=(0.8, 0.6, 0.8), legend=True, units=units) v_end_l = [a + b for a, b in zip(v_P[0], vinf_in)] # 4 - And we iterate on the legs for i in range(0, legs): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[1 + 4 * i] * seq[i].radius, x[4 * i], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian(r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) plot_kepler(ax, r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu, N=500, color='b', legend=False, units=units) # 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 + 1], dt, common_mu, False, False) plot_lambert(ax, l, sol=0, color='r', legend=False, units=units, N=500) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0]
def plot(self, x): # Making sure the leg corresponds to the requested chromosome self._compute_constraints_impl(x) start = epoch(x[0]) end = epoch(x[0] + x[1]) # Plotting commands fig = plt.figure() axis = fig.gca(projection='3d') # The Sun axis.scatter([0], [0], [0], color='y') # The leg plot_sf_leg(self.leg, units=AU, N=10, ax=axis) # The planets plot_planet( self.earth, start, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis) plot_planet( self.mars, end, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis) plt.show()
def __init__(self, seq = [io,io,europa], t0 = [epoch(7305.0),epoch(11322.0)], tof = [200,500], multi_objective = False ): """ * seq: list of jupiter moons defining the trajectory incipit * t0: list of two epochs defining the launch window * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) """ self.__n_legs = len(seq) self.tof = tof #dim = 5+4 * self.__n_legs-1 dim = 5+4*(len(seq)-1) obj_dim = multi_objective + 1 #First we call the constructor for the base PyGMO problem #As our problem is n dimensional, box-bounded (may be multi-objective), we write #(dim, integer dim, number of obj, number of con, number of inequality con, tolerance on con violation) super(mga_incipit,self).__init__(dim,0,obj_dim,0,0,0) #We then define all planets in the sequence and the common central body gravity as data members self.seq = seq self.common_mu = seq[0].mu_central_body #And we compute the bounds lb = [t0[0].mjd2000,0.0,0.0,tof[0],1e-5] ub = [t0[1].mjd2000,1.0,1.0,tof[1],1-1e-5] for i in range(1, self.__n_legs): lb = lb + [-2*pi ,1.1 , 1e-5 , 1e-5] ub = ub + [2*pi ,30.0, 1-1e-5, 1-1e-5] #Accounting for the fly-bys altitudes for i,pl in enumerate(seq[0:-1]): lb[6+4*i] = pl.safe_radius / pl.radius ub[6+4*i] = (pl.radius + 2000000) / pl.radius #And we set them self.set_bounds(lb,ub)
def plot_cluster_evolution(self, cluster_id=None, only_core=False, epochs=range(7500, 8400, 100), skip=100, alpha=0.3): """ Plots a cluster evolution at 9 prefixed epochs. """ if self.n_clusters < 1: print("No clusters have been found yet") return if cluster_id >= self.n_clusters or cluster_id < 0: print("cluster_id should be larger then 0 and smaller than the number of clusters (-1)") return if len(epochs) != 9: print("The epochs requested must be exactly 9 as to assemble 3x3 subplots") return import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D from PyKEP.orbit_plots import plot_planet from PyKEP import epoch if only_core: ids = self.core_members[cluster_id] else: ids = self.members[cluster_id] fig = plt.figure() for i, ep in enumerate(epochs): axis = fig.add_subplot(3, 3, i + 1, projection='3d') plt.axis('off') plt.title(epoch(ep).__repr__()[:11]) for pl in self._asteroids[::skip]: axis = plot_planet(pl, ax=axis, alpha=0.05, s=0) for cluster_member in ids: r, v = self._asteroids[cluster_member].eph(epoch(ep)) axis.scatter([r[0]], [r[1]], [r[2]], marker='o', alpha=alpha) plt.draw() plt.show() return fig
def plot(self, x): import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP import epoch, AU from PyKEP.sims_flanagan import sc_state from PyKEP.orbit_plots import plot_planet, plot_sf_leg # Creating the axis ........ fig = plt.figure() axis = fig.gca(projection='3d') # Plotting the Sun ........ axis.scatter([0], [0], [0], color='y') # Computing the legs self._compute_constraints_impl(x) # Plotting the legs for leg in self.__legs: plot_sf_leg(leg, units=AU, N=10, ax=axis) # Plotting the PyKEP.planets both at departure and arrival dates for i in range(self.__num_legs): idx = i * self.__dim_leg plot_planet(self.__seq[i], epoch(x[idx]), units=AU, legend=True, color=(0.7, 0.7, 1), s=30, ax=axis) plot_planet(self.__seq[i + 1], epoch(x[idx] + x[idx + 1]), units=AU, legend=False, color=(0.7, 0.7, 1), s=30, ax=axis) plt.show() return axis
def __init__(self, seq=[io, io, europa], t0=[epoch(7305.0), epoch(11322.0)], tof=[200, 500], multi_objective=False): """ * seq: list of jupiter moons defining the trajectory incipit * t0: list of two epochs defining the launch window * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) """ self.__n_legs = len(seq) self.tof = tof #dim = 5+4 * self.__n_legs-1 dim = 5 + 4 * (len(seq) - 1) obj_dim = multi_objective + 1 #First we call the constructor for the base PyGMO problem #As our problem is n dimensional, box-bounded (may be multi-objective), we write #(dim, integer dim, number of obj, number of con, number of inequality con, tolerance on con violation) super(mga_incipit, self).__init__(dim, 0, obj_dim, 0, 0, 0) #We then define all planets in the sequence and the common central body gravity as data members self.seq = seq self.common_mu = seq[0].mu_central_body #And we compute the bounds lb = [t0[0].mjd2000, 0.0, 0.0, tof[0], 1e-5] ub = [t0[1].mjd2000, 1.0, 1.0, tof[1], 1 - 1e-5] for i in range(1, self.__n_legs): lb = lb + [-2 * pi, 1.1, 1e-5, 1e-5] ub = ub + [2 * pi, 30.0, 1 - 1e-5, 1 - 1e-5] #Accounting for the fly-bys altitudes for i, pl in enumerate(seq[0:-1]): lb[6 + 4 * i] = pl.safe_radius / pl.radius ub[6 + 4 * i] = (pl.radius + 2000000) / pl.radius #And we set them self.set_bounds(lb, ub)
def _mga_1dsm_alpha_ctor( self, seq=[planet_ss('earth'), planet_ss('venus'), planet_ss('earth')], t0=[epoch(0), epoch(1000)], tof=[365.25, 5.0 * 365.25], vinf=[0.5, 2.5], multi_objective=False, add_vinf_dep=False, add_vinf_arr=True): """ Constructs an mga_1dsm problem (alpha-encoding) USAGE: problem.mga_1dsm(seq = [planet_ss('earth'),planet_ss('venus'),planet_ss('earth')], t0 = [epoch(0),epoch(1000)], tof = [365.25,5.0 * 365.25], vinf = [0.5, 2.5], multi_objective = False, add_vinf_dep = False, add_vinf_arr = True) * seq: list of PyKEP planets defining the encounter sequence (including the starting planet) * t0: list of two epochs defining the launch window * tof: list of two floats defining the minimum and maximum allowed mission length (days) * vinf: list of two floats defining the minimum and maximum allowed initial hyperbolic velocity at launch (km/sec) * multi_objective: when True constructs a multiobjective problem (dv, T) * add_vinf_dep: when True the computed Dv includes the initial hyperbolic velocity (at launch) * add_vinf_arr: when True the computed Dv includes the final hyperbolic velocity (at arrival) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof[0]) arg_list.append(tof[1]) arg_list.append(vinf[0]) arg_list.append(vinf[1]) arg_list.append(multi_objective) arg_list.append(add_vinf_dep) arg_list.append(add_vinf_arr) self._orig_init(*arg_list)
def opt_dt(tt1, tt2): t1 = epoch(tt1) t2 = epoch(tt2) #print t1 dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC rE, vE = plEarth.eph(t1) vE = array(vE) rM, vM = plJupiter.eph(t2) vM = array(vM) l = lambert_problem(rE, rM, dt, MU_SUN) vEl = array(l.get_v1()[0]) dvE = (vEl - vE) vMl = array(l.get_v2()[0]) dvM = (vMl - vM) dvMTot = linalg.norm(dvM) dvETot = linalg.norm(dvE) dvTot = dvMTot + dvETot print " t1 ", tt1, " t2 ", tt2, " dt ", (tt2 - tt1), " dv ", dvTot return vE, vM, vEl, vMl
def _objfun_impl(self, x): #1 - we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience T = x[3::4] #2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (self.__n_legs)) r_P = list([None] * (self.__n_legs)) v_P = list([None] * (self.__n_legs)) DV = list([None] * (self.__n_legs)) for i, planet in enumerate(self.seq): t_P[i] = epoch(x[0] + sum(T[:i + 1])) r_P[i], v_P[i] = self.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, self.common_mu, False, False) #Lambert arc to reach seq[1] v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] #First DSM occuring at the very beginning (will be cancelled by the optimizer) DV[0] = abs(norm(v_beg_l) - 3400) #4 - And we proceed with each successive leg for i in xrange(1, self.__n_legs): #Fly-by v_out = fb_prop(v_end_l, v_P[i - 1], x[1 + 4 * i] * self.seq[i - 1].radius, x[4 * i], self.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, self.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, self.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)]) return (sum(DV), )
def _part_plot(x, units, axis, seq, start_mjd2000, vinf_in): """ Plots the trajectory represented by a decision vector x = [beta,rp,eta,T] * N associated to a sequence seq, a start_mjd2000 and an incoming vinf_in """ from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm legs = len(x) / 4 common_mu = seq[0].mu_central_body # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = x[3::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (legs + 1)) r_P = list([None] * (legs + 1)) v_P = list([None] * (legs + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(start_mjd2000 + sum(T[:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(planet, t0=t_P[i], color=( 0.8, 0.6, 0.8), legend=True, units = units, ax=axis) v_end_l = [a + b for a, b in zip(v_P[0], vinf_in)] # 4 - And we iterate on the legs for i in range(0, legs): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[1 + 4 * i] * seq[i].radius, x[4 * i], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian( r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) plot_kepler(r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu, N=500, color='b', legend=False, units=units, ax=axis) # 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 + 1], dt, common_mu, False, False) plot_lambert( l, sol=0, color='r', legend=False, units=units, N=500, ax=axis) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0]
def plot_initial_geometry(ni=0.0, mu=0.5): """ Visualizes the initial spaceraft conditions for the gtoc6 problem. Given a point on the initial spheres, \ it assumes a velocity (almost) pointing toward Jupiter. THIS IS ONLY A VISUALIZATION, the initial velocityshould not be taken as realistic. """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from math import sin, cos, acos, pi from PyKEP.orbit_plots import plot_kepler, plot_planet from PyKEP import DAY2SEC, propagate_lagrangian, epoch from scipy.linalg import norm ep = epoch(0.0) days = 300.0 r = [ JR * 1000 * cos(ni) * cos(mu), JR * 1000 * cos(ni) * sin(mu), JR * 1000 * sin(ni) ] VINF = 3400.0 v = [-d / norm(r) * 3400 for d in r] v = [d + 200 for d in v] fig = plt.figure() ax = fig.gca(projection='3d', aspect='equal') plot_planet(ax, io, color='r', units=JR, t0=ep, legend=True) plot_planet(ax, europa, color='b', units=JR, t0=ep, legend=True) plot_planet(ax, ganymede, color='k', units=JR, t0=ep, legend=True) plot_planet(ax, callisto, color='y', units=JR, t0=ep, legend=True) plot_kepler(ax, r, v, days * DAY2SEC, MU_JUPITER, N=200, units=JR, color='b') plt.plot([r[0] / JR], [r[1] / JR], [r[2] / JR], 'o') plt.show()
def get_coordinates(ep, planet, vinf_in, rp, beta): """ Computes the intersection between the vector of the spacecraft to the surface of the moon. USAGE: ms.get_coordinates(62500, gtoc6.europa, (0,0,10000), gtoc6.europa.radius + 10000, 0.3) @param ep epoch of fly-by @param planet the jupiter moon, i.e. gtoc6.io @param vinf_in relative entry velocity @param rp fly-by radius @param beta fly-by-plane orientation @return 3-tuple of cartesian coordinates of the periapsis vector in the body fixed reference frame""" # getting coordinates and speed of the moon eph = planet.eph(epoch(ep,epoch.epoch_type.MJD)) print eph # compute outgoing velocity v_in_abs = tuple(map(operator.add, vinf_in, eph[1])) print v_in_abs v_out_abs = fb_prop(v_in_abs, eph[1], rp, beta, planet.mu_self) print v_out_abs v_diff = np.array(tuple(map(operator.sub, v_in_abs, v_out_abs))) # constraint check vinf_out = tuple(map(operator.sub, v_out_abs, eph[1])) if np.linalg.norm(vinf_in) - np.linalg.norm(vinf_out) > 1.0: print 'WARNING: Constraint violation! Difference between vinf_in and vinf_out is larger than 1!' # compute periapsis vector peri = rp * v_diff / np.linalg.norm(v_diff) # body-fixed coordinate frame x, v = np.array(eph[0]), np.array(eph[1]) bhat1 = x * -1.0 / np.linalg.norm(x) bhat3 = np.cross(x, v) / np.linalg.norm(np.cross(x,v)) bhat2 = np.cross(bhat3, bhat1) # use dot product to get coordinates of periapsis vector in the body-fixed reference frame peri_hat = np.array( (np.dot(peri, bhat1), np.dot(peri, bhat2), np.dot(peri, bhat3)) ) # vector is now normalized to the sphere which has the soccer ball inside. # radius of this sphere is given by problem description as sqrt(9 * golden + 10) return tuple((peri_hat / np.linalg.norm(peri_hat)) * np.sqrt(9 * golden + 10))
def _mga_incipit_plot(self, x, plot_leg_0=False): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d', aspect='equal') ax.scatter(0, 0, 0, color='y') JR = 71492000.0 seq = self.get_sequence() common_mu = seq[0].mu_central_body r_P, v_P = seq[0].eph(epoch(x[0] + x[3])) # 3 - We start with the first leg: a lambert arc theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 # phi close to zero is in the moon orbit plane injection r = [cos(phi) * sin(theta), cos(phi) * cos(theta), sin(phi)] r = [JR * 1000 * d for d in r] l = lambert_problem(r, r_P, x[3] * DAY2SEC, common_mu, False, False) if (plot_leg_0): plot_lambert(ax, l, sol=0, color='k', legend=False, units=JR, N=500) # Lambert arc to reach seq[1] v_end_l = l.get_v2()[0] vinf_in = [a - b for a, b in zip(v_end_l, v_P)] _part_plot(x[4:], JR, ax, seq, x[0] + x[3], vinf_in) return ax
def plot_moons(epoch=epoch(0)): """ Plots the Galilean Moons of Jupiter at epoch USAGE: plot_moons(epoch = epoch(34654, epoch.epoch_type.MJD)): * epoch: the epoch one wants the galilean moons to be plotted at """ from PyKEP.orbit_plots import plot_planet from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') plot_planet(ax, io, color='r', units=JR, t0=epoch, legend=True) plot_planet(ax, europa, color='b', units=JR, t0=epoch, legend=True) plot_planet(ax, ganymede, color='k', units=JR, t0=epoch, legend=True) plot_planet(ax, callisto, color='y', units=JR, t0=epoch, legend=True) plt.show()