Example #1
0
def prop2b(x, v, dt):
    state_in = np.hstack((x, v))
    #print(state_in)
    state_out = sp.prop2b(cnst.GM, state_in, dt)
    #print(state_out)
    #     print(state_out)
    return state_out
Example #2
0
def propagate_arrows_2body(x, v, t, tp):
    """ Propagate arrows to the same time using spicepy's 2body propagation.

    Parameters:
    -----------
    x  ... array of 3D positions
    v  ... array of 3D velocities
    t  ... array of epochs for states (x,v)
    tp ... epoch to propagate state to

    Returns:
    --------
    xp ... array of propagated 3D positions
    vp ... array of propagated 3D velocities
    dt ... array of time deltas wrt the propatation epoch: tp-t
    """
    dt = np.array(tp - t)

    # Gaussian Gravitational Constant [au^1.5/Msun^0.5/D]
    gaussk = 0.01720209894846
    # default gravitational parameter [Gaussian units]
    gm = gaussk * gaussk

    if (x.ndim == 1):
        state = sp.prop2b(gm, np.hstack((x, v)), dt)
        xp = state[0:3]
        vp = state[3:6]

    elif (x.ndim == 2):
        lenx = len(x[:, 0])
        dimx = len(x[0, :])
        dimv = len(v[0, :])
        try:
            assert (dimx == dimv)
        except (TypeError):
            raise TypeError

        xp = []
        xp_add = xp.append
        vp = []
        vp_add = vp.append
        for i in range(lenx):
            state = sp.prop2b(gm, np.hstack((x[i, :], v[i, :])), dt[i])
            xp_add(state[0:3])
            vp_add(state[3:6])

    return np.array(xp), np.array(vp), dt
Example #3
0
def test_propagateUniversal():
    """
    Read the test dataset for the initial state vectors of each target at t1, then propagate
    those states to all t1 using THOR's 2-body propagator and SPICE's 2-body propagator (via spiceypy).
    Compare the resulting states and test how well they agree.
    """
    getSPICEKernels(KERNELS_DE430)
    setupSPICE(KERNELS_DE430, force=True)

    # Read vectors from test data set
    vectors_df = pd.read_csv(
        os.path.join(DATA_DIR, "vectors.csv")
    )

    # Get the target names
    targets = vectors_df["targetname"].unique()

    # Get the initial epochs
    t0 = Time(
        vectors_df["mjd_tdb"].values,
        scale="tdb",
        format="mjd"
    )

    # Set propagation epochs
    t1 = t0[0] + DT

    # Pull state vectors
    vectors = vectors_df[["x", "y", "z", "vx", "vy", "vz"]].values
    
    # Propagate initial states to each T1 using SPICE
    states_spice = []
    for i, target in enumerate(targets): 
        for dt in DT:
            states_spice.append(sp.prop2b(MU, list(vectors[i, :]), dt))
    states_spice = np.array(states_spice)
            
    # Repeat but now using THOR's universal 2-body propagator
    states_thor = propagateUniversal(
        vectors, 
        t0.tdb.mjd, 
        t1.tdb.mjd,  
        mu=MU, 
        max_iter=1000, 
        tol=1e-15
    )

    # Test 2-body propagation using THOR is
    # is within this tolerance of SPICE 2-body
    # propagation
    testOrbits(
       states_thor[:, 2:], 
       states_spice,
       orbit_type="cartesian", 
       position_tol=1*u.cm, 
       velocity_tol=(1*u.mm/u.s), 
       magnitude=True
    )
    return
Example #4
0
    def getRelPosition(self, flightTime):
        t = self.getTrajTime(flightTime)
        traj = self.getTrajectory(flightTime)

        area = traj.av * t
        absTime = self.launch + timedelta(seconds=flightTime)
        #print('t: ', self.launch+timedelta(seconds=flightTime))
        #print('tName: ', type(absTime).__name__)
        return np.array(sp.prop2b(traj.GM, traj.entranceState, t)[0:3])
Example #5
0
def test_propagateUniversal():
    """
    Query Horizons (via astroquery) for initial state vectors of each target at T0, then propagate
    those states to all T1 using THOR's 2-body propagator and SPICE's 2-body propagator (via spiceypy).
    Compare the resulting states and test how well they agree.
    """
    # Grab vectors from Horizons at initial epoch
    orbit_cartesian_horizons = getHorizonsVectors(TARGETS,
                                                  T1[:1],
                                                  location="@sun",
                                                  aberrations="geometric")
    orbit_cartesian_horizons = orbit_cartesian_horizons[[
        "x", "y", "z", "vx", "vy", "vz"
    ]].values

    # Propagate initial states to each T1 using SPICE
    states_spice = []
    for i, target in enumerate(TARGETS):
        for dt in DT:
            states_spice.append(
                sp.prop2b(MU, list(orbit_cartesian_horizons[i, :]), dt))
    states_spice = np.array(states_spice)

    # Repeat but now using THOR's universal 2-body propagator
    states_thor = propagateUniversal(orbit_cartesian_horizons,
                                     T0.tdb.mjd,
                                     T1.tdb.mjd,
                                     mu=MU,
                                     max_iter=1000,
                                     tol=1e-15)

    # Test 2-body propagation using THOR is
    # is within this tolerance of SPICE 2-body
    # propagation
    testOrbits(states_thor[:, 2:],
               states_spice,
               orbit_type="cartesian",
               position_tol=2 * u.cm,
               velocity_tol=(1 * u.mm / u.s),
               magnitude=True)
    return
