-
-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathkeplerlib.py
More file actions
624 lines (518 loc) · 19.7 KB
/
Copy pathkeplerlib.py
File metadata and controls
624 lines (518 loc) · 19.7 KB
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
from __future__ import division
import sys
import math
from numpy import(abs, amax, amin, arange, arccos, arctan, array, atleast_1d,
clip, copy, copyto, cos, cosh, exp, float64, full_like, log,
ndarray, newaxis, pi, power, repeat, sin, sinh, squeeze,
sqrt, sum, tan, tanh, zeros_like)
from skyfield.constants import AU_KM, DAY_S, DEG2RAD
from skyfield.functions import dots, length_of, mxv
from skyfield.descriptorlib import reify
from skyfield.elementslib import OsculatingElements, normpi
from skyfield.units import Distance, Velocity
from skyfield.vectorlib import VectorFunction
from skyfield.sgp4lib import _cross
_CONVERT_GM = DAY_S * DAY_S / AU_KM / AU_KM / AU_KM
class _KeplerOrbit(VectorFunction):
def __init__(self,
position,
velocity,
epoch,
mu_au3_d2,
center=None,
target=None,
):
""" Calculates the position of an object using 2 body propagation
Parameters
----------
position : Distance
Position vector at epoch with shape (3,)
velocity : Velocity
Velocity vector at epoch with shape (3,)
epoch : Time
Time corresponding to `position` and `velocity`
mu_au_d : float
Value of mu (G * M) in au^3/d^2
center : int
NAIF ID of the primary body, 399 for geocentric orbits, 10 for
heliocentric orbits
target : int
NAIF ID of the secondary body
"""
self.position_at_epoch = position
self.velocity_at_epoch = velocity
self.epoch = epoch
self.mu_au3_d2 = mu_au3_d2
self.center = center
self.target = target
self._rotation = None # TODO: make argument?
@classmethod
def _from_periapsis(
cls,
semilatus_rectum_au,
eccentricity,
inclination_degrees,
longitude_of_ascending_node_degrees,
argument_of_perihelion_degrees,
t_periapsis,
gm_km3_s2,
center=None,
target=None,
):
"""Build a `KeplerOrbit` given its parameters and date of periapsis."""
gm_au3_d2 = gm_km3_s2 * _CONVERT_GM
pos, vel = ele_to_vec(
semilatus_rectum_au,
eccentricity,
DEG2RAD * inclination_degrees,
DEG2RAD * longitude_of_ascending_node_degrees,
DEG2RAD * argument_of_perihelion_degrees,
0.0,
gm_au3_d2,
)
return cls(
Distance(pos),
Velocity(vel),
t_periapsis,
gm_au3_d2,
center,
target,
)
@classmethod
def _from_true_anomaly(cls, p, e, i, Om, w, v,
epoch,
mu_km_s=None,
mu_au3_d2=None,
center=None,
target=None,
):
""" Creates a `KeplerOrbit` object from elements using true anomaly
Parameters
----------
p : Distance
Semi-Latus Rectum
e : float
Eccentricity
i : Angle
Inclination
Om : Angle
Longitude of Ascending Node
w : Angle
Argument of periapsis
v : Angle
True anomaly
epoch : Time
Time corresponding to `position` and `velocity`
mu_km_s : float
Value of mu (G * M) in km^3/s^2
mu_au3_d2 : float
Value of mu (G * M) in au^3/d^2
center : int
NAIF ID of the primary body, 399 for geocentric orbits, 10 for
heliocentric orbits
target : int
NAIF ID of the secondary body
"""
if (mu_km_s and mu_au3_d2) or (not mu_km_s and not mu_au3_d2):
raise ValueError('Either mu_km_s or mu_au3_d2 should be used, but not both')
if mu_au3_d2:
mu_km_s = mu_au3_d2 * AU_KM**3 / DAY_S**2
position, velocity = ele_to_vec(p.km,
e,
i.radians,
Om.radians,
w.radians,
v.radians,
mu_km_s,
)
return cls(Distance(km=position),
Velocity(km_per_s=velocity),
epoch,
mu_km_s,
center=center,
target=target,
)
@classmethod
def _from_mean_anomaly(
cls,
semilatus_rectum_au,
eccentricity,
inclination_degrees,
longitude_of_ascending_node_degrees,
argument_of_perihelion_degrees,
mean_anomaly_degrees,
epoch,
gm_km3_s2,
center=None,
target=None,
):
""" Creates a `KeplerOrbit` object from elements using mean anomaly
Parameters
----------
p : Distance
Semi-Latus Rectum
e : float
Eccentricity
i : Angle
Inclination
Om : Angle
Longitude of Ascending Node
w : Angle
Argument of periapsis
M : Angle
Mean anomaly
epoch : Time
Time corresponding to `position` and `velocity`
mu_km_s : float
Value of mu (G * M) in km^3/s^2
mu_au3_d2 : float
Value of mu (G * M) in au^3/d^2
center : int
NAIF ID of the primary body, 399 for geocentric orbits, 10 for
heliocentric orbits
target : int
NAIF ID of the secondary body
"""
gm_au3_d2 = gm_km3_s2 * _CONVERT_GM
v = true_anomaly(
eccentricity,
DEG2RAD * mean_anomaly_degrees,
semilatus_rectum_au,
gm_au3_d2,
)
pos, vel = ele_to_vec(
semilatus_rectum_au,
eccentricity,
DEG2RAD * inclination_degrees,
DEG2RAD * longitude_of_ascending_node_degrees,
DEG2RAD * argument_of_perihelion_degrees,
v,
gm_au3_d2,
)
return cls(
Distance(pos),
Velocity(vel),
epoch,
gm_au3_d2,
center,
target,
)
def _at(self, time):
"""Propagate the KeplerOrbit to the given Time object
The Time object can contain one time, or an array of times
"""
pos, vel = propagate(
self.position_at_epoch.au,
self.velocity_at_epoch.au_per_d,
self.epoch.tt,
time.tt,
self.mu_au3_d2,
)
if self._rotation is not None:
pos = mxv(self._rotation, pos)
vel = mxv(self._rotation, vel)
return pos, vel, None, None
@reify
def elements_at_epoch(self):
return OsculatingElements(self.position_at_epoch,
self.velocity_at_epoch,
self.epoch,
mu_km_s = self.mu_au3_d2 / _CONVERT_GM,
)
def __str__(self):
ele = self.elements_at_epoch
if self.target_name:
return 'KeplerOrbit {0} {1} -> {2} {3}'.format(self.center,
self.center_name,
self.target,
self.target_name,
)
else:
ele = self.elements_at_epoch
string = 'KeplerOrbit {0} {1} -> q={2:.2}au e={3:.3f} i={4:.1f} Om={5:.1f} w={6:.1f}'
return string.format(self.center,
self.center_name,
ele.periapsis_distance.au,
ele.eccentricity,
ele.inclination.degrees,
ele.longitude_of_ascending_node.degrees,
ele.argument_of_periapsis.degrees,
)
def __repr__(self):
return '<{0}>'.format(str(self))
def true_anomaly(e, M, p, gm):
return_scalar = isinstance(e, (float, float64))
e, M, p = atleast_1d(e, M, p)
closed = e < 1.0
hyperbolic = e > 1.0
parabolic = ~closed & ~hyperbolic
v = zeros_like(e)
E_closed = eccentric_anomaly(e[closed], M[closed])
v[closed] = 2.0 * arctan(sqrt((1.0 + e[closed]) / (1.0 - e[closed])) * tan(E_closed/2))
E_hyperbolic = eccentric_anomaly(e[hyperbolic], M[hyperbolic])
v[hyperbolic] = 2.0 * arctan(sqrt((e[hyperbolic] + 1.0) / (e[hyperbolic] - 1.0)) * tanh(E_hyperbolic/2))
v[parabolic] = true_anomaly_parabolic(p[parabolic], gm, M[parabolic])
return v[0] if return_scalar else v
def eccentric_anomaly(e, M):
""" Iterates to solve Kepler's equation to find eccentric anomaly
Based on the algorithm in section 8.10.2 of the Explanatory Supplement
to the Astronomical Almanac, 3rd ed.
"""
M = normpi(M)
E = M + e*sin(M)
max_iters = 100
dM = M - (E - e*sin(E))
dE = dM/(1 - e*cos(E))
not_done = abs(dE) > 1e-14
iters = 1
while iters < max_iters:
if not not_done.any():
break
dM[not_done] = M[not_done] - (E[not_done] - e[not_done]*sin(E[not_done]))
dE[not_done] = dM[not_done]/(1 - e[not_done]*cos(E[not_done]))
E[not_done] += dE[not_done]
iters += 1
not_done = abs(dE) > 1e-14
else:
raise ValueError('failed to converge')
return E
def true_anomaly_parabolic(p, gm, M):
"""Calculates true anomaly from semi-latus rectum, gm, and mean anomaly.
Valid for parabolic orbits. Equations from
https://en.wikipedia.org/wiki/Parabolic_trajectory.
"""
delta_t = sqrt(2 * p**3 / gm) * M # from http://www.bogan.ca/orbits/kepler/orbteqtn.html
periapsis_distance = p / 2
A = 3 / 2 * sqrt(gm / (2 * periapsis_distance**3)) * delta_t
B = (A + (A*A + 1))**(1/3)
return 2 * arctan(B - 1/B)
def ele_to_vec(p, e, i, Om, w, v, mu):
"""Calculates state vectors from orbital elements. Also checks for invalid
sets of elements.
Based on equations from this document:
https://web.archive.org/web/*/http://ccar.colorado.edu/asen5070/handouts/kep2cart_2002.doc
"""
# Checks that true anomaly is less than arccos(-1/e) for hyperbolic orbits
if isinstance(e, ndarray) and isinstance(v, ndarray):
inds = (e>1)
if (v[inds]>arccos(-1/e[inds])).any():
raise ValueError('If eccentricity is >1, abs(true anomaly) cannot be more than arccos(-1/e)')
elif isinstance(e, ndarray) and not isinstance(v, ndarray):
inds = (e>1)
if (v>arccos(-1/e[inds])).any():
raise ValueError('If eccentricity is >1, abs(true anomaly) cannot be more than arccos(-1/e)')
elif isinstance(v, ndarray) and not isinstance(e, ndarray):
if e>1 and (v>arccos(-1/e)).any():
raise ValueError('If eccentricity is >1, abs(true anomaly) cannot be more than arccos(-1/e)')
else:
if e>1 and v>arccos(-1/e):
raise ValueError('If eccentricity is >1, abs(true anomaly) cannot be more than arccos(-1/e)')
# Checks that inclination is in the range [0, pi]
if isinstance(i, ndarray):
if not ((i>=0) * (i <= pi)).all():
raise ValueError('Inclination outside the range [0, pi] radians')
else:
if not 0 <= i <= pi:
raise ValueError('Inclination outside the range [0, pi] radians')
r = p/(1 + e*cos(v))
h = sqrt(p*mu)
u = v+w
X = r*(cos(Om)*cos(u) - sin(Om)*sin(u)*cos(i))
Y = r*(sin(Om)*cos(u) + cos(Om)*sin(u)*cos(i))
Z = r*(sin(i)*sin(u))
X_dot = X*h*e/(r*p)*sin(v) - h/r*(cos(Om)*sin(u) + sin(Om)*cos(u)*cos(i))
Y_dot = Y*h*e/(r*p)*sin(v) - h/r*(sin(Om)*sin(u) - cos(Om)*cos(u)*cos(i))
Z_dot = Z*h*e/(r*p)*sin(v) + h/r*sin(i)*cos(u)
# z and z_dot are independent of Om, so if Om is an array and the other
# elements are scalars, z and z_dot need to be repeated
if Z.size!=X.size:
Z = repeat(Z, X.size)
Z_dot = repeat(Z_dot, X.size)
return array([X, Y, Z]), array([X_dot, Y_dot, Z_dot])
dpmax = sys.float_info.max
def find_trunc():
denom = 2
factr = 2
trunc = 1
x = 1 / denom
while 1+x > 1:
denom = denom * (2+factr) * (1+factr)
factr = factr + 2
trunc = trunc + 1
x = 1 / denom
return trunc
trunc = find_trunc()
odd_factorials = array([math.factorial(i) for i in range(3, trunc*2, 2)])
even_factorials = array([math.factorial(i) for i in range(2, trunc*2, 2)])
exponents = arange(0, trunc-1)
stumpff_bound = -(log(2) + log(dpmax))**2
def stumpff(x):
"""Calculates Stumpff functions
Based on the function toolkit/src/spicelib/stmp03.f from the SPICE toolkit,
which can be downloaded from naif.jpl.nasa.gov/naif/toolkit_FORTRAN.html
"""
if x.min() < stumpff_bound:
raise ValueError('Argument below lower bound')
z = sqrt(abs(x))
c0 = zeros_like(x)
c1 = zeros_like(x)
c2 = zeros_like(x)
c3 = zeros_like(x)
low = x < -1
c0[low] = cosh(z[low])
c1[low] = sinh(z[low])/z[low]
high = x > 1
c0[high] = cos(z[high])
c1[high] = sin(z[high])/z[high]
mid = ~(low|high)
if sum(mid):
numerators = repeat(x[mid][:, newaxis], trunc-1, axis=1)
numerators[:, 1::2] *= -1
c3[mid] = sum(power(numerators, exponents)/odd_factorials, axis=1)
c2[mid] = sum(power(numerators, exponents)/even_factorials, axis=1)
c1[mid] = 1 - x[mid]*c3[mid]
c0[mid] = 1 - x[mid]*c2[mid]
not_mid = ~mid
c2[not_mid] = (1 - c0[not_mid])/x[not_mid]
c3[not_mid] = (1 - c1[not_mid])/x[not_mid]
return c0, c1, c2, c3
def propagate(position, velocity, t0, t1, gm):
"""Propagates a position and velocity vector with an array of times.
Based on the function toolkit/src/spicelib/prop2b.f from the SPICE toolkit,
which can be downloaded from naif.jpl.nasa.gov/naif/toolkit_FORTRAN.html
Parameters
----------
position : ndarray
Position vector with shape (3,)
velocity : ndarray
Velocity vector with shape (3,)
t0 : float
Time corresponding to `position` and `velocity`
t1 : float or ndarray
Time or times to propagate to
gm : float
Gravitational parameter in units that match the other arguments
"""
gm = atleast_1d(gm)
if (gm <= 0).any():
raise ValueError("'gm' should be positive")
if (length_of(velocity)).any() == 0:
raise ValueError('Velocity vector has zero magnitude')
if (length_of(position)).any() == 0:
raise ValueError('Position vector has zero magnitude')
if position.ndim == 1:
position = position[:, newaxis]
if velocity.ndim == 1:
velocity = velocity[:, newaxis]
r0 = length_of(position)
rv = dots(position, velocity)
hvec = _cross(position, velocity)
h2 = dots(hvec, hvec)
if (h2 == 0).any():
raise ValueError('Motion is not conical')
eqvec = _cross(velocity, hvec)/gm + -position/r0
e = length_of(eqvec)
q = h2 / (gm * (1+e))
f = 1 - e
b = sqrt(q/gm)
br0 = b * r0
b2rv = b * b * rv
bq = b * q
qovr0 = q / r0
maxc = amax(array([abs(br0),
abs(b2rv),
abs(bq),
abs(qovr0/bq)]), axis=0)
hyperbolic = (f<0)
bound = zeros_like(f)
fixed = log(dpmax/2) - log(maxc[hyperbolic])
rootf = sqrt(-f[hyperbolic])
logf = log(-f[hyperbolic])
bound[hyperbolic] = amin(array([fixed/rootf, (fixed + 1.5*logf)/rootf]), axis=0)
logbound = (log(1.5) + log(dpmax) - log(maxc[~hyperbolic])) / 3
bound[~hyperbolic] = exp(logbound)
# each of these arrays has 1 entry per orbit, so its shape is (#orbits, 1)
f = f[:, newaxis]
bq = bq[:, newaxis]
b2rv = b2rv[:, newaxis]
br0 = br0[:, newaxis]
qovr0 = qovr0[:, newaxis]
bound = bound[:, newaxis]
def kepler(x):
_, c1, c2, c3 = stumpff(f*x*x)
return x*(br0*c1 + x*(b2rv*c2 + x*bq*c3))
def kepler_1d(x, orb_inds):
_, c1, c2, c3 = stumpff(x*x*repeat(f, orb_inds))
return x*(c1*repeat(br0, orb_inds) + x*(c2*repeat(b2rv, orb_inds) + x*(c3*repeat(bq, orb_inds))))
t1 = atleast_1d(t1)
t0 = atleast_1d(t0)
if len(t0) == 1:
t0 = repeat(t0, position.shape[1])
# shape of 2 dimensional arrays from here on out should be (#orbits, len(t1))
dt = t1 - t0[:, newaxis]
x = dt/bq
copyto(x, -bound, where=(x<-bound))
copyto(x, bound, where=(x>bound))
kfun = kepler(x)
past = dt < 0
future = dt > 0
upper = zeros_like(dt, dtype='float64')
lower = zeros_like(dt, dtype='float64')
oldx = zeros_like(dt, dtype='float64')
copyto(lower, x, where=past)
copyto(upper, x, where=future)
while (kfun[past] > dt[past]).any():
copyto(upper, lower, where=past)
lower[past] *= 2
copyto(oldx, x, where=past)
orb_ind = sum(past, axis=1)
x[past] = clip(lower[past], repeat(-bound, orb_ind), repeat(bound, orb_ind))
if (x[past] == oldx[past]).any():
raise ValueError('The input delta time (dt) has a value of {0}.'
'This is beyond the range of DT for which we '
'can reliably propagate states. The limits for '
'this GM and initial state are from {1}'
'to {2}.'.format(dt, kepler(-bound), kepler(bound)))
kfun[past] = kepler_1d(x[past], orb_ind)
while (kfun[future] < dt[future]).any():
copyto(lower, upper, where=future)
upper[future] *= 2
copyto(oldx, x, where=future)
orb_ind = sum(future, axis=1)
x[future] = clip(upper[future], repeat(-bound, orb_ind), repeat(bound, orb_ind))
if (x[future] == oldx[future]).any():
raise ValueError('The input delta time (dt) has a value of {0}.'
'This is beyond the range of DT for which we '
'can reliably propagate states. The limits for '
'this GM and initial state are from {1} '
'to {2}.'.format(dt, kepler(-bound), kepler(bound)))
kfun[future] = kepler_1d(x[future], orb_ind)
x = copy(upper)
copyto(x, (upper+lower)/2, where=(lower<=upper))
lcount = zeros_like(dt)
mostc = full_like(dt, 1000)
not_done = (lower < x) & (x < upper)
while not_done.any():
orb_inds = sum(not_done, axis=1)
kfun[not_done] = kepler_1d(x[not_done], orb_inds)
high = (kfun > dt) & not_done
low = (kfun < dt) & not_done
same = (~high & ~low) & not_done
copyto(upper, x, where=(high|same))
copyto(lower, x, where=(low|same))
condition = not_done & (mostc > 64) & (upper != 0) & (lower != 0)
mostc[condition] = 64
lcount[condition] = 0
copyto(x, upper, where=(not_done & (lower>upper)))
copyto(x, (upper+lower)/2, where=(not_done & (lower<=upper)))
lcount += 1
not_done = (lower < x) & (x < upper) & (lcount < mostc)
c0, c1, c2, c3 = stumpff(f*x*x)
br = br0*c0 + x*(b2rv*c1 + x*bq*c2)
pc = 1 - qovr0 * x * x * c2
vc = dt - bq * x**3 * c3
pcdot = -qovr0 / br * x * c1
vcdot = 1 - bq / br * x * x * c2
position_prop = pc.T[newaxis, :, :]*position[:, newaxis, :] + vc.T[newaxis, :, :]*velocity[:, newaxis, :]
velocity_prop = pcdot.T[newaxis, :, :]*position[:, newaxis, :] + vcdot.T[newaxis, :, :]*velocity[:, newaxis, :]
return squeeze(position_prop), squeeze(velocity_prop)