コード例 #1
0
def propagateSimsFlanagan():
    "Test the propagation of SimsFlanagan back and forth using the velocities from Lambert"
    ### Using ephemeris
    # Lambert trajectory obtain terminal velocity vectors
    SF = CONFIG.SimsFlan_config()

    # Create bodies
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    mars = AL_2BP.Body('mars', 'red', mu = Cts.mu_M_m)

    # Calculate trajectory of the bodies based on ephem
    earthephem = pk.planet.jpl_lp('earth')
    marsephem = pk.planet.jpl_lp('mars')
    
    decv, l = findValidLambert()

    print(decv)

    Fit = Fitness(Nimp = SF.Nimp)
    Fit.calculateFitness(decv)
    Fit.printResult()

    # We plot
    mpl.rcParams['legend.fontsize'] = 10

    # Create the figure and axis
    fig = plt.figure(figsize = (16,5))
    ax1 = fig.add_subplot(1, 3, 1, projection='3d')
    ax1.scatter([0], [0], [0], color=['y'])

    ax2 = fig.add_subplot(1, 3, 2, projection='3d')
    ax2.scatter([0], [0], [0], color=['y'])
    ax2.view_init(90, 0)

    ax3 = fig.add_subplot(1, 3, 3, projection='3d')
    ax3.scatter([0], [0], [0], color=['y'])
    ax3.view_init(0,0)

    t1 = SF.t0.JD
    t2 = t1 + AL_BF.sec2days(decv[7])

    for ax in [ax1, ax2, ax3]:
        # Plot the planet orbits
        # plot_planet(earth, t0=t1, color=(0.8, 0.8, 1), legend=True, units=AU, axes=ax)
        # plot_planet(mars, t0=t2, color=(0.8, 0.8, 1), legend=True, units=AU, axes=ax)

        # Plot the Lambert solutions
        axis = plot_lambert(l, color='b', legend=True, units=AU, axes=ax)
        # axis = plot_lambert(l, sol=1, color='g', legend=True, units=AU, axes=ax)
        # axis = plot_lambert(l, sol=2, color='g', legend=True, units=AU, axes=ax)

    plt.show()
