Example #1
0
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)   
Example #2
0
    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), )
Example #3
0
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)
Example #5
0
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()
Example #6
0
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)
Example #7
0
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)
Example #8
0
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
Example #9
0
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
Example #10
0
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
Example #11
0
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]
Example #12
0
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)
Example #13
0
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
Example #14
0
	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),)   
Example #15
0
def getLambert(r):
    R2 = R20 * r
    a = NAN
    try:
        lambert_result = lambert_problem(R1, R2, dt)
        if lambert_result.is_reliable():
            a = lambert_result.get_a()[0]
    except:
        a = NAN
    #print " r,a ", r,a
    return a
def getLambert(r):
	R2 = R1 + R20*r
	a = NAN
	try:
		lambert_result =lambert_problem(R1,R2,dt )
		if lambert_result.is_reliable():
			a = lambert_result.get_a()[0]
	except:
		a= NAN
	#print " r,a ", r,a 
	return a
Example #17
0
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
Example #18
0
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 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
Example #20
0
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
Example #21
0
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
Example #22
0
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
Example #23
0
    def pretty(self, x):
        """
		Prints human readable information on the trajectory represented by the decision vector x
		
		Example::
		
		  prob.pretty(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))
        close_d = 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]
        close_d[0] = closest_distance(r, v_beg_l, r_P[0], v_end_l,
                                      self.common_mu)[0] / JR

        #First DSM occuring at the very beginning (will be cancelled by the optimizer)
        DV[0] = abs(norm(v_beg_l) - 3400)

        print "\nFirst Leg: 1000JR to " + self.seq[0].name
        print "\tDeparture: " + str(t_P[0]) + " (" + str(
            t_P[0].mjd2000) + " mjd2000) "
        print "\tDuration: " + str(T[0]) + "days"
        print "\tInitial Velocity Increment (m/s): " + str(DV[0])
        print "\tArrival relative velocity at " + self.seq[
            0].name + " (m/s): " + str(
                norm([a - b for a, b in zip(v_end_l, v_P[0])]))
        print "\tClosest approach distance: " + str(close_d[0])

        #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)
            tmp, ra = closest_distance(r_P[i - 1], v_out, r, v, 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]
            tmp2, ra2 = closest_distance(r, v_beg_l, r_P[i], v_end_l,
                                         self.common_mu)
            if tmp < tmp2:
                close_d[i] = tmp / JR
                ra = ra / JR
            else:
                close_d[i] = tmp2 / JR
                ra = ra2 / JR
            #DSM occuring at time nu2*T2
            DV[i] = norm([a - b for a, b in zip(v_beg_l, v)])
            print "\nleg no. " + str(i + 1) + ": " + self.seq[
                i - 1].name + " to " + self.seq[i].name
            print "\tDuration (days): " + str(T[i])
            print "\tFly-by epoch: " + str(t_P[i]) + " (" + str(
                t_P[i].mjd2000) + " mjd2000) "
            print "\tFly-by altitude (km): " + str(
                (x[4 * i + 1] * self.seq[i - 1].radius -
                 self.seq[i - 1].radius) / 1000)
            print "\tDSM after (days): " + str(x[4 * i + 2] * T[i])
            print "\tDSM magnitude (m/s): " + str(DV[i])
            print "\tClosest approach distance: " + str(close_d[i])
            print "\tApoapsis at closest distance: " + str(ra)

        print "\nArrival at " + self.seq[-1].name
        vel_inf = [a - b for a, b in zip(v_end_l, v_P[-1])]
        print "Arrival epoch: " + str(t_P[-1]) + " (" + str(
            t_P[-1].mjd2000) + " mjd2000) "
        print "Arrival Vinf (m/s): " + vel_inf.__repr__() + " - " + str(
            norm(vel_inf))
        print "Total mission time (days): " + str(sum(T))
Example #24
0
    def ic_from_mga_1dsm(self, x):
        """
        x_lt = prob.ic_from_mga_1dsm(x_mga)

        - x_mga: compatible trajectory as encoded by an mga_1dsm problem

        Returns an initial guess for the low-thrust trajectory, converting the mga_1dsm solution x_dsm. The user
        is responsible that x_mga makes sense (i.e. it is a viable mga_1dsm representation). The conversion is done by importing in the
        low-thrust encoding a) the launch date b) all the legs durations, c) the in and out relative velocities at each planet.
        All throttles are put to zero.

        Example::

          x_lt= prob.ic_from_mga_1dsm(x_mga)
        """
        from math import pi, cos, sin, acos
        from scipy.linalg import norm
        from PyKEP import propagate_lagrangian, lambert_problem, DAY2SEC, fb_prop

        retval = list([0.0] * self.dimension)
        # 1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T
        T = list([0] * (self.__n_legs))

        for i in range(len(T)):
            T[i] = log(x[2 + 4 * i])
        total = sum(T)
        T = [x[1] * time / total for time in T]

        retval[0] = x[0]
        for i in range(self.__n_legs):
            retval[1 + 8 * i] = T[i]
            retval[2 + 8 * i] = self.__sc.mass

        # 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))
        DV = 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 start with the first leg
        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)

        retval[3:6] = [Vinfx, Vinfy, Vinfz]

        v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[4] * T[0] * DAY2SEC, MU_SUN)

        # Lambert arc to reach seq[1]
        dt = (1 - x[4]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, MU_SUN)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        retval[6:9] = [a - b for a, b in zip(v_end_l, v_P[1])]

        # 4 - And we proceed with each successive leg
        for i in range(1, self.__n_legs):
            # Fly-by
            v_out = fb_prop(v_end_l, v_P[i], x[7 + (i - 1) * 4] * self.seq[i].radius, x[6 + (i - 1) * 4], self.seq[i].mu_self)
            retval[3 + i * 8:6 + i * 8] = [a - b for a, b in zip(v_out, v_P[i])]
            # s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out, x[8 + (i - 1) * 4] * T[i] * DAY2SEC, MU_SUN)
            # Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC
            l = lambert_problem(r, r_P[i + 1], dt, MU_SUN)
            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)])
            retval[6 + i * 8:9 + i * 8] = [a - b for a, b in zip(v_end_l, v_P[i + 1])]
        return retval
Example #25
0
def getTraj_simple(start_planet, arrive_planet, tlaunch, tarrive, N):
    '''
	Finds a trajectory between two objects orbiting the Sun

	USAGE: traj = getTraj(K1, K2, tlaunch, tarrive)
		K:  		array of object parameters.
		epoch:		epoch of Keplerian orbital elements (JD)
		a:  	 	semimajor axis (AU)
		e:  	 	eccentricity (none)
		i:  	 	inclination (deg)
		om: 	 	longitude of the ascending node (deg)
		w:  	 	argument of perihelion (deg)
		ma: 	 	mean anomaly at epoch (deg)
		mass: 	 	mass of object (kg)
		r: 	 	radius of object (m)
		sr:	 	safe radius to approach object (m)
		K1: 	 	[epoch1,a1,e1,i1,om1,w1,ma1,mass1,r1,sr1]
		K2: 	 	[epoch2,a2,e2,i2,om2,w2,ma2,mass2,r2,sr2]
		tlaunch: 	launch time (JD)
		tarrive: 	arrival time (JD)
		N:		number of points in calculated trajectory

	'''
    import numpy as np
    from PyKEP import epoch, DAY2SEC, SEC2DAY, AU, DEG2RAD, MU_SUN, planet_ss, lambert_problem, propagate_lagrangian, fb_vel

    # Create PyKEP epoch objects and calculate flight time
    t1 = epoch(tlaunch)
    t2 = epoch(tarrive)
    dt = (tarrive - tlaunch) * DAY2SEC

    rev = 0  #number of revolutions before intercept

    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(vout[0])+np.square(vout[1])+np.square(vout[2]))-np.sqrt( np.square(vin[0])+np.square(vin[1])+np.square(vin[2]))

    return dV
Example #26
0
def planet_asteroid(start_planet, target_name, tlaunch, tarrive, rev, N):
    # Create PyKEP epoch objects and calculate flight time
    t1 = epoch(tlaunch)
    t2 = epoch(tarrive)
    dt = (tarrive - tlaunch) * DAY2SEC

    import py.AsteroidDB as asteroidDB


    neo_db = asteroidDB.neo

    target = (item for item in neo_db if item["name"] == target_name).next()

    ep = epoch(target["epoch_mjd"], epoch.epoch_type.MJD)
    a = target["a"] * AU
    e = target["e"]
    i = target["i"] * DEG2RAD
    om = target["om"] * DEG2RAD
    w = target["w"] * DEG2RAD
    ma = target["ma"] * DEG2RAD
    as_mu = 1E17 * 6.67384E-11  # maybe need to calculate actual mass from density and radius
    r = (target["diameter"] / 2) * 1000
    sr = r * 1.1

    OBJ2 = planet(ep, (a, e, i, om, w, ma), MU_SUN, as_mu, r, sr)
    OBJ1 = planet_ss(start_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()[rev]
    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
Example #27
0
def _mga_incipit_plot_old(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
    legs = len(x) / 4
    seq = self.get_sequence()
    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)
    r_P = list([None] * legs)
    v_P = list([None] * legs)
    DV = list([None] * legs)

    for i, planet in enumerate(seq):
        t_P[i] = epoch(x[0] + sum(T[:i + 1]))
        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)

    # 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[0], T[0] * 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]
    v_beg_l = l.get_v1()[0]

    # 4 - And we proceed with each successive leg
    for i in range(1, 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)
        plot_kepler(ax,
                    r_P[i - 1],
                    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], 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
Example #28
0
def getTraj_simple(start_planet, arrive_planet, tlaunch, tarrive, N):
    '''
	Finds a trajectory between two objects orbiting the Sun

	USAGE: traj = getTraj(K1, K2, tlaunch, tarrive)
		K:  		array of object parameters.
		epoch:		epoch of Keplerian orbital elements (JD)
		a:  	 	semimajor axis (AU)
		e:  	 	eccentricity (none)
		i:  	 	inclination (deg)
		om: 	 	longitude of the ascending node (deg)
		w:  	 	argument of perihelion (deg)
		ma: 	 	mean anomaly at epoch (deg)
		mass: 	 	mass of object (kg)
		r: 	 	radius of object (m)
		sr:	 	safe radius to approach object (m)
		K1: 	 	[epoch1,a1,e1,i1,om1,w1,ma1,mass1,r1,sr1]
		K2: 	 	[epoch2,a2,e2,i2,om2,w2,ma2,mass2,r2,sr2]
		tlaunch: 	launch time (JD)
		tarrive: 	arrival time (JD)
		N:		number of points in calculated trajectory

	'''
    import numpy as np
    from PyKEP import epoch, DAY2SEC, SEC2DAY, AU, DEG2RAD, MU_SUN, planet, lambert_problem, propagate_lagrangian, fb_vel

    # Create PyKEP epoch objects and calculate flight time
    t1 = epoch(tlaunch)
    t2 = epoch(tarrive)
    dt = (tarrive - tlaunch) * DAY2SEC

    rev=0 #number of revolutions before intercept


    OBJ1 = planet.jpl_lp(start_planet)
    OBJ2 = planet.jpl_lp(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.jpl_lp(arrive_planet))
    #dV=np.sqrt( np.square(vout[0])+np.square(vout[1])+np.square(vout[2]))-np.sqrt( np.square(vin[0])+np.square(vin[1])+np.square(vin[2]))

    return dV
Example #29
0
def _get_penalty_data(self, x):
    """ getTrajectory takes a genome x, and returns a Trajectory variable that is a list of all r, v, and time of flights
		Trajectory = [[r0, v0_out, r1, v1_in, tof, rp, ra, Trev, vinf], [r1, v1_out, r2, v2_in, tof, rp, ra, Trev, vinf], [...]]
		tof in days
	"""

    from PyKEP import epoch, lambert_problem, propagate_lagrangian, fb_prop, DAY2SEC
    from math import pi, acos, cos, sin
    import numpy as np
    from _mass_penalty import get_rp_ra_Trev

    Trajectory = []

    #1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience
    T = x[3::4]

    # reconstruct properties that are known in _mga_incipit:
    self.seq = self.get_sequence()
    self.__n_legs = len(self.seq)
    self.common_mu = self.seq[0].mu_central_body

    #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]
    Tr = [tuple(r), v_beg_l, r_P[0], v_end_l, T[0] * DAY2SEC]
    rPvec = np.asarray(r_P[0])
    vPvec = np.asarray(v_end_l)
    Tr = Tr + get_rp_ra_Trev(rPvec, vPvec)
    vinf = vPvec - np.asarray(v_P[0])
    Tr = Tr + [vinf]
    Trajectory.append(Tr)

    #First DSM occuring at the very beginning (will be cancelled by the optimizer)
    DV[0] = abs(np.linalg.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)
        # append r, v, etc. to the Trajectory:
        Tr = [r_P[i - 1], v_out, r, v, x[4 * i + 2] * T[i] * DAY2SEC]
        rPvec = np.asarray(r)
        vPvec = np.asarray(v)
        Tr = Tr + get_rp_ra_Trev(rPvec, vPvec)
        vinf = []
        Tr = Tr + [vinf]
        Trajectory.append(Tr)

        #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]
        # append r, v, etc. to the Trajectory:
        Tr = [
            r, v_beg_l, r_P[i], v_end_l, (1 - x[4 * i + 2]) * T[i] * DAY2SEC
        ]
        rPvec = np.asarray(r_P[i])
        vPvec = np.asarray(v_end_l)
        Tr = Tr + get_rp_ra_Trev(rPvec, vPvec)
        vinf = vPvec - np.asarray(v_P[i])
        Tr = Tr + [vinf]
        Trajectory.append(Tr)

        #DSM occuring at time nu2*T2
        DV[i] = np.linalg.norm([a - b for a, b in zip(v_beg_l, v)])
    return Trajectory
Example #30
0
	def _objfun_impl(self,x):
		#1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience
		T = list([0]*(self.__n_legs))

		#sum_alpha = 0
		#for i in range(self.__n_legs-1):
		#	sum_alpha = sum_alpha+x[4+4*i]

		#for i in xrange(self.__n_legs-1):
		#	T[i] = (x[4+4*i]/sum_alpha)*x[3]


		for i in xrange(0,self.__n_legs):
			T[i] = (x[4+4*i]/sum(x[4::4]))*x[3]

		

		#print "\tDuration: " + str(T) + "days"
		#return(T,)

		#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[6+(i-1)*4]*self.seq[i-1].radius,x[5+(i-1)*4],self.seq[i-1].mu_self)
			#s/c propagation before the DSM
			r,v = propagate_lagrangian(r_P[i-1],v_out,x[7+(i-1)*4]*T[i]*DAY2SEC,self.common_mu)
			#Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
			dt = (1-x[7+(i-1)*4])*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]
			tmp2, ra2 = closest_distance(r,v_beg_l, r_P[i], v_end_l, self.common_mu)
			if tmp < tmp2:
				close_d[i] = tmp/JR
				ra = ra/JR
			else:
				close_d[i] = tmp2/JR
				ra = ra2/JR
			#DSM occuring at time nu2*T2
			DV[i] = norm([a-b for a,b in zip(v_beg_l,v)])


		coeff = 0.3
		for i in xrange(0,self.__n_legs):
			ratio[i] = (DV[i]/(T[i]*DAY2SEC))
			DV_2rj[i] = DV[i] + max((2.0-close_d[i]),0.0)*1000 + max((ratio[i]-coeff*(0.1/2000)),0.0)*100
			T_2rj[i] = T[i] + max((2.0-close_d[i]),0.0)*1000 + max((ratio[i]-coeff*(0.1/2000)),0.0)*100

		#if self.f_dimension == 1:
		#	return (sum(DV)
		#else:
		#	return (sum(DV), sum(T)) 

		if self.f_dimension == 1:
			return (sum(DV_2rj))
		else:
			return (sum(DV_2rj), sum(T_2rj)) 
Example #31
0
    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.orbit_plots import plot_planet, plot_lambert, plot_kepler

        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 recording the various times of flight (days) in the list T
        T = list([0] * (self.__n_legs))
        #a[-i] = x[-1-(i-1)*4]
        for i in xrange(self.__n_legs - 1):
            j = i + 1
            T[-j] = (x[5] - sum(T[-(j - 1):])) * x[-1 - (j - 1) * 4]
        T[0] = x[5] - sum(T)

        #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))
        DV = 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] = planet.eph(t_P[i])
            plot_planet(ax,
                        planet,
                        t0=t_P[i],
                        color=(0.8, 0.6, 0.8),
                        legend=True,
                        units=AU)

        #3 - We start with the first leg
        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_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[4] * T[0] * DAY2SEC,
                                    self.common_mu)
        plot_kepler(ax,
                    r_P[0],
                    v0,
                    x[4] * T[0] * DAY2SEC,
                    self.common_mu,
                    N=100,
                    color='b',
                    legend=False,
                    units=AU)

        #Lambert arc to reach seq[1]
        dt = (1 - x[4]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, self.common_mu, False, False)
        plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        #First DSM occuring at time nu1*T1
        DV[0] = norm([a - b for a, b in zip(v_beg_l, v)])

        #4 - And we proceed with each successive leg
        for i in range(1, self.__n_legs):
            #Fly-by
            v_out = fb_prop(v_end_l, v_P[i],
                            x[7 + (i - 1) * 4] * self.seq[i].radius,
                            x[6 + (i - 1) * 4], self.seq[i].mu_self)
            #s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out,
                                        x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                                        self.common_mu)
            plot_kepler(ax,
                        r_P[i],
                        v_out,
                        x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                        self.common_mu,
                        N=100,
                        color='b',
                        legend=False,
                        units=AU)
            #Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC

            l = lambert_problem(r, r_P[i + 1], dt, self.common_mu, False,
                                False)
            plot_lambert(ax,
                         l,
                         sol=0,
                         color='r',
                         legend=False,
                         units=AU,
                         N=1000)

            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)])

        plt.show()
Example #32
0
	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.orbit_plots import plot_planet, plot_lambert, plot_kepler

		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 recording the various times of flight (days) in the list T for convenience
		T = list([0]*(self.__n_legs))

		for i in xrange(self.__n_legs):
			T[i] = (x[4+4*i]/sum(x[4::4]))*x[3]

		
		#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])
			plot_planet(ax, planet, t0=t_P[i], color=(0.8,0.6,0.8), legend=True, units = JR)

		#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)
		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]
		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[6+(i-1)*4]*self.seq[i-1].radius,x[5+(i-1)*4],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+3]*T[i]*DAY2SEC,self.common_mu)
			plot_kepler(ax,r_P[i-1],v_out,x[7+(i-1)*4]*T[i]*DAY2SEC,self.common_mu,N = 500, color='b', legend=False, units = JR)
			#Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
			dt = (1-x[7+(i-1)*4])*T[i]*DAY2SEC
			l = lambert_problem(r,r_P[i],dt,self.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]
			#DSM occuring at time nu2*T2
			DV[i] = norm([a-b for a,b in zip(v_beg_l,v)])
 
		plt.show()
Example #33
0
	def stats(self,x):
		import matplotlib as mpl
		import matplotlib.pyplot as plt

		#1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience
		T = list([0]*(self.__n_legs))

		for i in xrange(self.__n_legs):
			T[i] = (x[4+4*i]/sum(x[4::4]))*x[3]

		#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))
		close_d = 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]
		close_d[0] = closest_distance(r,v_beg_l, r_P[0], v_end_l, self.common_mu)[0] / JR

		#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[6+(i-1)*4]*self.seq[i-1].radius,x[5+(i-1)*4],self.seq[i-1].mu_self)
			#s/c propagation before the DSM
			r,v = propagate_lagrangian(r_P[i-1],v_out,x[7+(i-1)*4]*T[i]*DAY2SEC,self.common_mu)
			tmp, ra = closest_distance(r_P[i-1],v_out, r,v, self.common_mu)
			#Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
			dt = (1-x[7+(i-1)*4])*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]
			tmp2, ra2 = closest_distance(r,v_beg_l, r_P[i], v_end_l, self.common_mu)
			if tmp < tmp2:
				close_d[i] = tmp/JR
				ra = ra/JR
			else:
				close_d[i] = tmp2/JR
				ra = ra2/JR
			#DSM occuring at time nu2*T2
			DV[i] = norm([a-b for a,b in zip(v_beg_l,v)])


		#print "Total mission time (days): " + str(sum(T))
		#print "Total DV (m/s): " + str(sum(DV))

		symbol_dict = {
			'io' : 'yo',
			'europa' : 'bo',
			'ganymede' : 'ro',
			'callisto' : 'ko' }

		#for i in xrange(0,self.__n_legs):
		#	plt.plot(sum(DV), sum(T), symbol_dict[self.seq[0].name])

		#n = 0
		ratio = list([0]*(self.__n_legs))
		coeff = 0.3
		for i in xrange(0,self.__n_legs):
			ratio[i] = (DV[i]/(T[i]*DAY2SEC))

		if close_d[0] >= 2:
			if close_d[1] >= 2:
				if close_d[2] >= 2:
					if close_d[3] >= 2:
						if ratio[1] <= coeff*(0.1/2000):
							if ratio[2] <= coeff*(0.1/2000):
								if ratio[3] <= coeff*(0.1/2000):
									if ratio[0] <= coeff*(0.1/2000):
										plt.plot(sum(DV), sum(T), symbol_dict[self.seq[0].name])

		#for i in xrange(0,self.__n_legs):
		#	if close_d[i] > 2:
		#		plt.plot(sum(DV), sum(T), symbol_dict[self.seq[0].name])
		#	else:
		#		print "\n the closest distance is less than 2*Rj " 
		#print "\n number of sequences that do not crash " + str(n) 
		plt.show()
Example #34
0
	def pretty(self,x):
		"""
		Prints human readable information on the trajectory represented by the decision vector x
		
		Example::
		
		  prob.pretty(x)
		"""

		#1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience
		T = list([0]*(self.__n_legs))

		for i in xrange(self.__n_legs):
			T[i] = (x[4+4*i]/sum(x[4::4]))*x[3]

		#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))
		close_d = 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]
		close_d[0] = closest_distance(r,v_beg_l, r_P[0], v_end_l, self.common_mu)[0] / JR

		#First DSM occuring at the very beginning (will be cancelled by the optimizer)
		DV[0] = abs(norm(v_beg_l) - 3400)

		print "\nFirst Leg: 1000JR to " + self.seq[0].name 
		print "\tDeparture: " + str(t_P[0]) + " (" + str(t_P[0].mjd2000) + " mjd2000) " 
		print "\tDuration: " + str(T[0]) + "days"
		print "\tInitial Velocity Increment (m/s): " + str(DV[0])
		print "\tArrival relative velocity at " + self.seq[0].name +" (m/s): " + str(norm([a-b for a,b in zip(v_end_l,v_P[0])]))
		print "\tClosest approach distance: " + str(close_d[0])

		#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[6+(i-1)*4]*self.seq[i-1].radius,x[5+(i-1)*4],self.seq[i-1].mu_self)
			#s/c propagation before the DSM
			r,v = propagate_lagrangian(r_P[i-1],v_out,x[7+(i-1)*4]*T[i]*DAY2SEC,self.common_mu)
			tmp, ra = closest_distance(r_P[i-1],v_out, r,v, self.common_mu)
			#Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
			dt = (1-x[7+(i-1)*4])*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]
			tmp2, ra2 = closest_distance(r,v_beg_l, r_P[i], v_end_l, self.common_mu)
			if tmp < tmp2:
				close_d[i] = tmp/JR
				ra = ra/JR
			else:
				close_d[i] = tmp2/JR
				ra = ra2/JR
			#DSM occuring at time nu2*T2
			DV[i] = norm([a-b for a,b in zip(v_beg_l,v)])

			print "\nleg no. " + str(i+1) + ": " + self.seq[i-1].name + " to " + self.seq[i].name 
			print "\tDuration (days): " + str(T[i])
			print "\tFly-by epoch: " + str(t_P[i]) + " (" + str(t_P[i].mjd2000) + " mjd2000) " 
			print "\tFly-by altitude (km): " + str((x[6+(i-1)*4]*self.seq[i-1].radius-self.seq[i-1].radius)/1000)
			print "\tDSM after (days): " + str(x[7+(i-1)*4]*T[i])
			print "\tDSM magnitude (m/s): " + str(DV[i]) 
			print "\tClosest approach distance: " + str(close_d[i])
			print "\tApoapsis at closest distance: " + str(ra)
			print "\tV in (m/s): " + str(v_end_l)
			print "\tV out (m/s): " + str(v_out)
		
		
		print "\nArrival at " + self.seq[-1].name
		vel_inf = [a-b for a,b in zip(v_end_l,v_P[-1])]
		print "Arrival epoch: " + str(t_P[-1]) + " (" + str(t_P[-1].mjd2000) + " mjd2000) " 
		print "Arrival Vinf (m/s): " + vel_inf.__repr__() + " - " + str(norm(vel_inf))
		print "Total mission time (days): " + str(sum(T))
		print "Total DV (m/s): " + str(sum(DV))
Example #35
0
def getTraj(K1, K2, tlaunch, tarrive, N):
    '''
	Finds a trajectory between two objects orbiting the Sun
		
	USAGE: traj = getTraj(K1, K2, tlaunch, tarrive)
		K:  		array of object parameters.
		epoch:		epoch of Keplerian orbital elements (JD)
		a:  	 	semimajor axis (AU)
		e:  	 	eccentricity (none)
		i:  	 	inclination (deg)
		om: 	 	longitude of the ascending node (deg)
		w:  	 	argument of perihelion (deg)
		ma: 	 	mean anomaly at epoch (deg)
		mass: 	 	mass of object (kg)  
		r: 	 	radius of object (m)
		sr:	 	safe radius to approach object (m)
		K1: 	 	[epoch1,a1,e1,i1,om1,w1,ma1,mass1,r1,sr1]
		K2: 	 	[epoch2,a2,e2,i2,om2,w2,ma2,mass2,r2,sr2]
		tlaunch: 	launch time (JD)
		tarrive: 	arrival time (JD)
		N:		number of points in calculated trajectory
	
	'''
    import numpy as np
    from PyKEP import epoch, DAY2SEC, SEC2DAY, AU, DEG2RAD, MU_SUN, planet, lambert_problem, propagate_lagrangian

    #Create PyKEP epoch objects and calculate flight time
    t1 = epoch(tlaunch, epoch.epoch_type.JD)
    t2 = epoch(tarrive, epoch.epoch_type.JD)
    dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC

    #First object
    K1[0] = epoch(K1[0],
                  epoch.epoch_type.JD)  #convert epoch to PyKEP epoch object
    K1[1] = K1[1] * AU  #convert AU to meters
    K1[3] = K1[3] * DEG2RAD  #convert angles from degrees to radians
    K1[4] = K1[4] * DEG2RAD
    K1[5] = K1[5] * DEG2RAD
    K1[6] = K1[6] * DEG2RAD
    K1[7] = K1[7] * 6.67384E-11  #convert mass to gravitational parameter mu
    OBJ1 = planet(K1[0], K1[1:7], MU_SUN, K1[7], K1[8], K1[9])

    #Second object
    K2[0] = epoch(K2[0],
                  epoch.epoch_type.JD)  #convert epoch to PyKEP epoch object
    K2[1] = K2[1] * AU  #convert AU to meters
    K2[3] = K2[3] * DEG2RAD  #convert angles from degrees to radians
    K2[4] = K2[4] * DEG2RAD
    K2[5] = K2[5] * DEG2RAD
    K2[6] = K2[6] * DEG2RAD
    K2[7] = K2[7] * 6.67384E-11  #convert mass to gravitational parameter mu
    OBJ2 = planet(K2[0], K2[1:7], MU_SUN, K2[7], K2[8], K2[9])

    #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]

    return traj
Example #36
0
t1 = epoch(0)
t2 = epoch(740)
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)

nmax = l.get_Nmax()
print "max number of revolutions", nmax

plot_lambert(ax, l, color=(1, 0, 0), legend=True, units=AU)
for i in range(1, nmax * 2 + 1):
    print i
    plot_lambert(ax,
                 l,
                 sol=i,
                 color=(1, 0, i / float(nmax * 2)),
                 legend=True,
                 units=AU)

Example #37
0
def _get_score_data_incipit(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
	"""
	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
	
	#2 - We compute the epochs and ephemerides of the planetary encounters
	ep_list = list([None] * nlegs)
	t_P = list([None] * nlegs)
	r_P = list([None] * nlegs)
	v_P = list([None] * nlegs)
	DV  = list([None] * nlegs)
	
	for i,planet in enumerate(seq):
		ep_list[i] = x[0]+sum(T[:i+1])
		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]

	#init lists for fly-by parameters
	vinf_list = []
	rp_list = []
	beta_list = []

	#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,nlegs):
		#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)
		
		vinf_list.append( [a-b for a,b in zip(v_end_l,v_P[i-1])] )
		rp_list.append(x[1+4*i]*seq[i-1].radius)
		beta_list.append(x[4*i])

		#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]
		
        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)
