Ejemplo n.º 1
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()
Ejemplo n.º 2
0
    def plot_orbits(self, pop, ax=None):
        import matplotlib.pylab as plt
        from mpl_toolkits.mplot3d import Axes3D

        A1, A2 = self._ast1, self._ast2

        if ax is None:
            fig = plt.figure()
            axis = fig.add_subplot(111, projection='3d')
        else:
            axis = ax

        plot_planet(A1, ax=axis, s=10, t0=epoch(self.lb[0]))
        plot_planet(A2, ax=axis, s=10, t0=epoch(self.ub[0]))
        for ind in pop:
            if ind.cur_f[0] == self._UNFEASIBLE:
                continue
            dep, arr = ind.cur_x
            rdep, vdep = A1.eph(epoch(dep))
            rarr, varr = A2.eph(epoch(arr))
            l = lambert_problem(rdep, rarr, (arr - dep) * DAY2SEC,
                                A1.mu_central_body, False, 1)
            axis = plot_lambert(l, ax=axis, alpha=0.8, color='k')

        if ax is None:
            plt.show()

        return axis
Ejemplo n.º 3
0
        def plot(self, x):
            import matplotlib as mpl
            from mpl_toolkits.mplot3d import Axes3D
            import matplotlib.pyplot as plt
            from PyKEP import epoch, AU
            from PyKEP.sims_flanagan import sc_state
            from PyKEP.orbit_plots import plot_planet, plot_sf_leg

            # Making sure the leg corresponds to the requested chromosome
            self._compute_constraints_impl(x)
            start = epoch(x[0])
            end = epoch(x[0] + x[1])

            # Plotting commands
            fig = plt.figure()
            axis = fig.gca(projection='3d')
            # The Sun
            axis.scatter([0], [0], [0], color='y')
            # The leg
            plot_sf_leg(self.__leg, units=AU, N=10, ax=axis)
            # The planets
            plot_planet(
                self.__earth, start, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis)
            plot_planet(
                self.__mars, end, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis)
            plt.show()
Ejemplo n.º 4
0
	def plot(self,x):
		import matplotlib as mpl
		from mpl_toolkits.mplot3d import Axes3D
		import matplotlib.pyplot as plt
		from PyKEP.orbit_plots import plot_planet, plot_sf_leg

		mpl.rcParams['legend.fontsize'] = 10
		fig = plt.figure()
		ax = fig.gca(projection='3d')
		ax.scatter(0,0,0, color='y')

		# 1 - We decode the chromosome extracting the time of flights
		T = list([0]*(self.__n_legs))
		for i in range(self.__n_legs):
			T[i] = x[2+i*8]
			
		#2 - We compute the epochs and ephemerides of the planetary encounters
		t_P = list([None] * (self.__n_legs+1))
		r_P = list([None] * (self.__n_legs+1))
		v_P = list([None] * (self.__n_legs+1))
		
		for i,planet in enumerate(self.seq):
			t_P[i+1] = epoch(self.tf - sum(T[i+1:]))
			r_P[i+1],v_P[i+1] = self.seq[i].eph(t_P[i+1])
			plot_planet(ax, self.seq[i], t_P[i+1], units=JR, legend = True,color='k')
			
		#And we insert a fake planet simulating the starting position
		t_P[0] = epoch(self.tf - sum(T))
		theta = x[0]
		phi = x[1]
		r = [cos(phi)*sin(theta), cos(phi)*cos(theta), sin(phi)] #phi close to zero is in the moon orbit plane injection
		r = [JR*1000*d for d in r]
		r_P[0] = r
		v_P[0] = x[4:7]
		
		#3 - We iterate through legs to compute mismatches and throttles constraints
		ceq = list()
		cineq = list()
		m0 = self.__sc.mass
		for i in range(self.__n_legs):

			if i!=0: #First Leg
				v = [a+b for a,b in zip(v_P[i],x[(4 + i * 8):(7 + i * 8)])]
			else:
				v = v_P[i]
			x0 = sc_state(r_P[i],v,m0)
			v = [a+b for a,b in zip(v_P[i+1],x[(7 + i * 8):(10 + i * 8)])]
			if (i==self.__n_legs-1): #Last leg
				v = [a+b for a,b in zip(v_P[i+1],self.vf)]
			xe = sc_state(r_P[i+1], v ,x[3+8*i])
			throttles = x[(8*self.__n_legs-1 + 3*sum(self.__n_seg[:i])):(8*self.__n_legs-1 + 3*sum(self.__n_seg[:i])+3*self.__n_seg[i])]
			self.__leg.set(t_P[i],x0,throttles,t_P[i+1],xe)
			plot_sf_leg(ax, self.__leg, units=JR,N=50)
			#update mass!
			m0 = x[3+8*i]
			ceq.extend(self.__leg.mismatch_constraints())
			cineq.extend(self.__leg.throttles_constraints())
			#raise Exception    
		plt.show()
		return ax
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
    def plot(self, ax=None, clusters=None, orbits=False, only_core=False):
        """Plots the clusters."""
        if self.n_clusters < 1:
            return

        import matplotlib.pylab as plt
        from mpl_toolkits.mplot3d import Axes3D

        if ax is None:
            fig = plt.figure()
            axis = fig.add_subplot(111, projection='3d')
        else:
            axis = ax

        axis.view_init(elev=30.0, azim=135.0)
        axis.set_aspect('equal')

        if orbits:
            from PyKEP.orbit_plots import plot_planet
            members = self.core_members if only_core else self.members
            for label in members if clusters is None else clusters:
                for planet in members[label]:
                    plot_planet(
                        self._asteroids[planet], t0=self._epoch, s=0, ax=axis)

        X, labels = list(zip(*[(x, label) for (x, label) in zip(self._X, self.labels)
                               if label > -.5 and (clusters is None or label in clusters)]))
        data = [[x[0], x[1], x[2]] for x in X]
        axis.scatter(*list(zip(*data)), c=labels, alpha=0.5)

        self._axis_equal_3d(axis)

        if ax is None:
            plt.show()
        return axis
Ejemplo n.º 7
0
    def plot_orbits(self, pop, ax=None):
        import matplotlib.pylab as plt
        from mpl_toolkits.mplot3d import Axes3D

        A1, A2 = self._ast1, self._ast2

        if ax is None:
            fig = plt.figure()
            axis = fig.add_subplot(111, projection='3d')
        else:
            axis = ax

        plot_planet(A1, ax=axis, s=10, t0=epoch(self.lb[0]))
        plot_planet(A2, ax=axis, s=10, t0=epoch(self.ub[0]))
        for ind in pop:
            if ind.cur_f[0] == self._UNFEASIBLE:
                continue
            dep, arr = ind.cur_x
            rdep, vdep = A1.eph(epoch(dep))
            rarr, varr = A2.eph(epoch(arr))
            l = lambert_problem(rdep, rarr, (arr - dep) * DAY2SEC, A1.mu_central_body, False, 1)
            axis = plot_lambert(l, ax=axis, alpha=0.8, color='k')

        if ax is None:
            plt.show()

        return axis
Ejemplo n.º 8
0
    def plot(self, ax=None, clusters=None, orbits=False, only_core=False):
        """Plots the clusters."""
        if self.n_clusters < 1:
            return

        import matplotlib.pylab as plt
        from mpl_toolkits.mplot3d import Axes3D

        if ax is None:
            fig = plt.figure()
            axis = fig.add_subplot(111, projection='3d')
        else:
            axis = ax
        
        axis.view_init(elev=30.0, azim=135.0)
        axis.set_aspect('equal')       

        if orbits:
            from PyKEP.orbit_plots import plot_planet
            members = self.core_members if only_core else self.members
            for label in members if clusters is None else clusters:
                for planet in members[label]:
                    plot_planet(self._asteroids[planet], t0=self._epoch, s=0, ax=axis)

        X, labels = zip(*[(x, label)  for (x, label) in zip(self._X, self.labels) 
                          if label > -.5 and (clusters is None or label in clusters)])
        data = [[x[0], x[1], x[2]] for x in X] 
        axis.scatter(*zip(*data), c=labels)

        self._axis_equal_3d(axis)

        if ax is None:
            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)
