Exemple #1
0
def gen_pop():

    mass=0.8111E+04
    diam=0.8960E+01
    m_to_A=128.651
    a=7159.5
    e=0.0001
    i=98.55
    raan=248.99
    aop=90.72
    M=47.37
    A=mass/m_to_A
    # epoch in unix seconds
    ut0=1241136000.0
    # modified julian day epoch
    mjd0 = dpt.jd_to_mjd(dpt.unix_to_jd(ut0))

    print('\n' + 'mjd0: {}'.format(mjd0) + '\n')

    _params = ['A', 'm', 'd', 'C_D', 'C_R']

    pop = Population(
        name='ENVISAT',
        extra_columns = _params,
        space_object_uses = [True]*len(_params),
        #propagator = PropagatorNeptune,
        propagator = PropagatorSGP4,
        propagator_options = {
            'out_frame': 'ITRF'
        },
    )

    pop.allocate(1)

    pop['oid'][0] = 1
    pop['a'][0] = a
    pop['e'][0] = e
    pop['i'][0] = i
    pop['raan'][0] = raan
    pop['aop'][0] = aop
    pop['mu0'][0] = M
    pop['mjd0'][0] = mjd0
    pop['A'][0] = A
    pop['m'][0] = mass
    pop['d'][0] = 1.0
    pop['C_D'][0] = 2.3
    pop['C_R'][0] = 1.0

    return pop
Exemple #2
0
# ----------------

n_closest = 5

loc_ecef = radar._tx[0].ecef.copy()
loc_ecef_norm = loc_ecef / n.linalg.norm(loc_ecef)

all_sat_ids = set([tle.tle_id(line1) for line1, line2 in TLEs])

for det_ID, data_dict in dets_data:

    t = data_dict['t']
    r = data_dict['r']
    v = data_dict['v']

    jd_check = dpt.unix_to_jd(t)

    r_ref = n.empty(r.shape, dtype=r.dtype)
    v_ref = n.empty(v.shape, dtype=v.dtype)

    correlation_data = {}
    #residulas = n.empty((4,1), dtype=n.float)

    t0 = time.time()

    jd_det = jd_check[0]

    PM_data = tle.get_Polar_Motion(jd_check)

    for sat_index, check_sat in enumerate(all_sat_ids):
Exemple #3
0
def test_envisat():
    import space_object as so

    mass = 0.8111E+04
    diam = 0.8960E+01
    m_to_A = 128.651
    a = 7159.5
    e = 0.0001
    i = 98.55
    raan = 248.99
    aop = 90.72
    M = 47.37
    A = mass / m_to_A
    # epoch in unix seconds
    ut0 = 1241136000.0
    # modified julian day epoch
    mjd0 = dpt.jd_to_mjd(dpt.unix_to_jd(ut0))

    print(mjd0)
    o = so.SpaceObject(
        a=a,
        e=e,
        i=i,
        raan=raan,
        aop=aop,
        mu0=M,
        C_D=2.3,
        A=A,
        m=mass,
        diam=diam,
        mjd0=mjd0,
        #propagator = PropagatorNeptune,
        propagator=PropagatorSGP4,
        propagator_options={'out_frame': 'ITRF'},
    )

    e3d = rlib.eiscat_3d()
    print("EISCAT Skibotn location x,y,z ECEF (meters)")
    print(e3d._tx[0].ecef)
    ski_ecef = e3d._tx[0].ecef

    print("EISCAT Skibotn location %1.3f %1.3f %1.3f (lat,lon,alt)" %
          (e3d._tx[0].lat, e3d._tx[0].lon, 0.0))

    t_obs = np.linspace(4440, 5280, num=100) + 31.974890
    t_obs2 = np.linspace(4440, 5280, num=100) + 31.974890 + 1.0

    print("MJD %1.10f %sZ" % (mjd0 + t_obs[0] / 3600.0 / 24.0,
                              ccsds_write.unix2datestr(ut0 + t_obs[0])))
    ecef = o.get_state(t_obs)
    ecef2 = o.get_state(t_obs2)

    print("ECEF state x,y,z,vx,vy,vz  (km and km/s)")
    print(ecef[:, 0] / 1e3)

    print(
        "Time (UTC)          Range (km)  Vel (km/s)  ECEF X (km) ECEF Y (km) ECEF Z (km)"
    )
    for i in range(len(t_obs)):
        dist = np.linalg.norm(ecef[0:3, i] - ski_ecef)
        dist2 = np.linalg.norm(ecef2[0:3, i] - ski_ecef)

        vel = (dist2 - dist) / 1.0
        print("%s   %1.3f %1.3f %1.3f %1.3f %1.3f" %
              (ccsds_write.unix2datestr(ut0 + t_obs[i]), dist / 1e3, vel / 1e3,
               ecef[0, i] / 1e3, ecef[1, i] / 1e3, ecef[2, i] / 1e3))