Example #38
0
def traj_planet_asteroid(source, dest, tlaunch, tarrive, rev, N):
    t1 = epoch(tlaunch)
    t2 = epoch(tarrive)
    dt = (tarrive - tlaunch) * DAY2SEC

    target = source['orbit']

    ep = epoch(jd_to_mjd(tlaunch), epoch.epoch_type.MJD)
    a = target["a"] * AU
    e = target["e"]
    i = target["i"] * DEG2RAD
    om = target["om"] * DEG2RAD
    w = target["w"] * DEG2RAD
    ma = target["ma"] * DEG2RAD
    as_mu = 1E17 * 6.67384E-11  # maybe need to calculate actual mass from density and radius
    r = (10 / 2) * 1000
    sr = r * 1.1

    OBJ1 = planet(ep, (a, e, i, om, w, ma), MU_SUN, as_mu, r, sr)

    target = dest['orbit']

    ep = epoch(jd_to_mjd(tarrive), epoch.epoch_type.MJD)
    a = target["a"] * AU
    e = target["e"]
    i = target["i"] * DEG2RAD
    om = target["om"] * DEG2RAD
    w = target["w"] * DEG2RAD
    ma = target["ma"] * DEG2RAD
    as_mu = 1E17 * 6.67384E-11  # maybe need to calculate actual mass from density and radius
    r = (10 / 2) * 1000
    sr = r * 1.1

    OBJ2 = planet(ep, (a, e, i, om, w, ma), MU_SUN, as_mu, r, sr)

    # 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.tolist(), x.tolist(), y.tolist(), z.tolist()]

    return traj