Ejemplo n.º 10
0
		def plot(self,x):
			import matplotlib as mpl
			from mpl_toolkits.mplot3d import Axes3D
			import matplotlib.pyplot as plt
			from PyKEP import epoch, AU
			from PyKEP.sims_flanagan import sc_state
			from PyKEP.orbit_plots import plot_planet, plot_sf_leg
			
			start = epoch(x[0])
			end = epoch(x[0] + x[1])
			r,v = self.__earth.eph(start)
			v = [a+b for a,b in zip(v,x[3:6])]
			x0 = sc_state(r,v,self.__sc.mass)
			r,v = self.__mars.eph(end)
			xe = sc_state(r, v ,x[2])
			self.__leg.set(start,x0,x[-3 * self.__nseg:],end,xe)
			
			fig = plt.figure()
			ax = fig.gca(projection='3d')
			#The Sun
			ax.scatter([0],[0],[0], color='y')
			#The leg
			plot_sf_leg(ax, self.__leg, units=AU,N=10)
			#The planets
			plot_planet(ax, self.__earth, start, units=AU, legend = True,color=(0.8,0.8,1))
			plot_planet(ax, self.__mars, end, units=AU, legend = True,color=(0.8,0.8,1))
			plt.show()
Ejemplo n.º 11
0
		def plot(self,x):
			import matplotlib as mpl
			from mpl_toolkits.mplot3d import Axes3D
			import matplotlib.pyplot as plt
			from PyKEP import epoch, AU, DAY2SEC
			from PyKEP.sims_flanagan import sc_state
			from PyKEP.orbit_plots import plot_planet, plot_sf_leg
			
			start = epoch(x[0])
			end = epoch(x[0] + x[1])
			
			r,v = self.__earth.eph(start)
			v = [a+b for a,b in zip(v,x[4:7])]
			x0 = sc_state(r,v,self.__sc.mass)
			
			r,v = self.__mars.eph(end)
			xe = sc_state(r, v ,x[3])
			self.__leg.set(start,x0,x[-3 * self.__nseg:],end,xe, x[2] * DAY2SEC)
			
			fig = plt.figure()
			axis = fig.gca(projection='3d')
			#The Sun
			axis.scatter([0],[0],[0], color='y')
			#The leg
			plot_sf_leg(self.__leg, units=AU,N=10, ax = axis)
			#The planets
			plot_planet(self.__earth, start, units=AU, legend = True,color=(0.8,0.8,1), ax = axis)
			plot_planet(self.__mars, end, units=AU, legend = True,color=(0.8,0.8,1), ax = axis)
			plt.show()
Ejemplo n.º 12
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()
Ejemplo n.º 13
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 import epoch, AU
		from PyKEP.sims_flanagan import sc_state
		from PyKEP.orbit_plots import plot_planet, plot_sf_leg
		
		fig = plt.figure()
		ax = fig.gca(projection='3d')

		#Plotting the Sun ........
		ax.scatter([0],[0],[0], color='y')
		
		#Plotting the legs .......
		
		# 1 - We decode the chromosome extracting the time of flights
		T = list([0]*(self.__n_legs))
		for i in range(self.__n_legs):
			T[i] = x[1+i*8]
			
		#2 - We compute the epochs and ephemerides of the planetary encounters
		t_P = list([None] * (self.__n_legs+1))
		r_P = list([None] * (self.__n_legs+1))
		v_P = list([None] * (self.__n_legs+1))
		
		for i,planet in enumerate(self.seq):
			t_P[i] = epoch(x[0] + sum(T[0:i]))
			r_P[i],v_P[i] = self.seq[i].eph(t_P[i])
		
		#3 - We iterate through legs to compute mismatches and throttles constraints
		ceq = list()
		cineq = list()
		m0 = self.__sc.mass
		for i in range(self.__n_legs):
			#First Leg
			v = [a+b for a,b in zip(v_P[i],x[(3 + i * 8):(6 + i * 8)])]
			x0 = sc_state(r_P[i],v,m0)
			v = [a+b for a,b in zip(v_P[i+1],x[(6 + i * 8):(11 + i * 8)])]
			xe = sc_state(r_P[i+1], v ,x[2 + i * 8])
			throttles = x[(1 +8 * self.__n_legs + 3*sum(self.__n_seg[:i])):(1 +8 * self.__n_legs + 3*sum(self.__n_seg[:i])+3*self.__n_seg[i])]
			self.__leg.set(t_P[i],x0,throttles,t_P[i+1],xe)
			#update mass!
			m0 = x[2+8*i]
			plot_sf_leg(ax, self.__leg, units=AU,N=10)
			
		#Plotting planets
		for i,planet in enumerate(self.seq):
			plot_planet(ax, planet, t_P[i], units=AU, legend = True,color=(0.7,0.7,1))

		plt.show()
Ejemplo n.º 14
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
Ejemplo n.º 15
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP import epoch, AU
        from PyKEP.sims_flanagan import sc_state
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        # Creating the axis if necessary
        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        # Plotting the Sun ........
        axis.scatter([0], [0], [0], color='y')

        # Computing the legs
        self._compute_constraints_impl(x)

        # Plotting the legs
        for leg in self.__legs:
            plot_sf_leg(leg, units=AU, N=10, ax=axis)

        # Plotting the PyKEP.planets both at departure and arrival dates
        for i in range(self.__num_legs):
            idx = i * self.__dim_leg
            plot_planet(self.__seq[i],
                        epoch(x[idx]),
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        s=30,
                        ax=axis)
            plot_planet(self.__seq[i + 1],
                        epoch(x[idx] + x[idx + 1]),
                        units=AU,
                        legend=False,
                        color=(0.7, 0.7, 1),
                        s=30,
                        ax=axis)
        plt.show()
        return axis
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
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]
Ejemplo n.º 19
0
def plot_initial_geometry(ni=0.0, mu=0.5):
  	"""
	Visualizes the initial spaceraft conditions for the gtoc6 problem. Given a point on the initial spheres, \
	it assumes a velocity (almost) pointing toward Jupiter.
	
	THIS IS ONLY A VISUALIZATION, the initial velocityshould not be taken as realistic.
	"""
  
	from mpl_toolkits.mplot3d import Axes3D
	import matplotlib.pyplot as plt
	from math import sin,cos,acos,pi
	from PyKEP.orbit_plots import plot_kepler, plot_planet
	from PyKEP import DAY2SEC, propagate_lagrangian, epoch
	from scipy.linalg import norm


	ep=epoch(0.0)
	days=300.0
	
	r = [JR*1000*cos(ni)*cos(mu), JR*1000*cos(ni)*sin(mu),JR*1000*sin(ni)]
	
	VINF = 3400.0
	v = [-d/norm(r)*3400 for d in r]
	v = [d+200 for d in v]
	
	fig = plt.figure()
	ax = fig.gca(projection='3d', aspect='equal')
	
	plot_planet(ax,io,color = 'r', units = JR, t0 = ep, legend=True)
	plot_planet(ax,europa,color = 'b', units = JR, t0 = ep, legend=True)
	plot_planet(ax,ganymede,color = 'k', units = JR, t0 = ep, legend=True)
	plot_planet(ax,callisto,color = 'y', units = JR, t0 = ep, legend=True)
	plot_kepler(ax,r,v,days*DAY2SEC,MU_JUPITER, N=200, units = JR, color = 'b')
	plt.plot([r[0]/JR],[r[1]/JR],[r[2]/JR],'o')
	plt.show()