Exemple #4
0
props = [
    p_sgp4,
    p_nept,
    p_orekit,
]

prop_dat = [
    ('-b', 'SGP4'),
    ('-g', 'NEPTUNE'),
    ('-k', 'Orekit'),
]

ut0 = 1241136000.0

# modified Julian day epoch
mjd0 = dpt.jd_to_mjd(dpt.unix_to_jd(ut0))
R_e = 6371.0
m_to_A = 128.651
mass = 0.8111E+04

init_data = {
    'a': 7159.5 * 1e3,
    'e': 0.0001,
    'inc': 98.55,
    'raan': 248.99,
    'aop': 90.72,
    'mu0': 47.37,
    'mjd0': mjd0,
    'C_D': 2.3,
    'C_R': 1.0,
    'm': mass,
Exemple #5
0
def correlate(data, station, population, metric, n_closest = 1, out_file = None, verbose=False, MPI_on=False):
    '''Given a mono-static measurement of ranges and rage-rates, a radar model and a population: correlate measurements with population.

    :param dict data: Dictionary that contains measurement data. Contents are described below.
    :param AntennaRX station: Model of receiver station that performed the measurement.
    :param Population population: Population to correlate against.
    :param function metric: Metric used to correlate measurement and simulation of population.
    :param int n_closest: Number of closest matches to output.
    :param str out_file: If not :code:`None`, save the output data to this path.
    :param bool MPI_on: If True use internal parallelization with MPI to calculate correlation. Turn to False to externally parallelize with MPI.
    

    **Measurement data:**

      The file must be a dictionary that contains three data-sets:
        * 't': Times in unix-seconds
        * 'r': Ranges in meters
        * 'v': Range-rates in meters per second
      They should all be numpy vectors of equal length.

    '''

    
    r = data['r']
    t = data['t']
    v = data['v']

    t_sort = t.argsort()
    t = t[t_sort]
    r = r[t_sort]
    v = v[t_sort]
    
    #lt correction
    lt_correction = r/scipy.constants.c
    t += lt_correction

    _day = 3600.0*24.0

    loc_ecef = station.ecef.copy()
    loc_ecef_norm = loc_ecef/n.linalg.norm(loc_ecef)

    jd_check = dpt.unix_to_jd(t)

    r_ref = n.empty(r.shape, dtype=r.dtype)
    v_ref = n.empty(v.shape, dtype=v.dtype)

    correlation_data = {}
    SO_generator = population.object_generator()

    if MPI_on:
        step = MPI.COMM_WORLD.size
        next_check = MPI.COMM_WORLD.rank
    else:
        step = 1
        next_check = 0

    for ind, obj in enumerate(SO_generator):
        if ind == next_check:
            if verbose:
                print('\n\nPID {} correlating {}/{} -------'.format(MPI.COMM_WORLD.rank, ind+1, len(population)))
                print(obj)
            
            jd_obj = dpt.mjd_to_jd(obj.mjd0)
            
            t_check = (jd_check - jd_obj)*_day
            states = obj.get_state(t_check)

            for jdi in range(jd_check.size):
                r_tmp = loc_ecef - states[:3,jdi]

                r_ref[jdi] = n.linalg.norm(r_tmp)
                v_ref[jdi] = n.dot(
                    states[3:,jdi],
                    r_tmp/r_ref[jdi],
                )

            residual_r_mu = n.mean(r_ref - r)
            residual_r_std = n.std(r_ref - r)
            residual_v_mu = n.mean(v_ref - v)
            residual_v_std = n.std(v_ref - v)
            if len(v_ref) > 1:
                residual_a = ((v_ref[-1] - v_ref[0]) - v[-1] - v[0])/(t[-1] - t[0])
            else:
                residual_a = 0

            if verbose:
                print('Residuals:')
                print('residual_r_mu  = {} m'.format(residual_r_mu))
                print('residual_r_std = {} m'.format(residual_r_std))
                print('residual_v_mu  = {} m/s'.format(residual_v_mu))
                print('residual_v_std = {} m/s'.format(residual_v_std))
                print('residual_a     = {} m/s^2'.format(residual_a))
            
            cdat = {
                    'r_ref': r_ref.copy(),
                    'v_ref': v_ref.copy(),
                    'sat_id': obj.oid,
                    'stat': [residual_r_mu, residual_r_std, residual_v_mu, residual_v_std, residual_a]
                }
            if obj.oid in correlation_data:
                correlation_data[obj.oid].append(cdat)
            else:
                correlation_data[obj.oid] = [cdat]

            next_check += step

    oids = population['oid']

    if step > 1:

        if MPI.COMM_WORLD.rank == 0:
            if verbose:
                print('---> PID %i: Receiving all results <barrier>'%(MPI.COMM_WORLD.rank))

            for T in range(1,MPI.COMM_WORLD.size):
                for ID in range(T,len(population),MPI.COMM_WORLD.size):
                    oid = oids[ID]
                    correlation_data[oid] = MPI.COMM_WORLD.recv(source=T, tag=oid)
                    if verbose:
                        print('PID{} recived packet {} from PID{} '.format(MPI.COMM_WORLD.rank, oid, T))
        else:
            if verbose:
                print('---> PID %i: Distributing all correlation results to process 0 <barrier>'%(MPI.COMM_WORLD.rank))

            for ID in range(MPI.COMM_WORLD.rank,len(population),MPI.COMM_WORLD.size):
                oid = oids[ID]
                MPI.COMM_WORLD.send(correlation_data[oid], dest=0, tag=oid)
        
        if verbose:
            print('---> Distributing done </barrier>')

    matches_cdat = []

    if MPI.COMM_WORLD.rank == 0 or not MPI_on:
        if verbose:
            print('Finding best matches.')
        
        match_metric = n.empty((len(correlation_data), 2), dtype = n.float64)
        key_list = []
        key_cnt = 0
        for key, cdats in correlation_data.items():
            key_list.append(key)
            tmp_metrics = n.empty((len(cdats),), dtype=n.float64)
            for cind, cdat in enumerate(cdats):
                tmp_metrics[cind] = metric(t, r, v, cdat['r_ref'], cdat['v_ref'])
            tmp_match = n.argmin(tmp_metrics)

            match_metric[key_cnt, 0] = tmp_metrics[tmp_match]
            match_metric[key_cnt, 1] = tmp_match
            if verbose:
                print('{}: {} metric'.format(key, match_metric[key_cnt]))
            key_cnt += 1


        match = n.argmin(match_metric[:,0])
        

        if len(match_metric) > n_closest:
            all_match = n.argpartition(match_metric[:,0], n_closest)
        else:
            all_match = list(range(len(correlation_data)))

        if verbose:
            print('Best match {}:{} at {} match metric'.format(
                key_list[match],
                int(match_metric[match,1]),
                match_metric[match,0],
            ))
        cdat = correlation_data[key_list[match]][int(match_metric[match,1])]

        r_ref = cdat['r_ref']
        v_ref = cdat['v_ref']

        if out_file is not None:

            with h5py.File(out_file, 'w') as h_corr:
                for key, cdat in correlation_data.items():
                    for dat_key, dat in cdat.items():
                        h_corr[key+'/'+dat_key] = n.array(dat)

                h_corr.attrs['sat_match'] = key_list[match]
                h_corr['residuals'] = n.array(cdat['stat'])

        if len(match_metric) > n_closest:
            for may_match in all_match[:n_closest]:
                matches_cdat.append(correlation_data[key_list[may_match]][int(match_metric[may_match,1])])
        else:
            for may_match in all_match:
                matches_cdat.append(correlation_data[key_list[may_match]][int(match_metric[may_match,1])])
    if step > 1:
        matches_cdat = MPI.COMM_WORLD.bcast(matches_cdat, root=0)

    return matches_cdat
Exemple #6
0
)
radar.set_scan(scan)

