def tryPolarOrbit(): _prop = propagator_orekit.PropagatorOrekit _opts = { 'in_frame': 'TEME', 'out_frame': 'ITRF', 'solar_activity_strength': 'WEAK', } prop = _prop(**_opts) init_data = { 'a': (R_e + 400.0) * 1e3, 'e': 0.01, 'inc': 90.0, 'raan': 10, 'aop': 10, 'mu0': 40.0, 'mjd0': 54832.0, 'C_D': 2.3, 'C_R': 1.0, 'm': 3.0, 'A': np.pi * (0.1)**2, } t = np.linspace(0, 48 * 3600.0, num=5000, dtype=np.float) ecefs = prop.get_orbit(t, **init_data) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecefs[0, :], ecefs[1, :], ecefs[2, :], ".", color="green") return fig, ax
def try2(): p = PropagatorRebound( in_frame='EME', out_frame='ITRF', ) init_data = { 'a': (R_e + 400.0) * 1e3, 'e': 0.01, 'inc': 90.0, 'raan': 10, 'aop': 10, 'mu0': 40.0, 'mjd0': 54832.0, 'C_D': 2.3, 'C_R': 1.0, 'm': 3.0, 'A': np.pi * (2.0 * 0.5)**2, } t = np.linspace(0, 1.0 * 24 * 3600.0, num=1000, dtype=np.float) ecefs1 = p.get_orbit(t, **init_data) max_range = init_data['a'] * 1.1 fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], "-b") ax.set_xlim(-max_range, max_range) ax.set_ylim(-max_range, max_range) ax.set_zlim(-max_range, max_range) plt.show()
def plot_mini_moons_propagation(d=10.0): #pop = Population.load('./data/NESCv9_mult1.h5') pop = plib.NESCv9_mini_moons(num=1, d_range=[0.1, 10.0], synchronize=False) pop.delete(slice(40, None)) gen = pop.object_generator() fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot([0], [0], [0], "xr", alpha=1) t_v = np.linspace(0, d * 24.0 * 3600.0, num=1000, dtype=np.float) for sobj in gen: states = sobj.get_orbit(t_v) ax.plot(states[0, :], states[1, :], states[2, :], "-b", alpha=0.05) max_range = 384400e3 * 1 ax.set_xlim(-max_range, max_range) ax.set_ylim(-max_range, max_range) ax.set_zlim(-max_range, max_range) plt.show()
def tryBackwards(): prop = PropagatorKepler(in_frame='ITRF', out_frame='ITRF') init_data = { 'mjd0': 57125.7729, 'C_D': 2.3, 'C_R': 1.0, 'm': 3.0, 'A': np.pi * (0.5 * 0.5)**2, } state0 = [ 2721793.785377, 1103261.736653, 6427506.515945, 6996.001258, -171.659563, -2926.43233 ] x, y, z, vx, vy, vz = state0 t = np.linspace(0, 24 * 3600.0, num=5000, dtype=np.float) ecefs1 = prop.get_orbit_cart(t, x, y, z, vx, vy, vz, **init_data) x, y, z, vx, vy, vz = ecefs1[:, -1].tolist() init_data['mjd0'] += t[-1] / (3600.0 * 24.0) ecefs2 = prop.get_orbit_cart(-t, x, y, z, vx, vy, vz, **init_data) print('Position diff: {} m'.format(ecefs1[:3, 0] - ecefs2[:3, -1])) print('Velocity diff: {} m/s'.format(ecefs1[3:, 0] - ecefs2[3:, -1])) dr = np.sqrt(np.sum((ecefs1[:3, ::-1] - ecefs2[:3, :])**2, axis=0)) dv = np.sqrt(np.sum((ecefs1[3:, ::-1] - ecefs2[3:, :])**2, axis=0)) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(211) ax.plot(t / 3600.0, dr * 1e-3) ax.set_xlabel('Time [h]') ax.set_ylabel('Position difference [km]') ax.set_title('Propagation backwards and forwards error') ax = fig.add_subplot(212) ax.plot(t / 3600.0, dv * 1e-3) ax.set_xlabel('Time [h]') ax.set_ylabel('Velocity difference [km/s]') fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], "-", color="green", alpha=0.5) ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], "-", color="red", alpha=0.5) plt.show()
def plot_detections(detections, radar, space_o, t_range=3600.0): '''Visualizes the detections made by a radar of a space object. ''' figs = [] for detection in detections: t = np.linspace(np.min(detection['tm']) - t_range, np.max(detection['tm']) + t_range, num=1000, dtype=np.float) passes = np.unique(np.array(detection['t0'])) print('{} detections of object over {} passes'.format( len(detection['tm']), len(passes))) ecefs1 = space_o.get_state(t) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) figs += [(fig, ax)] radar_scans.plot_radar_scan(radar._tx[0].scan, earth=True, ax=ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], "-", color="green", alpha=0.5) for det in detection['tm']: ecefs2 = space_o.get_state([det]) ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], ".", color="red", alpha=0.5) ax.plot( [radar._tx[0].ecef[0], ecefs2[0, 0]], [radar._tx[0].ecef[1], ecefs2[1, 0]], [radar._tx[0].ecef[2], ecefs2[2, 0]], "-", color="red", alpha=0.25, ) box = 1000e3 ax.set_xlim([radar._tx[0].ecef[0] - box, radar._tx[0].ecef[0] + box]) ax.set_ylim([radar._tx[0].ecef[1] - box, radar._tx[0].ecef[1] + box]) ax.set_zlim([radar._tx[0].ecef[2] - box, radar._tx[0].ecef[2] + box]) return figs
def plot_radar_scan(SC, earth=False, ax=None): '''Plot a full cycle of the scan pattern based on the :code:`_scan_time` and the :code:`_function_data['dwell_time']` variable. :param RadarScan SC: Scan to plot. :param bool earth: Plot the surface of the Earth. ''' if 'dwell_time' in SC._function_data: dwell_time = n.min(SC._function_data['dwell_time']) else: dwell_time = 0.05 if SC._scan_time is None: scan_time = dwell_time * 100.0 else: scan_time = SC._scan_time t = n.linspace(0.0, scan_time, num=n.round(2 * scan_time / dwell_time)) if ax is None: fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') ax.grid(False) ax.view_init(15, 5) plt.title(SC.name) plt.tight_layout() _figs = (fig, ax) else: _figs = (None, ax) if earth: plothelp.draw_earth_grid(ax) plothelp.draw_radar(ax, SC._lat, SC._lon) max_range = 4000e3 for i in range(len(t)): p0, k0 = SC.antenna_pointing(t[i]) p1 = p0 + k0 * max_range * 0.8 if k0[2] < 0: ax.plot([p0[0], p1[0]], [p0[1], p1[1]], [p0[2], p1[2]], alpha=0.5, color="red") else: ax.plot([p0[0], p1[0]], [p0[1], p1[1]], [p0[2], p1[2]], alpha=0.5, color="green") ax.set_xlim(p0[0] - max_range, p0[0] + max_range) ax.set_ylim(p0[1] - max_range, p0[1] + max_range) ax.set_zlim(p0[2] - max_range, p0[2] + max_range) return _figs
def plot_detections(radar, space_o, t_end=24.0 * 3600.0): t = np.linspace(0, t_end, num=10000) detections = simulate_scan.get_detections(space_o, radar, 0.0, t_end) simulate_scan.pp_det(detections) detections = detections[0] passes = np.unique(np.array(detections['t0'])) print('{} detections of object'.format(len(detections['tm']))) print('detection on {} passes'.format(len(passes))) ecefs1 = space_o.get_state(t) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) radar_scans.plot_radar_scan(radar._tx[0].scan, earth=True, ax=ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], "-", color="green", alpha=0.5) for det in detections['tm']: ecefs2 = space_o.get_state([det]) ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], ".", color="red", alpha=0.5) ax.plot( [radar._tx[0].ecef[0], ecefs2[0, 0]], [radar._tx[0].ecef[1], ecefs2[1, 0]], [radar._tx[0].ecef[2], ecefs2[2, 0]], "-", color="red", alpha=0.1, ) box = 1000e3 ax.set_xlim([radar._tx[0].ecef[0] - box, radar._tx[0].ecef[0] + box]) ax.set_ylim([radar._tx[0].ecef[1] - box, radar._tx[0].ecef[1] + box]) ax.set_zlim([radar._tx[0].ecef[2] - box, radar._tx[0].ecef[2] + box])
def plot_orb_conv(orb_init, res=100): o = n.empty((6, res), dtype=n.float) nu = n.linspace(0, 360.0, num=res, dtype=n.float) for i in range(res): o[:5, i] = orb_init o[5, i] = nu[i] x_dpt = dpt.kep2cart(o, m=n.array([1.0]), M_cent=M_e, radians=False) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') ax.view_init(15, 5) plothelp.draw_earth_grid(ax) max_range = orb_init[0] * 1.1 ax.plot([0, max_range], [0, 0], [0, 0], "-k") ax.plot([0, max_range], [0, 0], [0, 0], "-k", label='+x') ax.plot([0, 0], [0, max_range], [0, 0], "-b", label='+y') ax.set_xlim(-max_range, max_range) ax.set_ylim(-max_range, max_range) ax.set_zlim(-max_range, max_range) ax.plot(x_dpt[0, :], x_dpt[1, :], x_dpt[2, :], ".k", alpha=0.5, label='Converted elements') ax.plot([x_dpt[0, 0]], [x_dpt[1, 0]], [x_dpt[2, 0]], "or", alpha=1, label='$\\nu = 0$') ax.plot([x_dpt[0, int(res // 4)]], [x_dpt[1, int(res // 4)]], [x_dpt[2, int(res // 4)]], "oy", alpha=1, label='$\\nu = 0.5\pi$') ax.legend() plt.title( "Kep -> cart: a={} km, e={}, inc={} deg, omega={} deg, Omega={} deg ". format( orb_init[0] * 1e-3, orb_init[1], orb_init[2], orb_init[3], orb_init[4], ))
def plot_orbit_3d(ecefs): '''Plot a set of ECEF's in 3D using matplotlib. ''' fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') ax.view_init(15, 5) plothelp.draw_earth_grid(ax) ax.plot(ecefs[0, :], ecefs[1, :], ecefs[2, :], "-", alpha=0.75, color="black") plt.title("Orbital propagation") plt.show()
def tryFrame(): p = PropagatorOrekit(in_frame='ITRF', out_frame='ITRF') print(p) init_data = { 'a': (R_e + 400.0) * 1e3, 'e': 0.01, 'inc': 90.0, 'raan': 10, 'aop': 10, 'mu0': 40.0, 'mjd0': 57125.7729, 'C_D': 2.3, 'C_R': 1.0, 'm': 3.0, 'A': np.pi * 1.0**2, } t = np.linspace(0, 3 * 3600.0, num=500, dtype=np.float) ecefs1 = p.get_orbit(t, **init_data) print(p) p = PropagatorOrekit(in_frame='EME', out_frame='ITRF') ecefs2 = p.get_orbit(t, **init_data) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], ".", color="green", label='Initial frame: ITRF') ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], ".", color="red", label='Initial frame: EME') plt.legend() plt.show()
def try2(): p = PropagatorOrekit() d_v = [0.1, 0.2] init_data = { 'a': (R_e + 400.0) * 1e3, 'e': 0.01, 'inc': 90.0, 'raan': 10, 'aop': 10, 'mu0': 40.0, 'mjd0': 57125.7729, 'C_D': 2.3, 'C_R': 1.0, 'm': 3.0, 'A': np.pi * (d_v[0] * 0.5)**2, } t = np.linspace(0, 3 * 3600.0, num=500, dtype=np.float) ecefs1 = p.get_orbit(t, **init_data) init_data['A'] = np.pi * (d_v[1] * 0.5)**2 ecefs2 = p.get_orbit(t, **init_data) dr = np.sqrt(np.sum((ecefs1[:3, :] - ecefs2[:3, :])**2, axis=0)) dv = np.sqrt(np.sum((ecefs1[3:, :] - ecefs2[3:, :])**2, axis=0)) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(211) ax.plot(t / 3600.0, dr) ax.set_xlabel('Time [h]') ax.set_ylabel('Position difference [m]') ax.set_title('Propagation difference diameter {} vs {} m'.format( d_v[0], d_v[1])) ax = fig.add_subplot(212) ax.plot(t / 3600.0, dv) ax.set_xlabel('Time [h]') ax.set_ylabel('Velocity difference [m/s]') fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], ".", color="green") ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], ".", color="red") plt.show()
def test_prior(): import plothelp #initialize the radar setup 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) tx = radar._tx[0] pop = gen_pop() obj = pop.get_object(0) ecefs = obj.get_orbit(np.linspace(0,2*3600,num=2000, dtype=np.float64)) fname = '/home/danielk/IRF/IRF_GITLAB/SORTSpp/tests/tmp_test_data/ENVISAT_TRACKING/master/prior/1_init.oem' ''' fname_tracklet = '/home/danielk/IRF/IRF_GITLAB/SORTSpp/tests/tmp_test_data/ENVISAT_TRACKING/master/tracklets/1/track-1241140623-1-0_0.tdm' obs_data = ccsds_write.read_ccsds(fname_tracklet) sort_obs = np.argsort(obs_data['date']) obs_data = obs_data[sort_obs] r_sim = obs_data['range']*0.5 v_sim = obs_data['doppler_instantaneous']*0.5 t_sim = (obs_data['date'] - obs_data['date'][0])/np.timedelta64(1, 's') ''' data, meta = ccsds_write.read_oem(fname) print(data) print('== META ==') for key, val in meta.items(): print('{}: {}'.format(key,val)) fig = plt.figure(figsize=(15,15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(data['x'], data['y'], data['z'], '-b', label = 'Prior', alpha = 0.75) ax.plot(ecefs[0,:], ecefs[1,:], ecefs[2,:], '-g', label = 'Propagation', alpha = 0.75) ax.plot([tx.ecef[0]], [tx.ecef[1]], [tx.ecef[2]], 'or', label = 'E3D') ax.legend() plt.show()
def try_compare(): fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) fig2 = plt.figure(figsize=(15, 15)) axs = [ fig2.add_subplot(311), fig2.add_subplot(312), fig2.add_subplot(313), ] fig3 = plt.figure(figsize=(15, 15)) ax_compr = fig3.add_subplot(211) ax_compv = fig3.add_subplot(212) ecef_tx = radar._tx[0].ecef ax.plot([ecef_tx[0]], [ecef_tx[1]], [ecef_tx[2]], 'or', label='EISCAT 3D') t = np.arange(0, 3 * 3600.0, 60.0, dtype=np.float) for prop, dat in zip(props, prop_dat): ecefs = prop.get_orbit(t, **init_data) if dat[1] == 'SGP4': _ecef = ecefs print('=' * 30) print('Propagating with: {}\n'.format(prop)) ax.plot(ecefs[0, :], ecefs[1, :], ecefs[2, :], dat[0], label=dat[1], alpha=0.75) for ind in range(3): axs[ind].plot(t / 3600.0, ecefs[ind, :] * 1e-3, dat[0], label=dat[1], alpha=0.4) dr = np.sqrt(np.sum((_ecef[:3, :] - ecefs[:3, :])**2, axis=0)) dv = np.sqrt(np.sum((_ecef[3:, :] - ecefs[3:, :])**2, axis=0)) ax_compr.plot(t / 3600.0, dr * 1e-3, dat[0], label=dat[1], alpha=1) ax_compv.plot(t / 3600.0, dv * 1e-3, dat[0], label=dat[1], alpha=1) ax_compr.set( xlabel='Time [h]', ylabel='$|\mathbf{r}_i - \mathbf{r}_{SGP4}|$ difference ITRF [km]', ) ax_compv.set( xlabel='Time [h]', ylabel='$|\mathbf{v}_i - \mathbf{v}_{SGP4}|$ difference ITRF [km/s]', ) ax_compr.set_title('ENVISAT Propagation comparison') ax_compr.legend() ax_compv.legend() axs[0].set( xlabel='Time [h]', ylabel='X position ITRF [km]', ) axs[0].legend() axs[1].set( xlabel='Time [h]', ylabel='Y position ITRF [km]', ) axs[2].set( xlabel='Time [h]', ylabel='Z position ITRF [km]', ) axs[0].set_title('ENVISAT Propagation comparison') ax.set_title('ENVISAT Propagation comparison') ax.legend()
def tryTest1(): init_data = { 'a': 7500e3, 'e': 0, 'inc': 90.0, 'raan': 10, 'aop': 10, 'mu0': 40.0, 'mjd0': 57125.7729, 'C_D': 2.3, 'C_R': 1.0, 'm': 8000, 'A': 1.0, } mjd0 = dpt.jd_to_mjd(2457126.2729) orb_init_list = _gen_orbits(100) prop = PropagatorOrekit( in_frame='EME', out_frame='EME', ) t = np.linspace(0, 12 * 3600, num=100, dtype=np.float) for kep in orb_init_list: state_ref = dpt.kep2cart(kep, m=init_data['m'], M_cent=prop.M_earth, radians=False) state_kep = prop.get_orbit( t=t, mjd0=mjd0, a=kep[0], e=kep[1], inc=kep[2], raan=kep[4], aop=kep[3], mu0=dpt.true2mean(kep[5], kep[1], radians=False), C_D=init_data['C_D'], m=init_data['m'], A=init_data['A'], C_R=init_data['C_R'], radians=False, ) state_cart = prop.get_orbit_cart( t=t, mjd0=mjd0, x=state_ref[0], y=state_ref[1], z=state_ref[2], vx=state_ref[3], vy=state_ref[4], vz=state_ref[5], C_D=init_data['C_D'], m=init_data['m'], A=init_data['A'], C_R=init_data['C_R'], ) state_diff1 = np.abs(state_kep - state_cart) try: nt.assert_array_less( state_diff1[:3, :], np.full((3, t.size), 1e-5, dtype=state_diff1.dtype)) nt.assert_array_less( state_diff1[3:, :], np.full((3, t.size), 1e-7, dtype=state_diff1.dtype)) except: fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(211) ax.plot(t / 3600.0, np.sqrt(np.sum(state_diff1[:3, :], axis=0)) * 1e-3) ax.set_xlabel('Time [h]') ax.set_ylabel('Position difference [km]') ax.set_title( 'Propagation difference diameter simple vs advanced models') ax = fig.add_subplot(212) ax.plot(t / 3600.0, np.sqrt(np.sum(state_diff1[3:, :], axis=0)) * 1e-3) ax.set_xlabel('Time [h]') fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(state_kep[0, :], state_kep[1, :], state_kep[2, :], "-", alpha=0.5, color="green", label='KEP input') ax.plot(state_cart[0, :], state_cart[1, :], state_cart[2, :], "-", alpha=0.5, color="red", label='CART input') plt.legend() plt.show()
def tryModeldiff(): init_data = { 'a': 7500e3, 'e': 0.1, 'inc': 90.0, 'raan': 10, 'aop': 10, 'mu0': 40.0, 'mjd0': 57125.7729, 'C_D': 2.3, 'C_R': 1.0, 'm': 8000, 'A': 1.0, } t = np.linspace(0, 10 * 3600.0, num=10000, dtype=np.float) p2 = PropagatorOrekit() print(p2) ecefs2 = p2.get_orbit(t, **init_data) p1 = PropagatorOrekit(earth_gravity='Newtonian', radiation_pressure=False, solarsystem_perturbers=[], drag_force=False) print(p1) ecefs1 = p1.get_orbit(t, **init_data) dr = np.sqrt(np.sum((ecefs1[:3, :] - ecefs2[:3, :])**2, axis=0)) dv = np.sqrt(np.sum((ecefs1[3:, :] - ecefs2[3:, :])**2, axis=0)) r1 = np.sqrt(np.sum(ecefs1[:3, :]**2, axis=0)) r2 = np.sqrt(np.sum(ecefs1[:3, :]**2, axis=0)) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(311) ax.plot(t / 3600.0, dr * 1e-3) ax.set_xlabel('Time [h]') ax.set_ylabel('Position difference [km]') ax.set_title('Propagation difference diameter simple vs advanced models') ax = fig.add_subplot(312) ax.plot(t / 3600.0, dv * 1e-3) ax.set_xlabel('Time [h]') ax.set_ylabel('Velocity difference [km/s]') ax = fig.add_subplot(313) ax.plot(t / 3600.0, r1 * 1e-3, color="green", label='Simple model') ax.plot(t / 3600.0, r2 * 1e-3, color="red", label='Advanced model') ax.set_xlabel('Time [h]') ax.set_ylabel('Distance from Earth center [km]') plt.legend() fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecefs1[0, :], ecefs1[1, :], ecefs1[2, :], "-", alpha=0.5, color="green", label='Simple model') ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], "-", alpha=0.5, color="red", label='Advanced model') plt.legend() plt.show()
def plot_scan_for_object(obj, radar, t0, t1, plot_full_scan=False): # list of transmitters txs = radar._tx # list of receivers rxs = radar._rx num_t = simulate_tracking.find_linspace_num(t0, t1, obj.a * 1e3, obj.e, max_dpos=10e3) # time vector t = n.linspace(t0, t1, num=num_t, dtype=n.float) passes, _, _, _, _ = simulate_tracking.find_pass_interval(t, obj, radar) #format: passes # [tx num][pass num][0 = above, 1 = below] fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') ax.grid(False) ax.view_init(15, 5) plothelp.draw_earth_grid(ax) plot_radar_earth(ax, radar) scan_range = 1200e3 lab_done = False lab_done_so = False cycle_complete = False for txi, tx in enumerate(txs): for pas in passes[txi]: num_pass = int((pas[1] - pas[0]) / tx.scan.min_dwell_time) t_pass = n.linspace(pas[0], pas[1], num=num_pass, dtype=n.float) ecefs = obj.get_orbit(t_pass) if lab_done_so: ax.plot(ecefs[0, :], ecefs[1, :], ecefs[2, :], '-k') else: lab_done_so = True ax.plot(ecefs[0, :], ecefs[1, :], ecefs[2, :], '-k', label='Space Object') for I in range(num_pass): scan = tx.get_scan(t_pass[I]) if scan._scan_time is not None: if t_pass[I] - pas[0] > scan._scan_time: cycle_complete = True txp0, k0 = scan.antenna_pointing(t_pass[I]) if not plot_full_scan: if cycle_complete: continue if lab_done: ax.plot( [txp0[0], txp0[0] + k0[0] * scan_range], [txp0[1], txp0[1] + k0[1] * scan_range], [txp0[2], txp0[2] + k0[2] * scan_range], '-g', alpha=0.2, ) else: ax.plot( [txp0[0], txp0[0] + k0[0] * scan_range], [txp0[1], txp0[1] + k0[1] * scan_range], [txp0[2], txp0[2] + k0[2] * scan_range], '-g', alpha=0.01, label='Scan', ) lab_done = True max_range = 1500e3 ax.set_xlim(txs[0].ecef[0] - max_range, txs[0].ecef[0] + max_range) ax.set_ylim(txs[0].ecef[1] - max_range, txs[0].ecef[1] + max_range) ax.set_zlim(txs[0].ecef[2] - max_range, txs[0].ecef[2] + max_range) plt.legend() plt.show()
def scheduling_movie(tracks, tracks_t, radar, population, root, time_slice=0.2, time_len = 1.0/60.0/30.0): #create a better sorted data structure tx = radar._tx[0] point_data = [] track_data = [] for track,t_track in zip(tracks,tracks_t): if track[2]: for t in t_track: #tracklet point time, OID, source row = [t, track[4], track[6]] point_data.append( row ) #det time, det length, OID track_data.append([track[0], track[1], track[4]]) #sort according to time, should be coherrent-int sec spaced point_data.sort(key=lambda row: row[0]) track_data.sort(key=lambda row: row[0]) point_data_arr = np.array([x[0] for x in point_data]) if point_data[-1][0] - point_data[0][0] >= time_len*3600.0: t_lims = (point_data[0][0], point_data[0][0] + time_len*3600.0) else: t_lims = (point_data[0][0], point_data[-1][0]) plt.style.use('dark_background') fig = plt.figure(figsize=(15,15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax, alpha = 0.2, color='white') ax.grid(False) plt.axis('off') def data_gen(): t_curr = t_lims[0] data_list = {} trac_cnt = 0 active_list = [] t_ind = {} while t_curr < t_lims[1]: print(t_curr,' - ', t_lims[1]) t_exec_y = time.time() t_curr += time_slice print('Adding tracks') check_tracks = True while check_tracks: track = track_data[trac_cnt] check_tracks = track_data[trac_cnt+1][0] <= t_curr print('Adding:', t_curr, trac_cnt, track[0], check_tracks, 'next - ', track_data[trac_cnt+1][0], ' df ', track[1]/time_slice) if track[0] <= t_curr and trac_cnt not in active_list: t_vec = np.arange(t_curr, track[0] + track[1], time_slice) if len(t_vec) > 0: space_o = population.get_object(int(track[2])) ecef_traj = space_o.get_orbit(t_vec) #print(trac_cnt, track[0], track[1], t_vec) data_list[trac_cnt] = ecef_traj t_ind[trac_cnt] = 0 active_list.append(trac_cnt) trac_cnt += 1 print('removing tracks') del_lst = [] for aci,tri in enumerate(active_list): track = track_data[tri] if track[0]+track[1] <= t_curr: del data_list[tri] del t_ind[tri] del_lst.append(aci) del_lst.sort() del_lst = del_lst[::-1] for tri in del_lst: del active_list[tri] for ind,t_val in t_ind.items(): t_ind[ind] = t_val + 1 dt_arr = np.abs(point_data_arr - t_curr) point_ind = int(np.argmin(dt_arr)) point_t = point_data[point_ind][0] point_oid = point_data[point_ind][1] space_o = population.get_object(int(point_oid)) point = space_o.get_orbit(point_t) point.shape = (point.size,) print('yield time: ', (time.time() - t_exec_y)*60.0, ' min') yield t_ind, data_list, point, t_curr def run(data): # update the data t_ind, data_list, point, t_curr = data print((t_curr - t_lims[0])/(t_lims[1] - t_lims[0]),' done: ', 1.0/((t_curr - t_lims[0])/(t_lims[1] - t_lims[0]))*(time.time() - t0_exec)/3600.0, ' h left') titl.set_text('Simulation t=%.4f min' % (t_curr/60.0)) print('Updating plot') for tri,dat in data_list.items(): if len(ax_traj_list[tri].get_xydata()) == 0: print('- traj ', tri) ax_traj_list[tri].set_data( dat[0,:], dat[1,:], ) ax_traj_list[tri].set_3d_properties( dat[2,:], ) ax_traj_list[tri].figure.canvas.draw() if t_ind[tri] < dat.shape[1]: print('- point ', tri) ax_point_list[tri].set_data( dat[0,t_ind[tri]], dat[1,t_ind[tri]], ) ax_point_list[tri].set_3d_properties( dat[2,t_ind[tri]], ) ax_point_list[tri].figure.canvas.draw() for tri,tr_ax in enumerate(ax_traj_list): if len(tr_ax.get_xydata()) > 0: if tri not in data_list: ax_traj_list[tri].set_data([],[]) ax_traj_list[tri].set_3d_properties([]) ax_traj_list[tri].figure.canvas.draw() ax_point_list[tri].set_data([],[]) ax_point_list[tri].set_3d_properties([]) ax_point_list[tri].figure.canvas.draw() txp0,k0=tx.get_scan(t_curr).antenna_pointing(t_curr) print('- scan ') beam_len = 1000e3 ax_tx_scan.set_data( [tx.ecef[0],tx.ecef[0] + k0[0]*beam_len], [tx.ecef[1],tx.ecef[1] + k0[1]*beam_len], ) ax_tx_scan.set_3d_properties([tx.ecef[2],tx.ecef[2] + k0[2]*beam_len]) ax_tx_scan.figure.canvas.draw() print('- track') #radar beams ax_txb.set_data( [tx.ecef[0],point[0]], [tx.ecef[1],point[1]], ) ax_txb.set_3d_properties([tx.ecef[2],point[2]]) ax_txb.figure.canvas.draw() for rxi in range(len(radar._rx)): print('- reciv ', rxi) ax_rxb_list[rxi].set_data( [radar._rx[rxi].ecef[0],point[0]], [radar._rx[rxi].ecef[1],point[1]], ) ax_rxb_list[rxi].set_3d_properties([radar._rx[rxi].ecef[2],point[2]]) ax_rxb_list[rxi].figure.canvas.draw() print('returning axis') return ax_traj_list, ax_txb, ax_rxb_list, ax_tx_scan #traj #ax_traj = ax.plot(ecef_traj[0,:],ecef_traj[1,:],ecef_traj[2,:],alpha=1,color="white") ax_traj_list = [] ax_point_list = [] for track in track_data: ax_traj, = ax.plot([],[],[],alpha=0.5,color="white") ax_traj_list.append(ax_traj) ax_point, = ax.plot([],[],[],'.',alpha=1,color="yellow") ax_point_list.append(ax_point) #init ecef_point = tx.ecef #radar beams ax_txb, = ax.plot( [tx.ecef[0],ecef_point[0]], [tx.ecef[1],ecef_point[1]], [tx.ecef[2],ecef_point[2]], alpha=1,color="green", ) ax_tx_scan, = ax.plot( [tx.ecef[0],ecef_point[0]], [tx.ecef[1],ecef_point[1]], [tx.ecef[2],ecef_point[2]], alpha=1,color="yellow", ) ax_rxb_list = [] for rx in radar._rx: ax_rxb, = ax.plot( [rx.ecef[0],ecef_point[0]], [rx.ecef[1],ecef_point[1]], [rx.ecef[2],ecef_point[2]], alpha=1,color="green", ) ax_rxb_list.append(ax_rxb) delta = 1500e3 ax.set_xlim([tx.ecef[0] - delta,tx.ecef[0] + delta]) ax.set_ylim([tx.ecef[1] - delta,tx.ecef[1] + delta]) ax.set_zlim([tx.ecef[2] - delta,tx.ecef[2] + delta]) titl = fig.text(0.5,0.94,'',size=22,horizontalalignment='center') t0_exec = time.time() print('setup done, starting anim') ani = animation.FuncAnimation(fig, run, data_gen, blit=False, #interval=1.0e3*time_slice, repeat=True, ) print('Anim done, writing movie') fps = int(1.0/time_slice) if fps == 0: fps = 10 Writer = animation.writers['ffmpeg'] writer = Writer(metadata=dict(artist='Daniel Kastinen'),fps=fps) ani.save(root + 'scheduler_movie.mp4', writer=writer) print('showing plot') plt.show()
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()
if comm.rank != 0: exit() pop.objs = pop.objs[prop_ok] states = states[:, :, prop_ok] dets['t'] = np.array(dets['t']) dets['r'] = np.array(dets['r']) dets['v'] = np.array(dets['v']) plt.style.use('dark_background') fig = plt.figure(figsize=(14, 14)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax, alpha=0.2, color='white') ax.grid(False) plt.axis('off') #traj ax_traj_list = [] ax_point_list = [] for ind in range(len(pop)): ax_traj, = ax.plot([], [], [], '-', alpha=0.5, color="white") ax_traj_list.append(ax_traj) ax_point, = ax.plot([], [], [], '.', alpha=1, color="blue") ax_point_list.append(ax_point) #init
def plot_radar_scan_movie(SC, earth=False, rotate=False, save_str=''): '''Create a animation of the scan pattern based on the :code:`_scan_time` and the :code:`_function_data['dwell_time']` variable. :param RadarScan SC: Scan to plot. :param bool earth: Plot the surface of the Earth. :param str save_str: String of path to output movie file. Requers an avalible ffmpeg encoder on the system. If string is empty no movie is saved. ''' if 'dwell_time' in SC._function_data: dwell_time = n.min(SC._function_data['dwell_time']) else: dwell_time = 0.05 if SC._scan_time is None: scan_time = dwell_time * 100.0 else: scan_time = SC._scan_time t = n.linspace(0.0, scan_time, num=n.round(2 * scan_time / dwell_time)) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') ax.view_init(15, 5) def update_text(SC, t): return SC.name + ', t=%.4f s' % (t * 1e0, ) titl = fig.text(0.5, 0.94, update_text(SC, t[0]), size=22, horizontalalignment='center') max_range = 4000e3 p0, k0 = SC.antenna_pointing(0) p1 = p0 + k0 * max_range * 0.8 if earth: plothelp.draw_earth_grid(ax) else: plothelp.draw_earth(ax) plothelp.draw_radar(ax, SC._lat, SC._lon) if k0[2] < 0: beam = ax.plot([p0[0], p1[0]], [p0[1], p1[1]], [p0[2], p1[2]], alpha=0.5, color="red") else: beam = ax.plot([p0[0], p1[0]], [p0[1], p1[1]], [p0[2], p1[2]], alpha=0.5, color="green") ax.set_xlim(p0[0] - max_range, p0[0] + max_range) ax.set_ylim(p0[1] - max_range, p0[1] + max_range) ax.set_zlim(p0[2] - max_range, p0[2] + max_range) interval = scan_time * 1e3 / float(len(t)) rotations = n.linspace(0., 360. * 2, num=len(t)) % 360.0 def update(ti, beam): _t = t[ti] p0, k0 = SC.antenna_pointing(_t) p1 = p0 + k0 * max_range * 0.8 titl.set_text(update_text(SC, _t)) beam.set_data([p0[0], p1[0]], [p0[1], p1[1]]) beam.set_3d_properties([p0[2], p1[2]]) if k0[2] < 0: beam.set_color("red") else: beam.set_color("green") if rotate: ax.view_init(15, rotations[ti]) return beam, ani = animation.FuncAnimation(fig, update, frames=range(len(t)), fargs=(beam), interval=interval, blit=False) if len(save_str) > 0: # Set up formatting for the movie files Writer = animation.writers['ffmpeg'] writer = Writer(metadata=dict(artist='Daniel Kastinen'), bitrate=1800) ani.save(save_str, writer=writer) plt.tight_layout() plt.show()
C_R=1.0, oid=42, mjd0=57125.7729, propagator=PropagatorOrekit, propagator_options={ 'in_frame': 'TEME', 'out_frame': 'ITRF', }, ) ecefs2 = o3.get_state(t) fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') ax.view_init(15, 5) plothelp.draw_earth_grid(ax) ax.plot(ecefs[0, :], ecefs[1, :], ecefs[2, :], '-', alpha=0.5, color="black", label='SGP4') ax.plot(ecefs2[0, :], ecefs2[1, :], ecefs2[2, :], '-', alpha=0.5, color="green", label='Orekit') plt.title("Orbital propagation test")
def get_passes(o, radar, t0, t1, max_dpos=1e3, logger=None, plot=False, t_samp=None): '''Follow object and determine possible maintenance track window. I.e. get all passes of the object inside the radar system FOV. :param SpaceObject o: Space object to find passes for. :param RadarSystem radar: Radar system that defines the FOV. :param float t0: Start time for passes search in seconds relative space object epoch. :param float t1: Stop time for passes search in seconds relative space object epoch. :param float max_dpos: Maximum separation in km between orbital evaluation points. :param Logger logger: Logger object for logging the execution of the function. :param float t_samp: If not None, overrides the "max_dpos" variable and fixes a time-sampling. :return: Dictionary containing information about all passes of the space object inside the radar system FOV. :rtype: dict **Output dictionary:** * t: Three layers of lists where first layer is a list corresponding to every RX antenna of the radar system. Second layer is the a entry in the list for every pass. Last layer of lists is a list of two elements where the first is the time in seconds when object enters the FOV and second is the time in seconds when the object leaves the FOV. I.e. :code:`pass_start_time = passes["t"][tx_index][pass_index][0]` and :code:`pass_end_time = passes["t"][tx_index][pass_index][1]`. * snr: This structure has the same format as the "t" item but with an extra layer of lists of receivers before the bottom. Then instead of the bottom layer of lists being start and stop times it records the peak SNR at the first item and the time of that peak SNR in the second item. I.e. :code:`pass_peak_snr = passes["snr"][tx_index][pass_index][rx_index][0]` and :code:`pass_peak_snr_time = passes["snr"][tx_index][pass_index][rx_index][1]`. ''' pass_struct = {"t": [], "snr": []} if t_samp is None: num_t = find_linspace_num(t0, t1, o.a * 1e3, o.e, max_dpos=max_dpos) t = n.linspace(t0, t1, num=num_t, dtype=n.float64) else: t = n.arange(t0, t1, t_samp, dtype=n.float64) num_t = len(t) if logger is not None: logger.debug("n_points %d %1.2f" % (num_t, max_dpos)) # time vector if logger is not None: date0_y, date0_m, date0_d = dpt.jd_to_date(dpt.mjd_to_jd(o.mjd0)) logger.debug( '--> Getting {} orbit location between: {:.5f} h and {:.5f} h relative {}-{}-{}' .format( num_t, t[0] / (3600), t[-1] / (3600), date0_y, date0_m, date0_d, )) passes, passes_id, idx_v, postx_v, posrx_v = find_pass_interval( t, o, radar, logger=logger) if logger is not None: logger.debug("passes:\n {}".format(passes)) tx_dets = 0 for idx in idx_v: if len(idx) > 0: tx_dets += 1 if tx_dets == 0: if logger is not None: logger.debug("no passes visible from any RX station") return pass_struct if logger is not None: logger.debug("--> List of passes constructed") logger.debug("{}".format(passes)) snrs = [None] * len(radar._tx) for txi, idx in enumerate(idx_v): if len(idx) > 0: snrs[txi] = [None] * len(passes[txi]) tx = radar._tx[txi] for pid, pass_ids in enumerate(passes_id[txi]): idx_p = idx[pass_ids[0]:pass_ids[1]] if logger is not None: logger.debug("{}".format(idx_p)) logger.debug("{}".format(pass_ids)) snrs[txi][pid] = [None] * len(radar._rx) rx_dets = 0 for rxi, rx in enumerate(radar._rx): snr_curve = [] for I in idx_p: tx_dist = n.linalg.norm(postx_v[txi][:, I]) k0 = coord.ecef2local( lat=tx.lat, lon=tx.lon, alt=tx.alt, x=postx_v[txi][0, I], y=postx_v[txi][1, I], z=postx_v[txi][2, I], ) tx.beam.point_k0(k0) gain_tx = tx.beam.gain(k0) rx_dist = n.linalg.norm(posrx_v[rxi][:, I]) # point towards object k0 = coord.ecef2local( lat=rx.lat, lon=rx.lon, alt=rx.alt, x=posrx_v[txi][0, I], y=posrx_v[txi][1, I], z=posrx_v[txi][2, I], ) rx.beam.point_k0(k0) gain_rx = rx.beam.gain(k0) snr = debris.hard_target_enr( gain_tx, gain_rx, rx.wavelength, tx.tx_power, tx_dist, rx_dist, diameter_m=o.d, bandwidth=tx.coh_int_bandwidth, rx_noise_temp=rx.rx_noise) if logger is not None: logger.debug( '\n--> TX-d: %.2f km | TX-g: %.2f dB' % (tx_dist * 1e-3, 10.0 * n.log10(gain_tx))) logger.debug( '--> RX-d: %.2f km | RX-g: %.2f dB' % (rx_dist * 1e-3, 10.0 * n.log10(gain_rx))) logger.debug('--> SNR: %.2f dB ' % (10.0 * n.log10(snr))) snr_curve.append(snr) snr_curve = n.array(snr_curve) if plot: snr_curve_dB = 10.0 * n.log10(snr_curve) snr_curve_dB[snr_curve_dB < 0] = 0 plt.plot(t[idx_p], snr_curve_dB) plt.plot(t[idx_p[n.argmax(snr_curve)]], n.max(snr_curve_dB), 'or') plt.title("tx %i, pass %i, rx %i" % (txi, pid, rxi)) plt.show() print('SNR max: %.2f @ %.2f h' % (n.max(snr_curve_dB), t[idx_p[n.argmax(snr_curve)]] / 3600.0)) if len(snr_curve) > 0: snr_max = n.max(snr_curve) else: snr_max = 0.0 if snr_max >= tx.enr_thresh: rx_dets += 1 snrs[txi][pid][rxi] = [ snr_max, t[idx_p[n.argmax(snr_curve)]] ] else: snrs[txi][pid][rxi] = [0, 0] if rx_dets == 0: snrs[txi][pid] = None if plot: fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection='3d') plothelp.draw_earth_grid(ax) ax.plot(ecef[0, :], ecef[1, :], ecef[2, :], alpha=1, color="black") for I in idx_p: ax.plot([tx.ecef[0], tx.ecef[0] + postx_v[txi][0, I]], [tx.ecef[1], tx.ecef[1] + postx_v[txi][1, I]], [tx.ecef[2], tx.ecef[2] + postx_v[txi][2, I]], alpha=0.5, color="red") for rxi, rx in enumerate(radar._rx): ax.plot( [rx.ecef[0], rx.ecef[0] + posrx_v[rxi][0, I]], [rx.ecef[1], rx.ecef[1] + posrx_v[rxi][1, I]], [rx.ecef[2], rx.ecef[2] + posrx_v[rxi][2, I]], alpha=0.5, color="red") delta = 1000e3 ax.set_xlim([tx.ecef[0] - delta, tx.ecef[0] + delta]) ax.set_ylim([tx.ecef[1] - delta, tx.ecef[1] + delta]) ax.set_zlim([tx.ecef[2] - delta, tx.ecef[2] + delta]) plt.show() passes[txi] = [ x for ix, x in enumerate(passes[txi]) if snrs[txi][ix] is not None ] #remove tracks that were not above detection tresholds at any pair snrs[txi] = [ x for x in snrs[txi] if x is not None ] #remove tracks that were not above detection tresholds at any pair for txi, tx_snr in enumerate(snrs): if tx_snr is None: snrs[txi] = [] for txi, tx_pass in enumerate(passes): if tx_pass is None: passes[txi] = [] pass_struct['snr'] = snrs pass_struct['t'] = passes return pass_struct