Ejemplo n.º 20
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]
Ejemplo n.º 21
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP import epoch, AU
        from PyKEP.sims_flanagan import sc_state
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        # Creating the axis if necessary
        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        # Plotting the Sun ........
        axis.scatter([0], [0], [0], color='y')

        # Computing the legs
        self._compute_constraints_impl(x)

        # Plotting the legs
        for leg in self.__legs:
            plot_sf_leg(leg, units=AU, N=10, ax=axis)

        # Plotting the PyKEP.planets both at departure and arrival dates
        for i in range(self.__num_legs):
            idx = i * self.__dim_leg
            plot_planet(self.__seq[i], epoch(x[idx]), units=AU, legend=True, color=(0.7, 0.7, 1), s=30, ax=axis)
            plot_planet(self.__seq[i + 1], epoch(x[idx] + x[idx + 1]), units=AU, legend=False, color=(0.7, 0.7, 1), s=30, ax=axis)
        plt.show()
        return axis
Ejemplo n.º 22
0
    def plot(self, x):
        # Making sure the leg corresponds to the requested chromosome
        self._compute_constraints_impl(x)
        start = epoch(x[0])
        end   = epoch(x[0] + x[1])

        # Plotting commands
        fig = plt.figure()
        axis = fig.gca(projection='3d')
        # The Sun
        axis.scatter([0], [0], [0], color='y')
        # The leg
        plot_sf_leg(self.leg, units=AU, N=10, ax=axis)
        # The planets
        plot_planet(
            self.earth, start, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis)
        plot_planet(
            self.mars, end, units=AU, legend=True, color=(0.8, 0.8, 1), ax = axis)
        plt.show()
Ejemplo n.º 23
0
    def plot(self, x):
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP import epoch, AU
        from PyKEP.sims_flanagan import sc_state
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        # Creating the axis ........
        fig = plt.figure()
        axis = fig.gca(projection='3d')

        # Plotting the Sun ........
        axis.scatter([0], [0], [0], color='y')

        # Computing the legs
        self._compute_constraints_impl(x)

        # Plotting the legs
        for leg in self.__legs:
            plot_sf_leg(leg, units=AU, N=10, ax=axis)

        # Plotting the PyKEP.planets both at departure and arrival dates
        for i in range(self.__num_legs):
            idx = i * self.__dim_leg
            plot_planet(self.__seq[i],
                        epoch(x[idx]),
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        s=30,
                        ax=axis)
            plot_planet(self.__seq[i + 1],
                        epoch(x[idx] + x[idx + 1]),
                        units=AU,
                        legend=False,
                        color=(0.7, 0.7, 1),
                        s=30,
                        ax=axis)
        plt.show()
        return axis
Ejemplo n.º 24
0
        def plot(self, x):
            import matplotlib as mpl
            from mpl_toolkits.mplot3d import Axes3D
            import matplotlib.pyplot as plt
            from PyKEP import epoch, AU
            from PyKEP.sims_flanagan import sc_state
            from PyKEP.orbit_plots import plot_planet, plot_sf_leg

            t_E = epoch(x[0])
            t_V = epoch(x[0] + x[1])
            t_M = epoch(x[0] + x[1] + x[9])
            rE, vE = self.__earth.eph(t_E)
            rV, vV = self.__venus.eph(t_V)
            rM, vM = self.__mercury.eph(t_M)

            #First Leg
            v = [a + b for a, b in zip(vE, x[3:6])]
            x0 = sc_state(rE, v, self.__sc.mass)
            v = [a + b for a, b in zip(vV, x[6:9])]
            xe = sc_state(rV, v, x[2])
            self.__leg1.set(
                t_E, x0,
                x[-3 * (self.__nseg1 + self.__nseg2):-self.__nseg2 * 3], t_V,
                xe)

            #Second leg
            v = [a + b for a, b in zip(vV, x[11:14])]
            x0 = sc_state(rV, v, x[2])
            v = [a + b for a, b in zip(vM, x[14:17])]
            xe = sc_state(rM, v, x[10])
            self.__leg2.set(t_E, x0, x[(-3 * self.__nseg2):], t_V, xe)

            fig = plt.figure()
            axis = fig.gca(projection='3d')

            #The Sun
            axis.scatter([0], [0], [0], color='y')
            #The legs
            plot_sf_leg(self.__leg1, units=AU, N=10, ax=axis)
            plot_sf_leg(self.__leg2, units=AU, N=10, ax=axis)
            #The planets
            plot_planet(self.__earth,
                        t_E,
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        ax=axis)
            plot_planet(self.__venus,
                        t_V,
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        ax=axis)
            plot_planet(self.__mercury,
                        t_M,
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        ax=axis)
            plt.show()
Ejemplo n.º 25
0
def _pl2pl_fixed_time_plot(self, x):
    from PyGMO import problem, algorithm, population
    from PyKEP import sims_flanagan, AU
    from PyKEP.orbit_plots import plot_planet, plot_sf_leg
    from PyKEP import phasing
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from mpl_toolkits.mplot3d import Axes3D

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    ax.scatter(0, 0, 0, color='y')
    ast1, ast2 = self.get_sequence()
    leg = self.get_leg()
    t_i = self.get_t0()
    t_f = self.get_t1()

    # Get initial sc state
    sc = leg.get_spacecraft()
    r, v = ast1.eph(t_i)
    xi = sims_flanagan.sc_state(r, v, sc.mass)

    # Get final sc state
    r, v = ast2.eph(t_f)
    xf = sims_flanagan.sc_state(r, v, x[0])

    # Update leg with final sc state and throttles
    leg.set(t_i, xi, x[1:], t_f, xf)

    # Plot asteroid orbits
    plot_planet(ast1, t0=t_i, color=(0.8, 0.6, 0.4), legend=True, units=AU, ax=ax)
    plot_planet(ast2, t0=t_f, color=(0.8, 0.6, 0.8), legend=True, units=AU, ax=ax)

    # Plot Sims-Flanagan leg
    plot_sf_leg(leg, units=AU, N=50, ax=ax)

    return ax
Ejemplo n.º 26
0
    def plot_cluster_evolution(self,
                               cluster_id=None,
                               only_core=False,
                               epochs=range(7500, 8400, 100),
                               skip=100,
                               alpha=0.3):
        """
        Plots a cluster evolution at 9 prefixed epochs.


        """
        if self.n_clusters < 1:
            print("No clusters have been found yet")
            return
        if cluster_id >= self.n_clusters or cluster_id < 0:
            print(
                "cluster_id should be larger then 0 and smaller than the number of clusters (-1)"
            )
            return
        if len(epochs) != 9:
            print(
                "The epochs requested must be exactly 9 as to assemble 3x3 subplots"
            )
            return

        import matplotlib.pylab as plt
        from mpl_toolkits.mplot3d import Axes3D
        from PyKEP.orbit_plots import plot_planet
        from PyKEP import epoch

        if only_core:
            ids = self.core_members[cluster_id]
        else:
            ids = self.members[cluster_id]

        fig = plt.figure()
        for i, ep in enumerate(epochs):
            axis = fig.add_subplot(3, 3, i + 1, projection='3d')

            plt.axis('off')
            plt.title(epoch(ep).__repr__()[:11])
            for pl in self._asteroids[::skip]:
                axis = plot_planet(pl, ax=axis, alpha=0.05, s=0)
            for cluster_member in ids:
                r, v = self._asteroids[cluster_member].eph(epoch(ep))
                axis.scatter([r[0]], [r[1]], [r[2]], marker='o', alpha=alpha)

        plt.draw()
        plt.show()
        return fig