sims = []

data_file = './data/microsatR_uhf.h5'

with h5py.File(data_file, 'r') as hf:
    t_obs = hf['t'].value
    r_obs = hf['r'].value
    v_obs = hf['v'].value

dt = np.datetime64('2019-04-02T12:01')
mjd = dpt.npdt2mjd(dt)

t_obs = (dpt.jd_to_mjd(dpt.unix_to_jd(t_obs)) -
         mjd) * 3600.0 * 24.0 + 2.0 * 3600.0  #maybe not gmt
t_sort = np.argsort(t_obs)
t_obs = t_obs[t_sort]
r_obs = r_obs[t_sort]
v_obs = v_obs[t_sort]

t_select = t_obs < 24.0 * 3600.0

t_obs = t_obs[t_select]
r_obs = r_obs[t_select]
v_obs = v_obs[t_select]

for branch_name in branch_names:

    fname = sim_root + '/{}_population.h5'.format(branch_name)
Exemple #7
0
    sim.run_scheduler()

    sim.status(fout='{}h_to_{}h_scheduler'.format(0, int(SIM_TIME)))

if part == 3:
    sim.set_version(branch_name)
    sim.load()

    data_file = './data/microsatR_uhf.h5'

    with h5py.File(data_file, 'r') as hf:
        t_obs = hf['t'].value
        r_obs = hf['r'].value
        v_obs = hf['v'].value

    t_obs = (dpt.jd_to_mjd(dpt.unix_to_jd(t_obs)) - mjd)*3600.0*24.0 + 2.0*3600.0 #maybe not gmt
    t_sort = np.argsort(t_obs)
    t_obs = t_obs[t_sort]
    r_obs = r_obs[t_sort]
    v_obs = v_obs[t_sort]

    t_select = t_obs < SIM_TIME*3600.0

    t_obs = t_obs[t_select]
    r_obs = r_obs[t_select]
    v_obs = v_obs[t_select]

    #create RV_T plots, 

    fig, axs = plt.subplots(2,1,figsize=(12,8),dpi=80)
    axs[0].hist(sim.population['m'])