Example #39
0
    def _objfun_impl(self, x):
        #1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T
        T = list([0] * (self.__n_legs))

        for i in xrange(self.__n_legs - 1):
            j = i + 1
            T[-j] = (x[5] - sum(T[-(j - 1):])) * x[-1 - (j - 1) * 4]
        T[0] = x[5] - sum(T)

        #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))
        DV = list([0.0] * (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 start with the first leg
        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_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[4] * T[0] * DAY2SEC,
                                    self.common_mu)

        #Lambert arc to reach seq[1]
        dt = (1 - x[4]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, self.common_mu, False, False)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        #First DSM occuring at time nu1*T1
        DV[0] = norm([a - b for a, b in zip(v_beg_l, v)])

        #4 - And we proceed with each successive leg
        for i in range(1, self.__n_legs):
            #Fly-by
            v_out = fb_prop(v_end_l, v_P[i],
                            x[7 + (i - 1) * 4] * self.seq[i].radius,
                            x[6 + (i - 1) * 4], self.seq[i].mu_self)
            #s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out,
                                        x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                                        self.common_mu)
            #Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC
            l = lambert_problem(r, r_P[i + 1], 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)])

        #Last Delta-v
        if self.__add_vinf_arr:
            DV[-1] = norm([a - b for a, b in zip(v_end_l, v_P[-1])])

        if self.__add_vinf_dep:
            DV[0] += x[3]

        if self.f_dimension == 1:
            return (sum(DV), )
        else:
            return (sum(DV), sum(T))
