-
Notifications
You must be signed in to change notification settings - Fork 112
/
gauss_method.py
1842 lines (1549 loc) · 80.9 KB
/
gauss_method.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
"""Implements Gauss' method for three topocentric right ascension and
declination measurements of celestial bodies. Supports both Earth-centered and
Sun-centered orbits."""
import numpy as np
from astropy.coordinates import Longitude, SkyCoord
from astropy.coordinates import solar_system_ephemeris, get_body_barycentric
from astropy import units as uts
from astropy import constants as cts
from astropy.time import Time
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from poliastro.stumpff import c2, c3
from astropy.coordinates.earth_orientation import obliquity
from astropy.coordinates.matrix_utilities import rotation_matrix
import argparse
# declare astronomical constants in appropriate units
au = cts.au.to(uts.Unit('km')).value
mu_Sun = cts.GM_sun.to(uts.Unit('au3 / day2')).value
mu_Earth = cts.GM_earth.to(uts.Unit('km3 / s2')).value
c_light = cts.c.to(uts.Unit('au/day'))
earth_f = 0.003353
Re = cts.R_earth.to(uts.Unit('km')).value
# load JPL DE432s ephemeris SPK kernel
# 'de432s.bsp' is automatically loaded by astropy, via jplephem
# 'de432s.bsp' is about 10MB in size and will be automatically downloaded if not present yet in astropy's cache
# for more information, see astropy.coordinates.solar_system_ephemeris documentation
solar_system_ephemeris.set('de432s')
#compute rotation matrices from equatorial to ecliptic frame and viceversa
obliquity_j2000 = obliquity(2451544.5) # mean obliquity of the ecliptic at J2000.0
rot_equat_to_eclip = rotation_matrix( obliquity_j2000, 'x') #rotation matrix from equatorial to ecliptic frames
rot_eclip_to_equat = rotation_matrix(-obliquity_j2000, 'x') #rotation matrix from ecliptic to equatorial frames
# set output from printed arrays at full precision
np.set_printoptions(precision=16)
# convention:
# a: semi-major axis
# e: eccentricity
# taup: time of pericenter passage
# Euler angles:
# omega: argument of pericenter
# I: inclination
# Omega: longitude of ascending node
#rotation about the z-axis about an angle `ang`
def rotz(ang):
cos_ang = np.cos(ang)
sin_ang = np.sin(ang)
return np.array(((cos_ang,-sin_ang,0.0), (sin_ang, cos_ang,0.0), (0.0,0.0,1.0)))
#rotation about the x-axis about an angle `ang`
def rotx(ang):
cos_ang = np.cos(ang)
sin_ang = np.sin(ang)
return np.array(((1.0,0.0,0.0), (0.0,cos_ang,-sin_ang), (0.0,sin_ang,cos_ang)))
#rotation from the orbital plane to the inertial frame
#it is composed of the following rotations, in that order:
#1) rotation about the z axis about an angle `omega` (argument of pericenter)
#2) rotation about the x axis about an angle `I` (inclination)
#3) rotation about the z axis about an angle `Omega` (longitude of ascending node)
def orbplane2frame_(omega,I,Omega):
P2_mul_P3 = np.matmul(rotx(I),rotz(omega))
return np.matmul(rotz(Omega),P2_mul_P3)
def orbplane2frame(x):
return orbplane2frame_(x[0],x[1],x[2])
# get Keplerian range
def kep_r_(a, e, f):
return a*(1.0-e**2)/(1.0+e*np.cos(f))
def kep_r(x):
return kep_r_(x[0],x[1],x[2])
# get cartesian positions wrt orbital plane
def xyz_orbplane_(a, e, f):
r = kep_r_(a, e, f)
return np.array((r*np.cos(f),r*np.sin(f),0.0))
def xyz_orbplane(x):
return xyz_orbplane_(x[0],x[1],x[2])
# get cartesian positions wrt inertial frame from orbital elements
def xyz_frame2(a,e,f,omega,I,Omega):
return np.matmul( orbplane2frame_(omega,I,Omega) , xyz_orbplane_(a, e, f) )
def xyz_frame(x):
return np.matmul( orbplane2frame(x[3:6]) , xyz_orbplane(x[0:3]) )
# get mean motion from mass parameter (mu) and semimajor axis (a)
def meanmotion(mu,a):
return np.sqrt(mu/(a**3))
# get mean anomaly from mean motion (n), time (t) and time of pericenter passage (taup)
def meananomaly(n, t, taup):
return np.mod(n*(t-taup), 2.0*np.pi)
# compute eccentric anomaly (E) from eccentricity (e) and mean anomaly (M)
def eccentricanomaly(e,M):
M0 = np.mod(M,2*np.pi)
E0 = M0 + np.sign(np.sin(M0))*0.85*e #Murray-Dermotts' initial estimate
# successive approximations via Newtons' method
for i in range(0,4):
#TODO: implement modified Newton's method for Kepler's equation (Murray-Dermott)
Eans = E0 - (E0-e*np.sin(E0)-M0)/(1.0-e*np.cos(E0))
E0 = Eans
return E0
# compute true anomaly (f) from eccentricity (e) and eccentric anomaly (E)
def trueanomaly(e,E):
Enew = np.mod(E,2.0*np.pi)
return 2.0*np.arctan( np.sqrt((1.0+e)/(1.0-e))*np.tan(Enew/2) )
# compute eccentric anomaly (E) from eccentricity (e) and true anomaly (f)
def truean2eccan(e, f):
fnew = np.mod(f,2.0*np.pi)
return 2.0*np.arctan( np.sqrt((1.0-e)/(1.0+e))*np.tan(fnew/2) )
# compute true anomaly from eccentricity and mean anomaly
def meanan2truean(e,M):
return trueanomaly(e, eccentricanomaly(e, M))
# compute true anomaly from time, a, e, mu and taup
def time2truean(a, e, mu, t, taup):
return meanan2truean(e, meananomaly(meanmotion(mu, a), t, taup))
# compute cartesian positions (x,y,z) at time t
# for mass parameter mu from orbital elements a, e, taup, I, omega, Omega
def orbel2xyz(t, mu, a, e, taup, omega, I, Omega):
# compute true anomaly at time t
f = time2truean(a, e, mu, t, taup)
# get cartesian positions wrt inertial frame from orbital elements
return xyz_frame2(a, e, f, omega, I, Omega)
def load_mpc_observatories_data(mpc_observatories_fname):
"""Load Minor Planet Center observatories data using numpy's genfromtxt function.
Args:
mpc_observatories_fname (str): file name with MPC observatories data.
Returns:
ndarray: data read from the text file (output from numpy.genfromtxt)
"""
obs_dt = 'S3, f8, f8, f8, S48'
obs_delims = [4, 10, 9, 10, 48]
return np.genfromtxt(mpc_observatories_fname, dtype=obs_dt, names=True, delimiter=obs_delims, autostrip=True, encoding=None)
def load_sat_observatories_data(sat_observatories_fname):
"""Load COSPAR satellite tracking observatories data using numpy's genfromtxt function.
Args:
sat_observatories_fname (str): file name with COSPAR observatories data.
Returns:
ndarray: data read from the text file (output from numpy.genfromtxt)
"""
obs_dt = 'i8, S2, f8, f8, f8, S18'
obs_delims = [4, 3, 10, 10, 8, 21]
return np.genfromtxt(sat_observatories_fname, dtype=obs_dt, names=True, delimiter=obs_delims, autostrip=True, encoding=None, skip_header=1)
def get_observatory_data(observatory_code, mpc_observatories_data):
"""Load individual data of MPC observatory corresponding to given observatory code.
Args:
observatory_code (int): MPC observatory code.
mpc_observatories_data (string): path to file containing MPC observatories data.
Returns:
ndarray: observatory data corresponding to code.
"""
arr_index = np.where(mpc_observatories_data['Code'] == observatory_code)
return mpc_observatories_data[arr_index[0][0]]
def get_station_data(station_code, sat_observatories_data):
"""Load individual data of COSPAR satellite tracking observatory corresponding to given observatory code.
Args:
observatory_code (int): COSPAR station code.
Returns:
ndarray: station data (Lat, Long, Elev) corresponding to observatory code.
"""
arr_index = np.where(sat_observatories_data['No'] == station_code)
return sat_observatories_data[arr_index[0][0]]
def load_mpc_data(fname):
"""Loads minor planet position observation data from MPC-formatted files.
MPC format for minor planet observations is described at
https://www.minorplanetcenter.net/iau/info/OpticalObs.html
TODO: Add support for comets and natural satellites.
Add support for radar observations:
https://www.minorplanetcenter.net/iau/info/RadarObs.html
See also NOTE 2 in:
https://www.minorplanetcenter.net/iau/info/OpticalObs.html
Args:
fname (string): name of the MPC-formatted text file to be parsed
Returns:
x (ndarray): array of minor planet position observations following the
MPC format.
"""
# dt is the dtype for MPC-formatted text files
dt = 'i8,S7,S1,S1,S1,i8,i8,i8,f8,U24,S9,S6,S6,S3'
# mpc_names correspond to the dtype names of each field
mpc_names = ['mpnum','provdesig','discovery','publishnote','j2000','yr','month','day','utc','radec','9xblank','magband','6xblank','observatory']
# mpc_delims are the fixed-width column delimiter following MPC format description
mpc_delims = [5,7,1,1,1,4,3,3,7,24,9,6,6,3]
return np.genfromtxt(fname, dtype=dt, names=mpc_names, delimiter=mpc_delims, autostrip=True)
def load_iod_data(fname):
"""Loads satellite position observation data files following the Interactive
Orbit Determination format (IOD). Currently, the only supported angle format
is 2, as specified in IOD format. IOD format is described at
http://www.satobs.org/position/IODformat.html.
TODO: add other IOD angle sub-formats; construct numpy array according to different
angle formats. Possible solution: read angle subformat; if angle subformat
equals 2, continue; otherwise, convert data to angle subformat 2.
Args:
fname (string): name of the IOD-formatted text file to be parsed
Returns:
x (numpy array): array of satellite position observations following the
IOD format, with angle format code = 2.
"""
# dt is the dtype for IOD-formatted text files
dt = 'S15, i8, S1, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, S1, S1'
# iod_names correspond to the dtype names of each field
iod_names = ['object', 'station', 'stationstatus', 'yr', 'month', 'day',
'hr', 'min', 'sec', 'msec', 'timeM', 'timeX', 'angformat', 'epoch', 'raHH',
'raMM','rammm','decDD','decMM','decmmm','radecM','radecX','optical','vismag']
# TODO: read first line, get sub-format, construct iod_delims from there
# as it is now, it only works for the given test file iod_data.txt
# iod_delims are the fixed-width column delimiter followinf IOD format description
iod_delims = [15, 5, 2, 5, 2, 2,
2, 2, 2, 3, 2, 1, 2, 1, 3,
2, 3, 3, 2, 2, 2, 1, 2, 1]
return np.genfromtxt(fname, dtype=dt, names=iod_names, delimiter=iod_delims, autostrip=True)
def observerpos_mpc(long, parallax_s, parallax_c, t_utc):
"""Compute geocentric observer position at UTC instant t_utc, for Sun-centered orbits,
at a given observation site defined by its longitude, and parallax constants S and C.
Formula taken from top of page 266, chapter 5, Orbital Mechanics book (Curtis).
The parallax constants S and C are defined by:
S=rho cos phi' C=rho sin phi', where
rho: slant range
phi': geocentric latitude
Args:
long (float): longitude of observing site
parallax_s (float): parallax constant S of observing site
parallax_c (float): parallax constant C of observing site
t_utc (astropy.time.Time): UTC time of observation
Returns:
1x3 numpy array: cartesian components of observer's geocentric position
"""
# Earth's equatorial radius in kilometers
# Re = cts.R_earth.to(uts.Unit('km')).value
# define Longitude object for the observation site longitude
long_site = Longitude(long, uts.degree, wrap_angle=360.0*uts.degree)
# compute sidereal time of observation at site
t_site_lmst = t_utc.sidereal_time('mean', longitude=long_site)
lmst_rad = t_site_lmst.rad # np.deg2rad(lmst_hrs*15.0) # radians
# compute cartesian components of geocentric (non rotating) observer position
x_gc = Re*parallax_c*np.cos(lmst_rad)
y_gc = Re*parallax_c*np.sin(lmst_rad)
z_gc = Re*parallax_s
return np.array((x_gc,y_gc,z_gc))
def observerpos_sat(lat, long, elev, t_utc):
"""Compute geocentric observer position at UTC instant t_utc, for Earth-centered orbits,
at a given observation site defined by its longitude, geodetic latitude and elevation above reference ellipsoid.
Formula taken from bottom of page 265 (Eq. 5.56), chapter 5, Orbital Mechanics book (Curtis).
Args:
lat (float): geodetic latitude (deg)
long (float): longitude (deg)
elev (float): elevation above reference ellipsoid (m)
t_utc (astropy.time.Time): UTC time of observation
Returns:
1x3 numpy array: cartesian components of observer's geocentric position
"""
# Earth's equatorial radius in kilometers
# Re = cts.R_earth.to(uts.Unit('km')).value
# define Longitude object for the observation site longitude
long_site = Longitude(long, uts.degree, wrap_angle=180.0*uts.degree)
# compute sidereal time of observation at site
t_site_lmst = t_utc.sidereal_time('mean', longitude=long_site)
lmst_rad = t_site_lmst.rad # np.deg2rad(lmst_hrs*15.0) # radians
# latitude
phi_rad = np.deg2rad(lat)
# convert ellipsoid coordinates to cartesian
cos_phi = np.cos( phi_rad )
cos_phi_cos_theta = cos_phi*np.cos( lmst_rad )
cos_phi_sin_theta = cos_phi*np.sin( lmst_rad )
sin_phi = np.sin( phi_rad )
denum = np.sqrt(1.0-(2.0*earth_f-earth_f**2)*sin_phi**2)
r_xy = Re/denum+elev/1000.0
r_z = Re*((1.0-earth_f)**2)/denum+elev/1000.0
# compute cartesian components of geocentric (non-rotating) observer position
x_gc = r_xy*cos_phi_cos_theta
y_gc = r_xy*cos_phi_sin_theta
z_gc = r_z*sin_phi
return np.array((x_gc,y_gc,z_gc))
def losvector(ra_rad, dec_rad):
"""Compute line-of-sight (LOS) vector for given values of right ascension
and declination. Both angles must be provided in radians.
Args:
ra_rad (float): right ascension (rad)
dec_rad (float): declination (rad)
Returns:
1x3 numpy array: cartesian components of LOS vector.
"""
cosa_cosd = np.cos(ra_rad)*np.cos(dec_rad)
sina_cosd = np.sin(ra_rad)*np.cos(dec_rad)
sind = np.sin(dec_rad)
return np.array((cosa_cosd, sina_cosd, sind))
def lagrangef(mu, r2, tau):
"""Compute 1st order approximation to Lagrange's f function.
Args:
mu (float): gravitational parameter attracting body
r2 (float): radial distance
tau (float): time interval
Returns:
float: Lagrange's f function value
"""
return 1.0-0.5*(mu/(r2**3))*(tau**2)
def lagrangeg(mu, r2, tau):
"""Compute 1st order approximation to Lagrange's g function.
Args:
mu (float): gravitational parameter attracting body
r2 (float): radial distance
tau (float): time interval
Returns:
float: Lagrange's g function value
"""
return tau-(1.0/6.0)*(mu/(r2**3))*(tau**3)
# Set of functions for cartesian states -> Keplerian elements
def kep_h_norm(x, y, z, u, v, w):
"""Compute norm of specific angular momentum vector h.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
Returns:
float: norm of specific angular momentum vector, h.
"""
return np.sqrt( (y*w-z*v)**2 + (z*u-x*w)**2 + (x*v-y*u)**2 )
def kep_h_vec(x, y, z, u, v, w):
"""Compute specific angular momentum vector h.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
Returns:
float: specific angular momentum vector, h.
"""
return np.array((y*w-z*v, z*u-x*w, x*v-y*u))
def semimajoraxis(x, y, z, u, v, w, mu):
"""Compute value of semimajor axis, a.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
Returns:
float: semimajor axis, a
"""
myRadius=np.sqrt((x**2)+(y**2)+(z**2))
myVelSqr=(u**2)+(v**2)+(w**2)
return 1.0/( (2.0/myRadius)-(myVelSqr/mu) )
def eccentricity(x, y, z, u, v, w, mu):
"""Compute value of eccentricity, e.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
Returns:
float: eccentricity, e
"""
h2 = ((y*w-z*v)**2) + ((z*u-x*w)**2) + ((x*v-y*u)**2)
a = semimajoraxis(x,y,z,u,v,w,mu)
quotient = h2/( mu*a )
return np.sqrt(1.0 - quotient)
def inclination(x, y, z, u, v, w):
"""Compute value of inclination, I.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
Returns:
float: inclination, I
"""
my_hz = x*v-y*u
my_h = np.sqrt( (y*w-z*v)**2 + (z*u-x*w)**2 + (x*v-y*u)**2 )
return np.arccos(my_hz/my_h)
def longascnode(x, y, z, u, v, w):
"""Compute value of longitude of ascending node, computed as
the angle between x-axis and the vector n = (-hy,hx,0), where hx, hy, are
respectively, the x and y components of specific angular momentum vector, h.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
Returns:
float: longitude of ascending node
"""
res = np.arctan2(y*w-z*v, x*w-z*u) # remember atan2 is atan2(y/x)
if res >= 0.0:
return res
else:
return res+2.0*np.pi
def rungelenz(x, y, z, u, v, w, mu):
"""Compute the cartesian components of Laplace-Runge-Lenz vector.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
Returns:
float: Laplace-Runge-Lenz vector
"""
r = np.sqrt(x**2+y**2+z**2)
lrl_x = ( -(z*u-x*w)*w+(x*v-y*u)*v )/mu-x/r
lrl_y = ( -(x*v-y*u)*u+(y*w-z*v)*w )/mu-y/r
lrl_z = ( -(y*w-z*v)*v+(z*u-x*w)*u )/mu-z/r
return np.array((lrl_x, lrl_y, lrl_z))
def argperi(x, y, z, u, v, w, mu):
"""Compute the argument of pericenter.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
Returns:
float: argument of pericenter
"""
#n = (z-axis unit vector)×h = (-hy, hx, 0)
n = np.array((x*w-z*u, y*w-z*v, 0.0))
e = rungelenz(x,y,z,u,v,w,mu) #cartesian comps. of Laplace-Runge-Lenz vector
n = n/np.sqrt(n[0]**2+n[1]**2+n[2]**2)
e = e/np.sqrt(e[0]**2+e[1]**2+e[2]**2)
cos_omega = np.dot(n, e)
if e[2] >= 0.0:
return np.arccos(cos_omega)
else:
return 2.0*np.pi-np.arccos(cos_omega)
def trueanomaly5(x, y, z, u, v, w, mu):
"""Compute the true anomaly from cartesian state.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
Returns:
float: true anomaly
"""
r_vec = np.array((x, y, z))
r_vec = r_vec/np.linalg.norm(r_vec, ord=2)
e_vec = rungelenz(x, y, z, u, v, w, mu)
e_vec = e_vec/np.linalg.norm(e_vec, ord=2)
v_vec = np.array((u, v, w))
v_r_num = np.dot(v_vec, r_vec)
if v_r_num>=0.0:
return np.arccos(np.dot(e_vec, r_vec))
elif v_r_num<0.0:
return 2.0*np.pi-np.arccos(np.dot(e_vec, r_vec))
def taupericenter(t, e, f, n):
"""Compute the time of pericenter passage.
Args:
t (float): current time
e (float): eccentricity
f (float): true anomaly
n (float): Keplerian mean motion
Returns:
float: time of pericenter passage
"""
E0 = truean2eccan(e, f)
M0 = np.mod(E0-e*np.sin(E0), 2.0*np.pi)
return t-M0/n
def alpha(x, y, z, u, v, w, mu):
"""Compute the inverse of the semimajor axis.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
Returns:
float: alpha = 1/a
"""
myRadius=np.sqrt((x**2)+(y**2)+(z**2))
myVelSqr=(u**2)+(v**2)+(w**2)
return (2.0/myRadius)-(myVelSqr/mu)
def univkepler(dt, x, y, z, u, v, w, mu, iters=5, atol=1e-15):
"""Compute the current value of the universal Kepler anomaly, xi.
Args:
dt (float): time interval
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
w (float): z-component of velocity
mu (float): gravitational parameter
iters (int): number of iterations of Newton-Raphson process
atol (float): absolute tolerance of Newton-Raphson process
Returns:
float: alpha = 1/a
"""
# compute preliminaries
r0 = np.sqrt((x**2)+(y**2)+(z**2))
v20 = (u**2)+(v**2)+(w**2)
vr0 = (x*u+y*v+z*w)/r0
alpha0 = (2.0/r0)-(v20/mu)
# compute initial estimate for xi
xi = np.sqrt(mu)*np.abs(alpha0)*dt
i = 0
ratio_i = 1.0
while np.abs(ratio_i)>atol and i<iters:
xi2 = xi**2
z_i = alpha0*(xi2)
a_i = (r0*vr0)/np.sqrt(mu)
b_i = 1.0-alpha0*r0
C_z_i = c2(z_i)
S_z_i = c3(z_i)
f_i = a_i*xi2*C_z_i + b_i*(xi**3)*S_z_i + r0*xi - np.sqrt(mu)*dt
g_i = a_i*xi*(1.0-z_i*S_z_i) + b_i*xi2*C_z_i+r0
ratio_i = f_i/g_i
xi = xi - ratio_i
i += 1
return xi
def lagrangef_(xi, z, r):
"""Compute current value of Lagrange's f function.
Args:
xi (float): universal Kepler anomaly
z (float): xi**2/alpha
r (float): radial distance
Returns:
float: Lagrange's f function value
"""
return 1.0-(xi**2)*c2(z)/r
def lagrangeg_(tau, xi, z, mu):
"""Compute current value of Lagrange's g function.
Args:
tau (float): time interval
xi (float): universal Kepler anomaly
z (float): xi**2/alpha
r (float): radial distance
Returns:
float: Lagrange's g function value
"""
return tau-(xi**3)*c3(z)/np.sqrt(mu)
def get_observations_data(mpc_object_data, inds):
"""Extract three ra/dec observations from MPC observation data file.
Args:
mpc_object_data (string): file path to MPC observation data of object
inds (int array): indices of requested data
Returns:
obs_radec (1x3 SkyCoord array): ra/dec observation data
obs_t (1x3 Time array): time observation data
site_codes (1x3 int array): corresponding codes of observation sites
"""
# construct SkyCoord 3-element array with observational information
timeobs = np.zeros((3,), dtype=Time)
obs_radec = np.zeros((3,), dtype=SkyCoord)
obs_t = np.zeros((3,))
timeobs[0] = Time( datetime(mpc_object_data['yr'][inds[0]], mpc_object_data['month'][inds[0]], mpc_object_data['day'][inds[0]]) + timedelta(days=mpc_object_data['utc'][inds[0]]) )
timeobs[1] = Time( datetime(mpc_object_data['yr'][inds[1]], mpc_object_data['month'][inds[1]], mpc_object_data['day'][inds[1]]) + timedelta(days=mpc_object_data['utc'][inds[1]]) )
timeobs[2] = Time( datetime(mpc_object_data['yr'][inds[2]], mpc_object_data['month'][inds[2]], mpc_object_data['day'][inds[2]]) + timedelta(days=mpc_object_data['utc'][inds[2]]) )
obs_radec[0] = SkyCoord(mpc_object_data['radec'][inds[0]], unit=(uts.hourangle, uts.deg), obstime=timeobs[0])
obs_radec[1] = SkyCoord(mpc_object_data['radec'][inds[1]], unit=(uts.hourangle, uts.deg), obstime=timeobs[1])
obs_radec[2] = SkyCoord(mpc_object_data['radec'][inds[2]], unit=(uts.hourangle, uts.deg), obstime=timeobs[2])
# construct vector of observation time (continous variable)
obs_t[0] = obs_radec[0].obstime.tdb.jd
obs_t[1] = obs_radec[1].obstime.tdb.jd
obs_t[2] = obs_radec[2].obstime.tdb.jd
site_codes = [mpc_object_data['observatory'][inds[0]], mpc_object_data['observatory'][inds[1]], mpc_object_data['observatory'][inds[2]]]
return obs_radec, obs_t, site_codes
def get_observations_data_sat(iod_object_data, inds):
"""Extract three ra/dec observations from IOD observation data file.
Args:
iod_object_data (string): file path to sat tracking observation data of object
inds (int array): indices of requested data
Returns:
obs_radec (1x3 SkyCoord array): ra/dec observation data
obs_t (1x3 Time array): time observation data
site_codes (1x3 int array): corresponding codes of observation sites
"""
# construct SkyCoord 3-element array with observational information
timeobs = np.zeros((3,), dtype=Time)
obs_radec = np.zeros((3,), dtype=SkyCoord)
obs_t = np.zeros((3,))
td1 = timedelta(hours=1.0*iod_object_data['hr'][inds[0]], minutes=1.0*iod_object_data['min'][inds[0]], seconds=(iod_object_data['sec'][inds[0]]+iod_object_data['msec'][inds[0]]/1000.0))
td2 = timedelta(hours=1.0*iod_object_data['hr'][inds[1]], minutes=1.0*iod_object_data['min'][inds[1]], seconds=(iod_object_data['sec'][inds[1]]+iod_object_data['msec'][inds[1]]/1000.0))
td3 = timedelta(hours=1.0*iod_object_data['hr'][inds[2]], minutes=1.0*iod_object_data['min'][inds[2]], seconds=(iod_object_data['sec'][inds[2]]+iod_object_data['msec'][inds[2]]/1000.0))
timeobs[0] = Time( datetime(iod_object_data['yr'][inds[0]], iod_object_data['month'][inds[0]], iod_object_data['day'][inds[0]]) + td1 )
timeobs[1] = Time( datetime(iod_object_data['yr'][inds[1]], iod_object_data['month'][inds[1]], iod_object_data['day'][inds[1]]) + td2 )
timeobs[2] = Time( datetime(iod_object_data['yr'][inds[2]], iod_object_data['month'][inds[2]], iod_object_data['day'][inds[2]]) + td3 )
raHHMMmmm0 = iod_object_data['raHH'][inds[0]] + (iod_object_data['raMM'][inds[0]]+iod_object_data['rammm'][inds[0]]/1000.0)/60.0
raHHMMmmm1 = iod_object_data['raHH'][inds[1]] + (iod_object_data['raMM'][inds[1]]+iod_object_data['rammm'][inds[1]]/1000.0)/60.0
raHHMMmmm2 = iod_object_data['raHH'][inds[2]] + (iod_object_data['raMM'][inds[2]]+iod_object_data['rammm'][inds[2]]/1000.0)/60.0
decDDMMmmm0 = iod_object_data['decDD'][inds[0]] + (iod_object_data['decMM'][inds[0]]+iod_object_data['decmmm'][inds[0]]/1000.0)/60.0
decDDMMmmm1 = iod_object_data['decDD'][inds[1]] + (iod_object_data['decMM'][inds[1]]+iod_object_data['decmmm'][inds[1]]/1000.0)/60.0
decDDMMmmm2 = iod_object_data['decDD'][inds[2]] + (iod_object_data['decMM'][inds[2]]+iod_object_data['decmmm'][inds[2]]/1000.0)/60.0
obs_radec[0] = SkyCoord(ra=raHHMMmmm0, dec=decDDMMmmm0, unit=(uts.hourangle, uts.deg), obstime=timeobs[0])
obs_radec[1] = SkyCoord(ra=raHHMMmmm1, dec=decDDMMmmm1, unit=(uts.hourangle, uts.deg), obstime=timeobs[1])
obs_radec[2] = SkyCoord(ra=raHHMMmmm2, dec=decDDMMmmm2, unit=(uts.hourangle, uts.deg), obstime=timeobs[2])
# construct vector of observation time (continous variable)
obs_t[0] = (timeobs[0]-timeobs[0]).sec
obs_t[1] = (timeobs[1]-timeobs[0]).sec
obs_t[2] = (timeobs[2]-timeobs[0]).sec
site_codes = [iod_object_data['station'][inds[0]], iod_object_data['station'][inds[1]], iod_object_data['station'][inds[2]]]
return obs_radec, obs_t, site_codes
def earth_ephemeris(t_tdb):
"""Compute heliocentric position of Earth at Julian date `t_tdb` (TDB, days),
according to SPK kernel defined by astropy.coordinates.solar_system_ephemeris.
Args:
t_tdb (float): TDB instant of requested position
Returns:
(1x3 array): cartesian position in km
"""
t = Time(t_tdb, format='jd', scale='tdb')
ye = get_body_barycentric('earth', t)
ys = get_body_barycentric('sun', t)
y = ye - ys
return y.xyz.value
def observer_wrt_sun(long, parallax_s, parallax_c, t_utc):
"""Compute position of observer at Earth's surface, with respect
to the Sun, in equatorial frame.
Args:
long (float): longitude of observing site
parallax_s (float): parallax constant S of observing site
parallax_c (float): parallax constant C of observing site
t_utc (Time): UTC time of observation
Returns:
(1x3 array): cartesian vector
"""
t_jd_tdb = t_utc.tdb.jd
xyz_es = earth_ephemeris(t_jd_tdb)
xyz_oe = observerpos_mpc(long, parallax_s, parallax_c, t_utc)
return (xyz_oe+xyz_es)/au
def object_wrt_sun(t_utc, a, e, taup, omega, I, Omega):
"""Compute position of celestial object with respect to the Sun, in equatorial frame.
Args:
t_utc (Time): UTC time of observation
a (float): semimajor axis
e (float): eccentricity
taup (float): time of pericenter passage
omega (float): argument of pericenter
I (float): inclination
Omega (float): longitude of ascending node
Returns:
(1x3 array): cartesian vector
"""
t_jd_tdb = t_utc.tdb.jd
xyz_eclip = orbel2xyz(t_jd_tdb, mu_Sun, a, e, taup, omega, I, Omega)
return np.matmul(rot_eclip_to_equat, xyz_eclip)
def rho_vec(long, parallax_s, parallax_c, t_utc, a, e, taup, omega, I, Omega):
"""Compute slant range vector.
Args:
long (float): longitude of observing site
parallax_s (float): parallax constant S of observing site
parallax_c (float): parallax constant C of observing site
t_utc (Time): UTC time of observation
a (float): semimajor axis
e (float): eccentricity
taup (float): time of pericenter passage
omega (float): argument of pericenter
I (float): inclination
Omega (float): longitude of ascending node
Returns:
(1x3 array): cartesian vector
"""
return object_wrt_sun(t_utc, a, e, taup, omega, I, Omega)-observer_wrt_sun(long, parallax_s, parallax_c, t_utc)
def rhovec2radec(long, parallax_s, parallax_c, t_utc, a, e, taup, omega, I, Omega):
"""Transform slant range vector to ra/dec values.
Args:
long (float): longitude of observing site
parallax_s (float): parallax constant S of observing site
parallax_c (float): parallax constant C of observing site
t_utc (Time): UTC time of observation
a (float): semimajor axis
e (float): eccentricity
taup (float): time of pericenter passage
omega (float): argument of pericenter
I (float): inclination
Omega (float): longitude of ascending node
Returns:
ra_rad (float): right ascension (rad)
dec_rad (float): declination (rad)
"""
r_v = rho_vec(long, parallax_s, parallax_c, t_utc, a, e, taup, omega, I, Omega)
r_v_norm = np.linalg.norm(r_v, ord=2)
r_v_unit = r_v/r_v_norm
cosd_cosa = r_v_unit[0]
cosd_sina = r_v_unit[1]
sind = r_v_unit[2]
ra_rad = np.arctan2(cosd_sina, cosd_cosa)
dec_rad = np.arcsin(sind)
if ra_rad <0.0:
return ra_rad+2.0*np.pi, dec_rad
else:
return ra_rad, dec_rad
def angle_diff_rad(a1, a2):
"""Compute shortest signed difference between two angles. Input angles
are assumed to be in radians. Result is returned in radians. Code adapted
from https://rosettacode.org/wiki/Angle_difference_between_two_bearings#Python.
Args:
a1 (float): angle 1 in radians
a2 (float): angle 2 in radians
Returns:
r (float): shortest signed difference in radians
"""
r = (a2 - a1) % (2.0*np.pi)
# Python modulus has same sign as divisor, which is positive here,
# so no need to consider negative case
if r >= np.pi:
r -= (2.0*np.pi)
return r
def radec_residual_mpc(x, t_ra_dec_datapoint, long, parallax_s, parallax_c):
"""Compute observed minus computed (O-C) residual for a given ra/dec
datapoint, represented as a SkyCoord object, for MPC observation data.
Args:
x (1x6 array): set of Keplerian elements
t_ra_dec_datapoint (SkyCoord): ra/dec datapoint
long (float): longitude of observing site
parallax_s (float): parallax constant S of observing site
parallax_c (float): parallax constant C of observing site
Returns:
(1x2 array): right ascension difference, declination difference
"""
ra_comp, dec_comp = rhovec2radec(long, parallax_s, parallax_c, t_ra_dec_datapoint.obstime, x[0], x[1], x[2], x[3], x[4], x[5])
ra_obs, dec_obs = t_ra_dec_datapoint.ra.rad, t_ra_dec_datapoint.dec.rad
#"unsigned" distance between points in torus
diff_ra = angle_diff_rad(ra_obs, ra_comp)
diff_dec = angle_diff_rad(dec_obs, dec_comp)
return np.array((diff_ra,diff_dec))
def radec_residual_rov_mpc(x, t, ra_obs_rad, dec_obs_rad, long, parallax_s, parallax_c):
"""Compute right ascension and declination observed minus computed (O-C) residual,
using precomputed vector of observed ra/dec values, for MPC observation data.
Args:
x (1x6 array): set of Keplerian elements
t (Time): time of observation
ra_obs_rad (float): observed right ascension (rad)
dec_obs_rad (float): observed declination (rad)
long (float): longitude of observing site
parallax_s (float): parallax constant S of observing site
parallax_c (float): parallax constant C of observing site
Returns:
(1x2 array): right ascension difference, declination difference
"""
ra_comp, dec_comp = rhovec2radec(long, parallax_s, parallax_c, t, x[0], x[1], x[2], x[3], x[4], x[5])
#"unsigned" distance between points in torus
diff_ra = angle_diff_rad(ra_obs_rad, ra_comp)
diff_dec = angle_diff_rad(dec_obs_rad, dec_comp)
return np.array((diff_ra,diff_dec))
def get_observer_pos_wrt_sun(mpc_observatories_data, obs_radec, site_codes):
"""Compute position of observer at Earth's surface, with respect
to the Sun, in equatorial frame, during 3 distinct instants.
Args:
mpc_observatories_data (string): path to file containing MPC observatories data.
obs_radec (1x3 SkyCoord array): three rad/dec observations
site_codes (1x3 int array): MPC codes of observation sites
Returns:
R (1x3 array): cartesian position vectors (observer wrt Sun)
Ea_hc_pos (1x3 array): cartesian position vectors (Earth wrt Sun)
"""
# astronomical unit in km
Ea_hc_pos = np.array((np.zeros((3,)),np.zeros((3,)),np.zeros((3,))))
R = np.array((np.zeros((3,)),np.zeros((3,)),np.zeros((3,))))
# load MPC observatory data
obsite1 = get_observatory_data(site_codes[0], mpc_observatories_data)
obsite2 = get_observatory_data(site_codes[1], mpc_observatories_data)
obsite3 = get_observatory_data(site_codes[2], mpc_observatories_data)
# compute TDB instant of each observation
t_jd1_tdb_val = obs_radec[0].obstime.tdb.jd
t_jd2_tdb_val = obs_radec[1].obstime.tdb.jd
t_jd3_tdb_val = obs_radec[2].obstime.tdb.jd
Ea_jd1 = earth_ephemeris(t_jd1_tdb_val)
Ea_jd2 = earth_ephemeris(t_jd2_tdb_val)
Ea_jd3 = earth_ephemeris(t_jd3_tdb_val)
Ea_hc_pos[0] = Ea_jd1/au
Ea_hc_pos[1] = Ea_jd2/au
Ea_hc_pos[2] = Ea_jd3/au
R[0] = ( Ea_jd1 + observerpos_mpc(obsite1['Long'], obsite1['sin'], obsite1['cos'], obs_radec[0].obstime) )/au
R[1] = ( Ea_jd2 + observerpos_mpc(obsite2['Long'], obsite2['sin'], obsite2['cos'], obs_radec[1].obstime) )/au
R[2] = ( Ea_jd3 + observerpos_mpc(obsite3['Long'], obsite3['sin'], obsite3['cos'], obs_radec[2].obstime) )/au
return R, Ea_hc_pos
def get_observer_pos_wrt_earth(sat_observatories_data, obs_radec, site_codes):
"""Compute position of observer at Earth's surface, with respect
to the Earth, in equatorial frame, during 3 distinct instants.
Args:
sat_observatories_data (string): path to file containing COSPAR satellite tracking stations data.
obs_radec (1x3 SkyCoord array): three rad/dec observations
site_codes (1x3 int array): COSPAR codes of observation sites
Returns:
R (1x3 array): cartesian position vectors (observer wrt Earth)
"""
R = np.array((np.zeros((3,)),np.zeros((3,)),np.zeros((3,))))
# load MPC observatory data
obsite1 = get_station_data(site_codes[0], sat_observatories_data)
obsite2 = get_station_data(site_codes[1], sat_observatories_data)
obsite3 = get_station_data(site_codes[2], sat_observatories_data)
R[0] = observerpos_sat(obsite1['Latitude'], obsite1['Longitude'], obsite1['Elev'], obs_radec[0].obstime)
R[1] = observerpos_sat(obsite2['Latitude'], obsite2['Longitude'], obsite2['Elev'], obs_radec[1].obstime)
R[2] = observerpos_sat(obsite3['Latitude'], obsite3['Longitude'], obsite3['Elev'], obs_radec[2].obstime)
return R
def gauss_method_core(obs_radec, obs_t, R, mu, r2_root_ind=0):
"""Perform core Gauss method.
Args:
obs_radec (1x3 SkyCoord array): three rad/dec observations
obs_t (1x3 array): three times of observations
R (1x3 array): three observer position vectors
mu (float): gravitational parameter of center of attraction
r2_root_ind (int): index of Gauss polynomial root
Returns:
r1 (1x3 array): estimated position at first observation
r2 (1x3 array): estimated position at second observation
r3 (1x3 array): estimated position at third observation
v2 (1x3 array): estimated velocity at second observation
D (3x3 array): auxiliary matrix
rho1 (1x3 array): LOS vector at first observation
rho2 (1x3 array): LOS vector at second observation
rho3 (1x3 array): LOS vector at third observation
tau1 (float): time interval from second to first observation
tau3 (float): time interval from second to third observation
f1 (float): estimated Lagrange's f function value at first observation
g1 (float): estimated Lagrange's g function value at first observation
f3 (float): estimated Lagrange's f function value at third observation
g3 (float): estimated Lagrange's g function value at third observation
rho_1_sr (float): estimated slant range at first observation
rho_2_sr (float): estimated slant range at second observation
rho_3_sr (float): estimated slant range at third observation
"""
# get Julian date of observations
t1 = obs_t[0]
t2 = obs_t[1]