示例#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, AU, MU_SUN, lambert_problem
    from pykep.planet import jpl_lp
    from pykep.orbit_plots import plot_planet, plot_lambert

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

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

    t1 = epoch(0)
    t2 = epoch(640)
    dt = (t2.mjd2000 - t1.mjd2000) * DAY2SEC

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

    pl = jpl_lp('earth')
    plot_planet(pl, t0=t1, color=(0.8, 0.8, 1), legend=True, units=AU, ax=axis)
    rE, vE = pl.eph(t1)

    pl = jpl_lp('mars')
    plot_planet(pl, t0=t2, color=(0.8, 0.8, 1), legend=True, units=AU, ax=axis)
    rM, vM = pl.eph(t2)

    l = lambert_problem(rE, rM, dt, MU_SUN)
    plot_lambert(l, color='b', legend=True, units=AU, ax=axis)
    plot_lambert(l, sol=1, color='g', legend=True, units=AU, ax=axis)
    plot_lambert(l, sol=2, color='g', legend=True, units=AU, ax=axis)

    plt.show()
示例#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
示例#3
0
文件: _ex4.py 项目: darioizzo/pykep
    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()
示例#4
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
示例#5
0
def plot_innerKerbol(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
    print(epoch)
    fig = plt.figure()
    ax1 = fig.gca(projection='3d')

    #plot_planet(ax,Moho,color = 'y', units = 1.0, t0 = epoch, legend=True)
    #plot_planet(ax,Eve,color = 'm', units = 1.0, t0 = epoch, legend=True)
    #lot_planet(ax=ax1,Kerbin,color = 'c', units = 1.0, t0, legend=True)
    #plot_planet(ax = ax1,Duna,color = 'r', units = 1.0, t0 = epoch, legend=True)
    plot_planet(Moho, t0=epoch, color='y', legend=True, units=KAU, ax=ax1)
    plot_planet(Eve, t0=epoch, color='m', legend=True, units=KAU, ax=ax1)
    plot_planet(Kerbin, t0=epoch, color='c', legend=True, units=KAU, ax=ax1)
    plot_planet(Duna, t0=epoch, color='r', legend=True, units=KAU, ax=ax1)
    plot_planet(Jool, t0=epoch, color='g', legend=True, units=KAU, ax=ax1)
    ax1.set_xlim3d(-3, 3)
    ax1.set_ylim3d(-3, 3)
    ax1.set_zlim3d(-3, 3)
    plt.show()
    """
示例#6
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, axes=axis, s=10, t0=epoch(self.lb[0]))
        plot_planet(A2, axes=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, axes=axis, alpha=0.8, color='k')

        if ax is None:
            plt.show()

        return axis
示例#7
0
    def plot(self, x, axes=None, units=AU, N=60):
        """plot(self, x, axes=None, units=pk.AU, N=60)

        Plots the spacecraft trajectory.

        Args:
            - x (``tuple``, ``list``, ``numpy.ndarray``): Decision chromosome.
            - axes (``matplotlib.axes._subplots.Axes3DSubplot``): 3D axes to use for the plot
            - units (``float``, ``int``): Length unit by which to normalise data.
            - N (``float``): Number of points to plot per leg
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        from pykep.orbit_plots import plot_planet, plot_lambert

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

        T = self._decode_tofs(x)
        ep = np.insert(T, 0, x[0])  # [t0, T1, T2 ...]
        ep = np.cumsum(ep)  # [t0, t1, t2, ...]
        _, _, _, l, _ = self._compute_dvs(x)
        for pl, e in zip(self.seq, ep):
            plot_planet(pl, epoch(e), units=units, legend=True,
                        color=(0.7, 0.7, 1), axes=axes)
        for lamb in l:
            plot_lambert(lamb, N=N, sol=0, units=units, color='k',
                         legend=False, axes=axes, alpha=0.8)
        return axes
示例#8
0
文件: _ex4.py 项目: tniessen/pykep
    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, axes=axis)
        # The planets
        plot_planet(
            self.__earth, start, units=AU, legend=True, color=(0.8, 0.8, 1), axes=axis)
        plot_planet(
            self.__mars, end, units=AU, legend=True, color=(0.8, 0.8, 1), axes=axis)
        plt.show()
