Deleted the old Orbit.
[Orbitizer.git] /
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
#!/usr/bin/python3

from Body import Body
from Vector3D import *
from math import acos, asin, atan2, cos, pi, sin

class Orbit():
	def __init__(self, Primary, a = None, e = None, i = None, Omega = None, w = None, M = None):
		'''
		Creates an Orbit object for determining the behavior of an object
		with insignificant mass in orbit about a Primary body.
		
		@param Primary: The Primary body about which the object orbits.
		@type Primary: Body
		@param a: Semi-Major Axis [m]
		@type a: Number
		@param e: Eccentricity [radians]
		@type e: Number
		@param i: Inclination [radians]
		@type i: Number
		@param Omega: Longitude of the Ascending Node [radians]
		@type Omega: Number
		@param w: Argument of Periapsis [radians]
		@type w: Number
		@param M: Mean Anomaly [radians]
		'''
		
		self.Primary = Primary
		self.a = a
		self.e = e
		self.i = i
		self.Omega = Omega
		self.w = w
		self.M = M
		self._EIsDirty = True
	
	def EccentricAnomaly(self, M = None):
		'''
		Returns the Eccentric Anomaly in radians, optionally at a specified Mean
		Anomaly.
		
		@param M: Mean Anomaly [radians] (Optional)
		@type M: Number
		
		TODO: Add hyperbolic code for e > 1.
		'''
		
		# Check if we have a clean cache to avoid the loop.
		if not self._EIsDirty and M is None:
			return self._E
		
		if M is None:
			M = self.M
		
		# If the orbit is highly eccentric, start the guess with E=pi.
		if self.e > 0.8:
			E = pi
		# Otherwise, start the guess at M.
		else:
			E = M
		i = 0
		
		# Loop through a Newton solver to find E from Kepler's equation.
		while abs(E - self.e * sin(E) - M) > 1e-9:
			E = E - (E - self.e * sin(E) - M) / (1. - self.e * cos(E))
			i += 1
		
		# Record E and clean the cache.
		self._E = E
		self._EIsDirty = False
		return E
	
	def TrueAnomaly(self, E = None):
		'''
		Returns the True Anomaly in radians, optionally at a specified Eccentric
		Anomaly.
		
		@param E: Eccentric Anomaly [radians] (Optional)
		@type E: Number
		'''
		if E is None:
			E = self.EccentricAnomaly()
		
		return 2. * atan2((1. + self.e) ** .5 * sin(E / 2.), (1. - self.e) ** .5 * cos(E / 2.))
	
	def MeanMotion(self):
		'''
		Returns the Mean Motion in radians / second.
		'''
		return (self.Primary.GravParm() / self.a ** 3.) ** .5
	
	def PeriapsisVector(self):
		'''
		Returns the ijk vector of the periapsis point.
		@return: Periapsis vector [m, m, m]
		@rtype: Vector3D
		'''
		return self.PosVector(0)
	
	def Periapsis(self):
		'''
		Returns the radius at the apoapsis.
		@return: Periapsis radius [m]
		@rtype: Number
		'''
		return self.a * (1. - self.e)
	
	def ApoapsisVector(self):
		'''
		Returns the ijk vector of the apoapsis point.
		@return: Apoapsis vector [m, m, m]
		@rtype: Vector3D
		'''
		return self.PosVector(pi)
	
	def Apoapsis(self):
		'''
		Returns the radius at the apoapsis.
		@return: Apoapsis radius [m]
		@rtype: Number
		'''
		return self.a * (1. + self.e)
	
	def _PQVectors(self):
		'''
		Returns "P" and "Q" vectors for rotating the orbital frame about the
		primary when determining the cartesian position of the orbiting body.
		
		@rtype: (Vector3D, Vector3D)
		'''
		Px = cos(self.w) * cos(self.Omega) - sin(self.w) * sin(self.Omega) * cos(self.i)
		Py = cos(self.w) * sin(self.Omega) + sin(self.w) * cos(self.Omega) * cos(self.i)
		Pz = sin(self.w) * sin(self.i)
		
		Qx = -sin(self.w) * cos(self.Omega) - cos(self.w) * sin(self.Omega) * cos(self.i)
		Qy = -sin(self.w) * sin(self.Omega) + cos(self.w) * cos(self.Omega) * cos(self.i)
		Qz = sin(self.i) * cos(self.w)
		
		return (Vector3D(Px, Py, Pz), Vector3D(Qx, Qy, Qz))
	
	def PosVector(self, M = None):
		'''
		Returns the position state vector in meters, optionally at specified
		Mean Anomaly.
		
		@param M: Mean Anomaly [radians] (Optional)
		@type M: Number 
		'''
		a = self.a
		e = self.e
		E = self.EccentricAnomaly(M)
		P, Q = self._PQVectors()
		
		R = a * (cos(E) - e) * P + a * ((1 - e ** 2.) ** .5) * sin(E) * Q
		
		return R
	
	def VelVector(self, M = None):
		'''
		Returns the velocity state vector in meters, optionally at specified
		Mean Anomaly.
		
		@param M: Mean Anomaly [radians] (Optional)
		@type M: Number
		'''
		a = self.a
		e = self.e
		E = self.EccentricAnomaly(M)
		P, Q = self._PQVectors()
		EDot = self.MeanMotion() / (1 - self.e * cos(E))
		
		V = -a * sin(E) * EDot * P + a * ((1 - e ** 2.) ** .5) * cos(E) * EDot * Q
		
		return V
	
	def GetStateFromMeanAnomaly(self, M):
		'''
		Returns a tuple containing the R and V state vectors given mean anomaly "M". 
		
		@param M: Mean anomaly [radians]
		@type M: Number
		'''
		return (self.PosVector(M), self.VelVector(M))
	
	def FindAdditionalStateVectors(self, PosVector, VelVector):
		'''
		Calculates and returns the specific angular momentum, eccentricity, and
		ascending node vectors given the position and velocity vectors.
		
		@param PosVector: Position vector [m, m, m]
		@type PosVector: Vector3D
		@param VelVector: Velocity vector [m/s, m/s, m/s]
		@type VelVector: Vector3D
		'''
		
		HVector = PosVector * VelVector
		
		eVector = (VelVector * HVector) / self.Primary.GravParm() - PosVector / PosVector.Magnitude()
		
		ANVector = kVector * HVector
		
		return (HVector, eVector, ANVector)
	
	def GetElementsFromStateVectors(self, PosVector, VelVector):
		'''
		Returns the orbital elements from a given set of position and velocity vectors.
		
		@param PosVector: Position vector [m, m, m]
		@type PosVector: Vector3D
		@param VelVector: Velocity vector [m/s, m/s, m/s]
		@type VelVector: Vector3D
		'''
		
		HVector, eVector, ANVector = self.FindAdditionalStateVectors(PosVector, VelVector)
		
		VvE = VelVector.Magnitude() ** 2. / 2. - self.Primary.GravParm() / PosVector.Magnitude()
		a = -self.Primary.GravParm() / (2. * VvE)
		
		e = eVector.Magnitude()
		
		i = acos(HVector._k / HVector.Magnitude())
		
		try:
			Omega = acos(ANVector._i / ANVector.Magnitude())
			if ANVector._j < -1e-6:
				Omega =  2. * pi - Omega
		except ZeroDivisionError:
			Omega =  0.0
		
		try:
			n = ANVector.UnitVector()
			w = acos(n.Dot(eVector) / (n.Magnitude() * e))
			if eVector._k < -1e-6:
				w = 2. * pi - w
		except ZeroDivisionError:
			try:
				w = atan2(eVector._j / e, eVector._i / eVector.Magnitude())
			except ZeroDivisionError:
				w = 0
			if HVector._k < -1e-6:
				w = 2. * pi - w
		
		if e == 0 and i == 0:
			f = acos(PosVector._i / PosVector.Magnitude())
			if VelVector._i > 1e-6:
				f = 2. * pi - f
		elif e == 0:
			f = acos(ANVector.Dot(PosVector) / (ANVector.Magnitude() * PosVector.Magnitude()))
			if ANVector.Dot(VelVector) > 0:
				f = 2. * pi - f
		else:
			f = acos(eVector.Dot(PosVector) / (eVector.Magnitude() * PosVector.Magnitude()))
			if PosVector.Dot(VelVector) < 0:
				f = 2. * pi - f
		
		return (a, e, i, Omega, w, f)
	
	def GetEccentricAnomalyFromTrueAnomaly(self, f):
		'''
		Returns the eccentric anomaly at a given true anomaly.
		
		@param f: True Anomaly [radians]
		@type f: Number
		
		@return: Eccentric Anomaly [radians]
		@rtype: Number
		'''
		E = atan2((1 - self.e ** 2.) ** .5 * sin(f), (self.e + cos(f)))
		if E < 0:
			E = 2 * pi + E
		
		return E
	
	def GetMeanAnomalyFromEccentricAnomaly(self, E):
		'''
		Returns the mean anomaly at a given eccentric anomaly.
		
		@param E: Eccentric anomaly [radians]
		@type E: Number
		
		@return: Mean anomaly [radians]
		@rtype: Number
		'''
		return (E - self.e * sin(E))
	
	def GetMeanAnomalyFromTrueAnomaly(self, f):
		'''
		Returns the mean anomaly at a given true anomaly.
		@param f: True anomaly [radians]
		@type f: Number
		
		@return: Mean anomaly [radians]
		@rtype: Number
		'''
		return self.GetMeanAnomalyFromEccentricAnomaly(self.GetEccentricAnomalyFromTrueAnomaly(f))
	
	def GetTrueAnomalyFromPositionVector(self, PosVector, Tol = 1e-3):
		'''
		Attempts to find and return the true anomaly at a given position vector.
		If it fails, it prints an error and returns None.
		
		@param PosVector: The position vector at which to find the true anomaly
		@type PosVector: Number
		@param Tol: The tolerance to which the positions should match, in meters.  Defaults to .001.
		@type Tol: Number
		
		@return: True Anomaly
		@type: Number
		'''
		e = self.e
		i = self.i
		
		PeriapsisPosVector, PeriapsisVelVector = self.GetStateFromMeanAnomaly(0.)
		_, eVector, ANVector = self.FindAdditionalStateVectors(PeriapsisPosVector, PeriapsisVelVector)
		
		if e == 0 and i == 0:
			f = acos(PosVector._i / PosVector.Magnitude())
		#	if VelVector._i > 1e-6:
		#		f = 2. * pi - f
		elif e == 0:
			f = acos(ANVector.Dot(PosVector) / (ANVector.Magnitude() * PosVector.Magnitude()))
		#	if ANVector.Dot(VelVector) > 0:
		#		f = 2. * pi - f
		else:
			f = acos(eVector.Dot(PosVector) / (eVector.Magnitude() * PosVector.Magnitude()))
		#	if PosVector.Dot(VelVector) < 0:
		#		f = 2. * pi - f
		
		CheckPos1, _ = self.GetStateFromMeanAnomaly(self.GetMeanAnomalyFromTrueAnomaly(f))
		CheckPos2, _ = self.GetStateFromMeanAnomaly(self.GetMeanAnomalyFromTrueAnomaly(2. * pi - f))
		
		if (CheckPos1 - PosVector).Magnitude() < Tol:
			return f
		if (CheckPos2 - PosVector).Magnitude() < Tol:
			return (2. * pi - f)
		
		print("GetTrueAnomalyFromPositionVector: Position not on orbit")
		print("PosVector: {0}".format(PosVector))
		print("CheckPos1: {0}".format(CheckPos1), (CheckPos1 - PosVector).Magnitude())
		print("CheckPos2: {0}".format(CheckPos2), (CheckPos2 - PosVector).Magnitude())
	
	def UpdateFromTrueAnomaly(self, f):
		'''
		Updates the mean anomaly from a given true anomaly.
		@param f: True Anomaly [radians]
		@type f: Number
		'''
		self.M = self.GetMeanAnomalyFromTrueAnomaly(f)
	
	def UpdateFromVectors(self, PosVector, VelVector):
		'''
		Updates the orbital elements from a given set of position and velocity vectors.
		
		@param PosVector: Position vector [m, m, m]
		@type PosVector: Vector3D
		@param VelVector: Velocity vector [m/s, m/s, m/s]
		@type VelVector: Vector3D
		'''
		
		a, e, i, Omega, w, f = self.GetElementsFromStateVectors(PosVector, VelVector)
		
		self.a = a
		self.e = e
		self.i = i
		self.Omega = Omega
		self.w = w
		self.UpdateFromTrueAnomaly(f)
	
	def ConvertVectortoPRNFrame(self, Vector, M = None):
		'''
		Returns a Vector3D converted from the cartesian i, j, k frame to the
		prograde, radial, normal frame described by the orbital state,
		optionally at the specified mean anomaly.
		 
		@param Vector: The x, y, z vector to conver to P, R, N.
		@type Vector: Vector3D
		@param M: Mean anomaly [radians] (optional)
		@type M: Number
		'''
		PosVector = self.PosVector(M)
		VelVector = self.VelVector(M)
		
		PVector = VelVector.UnitVector()
		NVector = (PosVector * VelVector).UnitVector()
		RVector = PVector * NVector
		
		return Vector.ConvertToFrame(PVector, RVector, NVector)
	
	def __setattr__(self, Name, Value):
		'''
		Overrides the default attribute setter.
		@param Name: The name of the class attribute being set.
		@param Value: The value to which the named class attribute will be set.
		'''
		
		# When M is set, dirty and wipe the cached eccentric anomaly.
		if Name == 'M':
			self.__dict__['_EIsDirty'] = True
			self.__dict__['_E'] = None
			return super().__setattr__(Name, Value)
		# When e is set, check if the orbit is circular or elliptical.  If not,
		# report NYI.  Also, make sure the eccentricity isn't negative.
		if Name == 'e':
			if Value is None:
				return super().__setattr__(Name, Value)
			if Value >= 1:
				raise NotImplementedError("Parabolic and hyperbolic trajectories are not yet implemented.")
			if Value < 0:
				raise ValueError("The eccentricity must be in the domain [0, 1).")
			return super().__setattr__(Name, Value)
		
		
		return super().__setattr__(Name, Value)
	
	def GetString(self, M = None):
		if M is None:
			M = self.M
		'''
		Returns a long, multi-line string representing the orbit, optionally at
		specified mean anomaly.
		@param M: Mean anomaly [radians]
		@type M: Number 
		'''
		s  = "Orbiting '{0}'\n".format(self.Primary.Name)
		s += "a = {0} [m]\n".format(self.a)
		s += "e = {0}\n".format(self.e)
		s += "i = {0} [radians]\n".format(self.i)
		s += "Ω = {0} [radians]\n".format(self.Omega)
		s += "ω = {0} [radians]\n".format(self.w)
		s += "M = {0} [radians]\n".format(M)
		s += "E = {0} [radians]\n".format(self.EccentricAnomaly(M))
		s += "υ = {0} [radians]\n".format(self.TrueAnomaly(M))
		s += "\n"
		s += "Current Position: {0} (radius: {1})\n".format(self.PosVector(M), self.PosVector(M).Magnitude())
		s += "Current Velocity: {0} (magnitude: {1})\n".format(self.VelVector(M), self.VelVector(M).Magnitude())
		
		return s
	
	def __str__(self):
		'''
		Returns a long, multi-line string representing the orbit.
		'''
		
		return self.GetString()
	