Ejemplo n.º 27
0
def plot_initial_geometry(ni=0.0, mu=0.5):
    """
	Visualizes the initial spaceraft conditions for the gtoc6 problem. Given a point on the initial spheres, \
	it assumes a velocity (almost) pointing toward Jupiter.
	
	THIS IS ONLY A VISUALIZATION, the initial velocityshould not be taken as realistic.
	"""

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    from math import sin, cos, acos, pi
    from PyKEP.orbit_plots import plot_kepler, plot_planet
    from PyKEP import DAY2SEC, propagate_lagrangian, epoch
    from scipy.linalg import norm

    ep = epoch(0.0)
    days = 300.0

    r = [
        JR * 1000 * cos(ni) * cos(mu), JR * 1000 * cos(ni) * sin(mu),
        JR * 1000 * sin(ni)
    ]

    VINF = 3400.0
    v = [-d / norm(r) * 3400 for d in r]
    v = [d + 200 for d in v]

    fig = plt.figure()
    ax = fig.gca(projection='3d', aspect='equal')

    plot_planet(ax, io, color='r', units=JR, t0=ep, legend=True)
    plot_planet(ax, europa, color='b', units=JR, t0=ep, legend=True)
    plot_planet(ax, ganymede, color='k', units=JR, t0=ep, legend=True)
    plot_planet(ax, callisto, color='y', units=JR, t0=ep, legend=True)
    plot_kepler(ax,
                r,
                v,
                days * DAY2SEC,
                MU_JUPITER,
                N=200,
                units=JR,
                color='b')
    plt.plot([r[0] / JR], [r[1] / JR], [r[2] / JR], 'o')
    plt.show()
Ejemplo n.º 28
0
def plot_moons(epoch=epoch(0)):
    """
	Plots the Galilean Moons of Jupiter at epoch
	
	USAGE: plot_moons(epoch = epoch(34654, epoch.epoch_type.MJD)):

	* epoch: the epoch one wants the galilean moons to be plotted at
	
	"""
    from PyKEP.orbit_plots import plot_planet
    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    plot_planet(ax, io, color='r', units=JR, t0=epoch, legend=True)
    plot_planet(ax, europa, color='b', units=JR, t0=epoch, legend=True)
    plot_planet(ax, ganymede, color='k', units=JR, t0=epoch, legend=True)
    plot_planet(ax, callisto, color='y', units=JR, t0=epoch, legend=True)
    plt.show()
Ejemplo n.º 29
0
def plot_moons(epoch = epoch(0)):
	"""
	Plots the Galilean Moons of Jupiter at epoch
	
	USAGE: plot_moons(epoch = epoch(34654, epoch.epoch_type.MJD)):

	* epoch: the epoch one wants the galilean moons to be plotted at
	
	"""
	from PyKEP.orbit_plots import plot_planet
	from mpl_toolkits.mplot3d import Axes3D
	import matplotlib.pyplot as plt
	
	fig = plt.figure()
	ax = fig.gca(projection='3d')

	plot_planet(ax,io,color = 'r', units = JR, t0 = epoch, legend=True)
	plot_planet(ax,europa,color = 'b', units = JR, t0 = epoch, legend=True)
	plot_planet(ax,ganymede,color = 'k', units = JR, t0 = epoch, legend=True)
	plot_planet(ax,callisto,color = 'y', units = JR, t0 = epoch, legend=True)
	plt.show()
Ejemplo n.º 30
0
    def plot_cluster_evolution(self, cluster_id=None, only_core=False, epochs=range(7500, 8400, 100), skip=100, alpha=0.3):
        """
        Plots a cluster evolution at 9 prefixed epochs.


        """
        if self.n_clusters < 1:
            print("No clusters have been found yet")
            return
        if cluster_id >= self.n_clusters or cluster_id < 0:
            print("cluster_id should be larger then 0 and smaller than the number of clusters (-1)")
            return
        if len(epochs) != 9:
            print("The epochs requested must be exactly 9 as to assemble 3x3 subplots")
            return

        import matplotlib.pylab as plt
        from mpl_toolkits.mplot3d import Axes3D
        from PyKEP.orbit_plots import plot_planet
        from PyKEP import epoch

        if only_core:
            ids = self.core_members[cluster_id]
        else:
            ids = self.members[cluster_id]

        fig = plt.figure()
        for i, ep in enumerate(epochs):
            axis = fig.add_subplot(3, 3, i + 1, projection='3d')

            plt.axis('off')
            plt.title(epoch(ep).__repr__()[:11])
            for pl in self._asteroids[::skip]:
                axis = plot_planet(pl, ax=axis, alpha=0.05, s=0)
            for cluster_member in ids:
                r, v = self._asteroids[cluster_member].eph(epoch(ep))
                axis.scatter([r[0]], [r[1]], [r[2]], marker='o', alpha=alpha)

        plt.draw()
        plt.show()
        return fig
Ejemplo n.º 31
0
        def plot(self, x):
            import matplotlib as mpl
            from mpl_toolkits.mplot3d import Axes3D
            import matplotlib.pyplot as plt
            from PyKEP import epoch, AU
            from PyKEP.sims_flanagan import sc_state
            from PyKEP.orbit_plots import plot_planet, plot_sf_leg

            t_E = epoch(x[0])
            t_V = epoch(x[0] + x[1])
            t_M = epoch(x[0] + x[1] + x[9])
            rE, vE = self.__earth.eph(t_E)
            rV, vV = self.__venus.eph(t_V)
            rM, vM = self.__mercury.eph(t_M)

            # First Leg
            v = [a + b for a, b in zip(vE, x[3:6])]
            x0 = sc_state(rE, v, self.__sc.mass)
            v = [a + b for a, b in zip(vV, x[6:9])]
            xe = sc_state(rV, v, x[2])
            self.__leg1.set(
                t_E, x0, x[-3 * (self.__nseg1 + self.__nseg2):-self.__nseg2 * 3], t_V, xe)

            # Second leg
            v = [a + b for a, b in zip(vV, x[11:14])]
            x0 = sc_state(rV, v, x[2])
            v = [a + b for a, b in zip(vM, x[14:17])]
            xe = sc_state(rM, v, x[10])
            self.__leg2.set(t_E, x0, x[(-3 * self.__nseg2):], t_V, xe)

            fig = plt.figure()
            axis = fig.gca(projection='3d')

            # The Sun
            axis.scatter([0], [0], [0], color='y')
            # The legs
            plot_sf_leg(self.__leg1, units=AU, N=10, ax=axis)
            plot_sf_leg(self.__leg2, units=AU, N=10, ax=axis)
            # The planets
            plot_planet(
                self.__earth, t_E, units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis)
            plot_planet(
                self.__venus, t_V, units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis)
            plot_planet(
                self.__mercury, t_M, units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis)
            plt.show()