示例#9
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 pykep.planet 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, 0.7),
                        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, 0.7),
                        s=30,
                        ax=axis)

        # Computing the legs
        self.fitness(x)

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

        return axis
示例#10
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 pykep.planet 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, 0.7), 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, 0.7), s=30, ax=axis)

        # Computing the legs
        self.fitness(x)

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

        return axis
示例#11
0
    def plot(self, x, axes=None, units=AU, N=60):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from pykep.orbit_plots import plot_planet

        rvt_outs, rvt_ins, rvt_pls, _, _ = self._compute_dvs(x)
        rvt_outs = [
            rvt.rotate(self._rotation_axis, self._theta) for rvt in rvt_outs
        ]
        rvt_ins[1:] = [
            rvt.rotate(self._rotation_axis, self._theta) for rvt in rvt_ins[1:]
        ]
        rvt_pls = [
            rvt.rotate(self._rotation_axis, self._theta) for rvt in rvt_pls
        ]

        ep = [epoch(rvt_pl._t * SEC2DAY) for rvt_pl in rvt_pls]

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

        plt.xlim([-1, 1])
        # planets
        for pl, e in zip(self._seq, ep):
            plot_planet(pl,
                        e,
                        units=units,
                        legend=True,
                        color=(0.7, 0.7, 1),
                        axes=axes)

        # lamberts and resonances
        for i in range(0, len(self._seq) - 1):
            pl = self._seq[i]
            # stay at planet: it is a resonance colored black
            is_reso = pl == self._seq[i + 1]
            rvt_out = rvt_outs[i]
            tof = rvt_ins[i + 1]._t - rvt_out._t
            rvt_out.plot(tof,
                         units=units,
                         N=4 * N,
                         color="k" if is_reso else "r",
                         axes=axes)
        return axes
示例#12
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()
示例#13
0
文件: _dbscan.py 项目: wbnns/pykep
    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, axes=axis, alpha=0.05, s=0)
            for cluster_member in ids:
                r, _ = 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
示例#14
0
文件: _ex3.py 项目: darioizzo/pykep
    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()