if __name__ == "__main__":
	from random import random
	Kerbin = Body("Kerbin", Mass = 5.2915793e22, Radius = 600e3)
	Orbit1 = Orbit(Kerbin, random() * 3e6 + 7e5, random(), random() * pi / 2, random() * 2 * pi, 3 * pi / 2 + random() * pi / 2, random() * 2 * pi)
	print(Orbit1)
	
	Orbit2 = Orbit(Kerbin)
	Orbit2.UpdateFromVectors(Orbit1.PosVector(), Orbit1.VelVector())
	print(Orbit2)
	
	PosError = Orbit1.PosVector() - Orbit2.PosVector()
	VelError = Orbit1.VelVector() - Orbit2.VelVector()
	
	if PosError.Magnitude() > 1e-3:
		print("PosError: {0}".format(PosError))
	if VelError.Magnitude() > 1e-3:
		print("PosError: {0}".format(VelError))
	
	Orbit3 = Orbit(Kerbin, 1803823.21032378, 0.21141372855476, 55. * pi / 180., 0, 0, pi)
	print(Orbit3)
	
	Orbit4 = Orbit(Kerbin, 2185176.20087195, 0, 55. * pi / 180., 0, 0, 0)
	
	Orbit4AtOrbit3TrueAnomaly = Orbit4.GetTrueAnomalyFromPositionVector(Orbit3.PosVector())
	print("Current position on Orbit3 lies on Orbit4 at true anomaly {0}.".format(Orbit4AtOrbit3TrueAnomaly))
	Orbit4.UpdateFromTrueAnomaly(Orbit4AtOrbit3TrueAnomaly)
	
	print(Orbit4)
	
	print("Delta-V from Orbit3 to Orbit4 at {0} radians: {1:.6}".format(Orbit4AtOrbit3TrueAnomaly, Orbit4.VelVector() - Orbit3.VelVector()))
	PRNDeltaV = Orbit4.ConvertVectortoPRNFrame(Orbit4.VelVector() - Orbit3.VelVector())
	PRNDeltaV = round(PRNDeltaV, 6)
	print("Delta-V in PRN: {0:.6}".format(PRNDeltaV))