Example #40
0
def planet_asteroid(start_planet, target_name, tlaunch, tarrive, rev, N):
    # Create PyKEP epoch objects and calculate flight time
    t1 = epoch(tlaunch)
    t2 = epoch(tarrive)
    dt = (tarrive - tlaunch) * DAY2SEC

    import py.AsteroidDB as asteroidDB

    neo_db = asteroidDB.neo

    target = (item for item in neo_db if item["name"] == target_name).next()

    ep = epoch(target["epoch_mjd"], epoch.epoch_type.MJD)
    a = target["a"] * AU
    e = target["e"]
    i = target["i"] * DEG2RAD
    om = target["om"] * DEG2RAD
    w = target["w"] * DEG2RAD
    ma = target["ma"] * DEG2RAD
    as_mu = 1E17 * 6.67384E-11  # maybe need to calculate actual mass from density and radius
    r = (target["diameter"] / 2) * 1000
    sr = r * 1.1

    OBJ2 = planet(ep, (a, e, i, om, w, ma), MU_SUN, as_mu, r, sr)
    OBJ1 = planet_ss(
        start_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()[rev]
    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
Example #41
0
    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.orbit_plots import plot_planet, plot_lambert, plot_kepler

        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 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] * (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])
            plot_planet(ax,
                        planet,
                        t0=t_P[i],
                        color=(0.8, 0.6, 0.8),
                        legend=True,
                        units=JR)

        #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)
        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]
        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)
            plot_kepler(ax,
                        r_P[i - 1],
                        v_out,
                        x[4 * i + 2] * T[i] * DAY2SEC,
                        self.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], dt, self.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]
            #DSM occuring at time nu2*T2
            DV[i] = norm([a - b for a, b in zip(v_beg_l, v)])
        plt.show()
        return ax