コード例 #2
0
    def __SimsFlanagan(self,
                       SV_i,
                       thrust='free',
                       backwards=False,
                       saveState=False):
        """
        __SimsFlanagan:
            No impulse is not applied in the state 0 or final.
            Only in intermediate steps
        """
        t_i = self.t_t / (self.Nimp + 1)  # Divide time in 6 segments

        if saveState == True:  # save each state
            SV_list = np.zeros(((self.Nimp + 1) // 2 + 1, 6))
            SV_list[0, :] = SV_i

        # Propagate only until middle point to save computation time
        # ! Problems if Nimp is even
        for imp in range((self.Nimp + 1) // 2):
            # Create trajectory
            trajectory = AL_2BP.BodyOrbit(SV_i, 'Cartesian', self.sun)

            # Propagate the given time
            # Coordinates after propagation
            SV_i = trajectory.Propagation(t_i, 'Cartesian')

            # Add impulse if not in last point
            if imp != (self.Nimp + 1) // 2:
                if thrust == 'free':
                    if backwards == True:
                        SV_i[3:] -= self.DeltaV_list[
                            imp, :] * self.DeltaV_max  # Reduce the impulses
                    else:
                        SV_i[3:] += self.DeltaV_list[imp, :] * self.DeltaV_max
                elif thrust == 'tangential':
                    # If magnitude is backwards:
                    sign = np.sign(np.dot(SV_i[3:], self.DeltaV_list[imp, :]))
                    if backwards == True:
                        SV_i[3:] -= SV_i[3:] / np.linalg.norm(
                            SV_i[3:]) * sign * np.linalg.norm(
                                self.DeltaV_list[imp, :]
                            ) * self.DeltaV_max  # Reduce the impulses
                    else:
                        SV_i[3:] += SV_i[3:] / np.linalg.norm(
                            SV_i[3:]) * sign * np.linalg.norm(
                                self.DeltaV_list[imp, :]) * self.DeltaV_max

            else:  # To compare, only add impulse on the one forward to compare delta v
                if backwards != True:
                    SV_i[3:] += self.DeltaV_list[
                        imp, :] * self.DeltaV_max  # Reduce the impulses

            if saveState == True:
                SV_list[imp + 1, :] = SV_i

        if saveState == True:
            return SV_list  # All states
        else:
            return SV_i  # Last state
コード例 #3
0
def Lambert():
    #### Howard Curtis page 254
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    r_1 = np.array([5000, 10000, 2100]) * 1000
    r_2 = np.array([-14600, 2500, 7000]) * 1000

    lambert = AL_TR.Lambert(r_1, r_2, 3600, earth.mu)
    v1, v2 = lambert.TerminalVelVect()
    print(v1, v2) #Validated
コード例 #4
0
def propagateHohmann():
    # with a hohmann orbit the necessary parameters are found, propagating 
    # we should get to the planet
    # ephemeris retrieval
    date0 = np.array([27,1,2016,0])
    t_0 = AL_Eph.DateConv(date0,'calendar') #To JD
    transfertime = 258.8493

    # Create bodies
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    mars = AL_2BP.Body('mars', 'red', mu = Cts.mu_M_m)

    # Calculate trajectory of the bodies based on ephem
    earthephem = pk.planet.jpl_lp('earth')
    marsephem = pk.planet.jpl_lp('mars')
    r_E, v_E = earthephem.eph(t_0.JD_0)
    r_M, v_M = marsephem.eph(t_0.JD_0 + transfertime)

    orbit_E = AL_2BP.BodyOrbit(np.append(r_E, v_E), 'Cartesian', sun)
    earth.addOrbit(orbit_E)
    orbit_M = AL_2BP.BodyOrbit(np.append(r_M, v_M), 'Cartesian', sun)
    mars.addOrbit(orbit_M)

    # Create transfer in the first moment
    transfer1 = AL_TR.SystemBodies([earth, mars])

    t, r_E, v_E, r_M, v_M = transfer1.findDateWith180deg(date0, transfertime, [earthephem, marsephem],usingCircular=False)
    date_1 = AL_Eph.DateConv(t,'JD_0') #To JD
    transfer1.HohmannTransfer(r_0 = r_E, r_1 = r_M)

    # Propagate
    r0 = np.array(r_E)
    v0 = transfer1.vp_H * np.array(v_E) / np.linalg.norm(v_E)

    orbit_sp = AL_2BP.BodyOrbit(np.append(r0,v0), 'Cartesian', sun)
    x = orbit_sp.Propagation(transfer1.timeflight_H, 'Cartesian') # Coordinates after propagation

    # Compare with supposed solutions
    print("HOHMANN")
    vf = transfer1.va_H
    rf = np.array(r_M)
    print(rf)
    print("PROPAGATION")
    x = np.array(x)
    print(x)

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

    ax.scatter(0,0,0, color = 'yellow', s = 100)
    ax.scatter(r0[0],r0[1],r0[2], color = 'blue')
    ax.scatter(rf[0],rf[1],rf[2], color = 'red')
    ax.scatter(x[0], x[1], x[2], color = 'green')

    AL_Plot.set_axes_equal(ax)
    plt.show() # Validated: more or less. Points are close to each other
コード例 #5
0
def propagateSimsFlanaganForward():
    "Test the propagation of SimsFlanagan forward using the velocities from Lambert"
    ### Using ephemeris
    # Lambert trajectory obtain terminal velocity vectors
    SF = CONFIG.SimsFlan_config()

    # Create bodies
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    mars = AL_2BP.Body('mars', 'red', mu = Cts.mu_M_m)

    # Calculate trajectory of the bodies based on ephem
    earthephem = pk.planet.jpl_lp('earth')
    marsephem = pk.planet.jpl_lp('mars')
    
    decv, l = findValidLambert()
    print(decv)

    r_M, v_M = marsephem.eph(decv[6] + AL_BF.sec2days(decv[7]) )

    Fit = Propagate(Nimp = SF.Nimp)
    Fit.prop(decv, plot = True)
    print("Final", Fit.rv_final)
    print("Theoretical final", r_M,  AL_BF.convert3dvector(decv[3:6], "polar")+v_M)
コード例 #6
0
def CartKeplr():
    # From Mission Geometry slides
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)

    x = np.array([8751268.4691, -7041314.6869, 4846546.9938, \
                    332.2601039, -2977.0815768,-4869.8462227])
    x2 = np.array([-2700816.139,-3314092.801, 5266346.4207,\
                    5168.606551,-5597.546615,-868.8784452])
    x3 = np.array([10157768.1264, -6475997.0091, 2421205.9518,\
                1099.2953996, 3455.1059240, 4355.0978095])

    K = np.array([12158817.9615, 0.014074320051, 52.666016957,\
                    323.089150643, 148.382589129, 112.192638384])

    K2 = np.array([12269687.5912,  0.004932091570, 109.823277603,\
                134.625563565, 106.380426142, 301.149932402])

    print("CARTESIAN-KEPLERIAN")

    trajectory1 = AL_2BP.BodyOrbit(x, 'Cartesian', earth )
    print("Result vector 1")
    print(trajectory1.KeplerElem_deg) # Validated

    trajectory12 = AL_2BP.BodyOrbit(x2, 'Cartesian', earth)
    print("Result vector 2")
    print(trajectory12.KeplerElem_deg) # Validated

    trajectory13 = AL_2BP.BodyOrbit(x3, 'Cartesian', earth)
    print("Result vector 3")
    print(trajectory13.KeplerElem_deg) # Validated

    print("KEPLERIAN-CARTESIAN")

    trajectory2 = AL_2BP.BodyOrbit(K, 'Keplerian', earth, unitsI = 'deg')
    print("Result vector 1")
    print(trajectory2.r, trajectory2.v ) # Validated

    trajectory22 = AL_2BP.BodyOrbit(trajectory12.KeplerElem_deg, 'Keplerian', earth, unitsI = 'deg')
    print("Result vector 2")
    print(trajectory22.r, trajectory22.v ) # Validated

    trajectory23 = AL_2BP.BodyOrbit(K2, 'Keplerian', earth, unitsI = 'deg')
    print("Result vector 3")
    print(trajectory23.r, trajectory23.v ) # Validated`
コード例 #7
0
def propagateLambert():
    ### Using ephemeris
    # Lambert trajectory obtain terminal velocity vectors
    date0 = np.array([27,1,2016,0])
    t_0 = AL_Eph.DateConv(date0,'calendar') #To JD
    transfertime = 250

    # Create bodies
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    mars = AL_2BP.Body('mars', 'red', mu = Cts.mu_M_m)

    # Calculate trajectory of the bodies based on ephem
    earthephem = pk.planet.jpl_lp('earth')
    marsephem = pk.planet.jpl_lp('mars')
    r_E, v_E = earthephem.eph(t_0.JD_0)
    r_M, v_M = marsephem.eph(t_0.JD_0 + transfertime)

    orbit_E = AL_2BP.BodyOrbit(np.append(r_E, v_E), 'Cartesian', sun)
    earth.addOrbit(orbit_E)
    orbit_M = AL_2BP.BodyOrbit(np.append(r_M, v_M), 'Cartesian', sun)
    mars.addOrbit(orbit_M)

    # Create transfer in the first moment
    lambert = AL_TR.Lambert(np.array(r_E), np.array(r_M), AL_BF.days2sec(transfertime), sun.mu)
    v_0, v_f = lambert.TerminalVelVect()
    print(v_0)

    # Propagate
    orbit_sp = AL_2BP.BodyOrbit(np.append(r_E, v_0), 'Cartesian', sun)
    x = orbit_sp.Propagation(AL_BF.days2sec(transfertime), 'Cartesian') # Coordinates after propagation

    r0 = np.array(r_E)
    rf = np.array(r_M)

    print('Mars', r_M, 'Propagation', x, 'Error', abs(rf - x[0:3])) # Almost zero

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

    ax.scatter(0,0,0, color = 'yellow', s = 100)
    ax.scatter(r0[0],r0[1],r0[2], color = 'blue')
    ax.scatter(rf[0],rf[1],rf[2], color = 'red')
    ax.scatter(x[0], x[1], x[2], color = 'green')

    AL_Plot.set_axes_equal(ax)
    plt.show() # Validated
コード例 #8
0
    def __init__(self, *args, **kwargs):

        #Constants used
        Cts = AL_BF.ConstantsBook()  #Constants for planets

        # Define bodies involved
        self.Spacecraft = AL_2BP.Spacecraft()
        self.earthephem = pk.planet.jpl_lp('earth')
        self.marsephem = pk.planet.jpl_lp('mars')
        self.jupiterephem = pk.planet.jpl_lp('jupiter')
        self.venusephem = pk.planet.jpl_lp('venus')

        self.sun = AL_2BP.Body('Sun', 'yellow', mu=Cts.mu_S_m)
        self.earth = AL_2BP.Body('Earth', 'blue', mu=Cts.mu_E_m)
        self.mars = AL_2BP.Body('Mars', 'red', mu=Cts.mu_M_m)
        self.jupiter = AL_2BP.Body('Jupiter', 'green', mu=Cts.mu_J_m)
        self.venus = AL_2BP.Body('Venus', 'brown', mu=Cts.mu_V_m)

        departure = kwargs.get('departure', "Earth")
        arrival = kwargs.get('arrival', "Mars")

        if departure == 'Earth':
            self.departure = self.earth
            self.departureephem = self.earthephem
        elif departure == 'Mars':
            self.departure = self.mars
            self.departureephem = self.marsephem

        if arrival == 'Mars':
            self.arrival = self.mars
            self.arrivalephem = self.marsephem
        elif arrival == 'Jupiter':
            self.arrival = self.jupiter
            self.arrivalephem = self.jupiterephem
        elif arrival == 'Venus':
            self.arrival = self.venus
            self.arrivalephem = self.venusephem
        elif arrival == 'Earth':
            self.arrival = self.earth
            self.arrivalephem = self.earthephem

        # Settings
        self.color = ['blue', 'green', 'black', 'red', 'yellow', 'orange']

        # Choose odd number to compare easily in middle point
        self.Nimp = kwargs.get('Nimp', 11)
コード例 #9
0
def test_Exposin():

    # Verify with example
    print("VERIFICATION")
    r1 = 1
    r2 =  5
    psi = np.pi/2
    k2 = 1/4

    # eSin = AL_Sh.shapingMethod(sun.mu / Cts.AU_m**3)
    # gammaOptim_v = eSin.start(r1, r2, psi, 365*1.5, k2) # verified
    # Ni = 1
    # print(gammaOptim_v)
    # eSin.plot_sphere(r1, r2, psi, gammaOptim_v[Ni], Ni) # verified

    # Real life case
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    mars = AL_2BP.Body('mars', 'red', mu = Cts.mu_M_m)

    # Calculate trajectory of the bodies based on ephem
    earthephem = pk.planet.jpl_lp('earth')
    marsephem = pk.planet.jpl_lp('mars')
    
    date0 = np.array([27,1,2018,0])
    t0 = AL_Eph.DateConv(date0,'calendar') #To JD
    t_t = 350

    r_E, v_E = earthephem.eph( t0.JD_0 )
    r_M, v_M = marsephem.eph(t0.JD_0+ t_t )

    r_1 = r_E 
    r_2 = r_M 
    r_1_norm = np.linalg.norm( r_1 )
    r_2_norm = np.linalg.norm( r_2 )
    
    dot = np.dot(r_1[0:2], r_2[0:2])      # dot product between [x1, y1] and [x2, y2]
    det = r_1[0]*r_2[1] - r_2[0]*r_1[1]     # determinant
    psi = np.arctan2(det, dot) 
    psi = AL_BF.convertRange(psi, 'rad', 0 ,2*np.pi)
    
    k2 = 1/12

    eSin = AL_Sh.shapingMethod(sun.mu / AL_BF.AU**3)
    gammaOptim_v = eSin.calculategamma1(r_1_norm / AL_BF.AU, r_2_norm / AL_BF.AU, psi, \
        t_t, k2, plot = False)
    
    Ni = 1
    eSin.calculateExposin(Ni, gammaOptim_v[Ni],r_1_norm / AL_BF.AU, r_2_norm / AL_BF.AU, psi )
    eSin.plot_sphere(r_1_norm / AL_BF.AU, r_2_norm / AL_BF.AU, psi)
    v1, v2 = eSin.terminalVel(r_1_norm / AL_BF.AU, r_2_norm / AL_BF.AU, psi)
    t, a_T = eSin.calculateThrustProfile(r_1_norm / AL_BF.AU, r_2_norm / AL_BF.AU, psi)
    # print('a', a_T*AL_BF.AU)


    print("body coord", v1, v2)

    # print(v1[0]*Cts.AU_m, v1[1], v2[0]*Cts.AU_m, v2[1])

    # To heliocentric coordinates (2d approximation)
    def to_helioc(r, vx, vy):
        v_body = np.array([vx, vy, 0])
        # Convert to heliocentric
        angle = np.arctan2(r[1], r[0])
        v_h = AL_BF.rot_matrix(v_body, angle, 'z')

        return v_h

    v_1 = to_helioc(r_1, v1[0]*AL_BF.AU, v1[1]*AL_BF.AU)
    v_2 = to_helioc(r_2, v2[0]*AL_BF.AU, v2[1]*AL_BF.AU) 

    # def to_helioc(r, v, gamma):
    #     v_body = np.array([v*np.sin(gamma), \
    #                        v*np.cos(gamma),\
    #                        0])

    #     # Convert to heliocentric
    #     angle = np.arctan2(r[1], r[0])
    #     v_h = AL_BF.rot_matrix(v_body, angle, 'z')

    #     return v_h
    # v_1 = to_helioc(r_1, v1[0]*Cts.AU_m, v1[1])
    # v_2 = to_helioc(r_2, v2[0]*Cts.AU_m, v2[1])
    print("Helioc vel", v_1, v_2)
    print("with respect to body ", v_1-v_E, v_2-v_M)

    v_1_E = np.linalg.norm(v_1-v_E)
    v_2_M = np.linalg.norm(v_2-v_M)

    print("Final vel", v_1_E, v_2_M)
    
    ################################################3
    # Propagate with terminal velocity vectors
    SF = CONFIG.SimsFlan_config()    
    Fit = Fitness(Nimp = SF.Nimp)

    decv = np.zeros(len(SF.bnds))
    decv[6] = t0.JD_0
    decv[7] = AL_BF.days2sec(t_t)
    decv[0:3] = AL_BF.convert3dvector(v_1-v_E,'cartesian')
    decv[3:6] = AL_BF.convert3dvector(v_2- v_M,'cartesian')

    print('decv', decv[0:9])
    
    for i in range(SF.Nimp):
        # Acceleration on segment is average of extreme accelerations
        t_i = AL_BF.days2sec(t_t) / (SF.Nimp+1) *i
        t_i1 = AL_BF.days2sec(t_t) / (SF.Nimp+1) *(i+1)

        #find acceleration at a certain time
        a_i = eSin.accelerationAtTime(t_i)
        a_i1 = eSin.accelerationAtTime(t_i1)
        
        a = (a_i+a_i1)/2 # find the acceleration at a certain time
        print("a", a_i, a_i1, a)
        deltav_i = AL_BF.days2sec(t_t) / (SF.Nimp+1) * a*AL_BF.AU
        print(deltav_i)
        decv[8+3*i] = deltav_i /100
        decv[8+3*i+1] = 0
        decv[8+3*i+2] = 0

    Fit.calculateFeasibility(decv, plot = True, thrust = 'tangential')
    Fit.printResult()
コード例 #10
0
def validateSimsFlanagan():
    SF = CONFIG.SimsFlan_config()

    # Create bodies
    sun = AL_2BP.Body('sun', 'yellow', mu = Cts.mu_S_m)
    earth = AL_2BP.Body('earth', 'blue', mu = Cts.mu_E_m)
    mars = AL_2BP.Body('mars', 'red', mu = Cts.mu_M_m)
    Spacecraft = AL_2BP.Spacecraft( )

    # Calculate trajectory of the bodies based on ephem
    earthephem = pk.planet.jpl_lp('earth')
    marsephem = pk.planet.jpl_lp('mars')

    # Create a random decision vector
    DecV = np.zeros(len(SF.bnds))
    samples_rand = 1
    np.random.seed(1)
    for decv in range(len(SF.bnds)): 
        DecV[decv] = np.random.rand(samples_rand) * (SF.bnds[decv][1]-SF.bnds[decv][0]) + SF.bnds[decv][0]
    
    DecV[8:] = np.zeros(3*SF.Nimp)

    Fit = Fitness(Nimp = 21)
    Fit.adaptDecisionVector(DecV)
    r = Fit.r_p0
    r2 = Fit.r_p1
    v = Fit.v0
    v2 = Fit.vf
    imp = Fit.DeltaV_list.flatten()
    # imp = (0,0,0,0,0,0,0,0,0,0,0,0)
    m0 = Fit.m0

    # Pykep Sims-Flanagan
    start = pk.epoch(DecV[6])
    end = pk.epoch(DecV[6] + AL_BF.sec2days(DecV[7]) )
    sc = pk.sims_flanagan.spacecraft(m0, Spacecraft.T, Spacecraft.Isp)
    
    
    x0 = pk.sims_flanagan.sc_state(r,v,sc.mass)
    xe = pk.sims_flanagan.sc_state(r2,v2,sc.mass)
    l = pk.sims_flanagan.leg(start, x0, imp, end, xe, sc,pk.MU_SUN)

    ceq = l.mismatch_constraints()
    c = l.throttles_constraints()
    times,r,v,m = l.get_states()
    r_vec = np.zeros((len(r),3))
    for i in range(len(r)):
        r_vec[i, :] = r[i]
        plt.scatter(r[i][0], r[i][1], color = 'black')
        if i == 0:
            plt.scatter(r[i][0], r[i][1], color = 'blue')
        elif i == len(r)-1:
            plt.scatter(r[i][0], r[i][1], color = 'red')
        elif i == len(r)//2+1:
            plt.scatter(r[i][0], r[i][1], color = 'orange')
        elif i == len(r)//2:
            plt.scatter(r[i][0], r[i][1], color = 'green')
    # plt.show()
    # plt.plot(r_vec[:,0], r_vec[:,1])
    plt.grid()

    print("State middle point")
    print(r[len(r)//2], v[len(r)//2])
    print(r[len(r)//2+1], v[len(r)//2+1])

    print("Mismatch middle point")
    mis_r = -(np.array(r[len(r)//2]) - np.array(r[len(r)//2+1]))
    mis_v = -(np.array(v[len(r)//2] )- np.array(v[len(r)//2+1]))
    print(mis_r, mis_v)
    mis = np.append(mis_r, mis_v)


    Fit = Fitness(Nimp = SF.Nimp)
    Fit.calculateFitness(DecV, plot=True)
    cep2 = Fit.Error
    # print(Fit.SV_0, Fit.SV_f)

    for i in range(6):
        print(i, ceq[i], '%.4E'%cep2[i], '%.4E'%mis[i])
コード例 #11
0
    def plot3D(self, SV_f, SV_b, bodies, *args, **kwargs):
        """

        """
        # Create more points for display
        points = 10
        state_f = np.zeros(((points + 1) * (self.Nimp + 1) // 2 + 1, 6))
        state_b = np.zeros(((points + 1) * (self.Nimp + 1) // 2 + 1, 6))
        t_i = self.t_t / (self.Nimp + 1) / (points + 1)

        # Change velocity backwards to propagate backwards
        for j in range((self.Nimp + 1) // 2):
            state_f[(points + 1) * j, :] = SV_f[j, :]
            state_b[(points + 1) * j, :] = SV_b[j, :]
            for i in range(points):
                trajectory = AL_2BP.BodyOrbit(state_f[(points + 1) * j + i],
                                              'Cartesian', self.sun)
                state_f[(points + 1) * j + i + 1, :] = trajectory.Propagation(
                    t_i, 'Cartesian')

                trajectory_b = AL_2BP.BodyOrbit(
                    state_b[(points + 1) * j + i, :], 'Cartesian', self.sun)
                state_b[(points + 1) * j + i +
                        1, :] = trajectory_b.Propagation(t_i, 'Cartesian')

                # trajectory_b = AL_2BP.BodyOrbit(SV_b[j,:], 'Cartesian', self.sun)
                # state_b[(points+1)*j + i+1,:] = trajectory_b.Propagation(t_i*(i+1), 'Cartesian')

        state_f[-1, :] = SV_f[-1, :]
        state_b[-1, :] = SV_b[-1, :]

        # Plot
        fig = plt.figure()
        ax = Axes3D(fig)
        # ax.view_init(azim=0, elev=10)
        # plot planets
        ax.scatter(0,
                   0,
                   0,
                   color=bodies[0].color,
                   marker='o',
                   s=180,
                   alpha=0.5)
        ax.scatter(SV_f[0, 0],
                   SV_f[0, 1],
                   SV_f[0, 2],
                   c=bodies[1].color,
                   marker='o',
                   s=150,
                   alpha=0.5)
        ax.scatter(SV_b[0, 0],
                   SV_b[0, 1],
                   SV_b[0, 2],
                   c=bodies[2].color,
                   marker='o',
                   s=150,
                   alpha=0.5)

        # xy_annot = ()
        ax.text2D(
            0.01,
            0.90,
            'Error in position: %0.2E m\nError in velocity: %0.2E m/s\nMass of fuel: %i kg'
            % (self.Epnorm, self.Evnorm, self.m_fuel),
            transform=ax.transAxes)
        # plt.annotate(, xy_annot
        plt.legend([bodies[0].name, bodies[1].name, bodies[2].name])
        # plt.legend(['Error in position: %0.2E m'%self.Epnorm_norm, 'Error in velocity: %0.2E m/s'%self.Evnorm_norm] )

        # plot points for Sims-Flanagan
        x_f = SV_f[:, 0]
        y_f = SV_f[:, 1]
        z_f = SV_f[:, 2]

        x_b = SV_b[:, 0]
        y_b = SV_b[:, 1]
        z_b = SV_b[:, 2]

        ax.scatter(x_f, y_f, z_f, '^-', c=bodies[1].color)
        ax.scatter(x_b, y_b, z_b, '^-', c=bodies[2].color)

        # ax.scatter(x_f[-1],y_f[-1],z_f[-1], '^',c = bodies[1].color)
        # ax.scatter(x_b[-1],y_b[-1],z_b[-1], '^',c = bodies[2].color)

        # ax.plot(state_f[:,0],state_f[:,1], state_f[:,2], 'x-',color = bodies[1].color)
        # ax.plot(state_b[:,0],state_b[:,1], state_b[:,2], 'x-',color = bodies[2].color)
        ax.plot(state_f[:, 0],
                state_f[:, 1],
                state_f[:, 2],
                color=bodies[1].color)
        ax.plot(state_b[:, 0],
                state_b[:, 1],
                state_b[:, 2],
                color=bodies[2].color)

        ax.set_xlabel('x (m)')
        ax.set_ylabel('y (m)')
        ax.set_zlabel('z (m)')

        # Plot settings
        AL_Plot.set_axes_equal(ax)

        dpi = kwargs.get('dpi', 200)
        layoutSave = kwargs.get('layout', 'tight')
        plt.savefig('OptSol/resultopt3D.png', dpi=dpi, bbox_inches=layoutSave)

        plt.show()
コード例 #12
0
    def DecV2inputV(self, typeinputs, newDecV=0):

        if type(newDecV) != int:
            self.adaptDecisionVector(newDecV)

        inputs = np.zeros(8)
        inputs[0] = self.t_t
        inputs[1] = self.m0

        if typeinputs == "deltakeplerian":

            # Elements of the spacecraft
            earth_elem = AL_2BP.BodyOrbit(self.SV_0, "Cartesian", self.sun)
            elem_0 = earth_elem.KeplerElem
            mars_elem = AL_2BP.BodyOrbit(self.SV_f, "Cartesian", self.sun)
            elem_f = mars_elem.KeplerElem

            K_0 = np.array(elem_0)
            K_f = np.array(elem_f)

            # Mean anomaly to true anomaly
            K_0[-1] = AL_2BP.Kepler(K_0[-1], K_0[1], 'Mean')[0]
            K_f[-1] = AL_2BP.Kepler(K_f[-1], K_f[1], 'Mean')[0]

            inputs[2:] = K_f - K_0
            inputs[2] = abs(inputs[2])  # absolute value
            inputs[3] = abs(inputs[3])  # absolute value
            inputs[4] = np.cos(inputs[4])  # cosine

            labels = [
                r'$t_t$', r'$m_0$', r'$\vert \Delta a \vert$',
                r'$\vert \Delta e \vert$', r'$cos( \Delta i) $',
                r'$ \Delta \Omega$', r'$ \Delta \omega$', r'$ \Delta \theta$'
            ]

        elif typeinputs == "deltakeplerian_planet":
            t_1 = self.t0 + AL_BF.sec2days(self.t_t)

            # Elements of the planets
            elem_0 = self.departureephem.osculating_elements(
                pk.epoch(self.t0, 'mjd2000'))
            elem_f = self.arrivalephem.osculating_elements(
                pk.epoch(t_1, 'mjd2000'))

            K_0 = np.array(elem_0)
            K_f = np.array(elem_f)

            # Mean anomaly to true anomaly
            K_0[-1] = AL_2BP.Kepler(K_0[-1], K_0[1], 'Mean')[0]
            K_f[-1] = AL_2BP.Kepler(K_f[-1], K_f[1], 'Mean')[0]

            inputs[2:] = K_f - K_0
            inputs[2] = abs(inputs[2])  # absolute value
            inputs[3] = abs(inputs[3])  # absolute value
            inputs[4] = np.cos(inputs[4])  # cosine

            labels = [
                r'$t_t$', r'$m_0$', r'$\vert \Delta a \vert$',
                r'$\vert \Delta e \vert$', r'$cos( \Delta i) $',
                r'$ \Delta \Omega$', r'$ \Delta \omega$', r'$ \Delta \theta$'
            ]

        elif typeinputs == "cartesian":
            delta_r = np.array(self.SV_f[0:3]) - np.array(self.SV_0[0:3])
            delta_v = np.array(self.SV_f[3:]) - np.array(self.SV_0[3:])
            inputs[2:5] = np.abs(delta_r)
            inputs[5:] = np.abs(delta_v)

            labels = [
                r'$t_t$', r'$m_0$', r'$\vert \Delta x \vert$',
                r'$\vert \Delta y \vert$', r'$\vert \Delta z \vert$',
                r'$\vert \Delta v_x \vert$', r'$\vert \Delta v_y \vert$',
                r'$\vert \Delta v_z \vert$'
            ]

        return inputs, labels