示例#15
0
def plottransfer():
    star = Star(1817514095, 1905216634)
    origin = Planet(1817514095, 1905216634, -455609026)
    target = Planet(1817514095, 1905216634, 272811578)
    origin_orbit_radius = origin.planet.radius + 200000
    target_orbit_radius = target.planet.radius + 200000

    flight_time = int(flask_request.values['flight_time'])

    t0 = epoch_from_string(str(datetime.now()))
    t0_number = int(t0.mjd2000)
    launch_time = int(flask_request.values['launch_time']) + t0_number

    t1 = epoch(int(launch_time))
    t2 = epoch(int(launch_time) + int(flight_time))

    fig = plt.figure(figsize=(4, 4))
    orbit_ax = fig.gca(projection='3d', proj_type='ortho')
    orbit_ax.scatter([0], [0], [0], color='orange')
    orbit_ax.set_aspect('equal')

    x_fig = plt.figure(figsize=(4, 4))
    x_ax = x_fig.gca()
    x_ax.scatter([0], [0], color='orange')

    y_fig = plt.figure(figsize=(4, 4))
    y_ax = y_fig.gca()
    y_ax.scatter([0], [0], color='orange')

    z_fig = plt.figure(figsize=(4, 4))
    z_ax = z_fig.gca()
    z_ax.scatter([0], [0], color='orange')

    plot_planet(origin.planet,
                t0=t1,
                color='green',
                legend=True,
                units=AU,
                ax=orbit_ax)
    plot_planet(target.planet,
                t0=t2,
                color='gray',
                legend=True,
                units=AU,
                ax=orbit_ax)

    o_x, o_y, o_z = plot_planet_2d(origin.planet, t0=t1)
    t_x, t_y, t_z = plot_planet_2d(target.planet, t0=t2)

    x_ax.plot(o_y, o_z, label=origin.planet.name, c='green')
    x_ax.scatter(o_y[0], o_z[0], s=40, color='green')
    x_ax.plot(t_y, t_z, label=target.planet.name, c='gray')
    x_ax.scatter(t_y[0], t_z[0], s=40, color='gray')

    y_ax.plot(o_x, o_z, label=origin.planet.name, c='green')
    y_ax.scatter(o_x[0], o_z[0], s=40, color='green')
    y_ax.plot(t_x, t_z, label=target.planet.name, c='gray')
    y_ax.scatter(t_x[0], t_z[0], s=40, color='gray')

    z_ax.plot(o_x, o_y, label=origin.planet.name, c='green')
    z_ax.scatter(o_x[0], o_y[0], s=40, color='green')
    z_ax.plot(t_x, t_y, label=target.planet.name, c='gray')
    z_ax.scatter(t_x[0], t_y[0], s=40, color='gray')

    max_value = max(max([abs(x) for x in orbit_ax.get_xlim()]),
                    max([abs(x) for x in orbit_ax.get_ylim()]))
    max_z_value = max([abs(z) for z in orbit_ax.get_zlim()])

    dt = (t2.mjd - t1.mjd) * DAY2SEC
    r1, v1 = origin.planet.eph(t1)
    r2, v2 = target.planet.eph(t2)
    lambert = lambert_problem(list(r1), list(r2), dt, star.gm)

    min_n = None
    min_delta_v = None
    for x in range(lambert.get_Nmax() + 1):
        vp_vec = np.array(v1)
        vs_vec = np.array(lambert.get_v1()[x])
        vsp_vec = vs_vec - vp_vec
        vsp = np.linalg.norm(vsp_vec)
        vo = sqrt(vsp * vsp + 2 * origin.planet.mu_self / origin_orbit_radius)
        inj_delta_v = vo - sqrt(origin.planet.mu_self / origin_orbit_radius)

        vp_vec = np.array(v2)
        vs_vec = np.array(lambert.get_v2()[x])
        vsp_vec = vs_vec - vp_vec
        vsp = np.linalg.norm(vsp_vec)
        vo = sqrt(vsp * vsp + 2 * target.planet.mu_self / target_orbit_radius)
        ins_delta_v = vo - sqrt(target.planet.mu_self / target_orbit_radius)

        if min_delta_v is None or inj_delta_v + ins_delta_v < min_delta_v:
            min_n = x
            min_delta_v = inj_delta_v + ins_delta_v

    plot_lambert(lambert,
                 color='purple',
                 sol=min_n,
                 legend=False,
                 units=AU,
                 ax=orbit_ax)

    l_x, l_y, l_z = plot_lambert_2d(lambert, sol=min_n)

    x_ax.plot(l_y, l_z, c='purple')
    y_ax.plot(l_x, l_z, c='purple')
    z_ax.plot(l_x, l_y, c='purple')

    orbit_ax.set_xlim(-max_value * 1.2, max_value * 1.2)
    orbit_ax.set_ylim(-max_value * 1.2, max_value * 1.2)
    orbit_ax.set_zlim(-max_z_value * 1.2, max_z_value * 1.2)

    x_ax.set_xlim(-1.0, 1.0)
    x_ax.set_ylim(-0.05, 0.05)

    y_ax.set_xlim(-1.0, 1.0)
    y_ax.set_ylim(-0.05, 0.05)

    z_ax.set_xlim(-1.0, 1.0)
    z_ax.set_ylim(-1.0, 1.0)

    fig.savefig('orbit')

    x_fig.savefig('orbit-x')
    y_fig.savefig('orbit-y')
    z_fig.savefig('orbit-z')

    plt.close('all')

    return jsonify(success=True)