Ejemplo n.º 32
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler

        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        axis.scatter(0, 0, 0, color='y')

        # 1 -  we 'decode' the chromosome recording the various deep space
        # manouvres timing (days) in the list T
        T = list([0] * (self.N_max - 1))

        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]

        # 2 - We compute the starting and ending position
        r_start, v_start = self.start.eph(epoch(x[0]))
        if self.phase_free:
            r_target, v_target = self.target.eph(epoch(x[-1]))
        else:
            r_target, v_target = self.target.eph(epoch(x[0] + x[1]))
        plot_planet(self.start,
                    t0=epoch(x[0]),
                    color=(0.8, 0.6, 0.8),
                    legend=True,
                    units=AU,
                    ax=axis)
        plot_planet(self.target,
                    t0=epoch(x[0] + x[1]),
                    color=(0.8, 0.6, 0.8),
                    legend=True,
                    units=AU,
                    ax=axis)

        # 3 - We loop across inner impulses
        rsc = r_start
        vsc = v_start
        for i, time in enumerate(T[:-1]):
            theta = 2 * pi * x[3 + 4 * i]
            phi = acos(2 * x[4 + 4 * i] - 1) - pi / 2

            Vinfx = x[5 + 4 * i] * cos(phi) * cos(theta)
            Vinfy = x[5 + 4 * i] * cos(phi) * sin(theta)
            Vinfz = x[5 + 4 * i] * sin(phi)

            # We apply the (i+1)-th impulse
            vsc = [a + b for a, b in zip(vsc, [Vinfx, Vinfy, Vinfz])]
            plot_kepler(rsc,
                        vsc,
                        T[i] * DAY2SEC,
                        self.__common_mu,
                        N=200,
                        color='b',
                        legend=False,
                        units=AU,
                        ax=axis)
            rsc, vsc = propagate_lagrangian(rsc, vsc, T[i] * DAY2SEC,
                                            self.__common_mu)

        cw = (ic2par(rsc, vsc, self.start.mu_central_body)[2] > pi / 2)
        # We now compute the remaining two final impulses
        # Lambert arc to reach seq[1]
        dt = T[-1] * DAY2SEC
        l = lambert_problem(rsc, r_target, dt, self.__common_mu, cw, False)
        plot_lambert(l,
                     sol=0,
                     color='r',
                     legend=False,
                     units=AU,
                     ax=axis,
                     N=200)
        plt.show()
        return axis
	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)


tt1 = 450

plot_planet(ax, plEarth, t0=epoch(tt1), color=(0.8, 0.8, 1), units=AU)
plot_planet(ax, plMars, t0=epoch(tt1), color=(0.8, 0.8, 1), units=AU)


for dtt in range(200, 350, 10):
    opt_dt(tt1, tt1 + dtt)


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)
    maxsize = max(abs(sz))
    r = maxsize / 2
    for ctr, dim in zip(centers, "xyz"):
        getattr(ax, "set_{}lim".format(dim))(ctr - r, ctr + r)
Ejemplo n.º 34
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
Ejemplo n.º 35
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP import epoch, AU
        from PyKEP.sims_flanagan import sc_state
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        # Creating the axis if necessary
        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        # Plotting the Sun ........
        axis.scatter([0], [0], [0], color='y')

        # Plotting the legs .......
        # 1 - We decode the chromosome extracting the time of flights
        T = list([0] * (self.__n_legs))
        for i in range(self.__n_legs):
            T[i] = x[1 + i * 8]

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

        for i, planet in enumerate(self.seq):
            t_P[i] = epoch(x[0] + sum(T[0:i]))
            r_P[i], v_P[i] = self.seq[i].eph(t_P[i])

        # 3 - We iterate through legs to compute mismatches and throttles constraints
        ceq = list()
        cineq = list()
        m0 = self.__sc.mass
        for i in range(self.__n_legs):
            # First Leg
            v = [a + b for a, b in zip(v_P[i], x[(3 + i * 8):(6 + i * 8)])]
            x0 = sc_state(r_P[i], v, m0)
            v = [a + b for a, b in zip(v_P[i + 1], x[(6 + i * 8):(11 + i * 8)])]
            xe = sc_state(r_P[i + 1], v, x[2 + i * 8])
            throttles = x[(1 + 8 * self.__n_legs + 3 * sum(self.__n_seg[:i])):(1 + 8 * self.__n_legs + 3 * sum(self.__n_seg[:i]) + 3 * self.__n_seg[i])]
            self.__leg.set(t_P[i], x0, throttles, t_P[i + 1], xe)
            # update mass!
            m0 = x[2 + 8 * i]
            plot_sf_leg(self.__leg, units=AU, N=10, ax=axis)

        # Plotting planets
        for i, planet in enumerate(self.seq):
            plot_planet(planet, t_P[i], units=AU, legend=True, color=(0.7, 0.7, 1), ax = axis)

        plt.show()
        return axis
Ejemplo n.º 36
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
            1.5 * AU,  # a	semimajor axis
            0.5,  # e	eccentricity
            30 * DEG2RAD,  # i	inclination
            i * 60 * DEG2RAD,  # W	longitude of accesing node
            0 * 60 * DEG2RAD,  # w	argument of periapsis
            0 * DEG2RAD  # M	mean anomaly
        ),
        MU_SUN,
        398600.4418e9,
        6378000,
        6900000,
        'testPlanet')
    pls.append(myPlanet)

t1 = epoch(0)
plot_planet(ax, earth, t0=t1, color=(0.8, 0.8, 0.8), legend=True, units=AU)
for i in range(len(pls)):
    plot_planet(ax,
                pls[i],
                t0=t1,
                color=(1 - i / 5.0, 0, i / 5.0),
                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]
Ejemplo n.º 38
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler

        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        axis.scatter(0, 0, 0, color='y')

        # 1 -  we 'decode' the chromosome recording the various deep space
        # manouvres timing (days) in the list T
        T = list([0] * (self.N_max - 1))

        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]

        # 2 - We compute the starting and ending position
        r_start, v_start = self.start.eph(epoch(x[0]))
        if self.phase_free:
            r_target, v_target = self.target.eph(epoch(x[-1]))
        else:
            r_target, v_target = self.target.eph(epoch(x[0] + x[1]))
        plot_planet(self.start, t0=epoch(x[0]), color=(0.8, 0.6, 0.8), legend=True, units = AU, ax=axis)
        plot_planet(self.target, t0=epoch(x[0] + x[1]), color=(0.8, 0.6, 0.8), legend=True, units = AU, ax=axis)

        # 3 - We loop across inner impulses
        rsc = r_start
        vsc = v_start
        for i, time in enumerate(T[:-1]):
            theta = 2 * pi * x[3 + 4 * i]
            phi = acos(2 * x[4 + 4 * i] - 1) - pi / 2

            Vinfx = x[5 + 4 * i] * cos(phi) * cos(theta)
            Vinfy = x[5 + 4 * i] * cos(phi) * sin(theta)
            Vinfz = x[5 + 4 * i] * sin(phi)

            # We apply the (i+1)-th impulse
            vsc = [a + b for a, b in zip(vsc, [Vinfx, Vinfy, Vinfz])]
            plot_kepler(rsc, vsc, T[
                        i] * DAY2SEC, self.__common_mu, N=200, color='b', legend=False, units=AU, ax=axis)
            rsc, vsc = propagate_lagrangian(
                rsc, vsc, T[i] * DAY2SEC, self.__common_mu)

        cw = (ic2par(rsc, vsc, self.start.mu_central_body)[2] > pi / 2)
        # We now compute the remaining two final impulses
        # Lambert arc to reach seq[1]
        dt = T[-1] * DAY2SEC
        l = lambert_problem(rsc, r_target, dt, self.__common_mu, cw, False)
        plot_lambert(
            l, sol=0, color='r', legend=False, units=AU, ax=axis, N=200)
        plt.show()
        return axis
pls = []
for i in range(5):
	myPlanet = planet(
	epoch(54000,epoch.epoch_type.MJD), (
	1.5 * AU,                    # a	semimajor axis
	0.5 ,               # e	eccentricity
	30 * DEG2RAD,     # i	inclination
	i*60 * DEG2RAD,     # W	longitude of accesing node
	0*60 * DEG2RAD,     # w	argument of periapsis
	0 * DEG2RAD      # M	mean anomaly
	), MU_SUN, 398600.4418e9, 6378000, 6900000,  'testPlanet' )
	pls.append(myPlanet)