Exemple #8
0
def test_OD(root, sub_path):

    import orbit_determination
    import TLE_tools as tle
    import dpt_tools as dpt
    import radar_library as rlib
    import propagator_sgp4
    #import propagator_orekit
    #import propagator_neptune
    import ccsds_write

    radar = rlib.eiscat_3d(beam='interp', stage=1)

    radar.set_FOV(max_on_axis=90.0, horizon_elevation=10.0)
    radar.set_SNR_limits(min_total_SNRdb=10.0, min_pair_SNRdb=1.0)
    radar.set_TX_bandwith(bw = 1.0e6)
    
    #prop = propagator_neptune.PropagatorNeptune()
    prop = propagator_sgp4.PropagatorSGP4()

    mass=0.8111E+04
    diam=0.8960E+01
    m_to_A=128.651

    params = dict(
        A = {
            'dist': None,
            'val': mass/m_to_A,
        },
        d = {
            'dist': None,
            'val': diam,
        },
        m = {
            'dist': None,
            'val': mass,
        },
        C_D = {
            'dist': None,
            'val': 2.3,
        },
    )

    fname = glob.glob(root + sub_path + '*.oem')[0]
    prior_data, prior_meta = ccsds_write.read_oem(fname)
    prior_sort = np.argsort(prior_data['date'])
    prior_data = prior_data[prior_sort][0]

    prior_mjd = dpt.npdt2mjd(prior_data['date'])
    prior_jd = dpt.mjd_to_jd(prior_mjd)

    state0 = np.empty((6,), dtype=np.float64)
    state0[0] = prior_data['x']
    state0[1] = prior_data['y']
    state0[2] = prior_data['z']
    state0[3] = prior_data['vx']
    state0[4] = prior_data['vy']
    state0[5] = prior_data['vz']
    
    #state0_ITRF = state0.copy()
    state0 = tle.ITRF_to_TEME(state0, prior_jd, 0.0, 0.0)
    #state0_TEME = state0.copy()
    
    #state0_ITRF_ref = tle.TEME_to_ITRF(state0_TEME, prior_jd, 0.0, 0.0)
    
    #print(state0_ITRF_ref - state0_ITRF)
    #exit()
    
    data_folder = root + sub_path
    
    data_h5 = glob.glob(data_folder + '*.h5')
    
    data_h5_sort = np.argsort(np.array([int(_h.split('/')[-1].split('-')[1]) for _h in data_h5])).tolist()
    
    true_prior_h5 = data_h5[data_h5_sort[0]]
    true_obs_h5 = data_h5[data_h5_sort[1]]
    
    print(true_prior_h5)
    print(true_obs_h5)
    
    with h5py.File(true_prior_h5, 'r') as hf:
        true_prior = hf['true_state'].value.T*1e3
        true_prior_jd = dpt.unix_to_jd(hf['true_time'].value)
    
    print('-- True time diff prior [s] --')
    prior_match_ind = np.argmin(np.abs(true_prior_jd-prior_jd))
    jd_diff = prior_jd - true_prior_jd[prior_match_ind]
    state0_true = true_prior[:,prior_match_ind]
    state0_true = tle.ITRF_to_TEME(state0_true, true_prior_jd[prior_match_ind], 0.0, 0.0)
    
    print(prior_match_ind)
    print(jd_diff*3600.0*24.0)

    with h5py.File(true_obs_h5, 'r') as hf:
        true_obs = hf['true_state'].value.T*1e3
        true_obs_jd = dpt.unix_to_jd(hf['true_time'].value)

    data_tdm = glob.glob(data_folder + '*.tdm')
    #this next line i wtf, maybe clean up
    data_tdm_sort = np.argsort(np.array([int(_h.split('/')[-1].split('-')[-1][2]) for _h in data_tdm])).tolist()
    
    ccsds_files = [data_tdm[_tdm] for _tdm in data_tdm_sort]
    
    print('prior true vs prior mean')
    print(state0_true - state0)
    
    for _fh in ccsds_files:
        print(_fh)
    
    r_obs_v = []
    r_sig_v = []
    v_obs_v = []
    v_sig_v = []
    t_obs_v = []

    for ccsds_file in ccsds_files:
        obs_data = ccsds_write.read_ccsds(ccsds_file)
        sort_obs = np.argsort(obs_data['date'])
        obs_data = obs_data[sort_obs]
        jd_obs = dpt.mjd_to_jd(dpt.npdt2mjd(obs_data['date']))

        date_obs = obs_data['date']
        sort_obs = np.argsort(date_obs)
        date_obs = date_obs[sort_obs]
        r_obs = obs_data['range'][sort_obs]*1e3 #to m
        v_obs = -obs_data['doppler_instantaneous'][sort_obs]*1e3 #to m/s
        #v_obs = obs_data['doppler_instantaneous'][sort_obs]*1e3 #to m/s
        r_sig = 2.0*obs_data['range_err'][sort_obs]*1e3 #to m
        v_sig = 2.0*obs_data['doppler_instantaneous_err'][sort_obs]*1e3 #to m/s

        #TRUNCATE FOR DEBUG
        inds = np.linspace(0,len(jd_obs)-1,num=10,dtype=np.int64)
        jd_obs = jd_obs[inds]
        r_obs = r_obs[inds]
        v_obs = v_obs[inds]
        r_sig = r_sig[inds]
        v_sig = v_sig[inds]

        if ccsds_file.split('/')[-1].split('.')[0] == true_obs_h5.split('/')[-1].split('.')[0]:
            print('-- True time diff obs [s] --')
            jd_diff = jd_obs - true_obs_jd[inds]
            print(jd_diff*3600.0*24.0)

        #r_sig = np.full(r_obs.shape, 100.0, dtype=r_obs.dtype)
        #v_sig = np.full(v_obs.shape, 10.0, dtype=v_obs.dtype)
        
        r_obs_v.append(r_obs)
        r_sig_v.append(r_sig)
        v_obs_v.append(v_obs)
        v_sig_v.append(v_sig)

        t_obs = (jd_obs - prior_jd)*(3600.0*24.0)

        #correct for light time approximently
        lt_correction = r_obs*0.5/scipy.constants.c
        t_obs -= lt_correction

        t_obs_v.append(t_obs)


    print('='*10 + 'Dates' + '='*10)
    print('{:<8}: {} JD'.format('Prior', prior_jd))
    for ind, _jd in enumerate(jd_obs):
        print('Obs {:<4}: {} JD'.format(ind, _jd))
    

    print('='*10 + 'Observations' + '='*10)
    print(len(jd_obs))
    
    prior = {}
    prior['cov'] = np.diag([1e3, 1e3, 1e3, 1e1, 1e1, 1e1])*1.0
    prior['mu'] = state0
    
    print('='*10 + 'Prior Mean' + '='*10)
    print(prior['mu'])

    print('='*10 + 'Prior Covariance' + '='*10)
    print(prior['cov'])
    
    rx_ecef = []
    for rx in radar._rx:
        rx_ecef.append(rx.ecef)
    tx_ecef = radar._tx[0].ecef
    tune = 0

    trace = orbit_determination.determine_orbit(
        num = 2000,
        r = r_obs_v,
        sd_r = r_sig_v,
        v = v_obs_v,
        sd_v = v_sig_v,
        grad_dx = [10.0]*3 + [1.0]*3,
        rx_ecef = rx_ecef,
        tx_ecef = tx_ecef,
        t = t_obs_v,
        mjd0 = prior_mjd,
        params = params,
        prior = prior,
        propagator = prop,
        step = 'Metropolis',
        step_opts = {
            'scaling': 0.75,
        },
        pymc_opts = {
            'tune': tune,
            'discard_tuned_samples': True,
            'cores': 1,
            'chains': 1,
            'parallelize': True,
        },
    )
    
    #if comm.rank != 0:
    #    exit()

    var = ['$X$ [km]', '$Y$ [km]', '$Z$ [km]', '$V_X$ [km/s]', '$V_Y$ [km/s]', '$V_Z$ [km/s]']

    fig = plt.figure(figsize=(15,15))

    for ind in range(6):
        ax = fig.add_subplot(231+ind)
        ax.plot(trace['state'][:,ind]*1e-3)
        ax.set(
            xlabel='Iteration',
            ylabel='{}'.format(var[ind]),
        )


    state1 = np.mean(trace['state'], axis=0)

    print('='*10 + 'Trace summary' + '='*10)
    print(pm.summary(trace))

    _form = '{:<10}: {}'

    print('='*10 + 'Prior Mean' + '='*10)
    for ind in range(6):
        print(_form.format(var[ind], state0[ind]*1e-3))

    print('='*10 + 'Posterior state mean' + '='*10)
    for ind in range(6):
        print(_form.format(var[ind], state1[ind]*1e-3))
    
    stated = state1 - state0

    print('='*10 + 'State shift' + '='*10)
    for ind in range(6):
        print(_form.format(var[ind], stated[ind]*1e-3))

    print('='*10 + 'True posterior' + '='*10)
    for ind in range(6):
        print(_form.format(var[ind], state0_true[ind]*1e-3))
    
    print('='*10 + 'Posterior error' + '='*10)
    for ind in range(6):
        print(_form.format(var[ind],(state1[ind] - state0_true[ind])*1e-3))
    
    print('='*10 + 'Parameter shift' + '='*10)
    theta0 = {}
    theta1 = {}
    for key, val in params.items():
        if val['dist'] is not None:
            theta0[key] = val['mu']
            theta1[key] = np.mean(trace[key], axis=0)[0]
            print('{}: {}'.format(key, theta1[key] - theta0[key]))
        else:
            theta0[key] = val['val']
            theta1[key] = val['val']


    range_v_prior = []
    vel_v_prior = []
    range_v = []
    vel_v = []
    range_v_true = []
    vel_v_true = []

    for rxi in range(len(rx_ecef)):
        t_obs = t_obs_v[rxi]
        print('Generating tracklet simulated data RX {}: {} points'.format(rxi, len(t_obs)))

        states0 = orbit_determination.propagate_state(state0, t_obs, dpt.jd_to_mjd(prior_jd), prop, theta0)
        states1 = orbit_determination.propagate_state(state1, t_obs, dpt.jd_to_mjd(prior_jd), prop, theta1)
        states0_true = orbit_determination.propagate_state(state0_true, t_obs, dpt.jd_to_mjd(prior_jd), prop, theta1)

        range_v_prior += [np.empty((len(t_obs), ), dtype=np.float64)]
        vel_v_prior += [np.empty((len(t_obs), ), dtype=np.float64)]
    
        range_v += [np.empty((len(t_obs), ), dtype=np.float64)]
        vel_v += [np.empty((len(t_obs), ), dtype=np.float64)]
    
        range_v_true += [np.empty((len(t_obs), ), dtype=np.float64)]
        vel_v_true += [np.empty((len(t_obs), ), dtype=np.float64)]

        for ind in range(len(t_obs)):
            range_v_prior[rxi][ind], vel_v_prior[rxi][ind] = orbit_determination.generate_measurements(states0[:,ind], rx_ecef[rxi], tx_ecef)
            range_v[rxi][ind], vel_v[rxi][ind] = orbit_determination.generate_measurements(states1[:,ind], rx_ecef[rxi], tx_ecef)
            range_v_true[rxi][ind], vel_v_true[rxi][ind] = orbit_determination.generate_measurements(states0_true[:, ind], rx_ecef[rxi], tx_ecef)


    prop_states = orbit_determination.propagate_state(
        state0,
        np.linspace(0, (np.max(jd_obs) - prior_jd)*(3600.0*24.0), num=1000),
        dpt.jd_to_mjd(prior_jd),
        prop,
        theta1,
    )
    
    '''
    pop = gen_pop()
    obj = pop.get_object(0)
    
    t_obs_pop = t_obs + (dpt.jd_to_mjd(prior_jd) - obj.mjd0)*3600.0*24.0
    states0_true2 = obj.get_state(t_obs_pop)
    
    print(states0_true2)
    print(states0_true2 - states0_true)
    '''
    fig = plt.figure(figsize=(15,15))
    ax = fig.add_subplot(111, projection='3d')
    plothelp.draw_earth_grid(ax)
    for ind, ecef in enumerate(rx_ecef):
        if ind == 0:
            ax.plot([ecef[0]], [ecef[1]], [ecef[2]], 'or', label='EISCAT 3D RX')
        else:
            ax.plot([ecef[0]], [ecef[1]], [ecef[2]], 'or')

    ax.plot(states0[0,:], states0[1,:], states0[2,:], 'xb', label = 'Prior', alpha = 0.75)
    ax.plot(states1[0,:], states1[1,:], states1[2,:], 'xr', label = 'Posterior', alpha = 0.75)
    ax.plot(prop_states[0,:], prop_states[1,:], prop_states[2,:], '-k', label = 'Prior-propagation', alpha = 0.5)
    ax.plot(true_prior[0,:], true_prior[1,:], true_prior[2,:], '-b', label = 'Prior-True', alpha = 0.75)
    ax.plot(true_obs[0,:], true_obs[1,:], true_obs[2,:], '-r', label = 'Posterior-True', alpha = 0.75)
    
    ax.legend()

    for rxi in range(len(rx_ecef)):

        fig = plt.figure(figsize=(15,15))
    
        t_obs_h = t_obs_v[rxi]/3600.0
        
        ax = fig.add_subplot(221)
        lns = []
        line1 = ax.plot(t_obs_h, (r_obs_v[rxi] - range_v[rxi])*1e-3, '-b', label='Maximum a posteriori: RX{}'.format(rxi))
        line0 = ax.plot(t_obs_h, (r_obs_v[rxi] - range_v_true[rxi])*1e-3, '.b', label='True prior: RX{}'.format(rxi))
        ax.set(
            xlabel='Time [h]',
            ylabel='2-way-Range residuals [km]',
        )
        ax2 = ax.twinx()
        line2 = ax2.plot(t_obs_h, (r_obs_v[rxi] - range_v_prior[rxi])*1e-3, '-k', label='Maximum a priori: RX{}'.format(rxi))
        ax.tick_params(axis='y', labelcolor='b')
        ax2.tick_params(axis='y', labelcolor='k')
    
        lns += line0+line1+line2
        labs = [l.get_label() for l in lns]
        ax.legend(lns, labs, loc=0)
    
        ax = fig.add_subplot(222)
        lns = []
        line1 = ax.plot(t_obs_h, (v_obs_v[rxi] - vel_v[rxi])*1e-3, '-b', label='Maximum a posteriori: RX{}'.format(rxi))
        line0 = ax.plot(t_obs_h, (v_obs_v[rxi] - vel_v_true[rxi])*1e-3, '.b', label='True prior: RX{}'.format(rxi))
        ax.set(
            xlabel='Time [h]',
            ylabel='2-way-Velocity residuals [km/s]',
        )
        ax2 = ax.twinx()
        line2 = ax2.plot(t_obs_h, (v_obs_v[rxi] - vel_v_prior[rxi])*1e-3, '-k', label='Maximum a priori: RX{}'.format(rxi))
        ax.tick_params(axis='y', labelcolor='b')
        ax2.tick_params(axis='y', labelcolor='k')
        
        lns += line0+line1+line2
        labs = [l.get_label() for l in lns]
        ax.legend(lns, labs, loc=0)

        ax = fig.add_subplot(223)
        ax.errorbar(t_obs_h, r_obs_v[rxi]*1e-3, yerr=r_sig_v[rxi]*1e-3, label='Measurements: RX{}'.format(rxi))
        ax.plot(t_obs_h, range_v[rxi]*1e-3, label='Maximum a posteriori: RX{}'.format(rxi))
        ax.plot(t_obs_h, range_v_prior[rxi]*1e-3, label='Maximum a priori: RX{}'.format(rxi))
        ax.set(
            xlabel='Time [h]',
            ylabel='2-way-Range [km]',
        )
        ax.legend()
        
        ax = fig.add_subplot(224)
        ax.errorbar(t_obs_h, v_obs_v[rxi]*1e-3, yerr=v_sig_v[rxi]*1e-3, label='Measurements: RX{}'.format(rxi))
        ax.plot(t_obs_h, vel_v[rxi]*1e-3, label='Maximum a posteriori: RX{}'.format(rxi))
        ax.plot(t_obs_h, vel_v_prior[rxi]*1e-3, label='Maximum a priori: RX{}'.format(rxi))
        ax.set(
            xlabel='Time [h]',
            ylabel='2-way-Velocity [km/s]',
        )
        ax.legend()
    
    #dpt.posterior(trace['state']*1e-3, var, show=False)
    plt.show()
Exemple #9
0
import numpy as np
import matplotlib.pyplot as plt

import dpt_tools as dpt
import TLE_tools as tle
import propagator_sgp4

prop = propagator_sgp4.PropagatorSGP4(
    polar_motion=False,
    out_frame='ITRF',
)

ut0 = 1241136000.0

# modified Julian day epoch
jd0 = dpt.unix_to_jd(ut0)
mjd0 = dpt.jd_to_mjd(jd0)
R_e = 6371.0
m_to_A = 128.651
mass = 0.8111E+04

init_data = {
    'a': 7159.5 * 1e3,
    'e': 0.0001,
    'inc': 98.55,
    'raan': 248.99,
    'aop': 90.72,
    'mu0': 47.37,
    'mjd0': mjd0,
    'C_D': 2.3,
    'C_R': 1.0,