示例#16
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,
                        axes=axis,
                        N=150)

        # 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[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,
                    axes=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, axes=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[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(r_P[i],
                        v_out,
                        x[8 + (i - 1) * 4] * T[i] * DAY2SEC,
                        self.common_mu,
                        N=100,
                        color='b',
                        legend=False,
                        units=AU,
                        axes=axis)
            # 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(l,
                         sol=0,
                         color='r',
                         legend=False,
                         units=AU,
                         N=1000,
                         axes=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
示例#17
0
    def plot(self, x, axes=None):
        """
        ax = prob.plot_trajectory(x, axes=None)

        - x: encoded trajectory
        - axes: 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 axes is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axes = fig.gca(projection='3d')

        axes.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=axes, s=0)
        plot_planet(self.target, t0=epoch(
            x[0] + x[1]), color=(0.8, 0.6, 0.8), legend=True, units=AU, ax=axes, s=0)

        DV_list = x[5::4]
        maxDV = max(DV_list)
        DV_list = [s / maxDV * 30 for s in DV_list]
        colors = ['b', 'r'] * (len(DV_list) + 1)

        # 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])]
            axes.scatter(rsc[0] / AU, rsc[1] / AU, rsc[2] /
                         AU, color='k', s=DV_list[i])
            plot_kepler(rsc, vsc, T[i] * DAY2SEC, self.__common_mu,
                        N=200, color=colors[i], legend=False, units=AU, ax=axes)
            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=colors[
                     i + 1], legend=False, units=AU, ax=axes, N=200)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]
        DV1 = norm([a - b for a, b in zip(v_beg_l, vsc)])
        DV2 = norm([a - b for a, b in zip(v_end_l, v_target)])

        axes.scatter(rsc[0] / AU, rsc[1] / AU, rsc[2] / AU,
                     color='k', s=min(DV1 / maxDV * 30, 40))
        axes.scatter(r_target[0] / AU, r_target[1] / AU,
                     r_target[2] / AU, color='k', s=min(DV2 / maxDV * 30, 40))

        return axes
ast_orbel = (2.77 * AU, 0.075, 9.65 * DEG2RAD, 80.33 * DEG2RAD,
             72.52 * DEG2RAD, 95.99 * DEG2RAD)  # a,e,i,W,w,M (SI and RAD)
ast_mu = 6e10
ast_radius = 1e5
ast_name = 'asteroid'
asteroid = keplerian(ast_time, ast_orbel, MU_SUN, ast_mu, ast_radius,
                     ast_radius * 1.1, ast_name)
rA, vA = asteroid.eph(ast_time)

#earth
pl = jpl_lp('earth')
rE, vE = pl.eph(ast_time)

# plot
fig = plt.figure()
axis = fig.gca(projection='3d')
axis.scatter([0], [0], [0], color='y')  #sun
plot_planet(asteroid,
            t0=ast_time,
            color=(1, 0.4, 0),
            legend=True,
            units=AU,
            ax=axis)  #asteroid
plot_planet(pl,
            t0=ast_time,
            color=(0.8, 0.8, 1),
            legend=True,
            units=AU,
            ax=axis)  #earth
plt.show()
示例#19
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
示例#20
0
    def plot(self, x, axes=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_sf_leg, plot_planet

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

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

        # 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 in range(len(self._seq)):
            t_P[i] = epoch(x[0] + sum(x[1:i * 8:8]))
            r_P[i], v_P[i] = self._seq[i].eph(t_P[i])
            plot_planet(self._seq[i],
                        t0=t_P[i],
                        units=AU,
                        legend=False,
                        color=(0.7, 0.7, 0.7),
                        s=30,
                        axes=ax)

        # We assemble the constraints.
        # 1 - Mismatch Constraints
        for i in range(self._n_legs):
            # Departure velocity of the spacecraft in the heliocentric frame
            v0 = [a + b for a, b in zip(v_P[i], x[3 + 8 * i:6 + 8 * i])]
            if i == 0:
                m0 = self._mass[1]
            else:
                m0 = x[2 + 8 * (i - 1)]
            x0 = sc_state(r_P[i], v0, m0)
            vf = [a + b for a, b in zip(v_P[i + 1], x[6 + 8 * i:9 + 8 * i])]
            xf = sc_state(r_P[i + 1], vf, x[2 + 8 * i])
            idx_start = 1 + 8 * self._n_legs + sum(self._n_seg[:i]) * 3
            idx_end = 1 + 8 * self._n_legs + sum(self._n_seg[:i + 1]) * 3
            self._leg.set(t_P[i], x0, x[idx_start:idx_end], t_P[i + 1], xf)
            plot_sf_leg(self._leg, units=AU, N=10, axes=ax, legend=False)

        return axes
示例#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')

        # 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
示例#22
0
    def _fitness_impl(self, decoded_x, logging=False, plotting=False, ax=None):
        """ Computation of the objective function. """

        saturn_distance_violated = 0

        # decode x
        t0, u, v, dep_vinf, etas, T, betas, rps = decoded_x

        # convert incoming velocity vector
        theta, phi = 2.0 * pi * u, acos(2.0 * v - 1.0) - pi / 2.0
        Vinfx = dep_vinf * cos(phi) * cos(theta)
        Vinfy = dep_vinf * cos(phi) * sin(theta)
        Vinfz = dep_vinf * sin(phi)

        # 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))
        lamberts = list([None] * (self._n_legs))
        v_outs = list([None] * (self._n_legs))
        DV = list([0.0] * (self._n_legs + 1))

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

        # first leg
        v_outs[0] = [Vinfx, Vinfy, Vinfz]  # bug fixed

        # check first leg up to DSM
        saturn_distance_violated += self.check_distance(
            r_P[0], v_outs[0], t0, etas[0] * T[0])
        r, v = propagate_lagrangian(r_P[0], v_outs[0],
                                    etas[0] * T[0] * DAY2SEC, self.common_mu)

        # Lambert arc to reach seq[1]
        dt = (1.0 - etas[0]) * T[0] * DAY2SEC
        lamberts[0] = lambert_problem(r, r_P[1], dt, self.common_mu, self.cw,
                                      0)
        v_end_l = lamberts[0].get_v2()[0]
        v_beg_l = lamberts[0].get_v1()[0]

        # First DSM occuring at time eta0*T0
        DV[0] = norm([a - b for a, b in zip(v_beg_l, v)])
        # checking first leg after DSM
        saturn_distance_violated += self.check_distance(
            r, v_beg_l, etas[0] * T[0], T[0])

        # successive legs
        for i in range(1, self._n_legs):
            # Fly-by
            v_outs[i] = fb_prop(v_end_l, v_P[i],
                                rps[i - 1] * self.seq[i].radius, betas[i - 1],
                                self.seq[i].mu_self)
            # checking next leg up to DSM
            saturn_distance_violated += self.check_distance(
                r_P[i], v_outs[i], T[i - 1], etas[i] * T[i])
            # s/c propagation before the DSM
            r, v = propagate_lagrangian(r_P[i], v_outs[i],
                                        etas[i] * T[i] * DAY2SEC,
                                        self.common_mu)
            # Lambert arc to reach next body
            dt = (1 - etas[i]) * T[i] * DAY2SEC
            lamberts[i] = lambert_problem(r, r_P[i + 1], dt, self.common_mu,
                                          self.cw, 0)
            v_end_l = lamberts[i].get_v2()[0]
            v_beg_l = lamberts[i].get_v1()[0]
            # DSM occuring at time eta_i*T_i
            DV[i] = norm([a - b for a, b in zip(v_beg_l, v)])
            # checking next leg after DSM
            saturn_distance_violated += self.check_distance(
                r, v_beg_l, etas[i] * T[i], T[i])

        # single dv penalty for now
        if saturn_distance_violated > 0:
            DV[-1] += DV_PENALTY

        arr_vinf = norm([a - b for a, b in zip(v_end_l, v_P[-1])])

        # last Delta-v
        if self._add_vinf_arr:
            DV[-1] = arr_vinf

        if self._add_vinf_dep:
            DV[0] += dep_vinf

        # pretty printing
        if logging:
            print("First leg: {} to {}".format(self.seq[0].name,
                                               self.seq[1].name))
            print("Departure: {0} ({1:0.6f} mjd2000)".format(
                t_P[0], t_P[0].mjd2000))
            print("Duration: {0:0.6f}d".format(T[0]))
            print("VINF: {0:0.3f}m/s".format(dep_vinf))
            print("DSM after {0:0.6f}d".format(etas[0] * T[0]))
            print("DSM magnitude: {0:0.6f}m/s".format(DV[0]))

            for i in range(1, self._n_legs):
                print("\nleg {}: {} to {}".format(i + 1, self.seq[i].name,
                                                  self.seq[i + 1].name))
                print("Duration: {0:0.6f}d".format(T[i]))
                print("Fly-by epoch: {0} ({1:0.6f} mjd2000)".format(
                    t_P[i], t_P[i].mjd2000))
                print("Fly-by radius: {0:0.6f} planetary radii".format(rps[i -
                                                                           1]))
                print("DSM after {0:0.6f}d".format(etas[i] * T[i]))
                print("DSM magnitude: {0:0.6f}m/s".format(DV[i]))

            print("\nArrival at {}".format(self.seq[-1].name))
            print("Arrival epoch: {0} ({1:0.6f} mjd2000)".format(
                t_P[-1], t_P[-1].mjd2000))
            print("Arrival Vinf: {0:0.3f}m/s".format(arr_vinf))
            print("Total mission time: {0:0.6f}d ({1:0.3f} years)".format(
                sum(T),
                sum(T) / 365.25))

        # plotting
        if plotting:
            ax.scatter(0, 0, 0, color='chocolate')
            for i, planet in enumerate(self.seq):
                plot_planet(planet,
                            t0=t_P[i],
                            color=pl2c[planet.name],
                            legend=True,
                            units=AU,
                            ax=ax)
            for i in range(0, self._n_legs):
                plot_kepler(r_P[i],
                            v_outs[i],
                            etas[i] * T[i] * DAY2SEC,
                            self.common_mu,
                            N=100,
                            color='b',
                            legend=False,
                            units=AU,
                            ax=ax)
            for l in lamberts:
                plot_lambert(l,
                             sol=0,
                             color='r',
                             legend=False,
                             units=AU,
                             N=1000,
                             ax=ax)

        # returning building blocks for objectives
        return (DV, T, arr_vinf, lamberts)
示例#23
0
    def plot(self, x, axes=None):
        """
        ax = prob.plot_trajectory(x, axes=None)

        - x: encoded trajectory
        - axes: 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 axes is None:
            mpl.rcParams['legend.fontsize'] = 10
            fig = plt.figure()
            axes = fig.gca(projection='3d')

        axes.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=axes,
                    s=0)
        plot_planet(self.target,
                    t0=epoch(x[0] + x[1]),
                    color=(0.8, 0.6, 0.8),
                    legend=True,
                    units=AU,
                    ax=axes,
                    s=0)

        DV_list = x[5::4]
        maxDV = max(DV_list)
        DV_list = [s / maxDV * 30 for s in DV_list]
        colors = ['b', 'r'] * (len(DV_list) + 1)

        # 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])]
            axes.scatter(rsc[0] / AU,
                         rsc[1] / AU,
                         rsc[2] / AU,
                         color='k',
                         s=DV_list[i])
            plot_kepler(rsc,
                        vsc,
                        T[i] * DAY2SEC,
                        self.__common_mu,
                        N=200,
                        color=colors[i],
                        legend=False,
                        units=AU,
                        ax=axes)
            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=colors[i + 1],
                     legend=False,
                     units=AU,
                     ax=axes,
                     N=200)
        v_end_l = l.get_v2()[0]
        v_beg_l = l.get_v1()[0]
        DV1 = norm([a - b for a, b in zip(v_beg_l, vsc)])
        DV2 = norm([a - b for a, b in zip(v_end_l, v_target)])

        axes.scatter(rsc[0] / AU,
                     rsc[1] / AU,
                     rsc[2] / AU,
                     color='k',
                     s=min(DV1 / maxDV * 30, 40))
        axes.scatter(r_target[0] / AU,
                     r_target[1] / AU,
                     r_target[2] / AU,
                     color='k',
                     s=min(DV2 / maxDV * 30, 40))

        return axes
示例#24
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