-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbeampark_rcs_estimation.py
executable file
·1892 lines (1608 loc) · 62.5 KB
/
beampark_rcs_estimation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from pathlib import Path
import pickle
import argparse
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from astropy.time import Time, TimeDelta
from tqdm import tqdm
import h5py
import sorts
import pyant
import pyorb
from convert_spade_events_to_h5 import get_spade_data
from convert_spade_events_to_h5 import read_spade, date2unix
from convert_spade_events_to_h5 import MIN_SNR
from convert_spade_events_to_h5 import read_extended_event_data, load_spade_extended
from discosweb_download import main as discosweb_download_main
try:
from mpi4py import MPI
comm = MPI.COMM_WORLD
except ImportError:
class COMM_WORLD:
rank = 0
size = 1
def Barrier(self):
pass
comm = COMM_WORLD()
'''
Example execution:
# individual event
./beampark_rcs_estimation.py estimate \
--matches-plotted 3 --min-gain 10.0 --min-snr 15.0 \
--inclination-samples 150 --anomaly-samples 100 \
--maximum-offaxis-angle 1.8 \
eiscat_uhf \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs_trunc_gain \
--event uhf_20211123_120429_800000
./beampark_rcs_estimation.py estimate \
--matches-plotted 3 --min-gain 10.0 --min-snr 15.0 \
--inclination-samples 150 --anomaly-samples 100 \
--maximum-offaxis-angle 1.8 \
eiscat_uhf \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs_trunc_gain \
--event uhf_20211123_123831_000000
./beampark_rcs_estimation.py estimate \
--matches-plotted 3 --min-gain 10.0 --min-snr 15.0 \
--inclination-samples 150 --anomaly-samples 100 \
eiscat_uhf \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs \
--event uhf_20211123_120429_800000
./beampark_rcs_estimation.py predict eiscat_uhf \
projects/output/russian_asat/{\
2021_11_23_spacetrack.tle,\
uhf/2021.11.23.h5,\
2021.11.23_uhf_correlation.pickle,\
2021.11.23_uhf_correlation_plots/eiscat_uhf_selected_correlations.npy} \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
projects/output/russian_asat/2021.11.23_uhf_rcs_trunc_gain \
--min-gain 10.0 --min-snr 15.0 \
--event uhf_20211123_120429_800000
# for all
mpirun -np 6 ./beampark_rcs_estimation.py estimate \
--matches-plotted 3 --min-gain 10.0 --min-snr 15.0 \
--inclination-samples 150 --anomaly-samples 100 \
eiscat_uhf \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs
# followed by
cp -rv ./projects/output/russian_asat/2021.11.23_uhf_rcs{,_trunc_gain}
mpirun -np 6 ./beampark_rcs_estimation.py estimate \
--matches-plotted 3 --min-gain 10.0 --min-snr 15.0 \
--inclination-samples 150 --anomaly-samples 100 \
--maximum-offaxis-angle 1.8 \
eiscat_uhf \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs_trunc_gain
./beampark_rcs_estimation.py predict eiscat_uhf \
projects/output/russian_asat/{\
2021_11_23_spacetrack.tle,\
uhf/2021.11.23.h5,\
2021.11.23_uhf_correlation.pickle,\
2021.11.23_uhf_correlation_plots/eiscat_uhf_selected_correlations.npy} \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
projects/output/russian_asat/2021.11.23_uhf_rcs \
--min-gain 10.0 --min-snr 15.0
./beampark_rcs_estimation.py predict eiscat_uhf \
projects/output/russian_asat/{\
2021_11_23_spacetrack.tle,\
uhf/2021.11.23.h5,\
2021.11.23_uhf_correlation.pickle,\
2021.11.23_uhf_correlation_plots/eiscat_uhf_selected_correlations.npy} \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
projects/output/russian_asat/2021.11.23_uhf_rcs_trunc_gain \
--min-gain 10.0 --min-snr 15.0
./beampark_rcs_estimation.py discos -k discos \
projects/output/russian_asat/{\
2021_11_23_spacetrack.tle,\
2021.11.23_uhf_correlation.pickle,\
2021.11.23_uhf_correlation_plots/eiscat_uhf_selected_correlations.npy,\
2021.11.23_uhf_rcs/}
./beampark_rcs_estimation.py collect \
eiscat_uhf \
projects/output/russian_asat/2021_11_23_spacetrack.tle \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs
./beampark_rcs_estimation.py collect \
eiscat_uhf \
projects/output/russian_asat/2021_11_23_spacetrack.tle \
~/data/spade/beamparks/uhf/2021.11.23/leo_bpark_2.1u_NO@uhf_extended/ \
./projects/output/russian_asat/2021.11.23_uhf_rcs_trunc_gain
'''
def offaxis_weighting(angles):
'''Weight for offaxis angle, normalized for this set of angles
'''
if angles.size == 0:
return np.ones_like(angles)
w = angles.copy()
w += 1 - np.min(w)
w = 1.0/w
w = w/np.sum(w)
return w
def matching_function(data, SNR_sim, off_angles, args, debug=False):
# Filter measurnments
_SNR_sim = SNR_sim.copy()
_SNR_sim[_SNR_sim <= 0] = np.nan
sndb = np.log10(data['SNR'].values)*10
snsdb = np.log10(_SNR_sim)*10
if np.all(np.isnan(_SNR_sim)):
match = np.nan
meta = [np.nan, np.nan]
return match, meta
max_sndb_x = np.log10(np.nanmax(data['SNR'].values))*10
max_sndb_y = np.log10(np.nanmax(_SNR_sim))*10
#ratio of peak signal and limit should be the same
#as the ratio of the simulated peak and the simulated signal
#use this to calculate the limit used in simulation
snrdb_lim_rel = max_sndb_x - args.min_snr
sns_lim = max_sndb_y - snrdb_lim_rel
#the normalized limit is, since the normalizations put peaks to 1
snrdb_lim_norm = -snrdb_lim_rel
off_weight = offaxis_weighting(off_angles)
sn = data['SNR'].values
xsn = np.full(sn.shape, np.nan, dtype=sn.dtype)
idx_x = sn > 0
if np.sum(idx_x) > 1:
xsn[idx_x] = np.log10(sn[idx_x]/np.nanmax(sn[idx_x]))
idx_x = np.logical_not(np.isnan(xsn))
sns = _SNR_sim
ysn = np.full(sns.shape, np.nan, dtype=sn.dtype)
idx_y = sns > 0
if np.sum(idx_y) > 1:
ysn[idx_y] = np.log10(sns[idx_y]/np.nanmax(sns[idx_y]))
idx_y = np.logical_not(np.isnan(ysn))
idx = np.logical_and(idx_x, idx_y)
tot = np.sum(idx)
dhit_idx = np.logical_and.reduce([
sndb > args.min_snr,
snsdb > sns_lim,
idx,
])
dcut_idx = np.logical_and.reduce([
np.logical_or(sndb <= args.min_snr, np.logical_not(idx_x)),
snsdb > sns_lim,
idx_y,
])
dmiss_idx = np.logical_and.reduce([
sndb > args.min_snr,
np.logical_or(snsdb <= sns_lim, np.logical_not(idx_y)),
idx_x,
])
dhit = np.nan
dcut = np.nan
dmiss = np.nan
if tot > 1:
if np.any(dhit_idx):
dhit = np.sum(((xsn[dhit_idx] - ysn[dhit_idx])*off_weight[dhit_idx])**2)
if np.any(dcut_idx):
dcut = np.sum(((ysn[dcut_idx] - snrdb_lim_norm)*off_weight[dcut_idx])**2)
if np.any(dmiss_idx):
dmiss = np.sum((xsn[dmiss_idx]*off_weight[dmiss_idx])**2)
match = dhit
if not np.isnan(dcut):
match += dcut
if not np.isnan(dmiss):
match += dmiss
match_0 = match
match = np.sqrt(match/len(SNR_sim))
meta = [dcut/len(SNR_sim), dmiss/len(SNR_sim)]
if debug:
print('idx_x: ', idx_x)
print('idx_y: ', idx_y)
print('idx: ', idx)
print('dhit_idx: ', dhit_idx)
print('dcut_idx: ', dcut_idx)
print('dmiss_idx: ', dmiss_idx)
print('tot: ', tot)
print('dhit: ', dhit)
print('dcut: ', dcut)
print('dmiss: ', dmiss)
print('match_0: ', match_0)
print('match: ', match)
print('meta: ', meta)
return match, meta
def locate_in_beam(x, orb, r_ecef, epoch):
orb0 = orb.copy()
orb0.i = x[0]
orb0.Omega = x[1]
orb0.anom = x[2]
pos = sorts.frames.convert(
epoch,
orb0.cartesian,
in_frame='TEME',
out_frame='ITRS',
).flatten()[:3]
dist = np.linalg.norm(pos - r_ecef)
return dist
def evaluate_sample(
data, orb,
inc, nu, t_,
epoch, radar, ecef_st,
prop,
):
orb_pert = orb.copy()
orb_pert.i = orb_pert.i + inc
orb_pert.anom = orb_pert.anom + nu
states_ecef = prop.propagate(t_, orb_pert, epoch=epoch)
local_pos = sorts.frames.ecef_to_enu(
radar.tx[0].lat,
radar.tx[0].lon,
radar.tx[0].alt,
states_ecef[:3, :] - ecef_st[:, None],
radians=False,
)
pth = local_pos/np.linalg.norm(local_pos, axis=0)
G_pth = radar.tx[0].beam.gain(pth)
diam = sorts.signals.hard_target_diameter(
G_pth,
G_pth,
radar.tx[0].wavelength,
radar.tx[0].power,
data['r'].values,
data['r'].values,
data['SNR'].values,
bandwidth=radar.tx[0].coh_int_bandwidth,
rx_noise_temp=radar.rx[0].noise,
radar_albedo=1.0,
)
SNR_sim = sorts.signals.hard_target_snr(
G_pth,
G_pth,
radar.tx[0].wavelength,
radar.tx[0].power,
data['r'].values,
data['r'].values,
diameter=1,
bandwidth=radar.tx[0].coh_int_bandwidth,
rx_noise_temp=radar.rx[0].noise,
radar_albedo=1.0,
)
return pth, diam, SNR_sim, G_pth
def plot_selection(ax, x, y, selector, styles, labels=None, colors=None):
not_selector = np.logical_not(selector)
x_sel = np.copy(x)
x_sel[not_selector] = np.nan
x_not_sel = np.copy(x)
x_not_sel[selector] = np.nan
y_sel = np.copy(y)
y_sel[not_selector] = np.nan
y_not_sel = np.copy(y)
y_not_sel[selector] = np.nan
if isinstance(styles, str):
styles = [styles, styles]
if isinstance(labels, str):
labels = [labels, labels]
sel_kw = {}
not_sel_kw = {}
if labels is not None:
if labels[0] is not None:
sel_kw['label'] = labels[0]
if labels[1] is not None:
not_sel_kw['label'] = labels[1]
if colors is not None:
if isinstance(colors, str):
sel_kw['color'] = colors
not_sel_kw['color'] = colors
else:
if colors[0] is not None:
sel_kw['color'] = colors[0]
if colors[1] is not None:
not_sel_kw['color'] = colors[1]
ax.plot(x_sel, y_sel, styles[0], **sel_kw)
ax.plot(x_not_sel, y_not_sel, styles[1], **not_sel_kw)
return ax
def plot_match(
data, diams,
t_, dt, use_data,
sn_s, sn_m, gain,
mch_rank, results_folder, radar,
pth, args, mdate, match_data,
):
fig, axes = plt.subplots(2, 3, figsize=(16, 8), sharex=True)
styles = ['-', '.-']
plot_selection(
ax=axes[0, 0],
x=data['t'].values,
y=diams*1e2,
selector=use_data,
styles=styles,
labels=['Used measurements', 'Not used measurements'],
colors='b',
)
axes[0, 0].set_ylabel('Diameter [cm]')
plot_selection(
ax=axes[0, 1],
x=data['t'].values,
y=np.log10(diams*1e2),
selector=use_data,
styles=styles,
labels=['Used measurements', 'Not used measurements'],
colors='b',
)
axes[0, 1].set_ylabel('Diameter [log10(cm)]')
interval = 0.6
max_sn = np.argmax(sn_m)
d_peak = diams[max_sn]*1e2
if not (np.isnan(d_peak) or np.isinf(d_peak)):
logd_peak = np.log10(d_peak)
axes[0, 0].set_ylim(d_peak*(1 - interval), d_peak*(1 + interval))
#axes[0, 1].set_ylim(logd_peak*(1 - interval), logd_peak*(1 + interval))
axes[1, 0].set_xlabel('Time [s]')
plot_selection(
ax=axes[1, 0],
x=data['t'].values,
y=sn_s,
selector=use_data,
styles=styles,
labels=['Estimated', None],
colors='b',
)
plot_selection(
ax=axes[1, 0],
x=data['t'].values,
y=sn_m,
selector=use_data,
styles=styles,
labels=['Measured', None],
colors='r',
)
plot_selection(
ax=axes[1, 1],
x=data['t'].values,
y=10*np.log10(sn_s),
selector=use_data,
styles=styles,
labels=['Estimated', None],
colors='b',
)
plot_selection(
ax=axes[1, 1],
x=data['t'].values,
y=10*np.log10(sn_m),
selector=use_data,
styles=styles,
labels=['Measured', None],
colors='r',
)
max_sndb_m = np.log10(np.max(data['SNR'].values))*10
axes[1, 1].axhline(-(max_sndb_m - args.min_snr), color='g', label='Minimum SNR')
axes[0, 2].axhline(args.min_snr, color='g', label='Minimum SNR')
plot_selection(
ax=axes[0, 2],
x=data['t'].values,
y=10*np.log10(data['SNR']),
selector=use_data,
styles=styles,
labels=['Used measurements', 'Not used measurements'],
colors='r',
)
axes[0, 2].legend()
axes[1, 2].axhline(args.min_gain, color='g', label='Minimum gain')
plot_selection(
ax=axes[1, 2],
x=data['t'].values,
y=gain,
selector=use_data,
styles=styles,
labels=[None, None],
colors='b',
)
axes[1, 2].legend()
axes[1, 0].legend()
axes[1, 1].set_xlabel('Time [s]')
axes[1, 2].set_xlabel('Time [s]')
axes[0, 2].set_ylabel('Measured SNR [dB]')
axes[1, 2].set_ylabel('Estimated Gain [dB]')
axes[1, 0].set_ylabel('Normalized SNR [1]')
axes[1, 1].set_ylabel('Normalized SNR [dB]')
title_date = results_folder.stem.split('_')
fig.suptitle(f'{title_date[0].upper()} - {mdate}:\nd_cut/N={match_data[0]:.2e}, d_miss/N={match_data[1]:.2e}, d_hit/N={match_data[2]:.2e}, D={match_data[3]:.2e}')
fig.savefig(results_folder / f'match{mch_rank}_data.{args.format}')
plt.close(fig)
fig, ax = plt.subplots(figsize=(12, 8))
pyant.plotting.gain_heatmap(
radar.tx[0].beam,
min_elevation=85.0,
ax=ax,
)
ax.plot(
pth[0, :],
pth[1, :],
'-r'
)
ax.set_xlabel('kx [1]')
ax.set_ylabel('ky [1]')
fig.savefig(results_folder / f'match{mch_rank}_traj_gain.{args.format}')
plt.close(fig)
def main_estimate(args):
dt = 1.0
radar = getattr(sorts.radars, args.radar)
output_pth = Path(args.output).resolve()
input_pth = Path(args.input).resolve()
input_pths = list(input_pth.rglob('*.hlist'))
input_summaries = list(input_pth.rglob('events.txt'))
event_names = [x.stem for x in input_pths]
output_pth.mkdir(exist_ok=True, parents=True)
prop = sorts.propagator.Kepler(
settings=dict(
in_frame='TEME',
out_frame='ITRS',
),
)
incs_mat, nus_mat = np.meshgrid(
np.linspace(
args.inclination_limits[0],
args.inclination_limits[1],
args.inclination_samples,
),
np.linspace(
args.anomaly_limits[0],
args.anomaly_limits[1],
args.anomaly_samples,
),
)
incs = incs_mat.reshape((incs_mat.size, ))
nus = nus_mat.reshape((nus_mat.size, ))
samps = len(incs)
event_data = read_extended_event_data(input_summaries, args)
# len(event_names)
inds = list(range(len(event_names)))
step = int(len(event_names)/comm.size + 1)
all_inds = [
np.array(inds[i:(i + step)], dtype=np.int64)
for i in range(0, len(inds), step)
]
assert all_inds[-1][-1] == inds[-1]
comm.Barrier()
pbar = tqdm(
total=len(all_inds[comm.rank]),
position=comm.rank*2,
desc=f'Rank-{comm.rank} events',
)
worker_inds = all_inds[comm.rank]
for evi in worker_inds:
event_name = event_names[evi]
pbar.set_description(f'Rank-{comm.rank} events [{event_name}]')
if len(args.event) > 0:
if not args.event == event_name:
pbar.update(1)
continue
event_indexing = event_data['event_name'] == event_name
if not np.any(event_indexing):
if args.v:
print(f'Warning: "{event_name}" not found in events.txt, skipping')
continue
event_row = event_data[event_indexing]
if args.v:
print('Processing:')
print(event_row)
results_folder = output_pth / event_name
results_folder.mkdir(exist_ok=True)
cache_file = results_folder / f'{event_name}_rcs.pickle'
match_file = results_folder / f'{event_name}_results.pickle'
data_path = input_pths[evi]
data = load_spade_extended(data_path)
radar.tx[0].beam.sph_point(
azimuth=event_row['AZ'].values[0],
elevation=event_row['EL'].values[0],
)
if args.v:
print(f'Setting pointing to: \n\
azimuth = {radar.tx[0].beam.azimuth} deg\n\
elevation = {radar.tx[0].beam.elevation} deg')
ecef_point = radar.tx[0].pointing_ecef
ecef_st = radar.tx[0].ecef
snr_max = np.argmax(data['SNR'].values)
r_obj = data['r'].values[snr_max]
r_ecef = ecef_st + r_obj*ecef_point
epoch = Time(data['unix'].values[snr_max], format='unix', scale='utc')
if args.v:
print(f'Epoch {epoch.iso}')
t_ = data['t'].values - data['t'].values[snr_max]
r_teme = sorts.frames.convert(
epoch,
np.hstack([r_ecef, np.ones_like(r_ecef)]),
in_frame='ITRS',
out_frame='TEME',
)
r_teme = r_teme[:3]
orb = pyorb.Orbit(
M0=pyorb.M_earth, m=0,
num=1, epoch=epoch,
degrees=True,
)
orb.update(
a = np.linalg.norm(r_teme),
e = 0,
omega = 0,
i = 0,
Omega = 0,
anom = 0,
)
v_norm = orb.speed[0]
x_hat = np.array([1, 0, 0], dtype=np.float64) # Z-axis unit vector
z_hat = np.array([0, 0, 1], dtype=np.float64) # Z-axis unit vector
# formula for creating the velocity vectors
b3 = r_teme/np.linalg.norm(r_teme) # r unit vector
b3 = b3.flatten()
b1 = np.cross(b3, z_hat) # Az unit vector
if np.linalg.norm(b1) < 1e-12:
b1 = np.cross(b3, x_hat) # Az unit vector
b1 = b1/np.linalg.norm(b1)
v_temes = v_norm*b1
orb.update(
x = r_teme[0],
y = r_teme[1],
z = r_teme[2],
vx = v_temes[0],
vy = v_temes[1],
vz = v_temes[2],
)
if args.v:
print(orb)
if cache_file.is_file() and not args.clobber:
if args.v:
print('Loading from cache...')
with open(cache_file, 'rb') as fh:
reses = pickle.load(fh)
else:
if args.v:
print('Simulating SNR curves...')
subpbar = tqdm(
total=samps,
position=comm.rank*2 + 1,
desc=f'Rank-{comm.rank} SNR sampling',
)
reses = []
for ind in range(samps):
res = evaluate_sample(
data, orb,
incs[ind], nus[ind], t_,
epoch, radar, ecef_st,
prop,
)
reses.append(res)
subpbar.update(1)
subpbar.close()
with open(cache_file, 'wb') as fh:
pickle.dump(reses, fh)
diams = [None for x in range(samps)]
SNR_sims = [None for x in range(samps)]
pths = [None for x in range(samps)]
gains = [None for x in range(samps)]
low_gains = [None for x in range(samps)]
pths_off_angle = [None for x in range(samps)]
for ind in range(samps):
pth, diam, SNR_sim, G_pth = reses[ind]
pths_off_angle[ind] = pyant.coordinates.vector_angle(
radar.tx[0].beam.pointing,
pth,
radians=False,
)
G_pth_db = 10*np.log10(G_pth)
gains[ind] = G_pth_db
low_gain_inds = G_pth_db < args.min_gain
high_offaxis_inds = pths_off_angle[ind] > args.maximum_offaxis_angle
rem_inds = np.logical_or(low_gain_inds, high_offaxis_inds)
diam[rem_inds] = np.nan
SNR_sim[rem_inds] = 0
pths[ind] = pth
diams[ind] = diam
SNR_sims[ind] = SNR_sim
low_gains[ind] = low_gain_inds
del reses
if args.v:
print('Calculating match values...')
matches = [None for x in range(samps)]
metas = [None for x in range(samps)]
for ind in range(samps):
matches[ind], metas[ind] = matching_function(
data, SNR_sims[ind], pths_off_angle[ind], args,
)
matches = np.array(matches)
matches_mat = matches.reshape(nus_mat.shape)
metas = np.array(metas)
snr_cut_matching = metas[:, 0].reshape(nus_mat.shape)
missed_points = metas[:, 1].reshape(nus_mat.shape)
use_data = np.log10(data['SNR'].values)*10 > args.min_snr
sn_m_max = np.max(data['SNR'].values)
sn_m = data['SNR'].values/sn_m_max
best_matches_inds = np.argsort(matches)
best_matches = matches[best_matches_inds]
best_diams = np.array([diams[ind][snr_max] for ind in best_matches_inds])
best_gains = np.array([gains[ind][snr_max] for ind in best_matches_inds])
best_ind = best_matches_inds[0]
# DEBUG
# matching_function(
# data, SNR_sims[best_ind], pths_off_angle[best_ind], args,
# debug=True,
# )
diams_at_peak = np.array([diams[ind][snr_max] for ind in np.arange(len(diams))])
diams_at_peak_mat = diams_at_peak.reshape(nus_mat.shape)
off_angles = np.zeros_like(matches)
for ind in range(samps):
off_angles[ind] = pyant.coordinates.vector_angle(
pths[ind][:, snr_max],
radar.tx[0].beam.pointing,
radians=False,
)
best_offaxis = off_angles[best_matches_inds]
off_angles_lin = off_angles.copy()
off_angles = off_angles.reshape(matches_mat.shape)
offset_angle = pyant.coordinates.vector_angle(
pths[best_ind][:, snr_max],
radar.tx[0].beam.pointing,
radians=False,
)
kv = np.array([pth[:, snr_max] for pth in pths]).T
azel = pyant.coordinates.cart_to_sph(kv, radians=True)
match_limit = (np.nanmax(matches) - np.nanmin(matches))*args.match_limit_fraction
prob_remover = matches > np.nanmin(matches) + match_limit
matches_prob = matches.copy()
not_idx = np.logical_or(prob_remover, np.isnan(matches_prob))
idx = np.logical_not(not_idx)
matches_prob[not_idx] = 0
matches_prob[idx] *= -1
matches_prob[idx] -= np.min(matches_prob[idx])
matches_prob[idx] /= np.sum(matches_prob[idx])
kx_mat = kv[0, :].reshape(matches_mat.shape)
ky_mat = kv[1, :].reshape(matches_mat.shape)
dkx_mat = kx_mat[1:, :-1] - kx_mat[:-1, :-1]
dky_mat = ky_mat[:-1, 1:] - ky_mat[:-1, :-1]
kA = dkx_mat*dky_mat
select_mat = np.full(matches_mat.shape, False, dtype=bool)
select_mat[:-1, :-1] = True
select = select_mat.reshape(matches.shape)
# just approximate by the sin
sph_area0 = kA.reshape((np.sum(select), ))/np.sin(azel[1, select])
sph_area = np.empty_like(matches)
sph_area[select] = sph_area0
sph_area[np.logical_not(select)] = np.nan
diams_prob = matches_prob/sph_area
diams_prob[np.isnan(diams_prob)] = 0
diams_prob[prob_remover] = 0
diams_prob /= np.sum(diams_prob)
diam_prob_dist, diam_prob_bins = np.histogram(
np.log10(diams_at_peak*1e2),
bins=np.linspace(0, 5, int(0.25*np.sqrt(len(diams_prob)))),
weights=diams_prob,
)
boresight_diam = sorts.signals.hard_target_diameter(
radar.tx[0].beam.gain(radar.tx[0].beam.pointing),
radar.tx[0].beam.gain(radar.tx[0].beam.pointing),
radar.tx[0].wavelength,
radar.tx[0].power,
data['r'].values[snr_max],
data['r'].values[snr_max],
data['SNR'].values[snr_max],
bandwidth=radar.tx[0].coh_int_bandwidth,
rx_noise_temp=radar.rx[0].noise,
radar_albedo=1.0,
)
if args.v:
print('== Best match ==')
print(f'Inclination offset {incs[best_ind]} deg')
print(f'Anom offset {nus[best_ind]} deg')
print(f'Offaxis angle {offset_angle} deg')
summary_data = dict(
best_matches_inds = best_matches_inds,
best_matches = best_matches,
best_diams = best_diams,
best_gains = best_gains,
best_offaxis = best_offaxis,
best_path = pths[best_ind],
paths = pths,
boresight_diam = boresight_diam,
best_inc = incs[best_ind],
best_anom = nus[best_ind],
snr_max_ind = snr_max,
matches = matches_mat,
snr_cut_matching = snr_cut_matching,
missed_points = missed_points,
diams_at_peak = diams_at_peak_mat,
diam_prob_dist = diam_prob_dist,
diam_prob_bins = diam_prob_bins,
)
with open(match_file, 'wb') as fh:
pickle.dump(summary_data, fh)
if args.v:
print('Plotting...')
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
pmesh = axes[0, 0].pcolormesh(
incs_mat,
nus_mat,
matches_prob.reshape(matches_mat.shape),
)
cbar = fig.colorbar(pmesh, ax=axes[0, 0])
cbar.set_label('Probability from Distance [1]')
axes[0, 0].set_ylabel('Anomaly perturbation [deg]')
# pmesh = axes[1, 0].pcolormesh(
# incs_mat,
# nus_mat,
# zenith_prob.reshape(matches_mat.shape),
# )
# cbar = fig.colorbar(pmesh, ax=axes[1, 0])
# cbar.set_label('Probability from off-axis angle [1]')
# axes[1, 0].set_xlabel('Inclination perturbation [deg]')
# axes[1, 0].set_ylabel('Anomaly perturbation [deg]')
pmesh = axes[0, 1].pcolormesh(
incs_mat,
nus_mat,
diams_prob.reshape(matches_mat.shape),
)
cbar = fig.colorbar(pmesh, ax=axes[0, 1])
cbar.set_label('Probability for diameter [1]')
pmesh = axes[1, 1].pcolormesh(
incs_mat,
nus_mat,
sph_area.reshape(matches_mat.shape),
)
cbar = fig.colorbar(pmesh, ax=axes[1, 1])
cbar.set_label('Sample angular area [sr]')
axes[1, 1].set_xlabel('Inclination perturbation [deg]')
fig.savefig(results_folder / f'diam_prob_funcs.{args.format}')
plt.close(fig)
fig, ax = plt.subplots(figsize=(12, 8))
pmesh = ax.pcolormesh(
incs_mat,
nus_mat,
np.log10(1e2*diams_at_peak).reshape(matches_mat.shape),
)
cbar = fig.colorbar(pmesh, ax=ax)
cbar.set_label('Diameter at peak SNR [log10(cm)]')
ax.set_xlabel('Inclination perturbation [deg]')
ax.set_ylabel('Anomaly perturbation [deg]')
fig.savefig(results_folder / f'diam_peak_heat.{args.format}')
plt.close(fig)
peak_diams_mat = 1e2*diams_at_peak.reshape(matches_mat.shape)
peak_small_lim = np.percentile(np.log10(matches[np.logical_not(np.isnan(matches))]).flatten(), 2)
peak_bool_map = np.log10(matches_mat) <= peak_small_lim
# peak_bool_map = np.logical_and.reduce([
# incs_mat >= -0.1,
# incs_mat <= 0.1,
# nus_mat >= -0.04,
# nus_mat <= 0.02,
# ])
# THIS IS JUST FOR PAPER PLOT
fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True, sharey=True)
# __cmap = peak_diams_mat
__cmap = np.log10(peak_diams_mat)
__cmap[np.logical_not(peak_bool_map)] = np.nan
pmesh = axes[0].pcolormesh(
incs_mat,
nus_mat,
__cmap,
cmap=sorts.plotting.colors.get_cmap('sunset'),
)
axes[0].plot(incs[best_ind], nus[best_ind], 'or')
if not np.all(np.isnan(peak_diams_mat)):
axes[0].set_xlim(
np.min(incs_mat[peak_bool_map]),
np.max(incs_mat[peak_bool_map]),
)
axes[0].set_ylim(
np.min(nus_mat[peak_bool_map]),
np.max(nus_mat[peak_bool_map]),
)
cbar = fig.colorbar(pmesh, ax=axes[0])
# cbar.set_label('Diameter at peak SNR\n[cm]')
cbar.set_label('Diameter at peak SNR\n[log10(cm)]')
axes[0].set_ylabel('Anomaly perturbation [deg]')
__cmap = np.log10(matches_mat)
__cmap[np.logical_not(peak_bool_map)] = np.nan
pmesh = axes[1].pcolormesh(
incs_mat,
nus_mat,
__cmap,
cmap=sorts.plotting.colors.get_cmap('sunset'),
)
axes[1].plot(incs[best_ind], nus[best_ind], 'or')
cbar = fig.colorbar(pmesh, ax=axes[1])
cbar.set_label('Distance function\n[log10(1)]')
axes[1].set_xlabel('Inclination perturbation [deg]')
axes[1].set_ylabel('Anomaly perturbation [deg]')
fig.savefig(results_folder / f'filt_diam_peak_heat.{args.format}')
plt.close(fig)
fig, ax = plt.subplots(figsize=(12, 8))
ax.bar(
(diam_prob_bins[:-1] + diam_prob_bins[1:])*0.5,
diam_prob_dist,
align='center',
width=np.diff(diam_prob_bins),
)
ax.set_xlabel('Diameter at peak SNR [log10(cm)]')
ax.set_ylabel('Probability (from Distance function) [1]')
fig.savefig(results_folder / f'diam_prob_dist.{args.format}')
plt.close(fig)
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(np.log10(best_diams*1e2), best_matches, '.', label='Samples')
ax.plot(
np.log10(best_diams[0]*1e2),
best_matches[0],
'or',
label='Best match',
)
ax.set_xlabel('Diameter at peak SNR [log10(cm)]')
ax.set_ylabel('Distance function [1]')
fig.savefig(results_folder / f'diam_match_dist.{args.format}')
plt.close(fig)
mch_rank = 0
for mch_ind in best_matches_inds[:args.matches_plotted]:
mch_rank += 1
sn_s = SNR_sims[mch_ind]/np.max(SNR_sims[mch_ind])
sn_s[sn_s <= 0] = np.nan
dhit = matches[mch_ind]**2
if not np.isnan(metas[mch_ind][0]):
dhit -= metas[mch_ind][0]
if not np.isnan(metas[mch_ind][1]):
dhit -= metas[mch_ind][1]
match_data = [
metas[mch_ind][0],
metas[mch_ind][1],
dhit,
matches[mch_ind],
]
plot_match(
data, diams[mch_ind],
t_, dt, use_data,
sn_s, sn_m, gains[mch_ind],
mch_rank, results_folder, radar,
pths[mch_ind], args, epoch.iso, match_data,