Example #42
0
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)
Example #43
0
def traj_planet_asteroid(source, dest, tlaunch, tarrive, rev, N):
    t1 = epoch(tlaunch)
    t2 = epoch(tarrive)
    dt = (tarrive - tlaunch) * DAY2SEC

    target = source['orbit']

    ep = epoch(jd_to_mjd(tlaunch), epoch.epoch_type.MJD)
    a = target["a"] * AU
    e = target["e"]
    i = target["i"] * DEG2RAD
    om = target["om"] * DEG2RAD
    w = target["w"] * DEG2RAD
    ma = target["ma"] * DEG2RAD
    as_mu = 1E17 * 6.67384E-11  # maybe need to calculate actual mass from density and radius
    r = (10 / 2) * 1000
    sr = r * 1.1

    OBJ1 = planet(ep, (a, e, i, om, w, ma), MU_SUN, as_mu, r, sr)

    target = dest['orbit']

    ep = epoch(jd_to_mjd(tarrive), epoch.epoch_type.MJD)
    a = target["a"] * AU
    e = target["e"]
    i = target["i"] * DEG2RAD
    om = target["om"] * DEG2RAD
    w = target["w"] * DEG2RAD
    ma = target["ma"] * DEG2RAD
    as_mu = 1E17 * 6.67384E-11  # maybe need to calculate actual mass from density and radius
    r = (10 / 2) * 1000
    sr = r * 1.1

    OBJ2 = planet(ep, (a, e, i, om, w, ma), MU_SUN, as_mu, r, sr)

    # 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.tolist(), x.tolist(), y.tolist(), z.tolist()]

    return traj
Example #44
0
def _mga_incipit_plot_old(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
    legs = len(x) / 4
    seq = self.get_sequence()
    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)
    r_P = list([None] * legs)
    v_P = list([None] * legs)
    DV = list([None] * legs)

    for i, planet in enumerate(seq):
        t_P[i] = epoch(x[0] + sum(T[:i + 1]))
        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)

    # 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[0], T[0] * 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]
    v_beg_l = l.get_v1()[0]

    # 4 - And we proceed with each successive leg
    for i in range(1, 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)
        plot_kepler(ax,
                    r_P[i - 1],
                    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], 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
