-
Notifications
You must be signed in to change notification settings - Fork 13
/
eph_util.py
3728 lines (3170 loc) · 146 KB
/
eph_util.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
"""GNSS utility functions, mostly based on satellite ephemerides.
Author: Jonas Beuchert
"""
try:
import autograd.numpy as np
except(ImportError):
print("""Package 'autograd' not found. 'autograd.numpy' is necessary for
coarse-time navigation via maximum-likelihood estimation. Falling
back to 'numpy'.""")
import numpy as np
import pymap3d as pm
try:
import mkl_fft as fft_lib
except(ImportError):
print("""Package 'mkl_fft' not found. Consider installing 'mkl_fft' with
'conda install -c intel mkl_fft' for faster FFT and IFFT. Falling
back to 'numpy.fft'.""")
import numpy.fft as fft_lib
def get_sat_pos_vel_acc(t, eph):
"""Calculate positions, velocities, and accelerations of satellites.
Accepts arrays for t / eph, i.e., can calculate multiple points in time
/ multiple satellites at once.
Does not interpolate GLONASS.
Implemented according to
Thompson, Blair F., et al. “Computing GPS Satellite Velocity and
Acceleration from the Broadcast Navigation Message.” Annual of
Navigation, vol. 66, no. 4, 2019, pp. 769–779.
https://www.gps.gov/technical/icwg/meetings/2019/09/GPS-SV-velocity-and-acceleration.pdf
Inputs:
t - GPS time(s) [s] (ignored for SBAS)
eph - Ephemeris as array(s)
Outputs:
positions - Satellite position(s) in ECEF XYZ as array(s) [m]
velocities - Satellite velocity/ies in ECEF XYZ as array(s) [m/s]
accelerations - Sat. acceleration(s) in ECEF XYZ as array(s) [m/s^2]
Author: Jonas Beuchert
"""
if not np.isnan(eph[2]).any(): # No SBAS / GLONASS
t = np.mod(t, 7 * 24 * 60 * 60)
cic = eph[13] # "cic"]
crs = eph[10] # "crs"]
Omega0 = eph[15] # "Omega0"]
Deltan = eph[4] # "Deltan"]
cis = eph[14] # "cis"]
M0 = eph[2] # "M0"]
i0 = eph[11] # "i0"]
cuc = eph[7] # "cuc"]
crc = eph[9] # "crc"]
e = eph[5] # "e"]
Omega = eph[6] # "Omega"]
cus = eph[8] # "cus"]
OmegaDot = eph[16] # "OmegaDot"]
sqrtA = eph[3] # "sqrtA"]
IDOT = eph[12] # "IDOT"]
toe = eph[20] # "toe"]
# Broadcast Navigation User Equations
# WGS 84 value of the earth’s gravitational constant for GPS user [m^3/s^2]
mu = 3.986005e14
# WGS 84 value of the earth’s rotation rate [rad/s]
OmegaeDot = 7.2921151467e-5
# Semi-major axis
A = sqrtA ** 2
# Computed mean motion [rad/s]
n0 = np.sqrt(mu / A ** 3)
# Time from ephemeris reference epoch
tk = np.array(t - toe)
# t is GPS system time at time of transmission, i.e., GPS time corrected
# for transit time (range/speed of light). Furthermore, tk shall be the
# actual total time difference between the time t and the epoch time toe,
# and must account for beginning or end of week crossovers. That is, if tk
# is greater than 302,400 seconds, subtract 604,800 seconds from tk. If tk
# is less than -302,400 seconds, add 604,800 seconds to tk.
with np.nditer(tk, op_flags=["readwrite"]) as it:
for tk_i in it:
if tk_i > 302400:
tk_i[...] = tk_i - 604800
elif tk_i < -302400:
tk_i[...] = tk_i + 604800
# Corrected mean motion
n = n0 + Deltan
# Mean anomaly
Mk = M0 + n * tk
# Kepler’s equation (Mk = Ek - e*np.sin(Ek)) solved for eccentric anomaly
# (Ek) by iteration:
# Initial value [rad]
Ek = Mk
# Refined value, three iterations, (j = 0,1,2)
for j in range(3):
Ek = Ek + (Mk - Ek + e * np.sin(Ek)) / (1 - e * np.cos(Ek))
# True anomaly (unambiguous quadrant)
nuk = 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ek / 2))
# Argument of Latitude
Phik = nuk + Omega
# Argument of Latitude Correction
deltauk = cus * np.sin(2 * Phik) + cuc * np.cos(2 * Phik)
# Radius Correction
deltark = crs * np.sin(2 * Phik) + crc * np.cos(2 * Phik)
# Inclination Correction
deltaik = cis * np.sin(2 * Phik) + cic * np.cos(2 * Phik)
# Corrected Argument of Latitude
uk = Phik + deltauk
# Corrected Radius
rk = A * (1 - e * np.cos(Ek)) + deltark
# Corrected Inclination
ik = i0 + deltaik + IDOT * tk
# Positions in Orbital Plane
xkDash = rk * np.cos(uk)
ykDash = rk * np.sin(uk)
# Corrected longitude of ascending node
Omegak = Omega0 + (OmegaDot - OmegaeDot) * tk - OmegaeDot * toe
# Earth-fixed coordinates
xk = xkDash * np.cos(Omegak) - ykDash * np.cos(ik) * np.sin(Omegak)
yk = xkDash * np.sin(Omegak) + ykDash * np.cos(ik) * np.cos(Omegak)
zk = ykDash * np.sin(ik)
# SV Velocity
# Eccentric anomaly rate
EkDot = n / (1 - e * np.cos(Ek))
# True anomaly rate
nukDot = EkDot * np.sqrt(1 - e ** 2) / (1 - e * np.cos(Ek))
# Corrected Inclination rate
dik_dt = IDOT + 2 * nukDot * (
cis * np.cos(2 * Phik) - cic * np.sin(2 * Phik)
)
# Corrected Argument of Latitude rate
ukDot = nukDot + 2 * nukDot * (
cus * np.cos(2 * Phik) - cuc * np.sin(2 * Phik)
)
# Corrected Radius rate
rkDot = e * A * EkDot * np.sin(Ek) + 2 * nukDot * (
crs * np.cos(2 * Phik) - crc * np.sin(2 * Phik)
)
# Longitude of ascending node rate
OmegakDot = OmegaDot - OmegaeDot
# In-plane x velocity
xkDashDot = rkDot * np.cos(uk) - rk * ukDot * np.sin(uk)
# In-plane y velocity
ykDashDot = rkDot * np.sin(uk) + rk * ukDot * np.cos(uk)
# Earth-fixed x velocity [m/s]
xkDot = (
-xkDash * OmegakDot * np.sin(Omegak)
+ xkDashDot * np.cos(Omegak)
- ykDashDot * np.sin(Omegak) * np.cos(ik)
- ykDash
* (
OmegakDot * np.cos(Omegak) * np.cos(ik)
- dik_dt * np.sin(Omegak) * np.sin(ik)
)
)
# Earth-fixed y velocity [m/s]
ykDot = (
xkDash * OmegakDot * np.cos(Omegak)
+ xkDashDot * np.sin(Omegak)
+ ykDashDot * np.cos(Omegak) * np.cos(ik)
- ykDash
* (
OmegakDot * np.sin(Omegak) * np.cos(ik)
+ dik_dt * np.cos(Omegak) * np.sin(ik)
)
)
# Earth-fixed z velocity [m/s]
zkDot = ykDash * dik_dt * np.cos(ik) + ykDashDot * np.sin(ik)
# SV Acceleration
# WGS 84 Earth equatorial radius [m]
RE = 6378137.0
# Oblate Earth gravity coefficient
J2 = 0.0010826262
# Oblate Earth acceleration factor
F = -3 / 2 * J2 * mu / rk ** 2 * (RE / rk) ** 2
# Earth-fixed x acceleration [m/s^2]
xkDotDot = (
-mu * xk / rk ** 3
+ F * ((1 - 5 * (zk / rk) ** 2) * xk / rk)
+ 2 * ykDot * OmegaeDot
+ xk * OmegaeDot ** 2
)
# Earth-fixed y acceleration [m/s^2]
ykDotDot = (
-mu * yk / rk ** 3
+ F * ((1 - 5 * (zk / rk) ** 2) * yk / rk)
- 2 * xkDot * OmegaeDot
+ yk * OmegaeDot ** 2
)
# Earth-fixed z acceleration [m/s^2]
zkDotDot = -mu * zk / rk ** 3 + F * ((3 - 5 * (zk / rk) ** 2) * zk / rk)
positions = np.array([xk, yk, zk]).T
velocities = np.array([xkDot, ykDot, zkDot]).T
accelerations = np.array([xkDotDot, ykDotDot, zkDotDot]).T
else: # SBAS
positions = 1.0e3 * np.array([eph[3], eph[6], eph[9]]).T
velocities = 1.0e3 * np.array([eph[4], eph[7], eph[10]]).T
accelerations = 1.0e3 * np.array([eph[5], eph[8], eph[11]]).T
if isinstance(t, np.ndarray) and len(eph.shape) == 1:
n_times = t.shape[0]
positions = np.tile(positions, (n_times, 1))
velocities = np.tile(velocities, (n_times, 1))
accelerations = np.tile(accelerations, (n_times, 1))
return positions, velocities, accelerations
def get_sat_pos_vel(t, eph):
"""Calculate positions and velocities of satellites.
Accepts arrays for t / eph, i.e., can calculate multiple points in time
/ multiple satellites at once.
Does not interpolate GLONASS.
Implemented according to
Thompson, Blair F., et al. “Computing GPS Satellite Velocity and
Acceleration from the Broadcast Navigation Message.” Annual of
Navigation, vol. 66, no. 4, 2019, pp. 769–779.
https://www.gps.gov/technical/icwg/meetings/2019/09/GPS-SV-velocity-and-acceleration.pdf
Inputs:
t - GPS time(s) [s] (ignored for SBAS)
eph - Ephemeris as array(s)
Outputs:
positions - Satellite position(s) in ECEF XYZ as array(s) [m]
velocities - Satellite velocity/ies in ECEF XYZ as array(s) [m/s]
Author: Jonas Beuchert
"""
if not np.isnan(eph[2]).any(): # No SBAS / GLONASS
t = np.mod(t, 7 * 24 * 60 * 60)
cic = eph[13] # "cic"]
crs = eph[10] # "crs"]
Omega0 = eph[15] # "Omega0"]
Deltan = eph[4] # "Deltan"]
cis = eph[14] # "cis"]
M0 = eph[2] # "M0"]
i0 = eph[11] # "i0"]
cuc = eph[7] # "cuc"]
crc = eph[9] # "crc"]
e = eph[5] # "e"]
Omega = eph[6] # "Omega"]
cus = eph[8] # "cus"]
OmegaDot = eph[16] # "OmegaDot"]
sqrtA = eph[3] # "sqrtA"]
IDOT = eph[12] # "IDOT"]
toe = eph[20] # "toe"]
# Broadcast Navigation User Equations
# WGS 84 value of the earth’s gravitational constant for GPS user [m^3/s^2]
mu = 3.986005e14
# WGS 84 value of the earth’s rotation rate [rad/s]
OmegaeDot = 7.2921151467e-5
# Semi-major axis
A = sqrtA ** 2
# Computed mean motion [rad/s]
n0 = np.sqrt(mu / A ** 3)
# Time from ephemeris reference epoch
tk = np.array(t - toe)
# t is GPS system time at time of transmission, i.e., GPS time corrected
# for transit time (range/speed of light). Furthermore, tk shall be the
# actual total time difference between the time t and the epoch time toe,
# and must account for beginning or end of week crossovers. That is, if tk
# is greater than 302,400 seconds, subtract 604,800 seconds from tk. If tk
# is less than -302,400 seconds, add 604,800 seconds to tk.
with np.nditer(tk, op_flags=["readwrite"]) as it:
for tk_i in it:
if tk_i > 302400:
tk_i[...] = tk_i - 604800
elif tk_i < -302400:
tk_i[...] = tk_i + 604800
# Corrected mean motion
n = n0 + Deltan
# Mean anomaly
Mk = M0 + n * tk
# Kepler’s equation (Mk = Ek - e*np.sin(Ek)) solved for eccentric anomaly
# (Ek) by iteration:
# Initial value [rad]
Ek = Mk
# Refined value, three iterations, (j = 0,1,2)
for j in range(3):
Ek = Ek + (Mk - Ek + e * np.sin(Ek)) / (1 - e * np.cos(Ek))
# True anomaly (unambiguous quadrant)
nuk = 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ek / 2))
# Argument of Latitude
Phik = nuk + Omega
# Argument of Latitude Correction
deltauk = cus * np.sin(2 * Phik) + cuc * np.cos(2 * Phik)
# Radius Correction
deltark = crs * np.sin(2 * Phik) + crc * np.cos(2 * Phik)
# Inclination Correction
deltaik = cis * np.sin(2 * Phik) + cic * np.cos(2 * Phik)
# Corrected Argument of Latitude
uk = Phik + deltauk
# Corrected Radius
rk = A * (1 - e * np.cos(Ek)) + deltark
# Corrected Inclination
ik = i0 + deltaik + IDOT * tk
# Positions in Orbital Plane
xkDash = rk * np.cos(uk)
ykDash = rk * np.sin(uk)
# Corrected longitude of ascending node
Omegak = Omega0 + (OmegaDot - OmegaeDot) * tk - OmegaeDot * toe
# Earth-fixed coordinates
xk = xkDash * np.cos(Omegak) - ykDash * np.cos(ik) * np.sin(Omegak)
yk = xkDash * np.sin(Omegak) + ykDash * np.cos(ik) * np.cos(Omegak)
zk = ykDash * np.sin(ik)
# SV Velocity
# Eccentric anomaly rate
EkDot = n / (1 - e * np.cos(Ek))
# True anomaly rate
nukDot = EkDot * np.sqrt(1 - e ** 2) / (1 - e * np.cos(Ek))
# Corrected Inclination rate
dik_dt = IDOT + 2 * nukDot * (
cis * np.cos(2 * Phik) - cic * np.sin(2 * Phik)
)
# Corrected Argument of Latitude rate
ukDot = nukDot + 2 * nukDot * (
cus * np.cos(2 * Phik) - cuc * np.sin(2 * Phik)
)
# Corrected Radius rate
rkDot = e * A * EkDot * np.sin(Ek) + 2 * nukDot * (
crs * np.cos(2 * Phik) - crc * np.sin(2 * Phik)
)
# Longitude of ascending node rate
OmegakDot = OmegaDot - OmegaeDot
# In-plane x velocity
xkDashDot = rkDot * np.cos(uk) - rk * ukDot * np.sin(uk)
# In-plane y velocity
ykDashDot = rkDot * np.sin(uk) + rk * ukDot * np.cos(uk)
# Earth-fixed x velocity [m/s]
xkDot = (
-xkDash * OmegakDot * np.sin(Omegak)
+ xkDashDot * np.cos(Omegak)
- ykDashDot * np.sin(Omegak) * np.cos(ik)
- ykDash
* (
OmegakDot * np.cos(Omegak) * np.cos(ik)
- dik_dt * np.sin(Omegak) * np.sin(ik)
)
)
# Earth-fixed y velocity [m/s]
ykDot = (
xkDash * OmegakDot * np.cos(Omegak)
+ xkDashDot * np.sin(Omegak)
+ ykDashDot * np.cos(Omegak) * np.cos(ik)
- ykDash
* (
OmegakDot * np.sin(Omegak) * np.cos(ik)
+ dik_dt * np.cos(Omegak) * np.sin(ik)
)
)
# Earth-fixed z velocity [m/s]
zkDot = ykDash * dik_dt * np.cos(ik) + ykDashDot * np.sin(ik)
positions = np.array([xk, yk, zk]).T
velocities = np.array([xkDot, ykDot, zkDot]).T
else: # SBAS
positions = 1.0e3 * np.array([eph[3], eph[6], eph[9]]).T
velocities = 1.0e3 * np.array([eph[4], eph[7], eph[10]]).T
if isinstance(t, np.ndarray) and len(eph.shape) == 1:
n_times = t.shape[0]
positions = np.tile(positions, (n_times, 1))
velocities = np.tile(velocities, (n_times, 1))
return positions, velocities
def get_sat_pos(t, eph):
"""Calculate positions of satellites.
Accepts arrays for t / eph, i.e., can calculate multiple points in time
/ multiple satellites at once.
Does not interpolate GLONASS.
Implemented according to
Thompson, Blair F., et al. “Computing GPS Satellite Velocity and
Acceleration from the Broadcast Navigation Message.” Annual of
Navigation, vol. 66, no. 4, 2019, pp. 769–779.
https://www.gps.gov/technical/icwg/meetings/2019/09/GPS-SV-velocity-and-acceleration.pdf
Inputs:
t - GPS time(s) [s] (ignored for SBAS)
eph - Ephemeris as array(s)
Outputs:
positions - Satellite position(s) in ECEF XYZ as array(s) [m]
Author: Jonas Beuchert
"""
if not np.isnan(eph[2]).any(): # No SBAS / GLONASS
t = np.mod(t, 7 * 24 * 60 * 60)
cic = eph[13] # "cic"]
crs = eph[10] # "crs"]
Omega0 = eph[15] # "Omega0"]
Deltan = eph[4] # "Deltan"]
cis = eph[14] # "cis"]
M0 = eph[2] # "M0"]
i0 = eph[11] # "i0"]
cuc = eph[7] # "cuc"]
crc = eph[9] # "crc"]
e = eph[5] # "e"]
Omega = eph[6] # "Omega"]
cus = eph[8] # "cus"]
OmegaDot = eph[16] # "OmegaDot"]
sqrtA = eph[3] # "sqrtA"]
IDOT = eph[12] # "IDOT"]
toe = eph[20] # "toe"]
# Broadcast Navigation User Equations
# WGS 84 value of the earth’s gravitational constant for GPS user [m^3/s^2]
mu = 3.986005e14
# WGS 84 value of the earth’s rotation rate [rad/s]
OmegaeDot = 7.2921151467e-5
# Semi-major axis
A = sqrtA ** 2
# Computed mean motion [rad/s]
n0 = np.sqrt(mu / A ** 3)
# Time from ephemeris reference epoch
tk = np.array(t - toe)
# t is GPS system time at time of transmission, i.e., GPS time corrected
# for transit time (range/speed of light). Furthermore, tk shall be the
# actual total time difference between the time t and the epoch time toe,
# and must account for beginning or end of week crossovers. That is, if tk
# is greater than 302,400 seconds, subtract 604,800 seconds from tk. If tk
# is less than -302,400 seconds, add 604,800 seconds to tk.
try:
with np.nditer(tk, op_flags=["readwrite"]) as it:
for tk_i in it:
if tk_i > 302400:
tk_i[...] = tk_i - 604800
elif tk_i < -302400:
tk_i[...] = tk_i + 604800
except TypeError:
for idx in np.arange(tk.shape[0]):
if tk[idx] > 302400:
tk[idx] = tk[idx] - 604800
elif tk[idx] < -302400:
tk[idx] = tk[idx] + 604800
# Corrected mean motion
n = n0 + Deltan
# Mean anomaly
Mk = M0 + n * tk
# Kepler’s equation (Mk = Ek - e*np.sin(Ek)) solved for eccentric anomaly
# (Ek) by iteration:
# Initial value [rad]
Ek = Mk
# Refined value, three iterations, (j = 0,1,2)
for j in range(3):
Ek = Ek + (Mk - Ek + e * np.sin(Ek)) / (1 - e * np.cos(Ek))
# True anomaly (unambiguous quadrant)
nuk = 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ek / 2))
# Argument of Latitude
Phik = nuk + Omega
# Argument of Latitude Correction
deltauk = cus * np.sin(2 * Phik) + cuc * np.cos(2 * Phik)
# Radius Correction
deltark = crs * np.sin(2 * Phik) + crc * np.cos(2 * Phik)
# Inclination Correction
deltaik = cis * np.sin(2 * Phik) + cic * np.cos(2 * Phik)
# Corrected Argument of Latitude
uk = Phik + deltauk
# Corrected Radius
rk = A * (1 - e * np.cos(Ek)) + deltark
# Corrected Inclination
ik = i0 + deltaik + IDOT * tk
# Positions in Orbital Plane
xkDash = rk * np.cos(uk)
ykDash = rk * np.sin(uk)
# Corrected longitude of ascending node
Omegak = Omega0 + (OmegaDot - OmegaeDot) * tk - OmegaeDot * toe
# Earth-fixed coordinates
xk = xkDash * np.cos(Omegak) - ykDash * np.cos(ik) * np.sin(Omegak)
yk = xkDash * np.sin(Omegak) + ykDash * np.cos(ik) * np.cos(Omegak)
zk = ykDash * np.sin(ik)
positions = np.array([xk, yk, zk]).T
else: # SBAS
positions = 1.0e3 * np.array([eph[3], eph[6], eph[9]]).T
if isinstance(t, np.ndarray) and len(eph.shape) == 1:
n_times = t.shape[0]
positions = np.tile(positions, (n_times, 1))
return positions
def get_sat_pos_sp3(gps_time, sp3, sv_list, system=None):
"""Calculate positions of satellites from precise orbits (SP3 file).
Inputs:
gps_time - GPS times [s] as numpy array
sp3 - Precise orbit supporting points as pandas.DataFrame from read_sp3
sv_list - Satellite indices (PRNs)
system - Character representing satellite navigation system:
'G' - GPS
'S' - SBAS
'R' - GLONASS
'E' - Galileo
'C' - BeiDou
'J' - QZSS
'I' - NavIC
None - Use character of 1st SP3 entry (default)
Output:
position - Satellite positions in ECEF XYZ as Nx3 array [m]
Author: Jonas Beuchert
Based on https://github.com/GNSSpy-Project/gnsspy/blob/fce079af37d585dc757c56539a98cc0dfe66f9de/gnsspy/position/interpolation.py
"""
def coord_interp(parameter):
"""
Interpolation of SP3 coordinates.
Fit polynomial to 4 hours (14400 seconds) period of SP3 Cartesian
coordinates and return to the interpolated coordinates.
Input:
parameter - Polynomial coefficients from numpy polyfit function
(numpy array)
Output:
interp_coord - Interpolated coordinates (numpy array)
"""
epoch = 0.0
time = np.array([
epoch**deg for deg in range(len(parameter)-1, -1, -1)
])
return np.matmul(parameter, time)
import pandas as pd
# Degree of polynomial interpolation, lower than 11 not recommended, above
# 16 not applicable for 15 minute intervals
poly_degree = 16
# Convert time
referenceDate = np.datetime64('1980-01-06') # GPS reference date
utc = np.timedelta64(int((gps_time[0]) * 1e9), 'ns') + referenceDate
# Check if numpy array has been passed for sv_list
if isinstance(sv_list, np.ndarray):
# Convert numpy array to list
sv_list = sv_list.astype(int).tolist()
# Check if system character must be read from SP3
if system is None:
# Use system character of 1st entry
system = sp3.index[0][1][0]
# Convert sv_list to strings
sv_list = [system + "{:02d}".format(sv) for sv in sv_list]
# Get time stamps
epoch_values = sp3.index.get_level_values("Epoch").unique()
# Difference between 2 time stamps
deltaT = epoch_values[1]-epoch_values[0]
# Get 17 data points
epoch_start = utc - np.timedelta64(2, 'h')
epoch_stop = utc + np.timedelta64(2, 'h') + deltaT
sp3_temp = sp3.loc[(slice(epoch_start, epoch_stop))].copy()
sp3_temp = sp3_temp.reorder_levels(["SV", "Epoch"])
# Initialize result
epoch_interp_List = np.zeros(shape=(len(sv_list), 3))
# Iterate over all satellites
for svIndex, sv in enumerate(sv_list):
fitTime = np.array([
(np.datetime64(t) - referenceDate) / np.timedelta64(1, 's')
- gps_time[svIndex]
for t in sp3_temp.loc[sv_list[0]].index.get_level_values("Epoch")
])
epoch_number = len(sp3_temp.loc[sv])
if epoch_number <= poly_degree:
print("Warning: Not enough epochs to predict for satellite",
sv, "| Epoch Count:", epoch_number, " - Polynomial Degree:",
poly_degree)
epoch_interp_List[svIndex, :] = np.full(shape=3, fill_value=None)
continue
# if epoch_number != 17:
# fitTime = [(sp3_temp.loc[sv].index[t]
# - sp3_temp.loc[sv].index[0]).seconds
# for t in range(epoch_number)]
# Fit sp3 coordinates to 16 deg polynomial
fitX = np.polyfit(fitTime, sp3_temp.loc[sv].X.copy(), deg=poly_degree)
fitY = np.polyfit(fitTime, sp3_temp.loc[sv].Y.copy(), deg=poly_degree)
fitZ = np.polyfit(fitTime, sp3_temp.loc[sv].Z.copy(), deg=poly_degree)
# sidereal_day = 0.99726956634
# period = sidereal_day
# P0 = 2.0*np.pi / period
# gps_day_sec = np.mod(gps_time, 24*60*60)
# gps_rel_time = gps_day_sec / 86400.0
# Timei = fitTime + gps_day_sec
# Timei = Timei / 86400.0
# Xi = sp3_temp.loc[sv].X.copy()
# Yi = sp3_temp.loc[sv].Y.copy()
# Zi = sp3_temp.loc[sv].Z.copy()
# A = np.zeros((poly_degree+1, poly_degree+1))
# A[:, 0] = np.ones(poly_degree+1)
# B = np.zeros(poly_degree+1)
# B[0] = 1.0
# ND = np.int((poly_degree) / 2)
# for i in np.arange(ND):
# kk = 1 + i*2
# P = P0 * (i+1)
# A[:, kk] = np.sin(P*Timei)
# A[:, kk+1] = np.cos(P*Timei)
# B[kk] = np.sin(P*gps_rel_time)
# B[kk+1] = np.cos(P*gps_rel_time)
# XCoeffs = np.linalg.lstsq(A, Xi, rcond=None)[0]
# YCoeffs = np.linalg.lstsq(A, Yi, rcond=None)[0]
# ZCoeffs = np.linalg.lstsq(A, Zi, rcond=None)[0]
# epoch_interp_List[svIndex, :] = 1000.0*np.array(
# [B@XCoeffs, B@YCoeffs, B@ZCoeffs]
# )
# Interpolate coordinates
x_interp = coord_interp(fitX) * 1000 # km to m
# x_velocity = _np.array([(x_interp[i+1]-x_interp[i])/interval if (i+1)<len(x_interp) else 0 for i in range(len(x_interp))])
y_interp = coord_interp(fitY) * 1000 # km to m
# y_velocity = _np.array([(y_interp[i+1]-y_interp[i])/interval if (i+1)<len(y_interp) else 0 for i in range(len(y_interp))])
z_interp = coord_interp(fitZ) * 1000 # km to m
# z_velocity = _np.array([(z_interp[i+1]-z_interp[i])/interval if (i+1)<len(z_interp) else 0 for i in range(len(z_interp))])
sv_interp = np.vstack((x_interp, y_interp, z_interp))
epoch_interp_List[svIndex, :] = sv_interp[:, 0]
# Restore original fitTime in case it has changed
# fitTime = np.linspace(0.0, deltaT.seconds*16.0, 17)
return epoch_interp_List
def find_eph(eph, sv, time):
"""Find the proper column in ephemeris array.
Inputs:
eph - Ephemeris array
sv - Satellite index (PRNs)
time - GPS time of week [s]
Output:
icol - Column index, NaN if ephemeris does not contain satellite
"""
icol = 0
isat = np.where(eph[0] == sv)[0]
n = isat.size
if n == 0:
return np.NaN
icol = isat[0]
dtmin = eph[20, icol] - time
for t in isat:
dt = eph[20, t] - time
if dt < 0:
if abs(dt) < abs(dtmin):
icol = t
dtmin = dt
return icol
def check_t(time):
"""Account for beginning or end of week crossover.
Input:
time - Time [s]
Output:
corrTime - Corrected time [s]
"""
half_week = 302400 # [s]
corrTime = time
if time > half_week:
corrTime = time - 2 * half_week
elif time < -half_week:
corrTime = time + 2 * half_week
return corrTime
def check_t_vectorized(time):
"""Account for beginning or end of week crossover.
Input:
time - Time [s], numpy.ndarray
Output:
corrTime - Corrected time [s]
"""
half_week = 302400 # [s]
corrTime = time
corrTime[time > half_week] = time[time > half_week] - 2 * half_week
corrTime[time < -half_week] = corrTime[time < -half_week] + 2 * half_week
return corrTime
def get_sat_clk_corr(transmit_time, prn, eph):
"""Compute satellite clock correction time.
Without relativistic correction.
Ephemeris provided as array.
Inputs:
transmit_time - Actual time when signal was transmitted [s]
prn - Satellite's PRN index (array)
eph - Ephemeris array
Output:
satClockCorr - Satellite clock corrections [s]
Author: Jonas Beuchert
"""
# GPS time with respect to 1980 to time of week (TOW)
transmit_time = np.mod(transmit_time, 7 * 24 * 60 * 60)
# Get ephemerides (find column of ephemeris matrix that matches satellite
# index and time)
if eph.ndim > 1 and eph.shape[1] != prn.shape[0]:
col = np.array([find_eph(eph, prn_i, transmit_time) for prn_i in prn])
eph = eph[:, col] # Extract column
# Find initial satellite clock correction
# Find time difference
dt = np.array([check_t(transmit_time - eph_20) for eph_20 in eph[20]])
# Calculate clock correction
satClkCorr = (eph[1] * dt + eph[19]) * dt + eph[19] # - eph.T_GD
# Apply correction
time = transmit_time - satClkCorr
# Find time difference
dt = np.array([check_t(t_eph_20) for t_eph_20 in time - eph[20]])
# Calculate clock correction
return (eph[1] * dt + eph[19]) * dt + eph[18]
# - eph.T_GD
def get_sat_clk_corr_vectorized(transmit_time, prn, eph):
"""Compute satellite clock correction time.
Without relativistic correction.
Navigation data provided as 2D NumPy array; transmission time and PRNs
provided as 1D NumPy array.
Inputs:
transmit_time - Actual times when signals were transmitted [s] (Nx1 array)
prn - Satellite's PRN indices (Nx1 array)
eph - Matching navigation data (21xN array)
Output:
sat_clock_corr - Satellite clock corrections [s] (Nx1 array)
Author: Jonas Beuchert
"""
# GPS time with respect to 1980 to time of week (TOW)
transmit_time = np.mod(transmit_time, 7 * 24 * 60 * 60)
# Get ephemerides (find column of ephemeris matrix that matches satellite
# index and time)
if eph.shape[1] != prn.shape[0]:
col = np.array([find_eph(eph, prn_i, transmit_time) for prn_i in prn])
eph = eph[:, col] # Extract column
# Find initial satellite clock correction
# Find time difference
dt = check_t_vectorized(transmit_time - eph[20])
# Calculate clock correction
satClkCorr = (eph[1] * dt + eph[19]) * dt + eph[19] # - eph.T_GD
# Apply correction
time = transmit_time - satClkCorr
# Find time difference
dt = check_t_vectorized(time - eph[20])
# Calculate clock correction
return (eph[1] * dt + eph[19]) * dt + eph[18]
# - eph.T_GD
def get_visible_sats(ht, p, eph, elev_mask=0, prn_list=range(1, 33)):
"""Estimate set of visible satellites.
Ephemeris provided as array.
Inputs:
ht - Receiver time hypothesis [s]
p - Receiver position hypothesis (latitude, longitude, elevation)
eph - Ephemeris as matrix
elev_mask - [Optional] Elevation mask: minimum elevation for satellite
to be considered to be visible [degrees], default 0
prn_list - [Optional] PRNs of satellites to search for, default 1-32
Output:
visSat - Indices of visible satellites
Author: Jonas Beuchert
"""
ht = np.mod(ht, 7 * 24 * 60 * 60)
# Crude transmit time estimate [s]
t = ht - 76.5e-3
# Empty array for result
visSat = np.array([], dtype=int)
# Loop over all satellite indices
for prn in prn_list:
col = find_eph(eph, prn, t)
if not np.isnan(col):
ephSat = eph[:, col]
# Get satellite position at estimated transmit time
satPos = get_sat_pos(t, ephSat)
if not np.isnan(satPos).any():
az, elev, slantRange = pm.ecef2aer(
satPos[0], satPos[1], satPos[2], p[0], p[1], p[2]
)
# Satellites with elevation larger than threshold
if elev > elev_mask:
# Add satellite index to result
visSat = np.append(visSat, prn)
return visSat
def get_doppler(ht, R, k, eph):
"""Calculate expected Doppler [Hz] for given time and position hypothesis.
Inputs:
ht - Time hypothesis (receiver) [s]
R - Receiver position (ECEF) [m,m,m]
k - Satellite index (PRN)
eph - Ephemeris
Output:
D - Doppler shift frequency [Hz]
Author: Jonas Beuchert
"""
# Speed of light [m/s]
c = 299792458
# Crude transmit time estimate [s]
t = ht - 76.5e-3
# GPS time with respect to 1980 to time of week (TOW)
tow = np.mod(t, 7 * 24 * 60 * 60)
# Find column of ephemeris matrix that matches satellite index and time
col = find_eph(eph, k, tow)
if np.isnan(col):
return np.NaN
else:
# Extract column
eph = eph[:, col]
for it in range(2): # 2 iterations to refine transmit time estimate
p = get_sat_pos(t, eph) # Satellite position estimate [m,m,m]
d = np.linalg.norm(R - p) / c # Propagation delay estimate [s]
t = ht - d # Transmit time estimate [s]
L1 = 1575.42e6 # GPS signal frequency [Hz]
P, V = get_sat_pos_vel(t, eph) # Satellite velocity [m/s,m/s,m/s]
lambd = c / L1 # Wave length of transmitted signal
# Doppler shift (cf. 'Cycle slip detection in single frequency GPS carrier
# phase observations using expected Doppler shift')
return (np.dot((R - P) / np.linalg.norm(R - P), V) / lambd)
def generate_ca_code(PRN):
"""Generate one of the GPS, EGNOS, or WAAS satellite C/A codes.
Input:
PRN - PRN number of the sequence
Output:
CAcode - Array containing the desired C/A code sequence (chips)
Author: Jonas Beuchert
"""
# Make the code shift array; the shift depends on the PRN number
# The g2s vector holds the appropriate shift of the g2 code to generate
# the C/A code (ex. for SV#19 - use a G2 shift of g2s(19) = 471)
g2s = [
5,
6,
7,
8,
17,
18,
139,
140,
141,
251,
252,
254,
255,
256,
257,
258,
469,
470,
471,
472,
473,
474,
509,
512,
513,