t1 = epoch(0)
plot_planet(ax,earth,    t0=t1, color=(0.8,0.8,0.8), legend=True, units = AU)
for i in range(len(pls)):
	plot_planet(ax,pls[i], t0=t1, color=(1-i/5.0,0,i/5.0), legend=True, units = AU)












Ejemplo n.º 40
0
    def plot_trajectory(self, x, units=AU, plot_segments=True, ax=None):
        """
        ax = prob.plot_trajectory(self, x, units=AU, plot_segments=True, ax=None)

        - x: encoded trajectory
        - units: the length unit to be used in the plot
        - plot_segments: when true plots also the segments boundaries
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        from PyKEP.orbit_plots import plot_planet, plot_taylor

        # Creating the axis if necessary
        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        n_seg = self.__n_seg
        fwd_seg = self.__fwd_seg
        bwd_seg = self.__bwd_seg
        t0 = x[0]
        T = x[1]
        isp = self.__sc.isp
        veff = isp * G0
        fwd_grid = t0 + T * self.__fwd_grid # days
        bwd_grid = t0 + T * self.__bwd_grid # days

        throttles = [x[3 + 3 * i : 6 + 3 * i] for i in range(n_seg)]
        alphas = [min(1., np.linalg.norm(t)) for t in throttles]

        times = np.concatenate((fwd_grid, bwd_grid))

        rfwd, rbwd, vfwd, vbwd, mfwd, mbwd, ufwd, ubwd, fwd_dt, bwd_dt = self._propagate(x)

        # Plotting the Sun, the Earth and the target
        axis.scatter([0], [0], [0], color='y')
        plot_planet(self.__earth, epoch(t0), units=units, legend=True, color=(0.7, 0.7, 1), ax=axis)
        plot_planet(self.target, epoch(t0 + T), units=units, legend=True, color=(0.7, 0.7, 1), ax=axis)

        # Forward propagation
        xfwd = [0.0] * (fwd_seg + 1)
        yfwd = [0.0] * (fwd_seg + 1)
        zfwd = [0.0] * (fwd_seg + 1)
        xfwd[0] = rfwd[0][0] / units
        yfwd[0] = rfwd[0][1] / units
        zfwd[0] = rfwd[0][2] / units

        for i in range(fwd_seg):
            plot_taylor(rfwd[i], vfwd[i], mfwd[i], ufwd[i], fwd_dt[i], MU_SUN, veff, N=10, units=units, color=(alphas[i], 0, 1-alphas[i]), ax=axis)
            xfwd[i+1] = rfwd[i+1][0] / units
            yfwd[i+1] = rfwd[i+1][1] / units
            zfwd[i+1] = rfwd[i+1][2] / units
        if plot_segments:
            axis.scatter(xfwd[:-1], yfwd[:-1], zfwd[:-1], label='nodes', marker='o', s=1)

        # Backward propagation
        xbwd = [0.0] * (bwd_seg + 1)
        ybwd = [0.0] * (bwd_seg + 1)
        zbwd = [0.0] * (bwd_seg + 1)
        xbwd[-1] = rbwd[-1][0] / units
        ybwd[-1] = rbwd[-1][1] / units
        zbwd[-1] = rbwd[-1][2] / units

        for i in range(bwd_seg):
            plot_taylor(rbwd[-i-1], vbwd[-i-1], mbwd[-i-1], ubwd[-i-1], -bwd_dt[-i-1], MU_SUN, veff, N=10, units=units, color=(alphas[-i-1], 0, 1-alphas[-i-1]), ax=axis)
            xbwd[-i-2] = rbwd[-i-2][0] / units
            ybwd[-i-2] = rbwd[-i-2][1] / units
            zbwd[-i-2] = rbwd[-i-2][2] / units
        if plot_segments:
            axis.scatter(xbwd[1:], ybwd[1:], zbwd[1:], marker='o', s=1)

        if ax is None:  # show only if axis is not set
            plt.show()

        return axis
Ejemplo n.º 41
0
	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)


tt1 = 450

plot_planet(ax, plEarth, t0=epoch(tt1), color=(0.8, 0.8, 1), units=AU)
plot_planet(ax, plMars, t0=epoch(tt1), color=(0.8, 0.8, 1), units=AU)

for dtt in range(200, 350, 10):
    opt_dt(tt1, tt1 + dtt)


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)
    maxsize = max(abs(sz))
    r = maxsize / 2
    for ctr, dim in zip(centers, 'xyz'):
        getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r)
Ejemplo n.º 42
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()
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')

t1 = epoch(0)
n = len(ilist)
for i in range(n):
    pl = planet_mpcorb(lines[ilist[i]])
    #print ilist[i], pl.orbital_elements[1], pl.orbital_elements[4]
    #print ilist[i], pl.orbital_elements
    print "=====", lines[ilist[i]]
    plot_planet(ax,
                pl,
                t0=t1,
                color=(1.0 - i / float(n), 0.5, i / float(n)),
                legend=True,
                units=AU)
    #plot_planet(ax,pl, t0=t1, color=(1.0-i/float(n),0.5,i/float(n)), legend=False, 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)
    maxsize = max(abs(sz))
    r = maxsize / 2
    for ctr, dim in zip(centers, 'xyz'):
        getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r)
Ejemplo n.º 44
0
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(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,
Ejemplo n.º 45
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
Ejemplo n.º 46
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 import epoch, AU
        from PyKEP.sims_flanagan import sc_state
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        fig = plt.figure()
        ax = fig.gca(projection='3d')

        #Plotting the Sun ........
        ax.scatter([0], [0], [0], color='y')

        #Plotting the legs .......

        # 1 - We decode the chromosome extracting the time of flights
        T = list([0] * (self.__n_legs))
        for i in range(self.__n_legs):
            T[i] = x[1 + i * 8]

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

        for i, planet in enumerate(self.seq):
            t_P[i] = epoch(x[0] + sum(T[0:i]))
            r_P[i], v_P[i] = self.seq[i].eph(t_P[i])

        #3 - We iterate through legs to compute mismatches and throttles constraints
        ceq = list()
        cineq = list()
        m0 = self.__sc.mass
        for i in range(self.__n_legs):
            #First Leg
            v = [a + b for a, b in zip(v_P[i], x[(3 + i * 8):(6 + i * 8)])]
            x0 = sc_state(r_P[i], v, m0)
            v = [
                a + b for a, b in zip(v_P[i + 1], x[(6 + i * 8):(11 + i * 8)])
            ]
            xe = sc_state(r_P[i + 1], v, x[2 + i * 8])
            throttles = x[(1 + 8 * self.__n_legs + 3 * sum(self.__n_seg[:i])):(
                1 + 8 * self.__n_legs + 3 * sum(self.__n_seg[:i]) +
                3 * self.__n_seg[i])]
            self.__leg.set(t_P[i], x0, throttles, t_P[i + 1], xe)
            #update mass!
            m0 = x[2 + 8 * i]
            plot_sf_leg(ax, self.__leg, units=AU, N=10)

        #Plotting planets
        for i, planet in enumerate(self.seq):
            plot_planet(ax,
                        planet,
                        t_P[i],
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1))

        plt.show()
Ejemplo n.º 47
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler

        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        axis.scatter(0, 0, 0, color='y')

        # 1 -  we 'decode' the chromosome recording the various times of flight
        # (days) in the list T and the cartesian components of vinf
        T, Vinfx, Vinfy, Vinfz = self._decode_times_and_vinf(x)

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

        # 3 - We start with the first leg
        v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[5] * T[0] * DAY2SEC,
                                    self.common_mu)

        plot_kepler(r_P[0],
                    v0,
                    x[5] * T[0] * DAY2SEC,
                    self.common_mu,
                    N=100,
                    color='b',
                    legend=False,
                    units=AU,
                    ax=axis)

        # Lambert arc to reach seq[1]
        dt = (1 - x[5]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, self.common_mu, False, False)
        plot_lambert(l, sol=0, color='r', legend=False, units=AU, ax=axis)
        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[8 + (i - 1) * 4] * self.seq[i].radius,
                            x[7 + (i - 1) * 4], self.seq[i].mu_self)
            # s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out,
                                        x[9 + (i - 1) * 4] * T[i] * DAY2SEC,
                                        self.common_mu)
            plot_kepler(r_P[i],
                        v_out,
                        x[9 + (i - 1) * 4] * T[i] * DAY2SEC,
                        self.common_mu,
                        N=100,
                        color='b',
                        legend=False,
                        units=AU,
                        ax=axis)
            # Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[9 + (i - 1) * 4]) * T[i] * DAY2SEC

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

            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 axis
Ejemplo n.º 48
0
    def plot(self, x):
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        mpl.rcParams['legend.fontsize'] = 10
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        ax.scatter(0, 0, 0, color='y')

        # 1 - We decode the chromosome extracting the time of flights
        T = list([0] * (self.__n_legs))
        for i in range(self.__n_legs):
            T[i] = x[2 + i * 8]

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

        for i, planet in enumerate(self.seq):
            t_P[i + 1] = epoch(self.tf - sum(T[i + 1:]))
            r_P[i + 1], v_P[i + 1] = self.seq[i].eph(t_P[i + 1])
            plot_planet(ax,
                        self.seq[i],
                        t_P[i + 1],
                        units=JR,
                        legend=True,
                        color='k')

        #And we insert a fake planet simulating the starting position
        t_P[0] = epoch(self.tf - sum(T))
        theta = x[0]
        phi = x[1]
        r = [cos(phi) * sin(theta),
             cos(phi) * cos(theta),
             sin(phi)]  #phi close to zero is in the moon orbit plane injection
        r = [JR * 1000 * d for d in r]
        r_P[0] = r
        v_P[0] = x[4:7]

        #3 - We iterate through legs to compute mismatches and throttles constraints
        ceq = list()
        cineq = list()
        m0 = self.__sc.mass
        for i in range(self.__n_legs):

            if i != 0:  #First Leg
                v = [a + b for a, b in zip(v_P[i], x[(4 + i * 8):(7 + i * 8)])]
            else:
                v = v_P[i]
            x0 = sc_state(r_P[i], v, m0)
            v = [
                a + b for a, b in zip(v_P[i + 1], x[(7 + i * 8):(10 + i * 8)])
            ]
            if (i == self.__n_legs - 1):  #Last leg
                v = [a + b for a, b in zip(v_P[i + 1], self.vf)]
            xe = sc_state(r_P[i + 1], v, x[3 + 8 * i])
            throttles = x[(8 * self.__n_legs - 1 + 3 * sum(self.__n_seg[:i])):(
                8 * self.__n_legs - 1 + 3 * sum(self.__n_seg[:i]) +
                3 * self.__n_seg[i])]
            self.__leg.set(t_P[i], x0, throttles, t_P[i + 1], xe)
            plot_sf_leg(ax, self.__leg, units=JR, N=50)
            #update mass!
            m0 = x[3 + 8 * i]
            ceq.extend(self.__leg.mismatch_constraints())
            cineq.extend(self.__leg.throttles_constraints())
            #raise Exception
        plt.show()
        return ax
Ejemplo n.º 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
Ejemplo n.º 50
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP import epoch, AU
        from PyKEP.sims_flanagan import sc_state
        from PyKEP.orbit_plots import plot_planet, plot_sf_leg

        # Creating the axis if necessary
        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        # Plotting the Sun ........
        axis.scatter([0], [0], [0], color='y')

        # Plotting the legs .......
        # 1 - We decode the chromosome extracting the time of flights
        T = list([0] * (self.__n_legs))
        for i in range(self.__n_legs):
            T[i] = x[1 + i * 8]

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

        for i, planet in enumerate(self.seq):
            t_P[i] = epoch(x[0] + sum(T[0:i]))
            r_P[i], v_P[i] = self.seq[i].eph(t_P[i])

        # 3 - We iterate through legs to compute mismatches and throttles constraints
        ceq = list()
        cineq = list()
        m0 = self.__sc.mass
        for i in range(self.__n_legs):
            # First Leg
            v = [a + b for a, b in zip(v_P[i], x[(3 + i * 8):(6 + i * 8)])]
            x0 = sc_state(r_P[i], v, m0)
            v = [
                a + b for a, b in zip(v_P[i + 1], x[(6 + i * 8):(11 + i * 8)])
            ]
            xe = sc_state(r_P[i + 1], v, x[2 + i * 8])
            throttles = x[(1 + 8 * self.__n_legs + 3 * sum(self.__n_seg[:i])):(
                1 + 8 * self.__n_legs + 3 * sum(self.__n_seg[:i]) +
                3 * self.__n_seg[i])]
            self.__leg.set(t_P[i], x0, throttles, t_P[i + 1], xe)
            # update mass!
            m0 = x[2 + 8 * i]
            plot_sf_leg(self.__leg, units=AU, N=10, ax=axis)

        # Plotting planets
        for i, planet in enumerate(self.seq):
            plot_planet(planet,
                        t_P[i],
                        units=AU,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        ax=axis)

        plt.show()
        return axis
Ejemplo n.º 51
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
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')


t1 = epoch(0)
n=len(ilist)
for i in range(n):
	pl = planet_mpcorb(lines[ilist[i]])
	#print ilist[i], pl.orbital_elements[1], pl.orbital_elements[4]
	#print ilist[i], pl.orbital_elements
	print "=====", lines[ilist[i]]
	plot_planet(ax,pl, t0=t1, color=(1.0-i/float(n),0.5,i/float(n)), legend=True, units = AU)
	#plot_planet(ax,pl, t0=t1, color=(1.0-i/float(n),0.5,i/float(n)), legend=False, 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)
    maxsize = max(abs(sz))
    r = maxsize/2
    for ctr, dim in zip(centers, 'xyz'):
        getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r)
								
axisEqual3D(ax)

show()
Ejemplo n.º 53
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
Ejemplo n.º 54
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()
Ejemplo n.º 55
0
    def plot(self, x, ax=None):
        """
        ax = prob.plot(x, ax=None)

        - x: encoded trajectory
        - ax: matplotlib axis where to plot. If None figure and axis will be created
        - [out] ax: matplotlib axis where to plot

        Plots the trajectory represented by a decision vector x on the 3d axis ax

        Example::

          ax = prob.plot(x)
        """
        import matplotlib as mpl
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler

        if ax is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axis = fig.gca(projection='3d')
        else:
            axis = ax

        axis.scatter(0, 0, 0, color='y')

        # 1 -  we 'decode' the chromosome recording the various times of flight
        # (days) in the list T and the cartesian components of vinf
        T, Vinfx, Vinfy, Vinfz = self._decode_times_and_vinf(x)

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

        # 3 - We start with the first leg
        v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])]
        r, v = propagate_lagrangian(r_P[0], v0, x[5] * T[0] * DAY2SEC, self.common_mu)

        plot_kepler(r_P[0], v0, x[5] * T[0] * DAY2SEC, self.common_mu, N=100, color='b', legend=False, units=AU, ax=axis)

        # Lambert arc to reach seq[1]
        dt = (1 - x[5]) * T[0] * DAY2SEC
        l = lambert_problem(r, r_P[1], dt, self.common_mu, False, False)
        plot_lambert(l, sol=0, color='r', legend=False, units=AU, ax=axis)
        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[8 + (i - 1) * 4] * self.seq[i].radius, x[7 + (i - 1) * 4], self.seq[i].mu_self)
            # s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_out, x[9 + (i - 1) * 4] * T[i] * DAY2SEC, self.common_mu)
            plot_kepler(r_P[i], v_out, x[9 + (i - 1) * 4] * T[i] * DAY2SEC, self.common_mu, N=100, color='b', legend=False, units=AU, ax=axis)
            # Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
            dt = (1 - x[9 + (i - 1) * 4]) * T[i] * DAY2SEC

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

            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 axis
Ejemplo n.º 56
0
    def AIO(self,x, doplot = True, doprint = True, rtrn_desc = True, dists_class = None):
        P = doprint
        plots_datas = list([None] * (self.__n))
        PLDists = list([None] * (self.__n-1))
        FBDates = list([None] * (self.__n-1))

        #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
        if P: 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)

        if P:
            print("Departure:        " + str(t_P[0]) + " (" + str(t_P[0].mjd2000) + " mjd2000) \n"
                  "Duration:         " + str(T[0]) + " days\n"
                  "VINF:             " + str(x[3] / 1000) + " km/sec\n"
                  "C3:               " + str((x[3] / 1000)**2) + " km^2/s^2")

        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)
        if P: 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, MU_SUN)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]

        # Append data needed for potential plot generation
        plots_datas[0] = [v0, x[4]*T[0]*DAY2SEC, l]

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

        #4 - And we proceed with each successive leg
        for i in range(1,self.__n):
            if P:
                print("\nleg no.           " + str(i+1) + ": " + self.seq[i].name + " to " + self.seq[i+1].name + "\n"
                      "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)
            PLDists[i-1] = (x[7+(i-1)*4] -1)*self.seq[i].radius/1000.
            FBDates[i-1] = t_P[i]

            if P:
                print("Fly-by epoch:     " + str(t_P[i]) + " (" + str(t_P[i].mjd2000) + " mjd2000) \n"
                      "Fly-by radius:    " + str(x[7+(i-1)*4]) + " planetary radii\n"
                      "Fly-by distance:  " + str( (x[7+(i-1)*4] -1)*self.seq[i].radius/1000.) + " km")

            #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)
            if P: 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, MU_SUN)
            v_end_l = l.get_v2()[0]
            v_beg_l = l.get_v1()[0]

            # Append data needed for potential plot generation
            plots_datas[i] = [v_out, x[8+(i-1)*4]*T[i]*DAY2SEC, l]

            #DSM occuring at time nu2*T2
            DV[i] = norm([a-b for a,b in zip(v_beg_l,v)])
            if P: print "DSM magnitude:    " + str(DV[i]) + "m/s"

        #Last Delta-v
        if P:  print "\nArrival at " + self.seq[-1].name
        DV[-1] = norm([a-b for a,b in zip(v_end_l,v_P[-1])])

        if P:
            print("Arrival Vinf:     " + str(DV[-1]) + "m/s  \n"
                  "Total mission time: " + str(sum(T)/365.25) + " years (" + str(sum(T)) + " days) \n"
                  "DSMs mag:         " + str(sum(DV[:-1])) + "m/s  \n"
                  "Entry Vel:        " + str(sqrt(2*(0.5*(DV[-1])**2 + 61933310.95))) + "m/s  \n"
                  "Entry epoch:      " + str(epoch(t_P[0].mjd2000 + sum(T))) )

        if doplot:
            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(figsize=(8, 8), dpi=80)
            ax = fig.gca(projection='3d')
            ax.scatter(0,0,0, color='y')

            for i,planet in enumerate(self.seq):
                plot_planet(ax, planet, t0=t_P[i], color=(0.8,0.6,0.8), legend=True, units = AU)

            for i, tpl in enumerate(plots_datas):
                plot_kepler(ax, r_P[i], tpl[0], tpl[1], MU_SUN ,N = 100, color='b', legend=False, units = AU)
                plot_lambert(ax, tpl[2], sol = 0, color='r', legend=False, units = AU)

            fig.tight_layout()
            plt.show()

        if dists_class is not None:
            for i, tpl in enumerate(plots_datas):
                dists_class.positions_kepler(r_P[i], tpl[0], tpl[1], MU_SUN ,index = 2*i)
                dists_class.positions_lambert(tpl[2], sol = 0, index = 2*(i+.5))
            dists_class.set_launch_epoch(t_P[0].mjd2000)
            return dists_class

        if rtrn_desc:
            import numpy as np
            from math import atan2

            desc = dict()
            for i in range(len(x)):
                desc[i] = x[i]

            theta = 2*pi*x[1]
            phi = acos(2*x[2]-1)-pi/2

            axtl = 23.43929*DEG2RAD # Earth axial tlit
            mactran = np.matrix([ [1,         0,          0],
                                  [0, cos(axtl), -sin(axtl)],
                                  [0, sin(axtl),  cos(axtl)] ]) # Macierz przejscia z helio do ECI

            macdegs = np.matrix([ [cos(phi)*cos(theta)],
                                  [cos(phi)*sin(theta)],
                                  [sin(phi)] ])
            aaa = mactran.dot(macdegs)
            theta_earth = atan2(aaa[1,0], aaa[0,0])    # Rektascensja asym
            phi_earth = asin(aaa[2,0])                 # Deklinacja asym
            desc['RA'] = 360+RAD2DEG*theta_earth
            desc['DEC'] = phi_earth*RAD2DEG

            desc['Ldate'] = str(t_P[0])
            desc['C3'] = (x[3] / 1000)**2

            desc['dVmag'] = sum(DV[:-1])
            desc['VinfRE'] = DV[-1]
            desc['VRE'] = (DV[-1]**2 + 2*61933310.95)**.5
            desc['REDate'] = str(epoch(t_P[0].mjd2000 + sum(T)))

            for i in range(1,self.__n):
                desc[self.seq[i].name[0].capitalize()+'Dist'] = PLDists[i-1]
                desc[self.seq[i].name[0].capitalize()+'FBDate'] = str(FBDates[i-1])

            return desc
mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')




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)
Ejemplo n.º 58
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()
		axis = fig.gca(projection='3d')
		axis.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))
		for i in range(0, self.__n_legs):
			T[i] = x[4+3*(self.__n_legs - 1) + i+1]
		
		#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(planet, t0=t_P[i], color=(0.8,0.6,0.8), legend=True, units = AU, ax=axis)

		#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(r_P[0],v0,x[4]*T[0]*DAY2SEC,self.common_mu,N = 100, color='b', legend=False, units = AU, ax=axis)

		#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(l, sol = 0, color='r', legend=False, units = AU, ax=axis)
		v_end_l = l.get_v2()[0]
		v_beg_l = l.get_v1()[0]

		#First DSM occurring 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[6+(i-1)*3]*self.seq[i].radius,x[5+(i-1)*3],self.seq[i].mu_self)
			#s/c propagation before the DSM
			r,v = propagate_lagrangian(r_P[i],v_out,x[7+(i-1)*3]*T[i]*DAY2SEC,self.common_mu)
			plot_kepler(r_P[i],v_out,x[7+(i-1)*3]*T[i]*DAY2SEC,self.common_mu,N = 100, color='b', legend=False, units = AU, ax=axis)
			#Lambert arc to reach Earth during (1-nu2)*T2 (second segment)
			dt = (1-x[7+(i-1)*3])*T[i]*DAY2SEC

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

			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)])
		plt.show()
		return axis