Example #45
0
def _mga_1dsm_tof_plot_old(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()

    n = (len(seq) - 1)
    # 1 -  we 'decode' the chromosome recording the various times of flight
    # (days) in the list T
    T = x[5::4]

    # 2 - We compute the epochs and ephemerides of the planetary encounters
    t_P = list([None] * (n + 1))
    r_P = list([None] * (n + 1))
    v_P = list([None] * (n + 1))
    DV = list([None] * (n + 1))

    for i, planet in enumerate(seq):
        t_P[i] = epoch(x[0] + sum(T[0: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=AU)

    # 3 - We start with the first leg
    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_P[0], [Vinfx, Vinfy, Vinfz])]
    r, v = propagate_lagrangian(r_P[0], v0, x[4] * T[0] * DAY2SEC,
                                seq[0].mu_central_body)
    plot_kepler(ax,
                r_P[0],
                v0,
                x[4] * T[0] * DAY2SEC,
                seq[0].mu_central_body,
                N=100,
                color='b',
                legend=False,
                units=AU)

    # Lambert arc to reach seq[1]
    dt = (1 - x[4]) * T[0] * DAY2SEC
    l = lambert_problem(r, r_P[1], 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]
    v_beg_l = l.get_v1()[0]

    # First DSM occuring at time nu1*T1
    DV[0] = norm([a - b for a, b in zip(v_beg_l, v)])

    # 4 - And we proceed with each successive leg
    for i in range(1, n):
        # Fly-by
        v_out = fb_prop(v_end_l, v_P[i], x[7 + (i - 1) * 4] * seq[i].radius,
                        x[6 + (i - 1) * 4], seq[i].mu_self)
        # s/c propagation before the DSM
        r, v = propagate_lagrangian(r_P[i], v_out,
                                    x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                                    seq[0].mu_central_body)
        plot_kepler(ax,
                    r_P[i],
                    v_out,
                    x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                    seq[0].mu_central_body,
                    N=100,
                    color='b',
                    legend=False,
                    units=AU)
        # Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
        dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC
        l = lambert_problem(r, r_P[i + 1], 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]
        v_beg_l = l.get_v1()[0]
        # DSM occurring at time nu2*T2
        DV[i] = norm([a - b for a, b in zip(v_beg_l, v)])
    return ax
Example #46
0

r1 = np.array([6778136,0,0])
# r2 = np.array([-6978136,0.00007,0])
r2 = np.array([0,6043243.047,3489068])
v0 = np.array([0,7668.558733,0])
# v3 = np.array([0.000000008,-7557.86574,0])
v3 = np.array([-7557.86574,0,0])


r1a = math.sqrt(r1[0]**2+r1[1]**2+r1[2]**2)

MU_EARTH = 3.986004418e14

dt = 3.1415926535* math.sqrt((r1a+100000)**3/MU_EARTH) # seconds
l = lambert_problem(r1, r2, dt*.5, MU_EARTH)
fig2 = plt.figure(2)
axis2 = fig2.gca(projection='3d')
axis2.scatter([0], [0], [0], color='y') 
plot_lambert(l, sol=0, ax=axis2, color='r')
# plot_lambert(l, sol=1, ax=axis2, color='r')
x0 = l.get_x()[0]
plot_kepler(r1, v0, dt*2, MU_EARTH, N=600, units=1, color='b',legend=False, ax=axis2)
plot_kepler(r2, v3, dt*2.2, MU_EARTH, N=600, units=1, color='b',legend=False, ax=axis2)
axis2.set_ylim3d(-1.2*6378000,1.2*6378000)
axis2.set_xlim3d(-1.2*6378000,1.2*6378000)
plt.xlabel('X coordinate [m]')
plt.ylabel('Y coordinate [m]')
# plt.zlabel('Z coordinate [m]')
# plt.ylabel('DV [m/s]')
plt.title('Lambert transfers for 200km altitude increase with different time of flight')
Example #47
0
def _mga_part_plot_old(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 range(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
Example #48
0
    def _objfun_impl(self,x):
        #1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T
        T = list([0]*(self.__n))
        #a[-i] = x[-1-(i-1)*4]
        for i in xrange(self.__n-1):
            j = i+1;
            T[-j] = (x[5] - sum(T[-(j-1):])) * x[-1-(j-1)*4]
        T[0] = x[5] - sum(T)

        #2 - We compute the epochs and ephemerides of the planetary encounters
        t_P = list([None] * (self.__n+1))
        r_P = list([None] * (self.__n+1))
        v_P = list([None] * (self.__n+1))
        DV = list([None] * (self.__n+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 start with the first leg
        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_P[0], [Vinfx,Vinfy,Vinfz])]
        r,v = propagate_lagrangian(r_P[0], v0, x[4]*T[0]*DAY2SEC, MU_SUN)

        #Lambert arc to reach seq[1]
        dt = (1-x[4])*T[0]*DAY2SEC
        l = lambert_problem(r,r_P[1],dt,MU_SUN)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        #First DSM occuring at time nu1*T1
        DV[0] = norm([a-b for a,b in zip(v_beg_l, v)])

        #4 - And we proceed with each successive leg
        for i in range(1,self.__n):
            #Fly-by
            v_out = fb_prop(v_end_l, v_P[i] ,x[7+(i-1)*4]*self.seq[i].radius, x[6+(i-1)*4], self.seq[i].mu_self)
            #s/c propagation before the DSM
            r,v = propagate_lagrangian(r_P[i], v_out, x[8+(i-1)*4]*T[i]*DAY2SEC, MU_SUN)
            #Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1-x[8+(i-1)*4])*T[i]*DAY2SEC
            l = lambert_problem(r, r_P[i+1], dt, MU_SUN)
            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)])

        #Last Delta-v
        DV[-1] = norm([a-b for a,b in zip(v_end_l,v_P[-1])])

        #moje
        Eh56500 = 61933310.95
        #Eh100000 = 61517435.56
        entry_Vel = (DV[-1]**2 + 2*Eh56500)**0.5
        entry_Vel2 = entry_Vel
        #axtl = 23.43929*DEG2RAD
        #DEC = abs(asin( sin(axtl)*cos(phi)*sin(theta) + cos(axtl)*sin(phi) ))*RAD2DEG # deklinacja asymptoty ucieczkowej
        sum_dv = sum(DV[:-1])
        eff_C3 = (x[3])**2

        if entry_Vel < self.entry_vel_barrier:
            entry_Vel2 = 0.0
            del DV[-1]

        #~ if eff_C3 < self.C3_barrier:
            #~ #eff_C3 = 0
            #~ pass

        if sum_dv < self.dsm_dv_barrier:
            sum_dv = 0+entry_Vel2
        else:
            sum_dv = sum(DV)

        if self.f_dimension == 1:
            return (sum_dv,)
        else:
            return (sum_dv, eff_C3, entry_Vel2) #,
Example #49
0
def _mga_1dsm_tof_plot_old(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()

    n = (len(seq) - 1)
    # 1 -  we 'decode' the chromosome recording the various times of flight
    # (days) in the list T
    T = x[5::4]

    # 2 - We compute the epochs and ephemerides of the planetary encounters
    t_P = list([None] * (n + 1))
    r_P = list([None] * (n + 1))
    v_P = list([None] * (n + 1))
    DV = list([None] * (n + 1))

    for i, planet in enumerate(seq):
        t_P[i] = epoch(x[0] + sum(T[0: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 = AU)

    # 3 - We start with the first leg
    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_P[0], [Vinfx, Vinfy, Vinfz])]
    r, v = propagate_lagrangian(
        r_P[0], v0, x[4] * T[0] * DAY2SEC, seq[0].mu_central_body)
    plot_kepler(
        ax,
        r_P[0],
        v0,
        x[4] *
        T[0] *
        DAY2SEC,
        seq[0].mu_central_body,
        N=100,
        color='b',
        legend=False,
        units=AU)

    # Lambert arc to reach seq[1]
    dt = (1 - x[4]) * T[0] * DAY2SEC
    l = lambert_problem(r, r_P[1], 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]
    v_beg_l = l.get_v1()[0]

    # First DSM occuring at time nu1*T1
    DV[0] = norm([a - b for a, b in zip(v_beg_l, v)])

    # 4 - And we proceed with each successive leg
    for i in range(1, n):
        # Fly-by
        v_out = fb_prop(v_end_l,
                        v_P[i],
                        x[7 + (i - 1) * 4] * seq[i].radius,
                        x[6 + (i - 1) * 4],
                        seq[i].mu_self)
        # s/c propagation before the DSM
        r, v = propagate_lagrangian(
            r_P[i], v_out, x[8 + (i - 1) * 4] * T[i] * DAY2SEC, seq[0].
            mu_central_body)
        plot_kepler(ax,
                    r_P[i],
                    v_out,
                    x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                    seq[0].mu_central_body,
                    N=100,
                    color='b',
                    legend=False,
                    units=AU)
        # Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
        dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC
        l = lambert_problem(r, r_P[i + 1], 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]
        v_beg_l = l.get_v1()[0]
        # DSM occurring at time nu2*T2
        DV[i] = norm([a - b for a, b in zip(v_beg_l, v)])
    return ax
t1 = epoch(0)
t2 = epoch(740)
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)