Example #6
0
    def rv(self, date):
        """Position and velocity vectors.

        Parameters
        ----------
        date : string, float, astropy Time, or datetime
          Processed via `util.date2time`.

        Returns
        -------
        r : ndarray
          Position vector. [km]
        v : ndarray
          Velocity vector. [km/s]

        """
        from .. import util
        jd = util.date2time(date).jd
        dt = (jd - self.jd) * 86400.0
        rv = np.array(spice.prop2b(self.GM, self.rv_i, dt))
        return rv[:3], rv[3:]
Example #7
0
def wait(pivot, state, deltaT):
    GM = pivot.Gmass[0]
    return sp.prop2b(GM, state, deltaT)
Example #8
0
    np.deg2rad(0),
    np.deg2rad(0),
    np.deg2rad(0), 0, cn.mu
])
states0 = sp.conics(elm0, 0)
sma = sma + 100
rp = sma * (1 - ecc)
elm1 = np.array([
    rp, ecc,
    np.deg2rad(10),
    np.deg2rad(0),
    np.deg2rad(0),
    np.deg2rad(0), 0, cn.mu
])
states1 = sp.conics(elm1, 0)
statesf = sp.prop2b(cn.mu, states1, tspan[-1])

# Method of Particular Solutions Shooting Method
[v0, mps_err] = mps_twobody(tspan, states0, statesf)
print("mps err:", mps_err)
states0_new = np.zeros(6)
states0_new[0:3] = states0[0:3]
states0_new[3:6] = v0[0:3]

# Scipy's Optimize
v0_guess = states0[3:6]
optres = minimize(residuals,
                  v0_guess[0:3],
                  args=(tspan, states0, statesf),
                  method='Nelder-Mead',
                  tol=1e-13)
Example #9
0
def propagate2body(x, v, t, tp, n_jobs):
    """ Propagate states to the same time using spicepy's 2body propagation.

    Parameters:
    -----------
    x            ... array of 3D heliocentric/barycentric positions
    v            ... array of 3D heliocentric/barycentric velocities
    t            ... array of epochs for states (x,v)
    tp           ... epoch to propagate state to
    n_jobs       ... number of worker processes for 2body propagation

    Returns:
    --------
    xp           ... array of propagated 3D positions
    vp           ... array of propagated 3D velocities
    dt           ... array of time deltas wrt the propatation epoch: tp-t
    """

    dt = np.array(tp - t)

    #     print('x.ndim',x.ndim)
    #     print('x.shape',x.shape)
    #     print('x',x)
    #     print('v',v)

    if (len(x) < 1):
        # empty
        xp = []
        vp = []

    elif (x.ndim == 1):
        state = sp.prop2b(cnst.GM, np.hstack((x, v)), dt)
        xp = state[0:3]
        vp = state[3:6]

    elif (x.ndim == 2):
        lenx = len(x[:, 0])
        #state = np.zeros((lenx,6))
        if (n_jobs > 1):
            #print('n_jobs:',n_jobs)
            #batchsize=np.rint(lenx/(n_jobs)/20).astype(int)
            #batchsize=10000*n_jobs
            #print('batch_size:', batchsize, ' of ', lenx)

            #             results = Parallel(n_jobs=n_jobs,
            #                                batch_size=batchsize,
            #                                pre_dispatch='2*n_jobs'
            #                                )(delayed(prop2b)(x[i,:],v[i,:],dt[i])
            #                                for i in range(lenx))

            results = Parallel(n_jobs=n_jobs,
                               batch_size='auto',
                               pre_dispatch='2*n_jobs')(
                                   delayed(prop2b)(x[i, :], v[i, :], dt[i])
                                   for i in range(lenx))
            state = np.array(results)
            #print('state',state)
        else:
            state = np.zeros((lenx, 6))
            for i in range(lenx):
                state[i, :] = sp.prop2b(cnst.GM, np.hstack((x[i, :], v[i, :])),
                                        dt[i])[0:6]

        #print('state', state)
        xp = state[:, 0:3]
        vp = state[:, 3:6]
    else:
        raise TypeError

    return xp, vp, dt
Example #10
0
def swingby(Rsoi, s0, GM, step=1e4):
    sf = s0[:]
    while np.linalg.norm(sf[:3]) / Rsoi < 1.001:  #need a failsafe
        sf = sp.prop2b(GM, sf, step)
    return sf