nmax = l.get_Nmax()
print "max number of revolutions",nmax

plot_lambert(ax,l      , color=(1,0,0), legend=True, units = AU)
for i in range(1,nmax*2+1):
	print i
	plot_lambert(ax,l,sol=i, color=(1,0,i/float(nmax*2)), legend=True, units = AU)



def axisEqual3D(ax):
    extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz'])
    sz = extents[:,1] - extents[:,0]
    centers = np.mean(extents, axis=1)
Example #51
0
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)
Example #52
0
    def ic_from_mga_1dsm(self, x):
        """
        x_lt = prob.ic_from_mga_1dsm(x_mga)

        - x_mga: compatible trajectory as encoded by an mga_1dsm problem

        Returns an initial guess for the low-thrust trajectory, converting the mga_1dsm solution x_dsm. The user
        is responsible that x_mga makes sense (i.e. it is a viable mga_1dsm representation). The conversion is done by importing in the
        low-thrust encoding a) the launch date b) all the legs durations, c) the in and out relative velocities at each planet.
        All throttles are put to zero.

        Example::

          x_lt= prob.ic_from_mga_1dsm(x_mga)
        """
        from math import pi, cos, sin, acos
        from scipy.linalg import norm
        from PyKEP import propagate_lagrangian, lambert_problem, DAY2SEC, fb_prop

        retval = list([0.0] * self.dimension)
        # 1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T
        T = list([0] * (self.__n_legs))

        for i in range(len(T)):
            T[i] = log(x[2 + 4 * i])
        total = sum(T)
        T = [x[1] * time / total for time in T]

        retval[0] = x[0]
        for i in range(self.__n_legs):
            retval[1 + 8 * i] = T[i]
            retval[2 + 8 * i] = self.__sc.mass

        # 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))
        DV = 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 start with the first leg
        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)

        retval[3:6] = [Vinfx, Vinfy, Vinfz]

        v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[4] * T[0] * DAY2SEC, MU_SUN)

        # Lambert arc to reach seq[1]
        dt = (1 - x[4]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, MU_SUN)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        retval[6:9] = [a - b for a, b in zip(v_end_l, v_P[1])]

        # 4 - And we proceed with each successive leg
        for i in range(1, self.__n_legs):
            # Fly-by
            v_out = fb_prop(v_end_l, v_P[i],
                            x[7 + (i - 1) * 4] * self.seq[i].radius,
                            x[6 + (i - 1) * 4], self.seq[i].mu_self)
            retval[3 + i * 8:6 +
                   i * 8] = [a - b for a, b in zip(v_out, v_P[i])]
            # s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out,
                                        x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                                        MU_SUN)
            # Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC
            l = lambert_problem(r, r_P[i + 1], dt, MU_SUN)
            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)])
            retval[6 + i * 8:9 +
                   i * 8] = [a - b for a, b in zip(v_end_l, v_P[i + 1])]
        return retval
Example #53
0
def _get_penalty_data(self,x):
	""" getTrajectory takes a genome x, and returns a Trajectory variable that is a list of all r, v, and time of flights
		Trajectory = [[r0, v0_out, r1, v1_in, tof, rp, ra, Trev, vinf], [r1, v1_out, r2, v2_in, tof, rp, ra, Trev, vinf], [...]]
		tof in days
	"""
	
	from PyKEP import epoch, lambert_problem, propagate_lagrangian, fb_prop, DAY2SEC;
	from math import pi, acos, cos, sin;
	import numpy as np;
	from _mass_penalty import get_rp_ra_Trev
	
	Trajectory = [];
	
	#1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T for convenience
	T = x[3::4]
	
	# reconstruct properties that are known in _mga_incipit:
	self.seq = self.get_sequence();
	self.__n_legs = len(self.seq);
	self.common_mu = self.seq[0].mu_central_body
	
	#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]
	Tr = [tuple(r), v_beg_l, r_P[0], v_end_l, T[0]*DAY2SEC];
	rPvec = np.asarray(r_P[0]);
	vPvec = np.asarray(v_end_l);
	Tr = Tr + get_rp_ra_Trev(rPvec, vPvec);
	vinf = vPvec - np.asarray(v_P[0]);
	Tr = Tr + [vinf];
	Trajectory.append(Tr);

	#First DSM occuring at the very beginning (will be cancelled by the optimizer)
	DV[0] = abs(np.linalg.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)
		# append r, v, etc. to the Trajectory:
		Tr = [r_P[i-1], v_out, r, v, x[4*i+2]*T[i]*DAY2SEC];
		rPvec = np.asarray(r);
		vPvec = np.asarray(v);
		Tr = Tr + get_rp_ra_Trev(rPvec, vPvec);
		vinf = [];
		Tr = Tr + [vinf];
		Trajectory.append(Tr);
		
		#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]
		# append r, v, etc. to the Trajectory:
		Tr = [r, v_beg_l, r_P[i], v_end_l, (1-x[4*i+2])*T[i]*DAY2SEC];
		rPvec = np.asarray(r_P[i]);
		vPvec = np.asarray(v_end_l);
		Tr = Tr + get_rp_ra_Trev(rPvec, vPvec);
		vinf = vPvec - np.asarray(v_P[i]);
		Tr = Tr + [vinf];
		Trajectory.append(Tr);
		
		
		#DSM occuring at time nu2*T2
		DV[i] = np.linalg.norm([a-b for a,b in zip(v_beg_l,v)])
	return Trajectory;  		
Example #54
0
def _get_penalty_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
    from _mass_penalty import get_rp_ra_Trev
    import numpy as np
    """
	This method returns the data needed to compute the score of a trajectory.
	"""

    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])

    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)
        #s/c propagation before the DSM
        r, v = propagate_lagrangian(r_P[i], v_out,
                                    x[4 * i + 2] * T[i] * DAY2SEC, common_mu)

        # append r, v, etc. to the Trajectory:
        Tr = [r_P[i - 1], v_out, r, v, x[4 * i + 2] * T[i] * DAY2SEC]
        rPvec = np.asarray(r)
        vPvec = np.asarray(v)
        Tr = Tr + get_rp_ra_Trev(rPvec, vPvec)
        vinf = []
        Tr = Tr + [vinf]
        Trajectory.append(Tr)

        #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]

        # append r, v, etc. to the Trajectory:
        Tr = [
            r, v_beg_l, r_P[i], v_end_l, (1 - x[4 * i + 2]) * T[i] * DAY2SEC
        ]
        rPvec = np.asarray(r_P[i])
        vPvec = np.asarray(v_end_l)
        Tr = Tr + get_rp_ra_Trev(rPvec, vPvec)
        vinf = vPvec - np.asarray(v_P[i])
        Tr = Tr + [vinf]
        Trajectory.append(Tr)

    return Trajectory
Example #55
0
def _get_penalty_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
	from _mass_penalty import get_rp_ra_Trev
	import numpy as np
	
	"""
	This method returns the data needed to compute the score of a trajectory.
	"""
	
	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])

	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)
		#s/c propagation before the DSM
		r,v = propagate_lagrangian(r_P[i],v_out,x[4*i+2]*T[i]*DAY2SEC,common_mu)
		
		# append r, v, etc. to the Trajectory:
		Tr = [r_P[i-1], v_out, r, v, x[4*i+2]*T[i]*DAY2SEC];
		rPvec = np.asarray(r);
		vPvec = np.asarray(v);
		Tr = Tr + get_rp_ra_Trev(rPvec, vPvec);
		vinf = [];
		Tr = Tr + [vinf];
		Trajectory.append(Tr);
		
		#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]
		
		# append r, v, etc. to the Trajectory:
		Tr = [r, v_beg_l, r_P[i], v_end_l, (1-x[4*i+2])*T[i]*DAY2SEC];
		rPvec = np.asarray(r_P[i]);
		vPvec = np.asarray(v_end_l);
		Tr = Tr + get_rp_ra_Trev(rPvec, vPvec);
		vinf = vPvec - np.asarray(v_P[i]);
		Tr = Tr + [vinf];
		Trajectory.append(Tr);

        return Trajectory;
Example #56
0
    def pretty(self, x):
        """
		Prints human readable information on the trajectory represented by the decision vector x
		
		Example::
		
		  prob.pretty(x)
		"""
        #1 -  we 'decode' the chromosome recording the various times of flight (days) in the list T
        T = list([0] * (self.__n_legs))
        #a[-i] = x[-1-(i-1)*4]
        for i in xrange(self.__n_legs - 1):
            j = i + 1
            T[-j] = (x[5] - sum(T[-(j - 1):])) * x[-1 - (j - 1) * 4]
        T[0] = x[5] - sum(T)

        #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))
        DV = 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 start with the first leg
        print "First Leg: " + self.seq[0].name + " to " + self.seq[1].name

        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)

        print "Departure: " + str(t_P[0]) + " (" + str(
            t_P[0].mjd2000) + " mjd2000) "
        print "Duration: " + str(T[0]) + "days"
        print "VINF: " + str(x[3] / 1000) + " km/sec"

        v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[4] * T[0] * DAY2SEC,
                                    self.common_mu)

        print "DSM after " + str(x[4] * T[0]) + " days"

        #Lambert arc to reach seq[1]
        dt = (1 - x[4]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, self.common_mu, False, False)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        #First DSM occuring at time nu1*T1
        DV[0] = norm([a - b for a, b in zip(v_beg_l, v)])
        print "DSM magnitude: " + str(DV[0]) + "m/s"

        #4 - And we proceed with each successive leg
        for i in range(1, self.__n_legs):
            print "\nleg no. " + str(
                i + 1) + ": " + self.seq[i].name + " to " + self.seq[i +
                                                                     1].name
            print "Duration: " + str(T[i]) + "days"
            #Fly-by
            v_out = fb_prop(v_end_l, v_P[i],
                            x[7 + (i - 1) * 4] * self.seq[i].radius,
                            x[6 + (i - 1) * 4], self.seq[i].mu_self)
            print "Fly-by epoch: " + str(t_P[i]) + " (" + str(
                t_P[i].mjd2000) + " mjd2000) "
            print "Fly-by radius: " + str(x[7 +
                                            (i - 1) * 4]) + " planetary radii"
            #s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out,
                                        x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                                        self.common_mu)
            print "DSM after " + str(x[8 + (i - 1) * 4] * T[i]) + " days"
            #Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC
            l = lambert_problem(r, r_P[i + 1], 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)])
            print "DSM magnitude: " + str(DV[i]) + "m/s"

        #Last Delta-v
        print "\nArrival at " + self.seq[-1].name
        DV[-1] = norm([a - b for a, b in zip(v_end_l, v_P[-1])])
        print "Arrival epoch: " + str(t_P[-1]) + " (" + str(
            t_P[-1].mjd2000) + " mjd2000) "
        print "Arrival Vinf: " + str(DV[-1]) + "m/s"
        print "Total mission time: " + str(sum(T) / 365.25) + " years"
Example #57
0
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)  
from PyKEP import lambert_problem


xs = arange(-2,2,0.05); nx=len(xs); 
ys = arange(-2,2,0.05); ny=len(ys); 
R1 = array([0.0,1.0,0.0])
R2 = array([0.0,0.0,0.0])
dt =0.7

axy = zeros((nx,ny))
for ix in range(nx):
	for iy in range(ny):
		R2[0] = xs[ix]; R2[1] = ys[iy];
		try:
			lambert_result =lambert_problem(R1,R2,dt )
		except:
			continue
		#lambert_result = lambert_problem([1,0,0],[0,1,0],5 * pi / 2. )
		if lambert_result.is_reliable():
			a = lambert_result.get_a()[0]
			axy[ix,iy]= a
			print ix,iy," R2= ",R2," a= ", a 
		else:
			print ix,iy," R2= ",R2," failed "


imshow( axy, vmax=2.5,vmin=0, interpolation='nearest' )
colorbar()

show()
Example #59
0
xs = arange(-2, 2, 0.05)
nx = len(xs)
ys = arange(-2, 2, 0.05)
ny = len(ys)
R1 = array([0.0, 1.0, 0.0])
R2 = array([0.0, 0.0, 0.0])
dt = 0.7

axy = zeros((nx, ny))
for ix in range(nx):
    for iy in range(ny):
        R2[0] = xs[ix]
        R2[1] = ys[iy]
        try:
            lambert_result = lambert_problem(R1, R2, dt)
        except:
            continue
        #lambert_result = lambert_problem([1,0,0],[0,1,0],5 * pi / 2. )
        if lambert_result.is_reliable():
            a = lambert_result.get_a()[0]
            axy[ix, iy] = a
            print ix, iy, " R2= ", R2, " a= ", a
        else:
            print ix, iy, " R2= ", R2, " failed "

imshow(axy, vmax=2.5, vmin=0, interpolation='nearest')
colorbar()

show()
'''
Example #60
0
def _get_score_data_incipit(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
    """
	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

    #2 - We compute the epochs and ephemerides of the planetary encounters
    ep_list = list([None] * nlegs)
    t_P = list([None] * nlegs)
    r_P = list([None] * nlegs)
    v_P = list([None] * nlegs)
    DV = list([None] * nlegs)

    for i, planet in enumerate(seq):
        ep_list[i] = x[0] + sum(T[:i + 1])
        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]

    #init lists for fly-by parameters
    vinf_list = []
    rp_list = []
    beta_list = []

    #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, nlegs):
        #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)

        vinf_list.append([a - b for a, b in zip(v_end_l, v_P[i - 1])])
        rp_list.append(x[1 + 4 * i] * seq[i - 1].radius)
        beta_list.append(x[4 * i])

        #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]

    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)