analytical-astro-prop 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ian Mackey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: analytical-astro-prop
3
+ Version: 0.1.0
4
+ Summary: Satellite orbit propagation with the equations of motion generated symbolically in SymPy, ready for auto-optimal-control
5
+ Author: Ian Mackey
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/idm23/analytical-astro-prop
8
+ Project-URL: Repository, https://github.com/idm23/analytical-astro-prop
9
+ Project-URL: Issues, https://github.com/idm23/analytical-astro-prop/issues
10
+ Keywords: astrodynamics,orbit-propagation,orbital-elements,equinoctial,zonal-harmonics,sympy
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
16
+ Classifier: Topic :: Scientific/Engineering :: Physics
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: numpy>=2.0
21
+ Requires-Dist: sympy>=1.12
22
+ Dynamic: license-file
23
+
24
+ # analytical-astro-prop
25
+
26
+ Satellite orbit propagation with the equations of motion generated
27
+ symbolically in SymPy. Every force model is a SymPy expression, so its
28
+ Jacobian is exact (an indirect method needs it for the costate equations, a
29
+ shooting method for the variational equations) and it compiles to fast
30
+ numerical code. The model that is optimized and the model that checks the
31
+ answer are the same expressions.
32
+
33
+ It is the dynamics layer for orbit problems in
34
+ [auto-optimal-control](https://github.com/idm23/auto-optimal-control) (AOC):
35
+ AOC's low-thrust transfers are written on this package's modified
36
+ equinoctial equations. This package never imports AOC, so it can be used on
37
+ its own.
38
+
39
+ > **Status: pre-alpha.** Two-body and zonal gravity (EGM2008, J2 to J6),
40
+ > Cartesian and modified equinoctial equations of motion with an optional
41
+ > thrust, and element conversions are in place.
42
+
43
+ ## What's in it
44
+
45
+ - `analytical_astro_prop.constants`: bodies (`EARTH`, with EGM2008 zonal
46
+ harmonics) and `CanonicalUnits` (`mu = 1`, lengths in a chosen unit).
47
+ - `analytical_astro_prop.elements`: Keplerian, Cartesian and modified
48
+ equinoctial elements, as NumPy conversions and as SymPy expressions.
49
+ - `analytical_astro_prop.forces`: accelerations as SymPy vectors. Point mass
50
+ and zonal harmonics, the zonals as the exact gradient of their potential,
51
+ and `rtn_basis` for the radial / transverse / normal frame.
52
+ - `analytical_astro_prop.dynamics`: `cartesian` (Newton) and `equinoctial`
53
+ (Gauss's variational equations) equations of motion, with any extra
54
+ acceleration, such as a thrust, added.
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ git clone https://github.com/idm23/analytical-astro-prop
60
+ cd analytical-astro-prop
61
+ uv sync
62
+ uv run pytest
63
+ ```
64
+
65
+ The package is not on PyPI yet.
66
+
67
+ ## Example: an orbit under J2, propagated in equinoctial elements
68
+
69
+ ```python
70
+ import numpy as np
71
+ import sympy as sp
72
+ from scipy.integrate import solve_ivp
73
+
74
+ from analytical_astro_prop import (EARTH, CanonicalUnits, Gravity, equinoctial,
75
+ equinoctial_to_keplerian, keplerian_to_equinoctial,
76
+ numeric)
77
+
78
+ units = CanonicalUnits.of(EARTH) # mu = 1, lengths in Earth radii
79
+ gravity = Gravity.of(EARTH, degree=2, units=units) # point mass + J2
80
+
81
+ mee = sp.symbols("p f g h k L", real=True)
82
+ rates = equinoctial(gravity, mee) # six SymPy expressions
83
+ rhs = numeric(rates, mee) # compiled to NumPy
84
+
85
+ # The ISS's orbit: 420 km, 51.6 deg, for one day.
86
+ x0 = keplerian_to_equinoctial(1 + 420 / EARTH.radius, 0.001, np.radians(51.6), 0.3, 0.0, 0.0)
87
+ sol = solve_ivp(lambda t, x: rhs(*x), (0, 86400 / units.time), x0, rtol=1e-10, atol=1e-12)
88
+ a, e, i, raan, argp, nu = equinoctial_to_keplerian(sol.y[:, -1])
89
+ print(f"the node moved {np.degrees(raan - 0.3):.2f} deg in a day") # about -5 deg
90
+ ```
91
+
92
+ Because `rates` are SymPy expressions, `sp.Matrix(rates).jacobian(mee)` is
93
+ the exact Jacobian, and a thrust is one more argument:
94
+ `equinoctial(gravity, mee, thrust=[0, T, 0])` pushes along the transverse
95
+ direction.
@@ -0,0 +1,72 @@
1
+ # analytical-astro-prop
2
+
3
+ Satellite orbit propagation with the equations of motion generated
4
+ symbolically in SymPy. Every force model is a SymPy expression, so its
5
+ Jacobian is exact (an indirect method needs it for the costate equations, a
6
+ shooting method for the variational equations) and it compiles to fast
7
+ numerical code. The model that is optimized and the model that checks the
8
+ answer are the same expressions.
9
+
10
+ It is the dynamics layer for orbit problems in
11
+ [auto-optimal-control](https://github.com/idm23/auto-optimal-control) (AOC):
12
+ AOC's low-thrust transfers are written on this package's modified
13
+ equinoctial equations. This package never imports AOC, so it can be used on
14
+ its own.
15
+
16
+ > **Status: pre-alpha.** Two-body and zonal gravity (EGM2008, J2 to J6),
17
+ > Cartesian and modified equinoctial equations of motion with an optional
18
+ > thrust, and element conversions are in place.
19
+
20
+ ## What's in it
21
+
22
+ - `analytical_astro_prop.constants`: bodies (`EARTH`, with EGM2008 zonal
23
+ harmonics) and `CanonicalUnits` (`mu = 1`, lengths in a chosen unit).
24
+ - `analytical_astro_prop.elements`: Keplerian, Cartesian and modified
25
+ equinoctial elements, as NumPy conversions and as SymPy expressions.
26
+ - `analytical_astro_prop.forces`: accelerations as SymPy vectors. Point mass
27
+ and zonal harmonics, the zonals as the exact gradient of their potential,
28
+ and `rtn_basis` for the radial / transverse / normal frame.
29
+ - `analytical_astro_prop.dynamics`: `cartesian` (Newton) and `equinoctial`
30
+ (Gauss's variational equations) equations of motion, with any extra
31
+ acceleration, such as a thrust, added.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ git clone https://github.com/idm23/analytical-astro-prop
37
+ cd analytical-astro-prop
38
+ uv sync
39
+ uv run pytest
40
+ ```
41
+
42
+ The package is not on PyPI yet.
43
+
44
+ ## Example: an orbit under J2, propagated in equinoctial elements
45
+
46
+ ```python
47
+ import numpy as np
48
+ import sympy as sp
49
+ from scipy.integrate import solve_ivp
50
+
51
+ from analytical_astro_prop import (EARTH, CanonicalUnits, Gravity, equinoctial,
52
+ equinoctial_to_keplerian, keplerian_to_equinoctial,
53
+ numeric)
54
+
55
+ units = CanonicalUnits.of(EARTH) # mu = 1, lengths in Earth radii
56
+ gravity = Gravity.of(EARTH, degree=2, units=units) # point mass + J2
57
+
58
+ mee = sp.symbols("p f g h k L", real=True)
59
+ rates = equinoctial(gravity, mee) # six SymPy expressions
60
+ rhs = numeric(rates, mee) # compiled to NumPy
61
+
62
+ # The ISS's orbit: 420 km, 51.6 deg, for one day.
63
+ x0 = keplerian_to_equinoctial(1 + 420 / EARTH.radius, 0.001, np.radians(51.6), 0.3, 0.0, 0.0)
64
+ sol = solve_ivp(lambda t, x: rhs(*x), (0, 86400 / units.time), x0, rtol=1e-10, atol=1e-12)
65
+ a, e, i, raan, argp, nu = equinoctial_to_keplerian(sol.y[:, -1])
66
+ print(f"the node moved {np.degrees(raan - 0.3):.2f} deg in a day") # about -5 deg
67
+ ```
68
+
69
+ Because `rates` are SymPy expressions, `sp.Matrix(rates).jacobian(mee)` is
70
+ the exact Jacobian, and a thrust is one more argument:
71
+ `equinoctial(gravity, mee, thrust=[0, T, 0])` pushes along the transverse
72
+ direction.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "analytical-astro-prop"
7
+ version = "0.1.0"
8
+ description = "Satellite orbit propagation with the equations of motion generated symbolically in SymPy, ready for auto-optimal-control"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Ian Mackey" }]
13
+ requires-python = ">=3.11"
14
+ keywords = ["astrodynamics", "orbit-propagation", "orbital-elements", "equinoctial", "zonal-harmonics", "sympy"]
15
+ classifiers = [
16
+ "Development Status :: 2 - Pre-Alpha",
17
+ "Intended Audience :: Science/Research",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Scientific/Engineering :: Astronomy",
21
+ "Topic :: Scientific/Engineering :: Physics",
22
+ ]
23
+ dependencies = [
24
+ "numpy>=2.0",
25
+ "sympy>=1.12",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/idm23/analytical-astro-prop"
30
+ Repository = "https://github.com/idm23/analytical-astro-prop"
31
+ Issues = "https://github.com/idm23/analytical-astro-prop/issues"
32
+
33
+ [dependency-groups]
34
+ # The tests integrate the generated equations with scipy.integrate.solve_ivp.
35
+ dev = ["pytest>=8.0", "scipy>=1.13"]
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ addopts = "--import-mode=importlib"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,36 @@
1
+ """Symbolic orbital dynamics: force models and equations of motion in SymPy.
2
+
3
+ Everything is a SymPy expression, so it can be differentiated exactly (an indirect
4
+ method needs the dynamics' Jacobian for its costate equations, a shooting method the
5
+ variational equations) and compiled. Numbers come from the same expressions through
6
+ :func:`numeric`, so the model that is optimized and the model that checks the answer
7
+ are one.
8
+
9
+ The package never imports ``auto_optimal_control``: it is a base that optimal control
10
+ problems are built on (``auto_optimal_control.orbits`` builds its low-thrust transfers
11
+ on :func:`equinoctial`), and its expressions go into ``derive`` as they are.
12
+
13
+ - :mod:`~analytical_astro_prop.constants`: bodies (Earth: EGM2008 zonal harmonics)
14
+ and canonical units.
15
+ - :mod:`~analytical_astro_prop.elements`: Keplerian, Cartesian and modified
16
+ equinoctial elements, symbolic and numeric.
17
+ - :mod:`~analytical_astro_prop.forces`: accelerations (point mass, zonal harmonics)
18
+ as SymPy vectors, and their projection on the radial / transverse / normal frame.
19
+ - :mod:`~analytical_astro_prop.dynamics`: equations of motion, Cartesian and modified
20
+ equinoctial (Gauss's variational equations), with any extra acceleration (a
21
+ thrust) added.
22
+ """
23
+
24
+ from analytical_astro_prop.constants import EARTH, Body, CanonicalUnits
25
+ from analytical_astro_prop.dynamics import cartesian, equinoctial
26
+ from analytical_astro_prop.elements import (cartesian_to_equinoctial,
27
+ equinoctial_to_cartesian,
28
+ equinoctial_to_keplerian,
29
+ keplerian_to_equinoctial,
30
+ symbolic_equinoctial_to_cartesian)
31
+ from analytical_astro_prop.forces import Gravity, numeric, rtn_basis
32
+
33
+ __all__ = ["EARTH", "Body", "CanonicalUnits", "Gravity", "cartesian", "equinoctial",
34
+ "cartesian_to_equinoctial", "equinoctial_to_cartesian", "equinoctial_to_keplerian",
35
+ "keplerian_to_equinoctial", "symbolic_equinoctial_to_cartesian", "numeric",
36
+ "rtn_basis"]
@@ -0,0 +1,65 @@
1
+ """Bodies and units.
2
+
3
+ Units are kilometres and seconds. :class:`CanonicalUnits` scales a problem so that
4
+ ``mu = 1`` and a chosen length is 1, which keeps an optimizer's unknowns near one.
5
+ """
6
+
7
+ import math
8
+ from dataclasses import dataclass, field
9
+
10
+ # EGM2008 fully normalized zonal coefficients C_n0 (tide-free), n = 2..6.
11
+ _EGM2008_C = {2: -4.84165143790815e-4, 3: 9.57161207093473e-7, 4: 5.39965866638991e-7,
12
+ 5: 6.86702913736681e-8, 6: -1.49953927978527e-7}
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Body:
17
+ """A central body: ``mu`` (km^3/s^2), reference ``radius`` (km), unnormalized zonal
18
+ coefficients ``J`` ({n: J_n}, the potential's ``-J_n (R/r)^n P_n(sin phi)`` terms)
19
+ and ``rotation`` rate (rad/s)."""
20
+
21
+ name: str
22
+ mu: float
23
+ radius: float
24
+ J: dict = field(default_factory=dict)
25
+ rotation: float = 0.0
26
+
27
+ def zonals(self, degree):
28
+ """``{n: J_n}`` for n = 2..degree."""
29
+ return {n: self.J[n] for n in range(2, degree + 1)}
30
+
31
+
32
+ EARTH = Body(
33
+ name="Earth",
34
+ mu=398600.4418, # km^3/s^2 (WGS84 / EGM2008)
35
+ radius=6378.1363, # km (EGM2008 reference radius)
36
+ # J_n = -C_n0 sqrt(2n + 1) unnormalizes a fully normalized zonal coefficient.
37
+ J={n: -c * math.sqrt(2 * n + 1) for n, c in _EGM2008_C.items()},
38
+ rotation=7.292115e-5, # rad/s
39
+ )
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class CanonicalUnits:
44
+ """Lengths in units of ``length`` km and times in ``sqrt(length^3 / mu)`` s, so that
45
+ ``mu = 1``. Velocities are then in units of the circular speed at ``length``."""
46
+
47
+ mu: float
48
+ length: float
49
+
50
+ @property
51
+ def time(self):
52
+ return math.sqrt(self.length ** 3 / self.mu)
53
+
54
+ @property
55
+ def speed(self):
56
+ return self.length / self.time
57
+
58
+ @property
59
+ def acceleration(self):
60
+ return self.length / self.time ** 2
61
+
62
+ @classmethod
63
+ def of(cls, body, length=None):
64
+ """Canonical units of ``body``, with ``length`` its radius by default."""
65
+ return cls(body.mu, body.radius if length is None else length)
@@ -0,0 +1,65 @@
1
+ """Equations of motion, Cartesian and modified equinoctial.
2
+
3
+ Both take a :class:`~analytical_astro_prop.forces.Gravity` and an optional extra
4
+ acceleration (a thrust ``T delta / m`` times its direction, say): in the inertial frame for
5
+ :func:`cartesian`, and in the radial / transverse / normal frame for
6
+ :func:`equinoctial`, which is the frame a thrust direction is usually given in.
7
+ The mass equation, if any, belongs to the caller.
8
+ """
9
+
10
+ import sympy as sp
11
+
12
+ from analytical_astro_prop.elements import equinoctial_frame, symbolic_equinoctial_to_cartesian
13
+
14
+
15
+ def cartesian(gravity, r, v, thrust=None):
16
+ """``d(r, v)/dt``: the six rates, as a list of SymPy expressions. ``thrust`` is an
17
+ inertial acceleration (3-vector) added to gravity's."""
18
+ a = gravity.acceleration(sp.Matrix(r))
19
+ if thrust is not None:
20
+ a = a + sp.Matrix(thrust)
21
+ return [*v, *a]
22
+
23
+
24
+ def equinoctial(gravity, mee, thrust=None):
25
+ """``d(p, f, g, h, k, L)/dt``: Gauss's variational equations in modified equinoctial
26
+ elements (Walker, Ireland & Owens 1985; Betts 2010 eq. 6.35), as a list of SymPy
27
+ expressions.
28
+
29
+ The perturbing acceleration ``Delta = (D_r, D_t, D_n)`` in the radial / transverse /
30
+ normal frame is gravity's beyond the point mass, projected on that frame, plus
31
+ ``thrust`` (a 3-vector in the same frame)::
32
+
33
+ q = 1 + f cos L + g sin L, s^2 = 1 + h^2 + k^2, z = h sin L - k cos L
34
+ p' = 2 p / q sqrt(p/mu) D_t
35
+ f' = sqrt(p/mu) ( D_r sin L + ((q + 1) cos L + f) D_t / q - z g D_n / q)
36
+ g' = sqrt(p/mu) (- D_r cos L + ((q + 1) sin L + g) D_t / q + z f D_n / q)
37
+ h' = sqrt(p/mu) s^2 cos L D_n / (2 q)
38
+ k' = sqrt(p/mu) s^2 sin L D_n / (2 q)
39
+ L' = sqrt(mu p) (q / p)^2 + sqrt(p/mu) z D_n / q
40
+ """
41
+ p, f, g, h, k, L = mee
42
+ mu = gravity.mu
43
+ D = sp.zeros(3, 1)
44
+ if gravity.J:
45
+ pos, _ = symbolic_equinoctial_to_cartesian(p, f, g, h, k, L, mu)
46
+ fh, gh, wh = equinoctial_frame(h, k)
47
+ ir = sp.cos(L) * fh + sp.sin(L) * gh
48
+ it = -sp.sin(L) * fh + sp.cos(L) * gh
49
+ a = gravity.perturbation(pos)
50
+ D = D + sp.Matrix([ir.dot(a), it.dot(a), wh.dot(a)])
51
+ if thrust is not None:
52
+ D = D + sp.Matrix(thrust)
53
+ Dr, Dt, Dn = D
54
+ q = 1 + f * sp.cos(L) + g * sp.sin(L)
55
+ s2 = 1 + h ** 2 + k ** 2
56
+ z = h * sp.sin(L) - k * sp.cos(L)
57
+ sq = sp.sqrt(p / mu)
58
+ return [
59
+ 2 * p / q * sq * Dt,
60
+ sq * (Dr * sp.sin(L) + ((q + 1) * sp.cos(L) + f) * Dt / q - z * g * Dn / q),
61
+ sq * (-Dr * sp.cos(L) + ((q + 1) * sp.sin(L) + g) * Dt / q + z * f * Dn / q),
62
+ sq * s2 * sp.cos(L) * Dn / (2 * q),
63
+ sq * s2 * sp.sin(L) * Dn / (2 * q),
64
+ sp.sqrt(mu * p) * (q / p) ** 2 + sq * z * Dn / q,
65
+ ]
@@ -0,0 +1,93 @@
1
+ """Orbital elements: Keplerian, Cartesian and modified equinoctial.
2
+
3
+ Modified equinoctial elements (Walker, Ireland & Owens 1985) are
4
+
5
+ p = a (1 - e^2) semi-latus rectum
6
+ f = e cos(omega + Omega) g = e sin(omega + Omega)
7
+ h = tan(i/2) cos Omega k = tan(i/2) sin Omega
8
+ L = Omega + omega + nu true longitude
9
+
10
+ and are regular for circular and equatorial orbits (only i = 180 deg is singular),
11
+ which is why low-thrust transfers are usually solved in them: five of the six move
12
+ slowly, and only ``L`` turns once per revolution.
13
+
14
+ The equinoctial frame: ``f_hat`` and ``g_hat`` span the orbit plane (``f_hat`` points
15
+ where ``L = 0``), and ``w_hat = f_hat x g_hat`` is the orbit normal,
16
+
17
+ f_hat = (1 + h^2 - k^2, 2hk, -2k) / s^2
18
+ g_hat = (2hk, 1 - h^2 + k^2, 2h) / s^2
19
+ w_hat = (2k, -2h, 1 - h^2 - k^2) / s^2, s^2 = 1 + h^2 + k^2.
20
+
21
+ The NumPy functions take and return arrays; :func:`symbolic_equinoctial_to_cartesian`
22
+ gives the same map as SymPy expressions.
23
+ """
24
+
25
+ import numpy as np
26
+ import sympy as sp
27
+
28
+
29
+ def _frame(h, k):
30
+ s2 = 1 + h ** 2 + k ** 2
31
+ fh = [(1 + h ** 2 - k ** 2) / s2, 2 * h * k / s2, -2 * k / s2]
32
+ gh = [2 * h * k / s2, (1 - h ** 2 + k ** 2) / s2, 2 * h / s2]
33
+ wh = [2 * k / s2, -2 * h / s2, (1 - h ** 2 - k ** 2) / s2]
34
+ return fh, gh, wh
35
+
36
+
37
+ def equinoctial_frame(h, k):
38
+ """``(f_hat, g_hat, w_hat)`` as SymPy 3-vectors (or numbers, for numbers)."""
39
+ fh, gh, wh = _frame(h, k)
40
+ return sp.Matrix(fh), sp.Matrix(gh), sp.Matrix(wh)
41
+
42
+
43
+ def symbolic_equinoctial_to_cartesian(p, f, g, h, k, L, mu):
44
+ """Position and velocity (SymPy 3-vectors) from modified equinoctial elements."""
45
+ fh, gh, _ = equinoctial_frame(h, k)
46
+ w = 1 + f * sp.cos(L) + g * sp.sin(L)
47
+ r = p / w
48
+ pos = r * (sp.cos(L) * fh + sp.sin(L) * gh)
49
+ vel = sp.sqrt(mu / p) * (-(g + sp.sin(L)) * fh + (f + sp.cos(L)) * gh)
50
+ return pos, vel
51
+
52
+
53
+ def equinoctial_to_cartesian(mee, mu):
54
+ """``(r, v)`` from ``mee = (p, f, g, h, k, L)`` (NumPy)."""
55
+ p, f, g, h, k, L = np.asarray(mee, dtype=float)
56
+ fh, gh, _ = (np.array(v) for v in _frame(h, k))
57
+ w = 1 + f * np.cos(L) + g * np.sin(L)
58
+ r = p / w * (np.cos(L) * fh + np.sin(L) * gh)
59
+ v = np.sqrt(mu / p) * (-(g + np.sin(L)) * fh + (f + np.cos(L)) * gh)
60
+ return r, v
61
+
62
+
63
+ def cartesian_to_equinoctial(r, v, mu):
64
+ """``(p, f, g, h, k, L)`` from position and velocity (NumPy); ``L`` in (-pi, pi]."""
65
+ r, v = np.asarray(r, dtype=float), np.asarray(v, dtype=float)
66
+ hv = np.cross(r, v)
67
+ hn = np.linalg.norm(hv)
68
+ p = hn ** 2 / mu
69
+ w = hv / hn # (sin i sin O, -sin i cos O, cos i)
70
+ if w[2] <= -1 + 1e-14:
71
+ raise ValueError("retrograde equatorial orbit: modified equinoctial elements are singular")
72
+ h, k = -w[1] / (1 + w[2]), w[0] / (1 + w[2])
73
+ fh, gh, _ = (np.array(x) for x in _frame(h, k))
74
+ e = np.cross(v, hv) / mu - r / np.linalg.norm(r)
75
+ return np.array([p, e @ fh, e @ gh, h, k, np.arctan2(r @ gh, r @ fh)])
76
+
77
+
78
+ def keplerian_to_equinoctial(a, e, i, raan, argp, nu):
79
+ """``(p, f, g, h, k, L)`` from Keplerian elements (angles in radians)."""
80
+ return np.array([a * (1 - e ** 2), e * np.cos(argp + raan), e * np.sin(argp + raan),
81
+ np.tan(i / 2) * np.cos(raan), np.tan(i / 2) * np.sin(raan),
82
+ raan + argp + nu])
83
+
84
+
85
+ def equinoctial_to_keplerian(mee):
86
+ """``(a, e, i, raan, argp, nu)`` from ``(p, f, g, h, k, L)``; for a circular or
87
+ equatorial orbit the undefined angles are taken as zero."""
88
+ p, f, g, h, k, L = np.asarray(mee, dtype=float)
89
+ e = np.hypot(f, g)
90
+ i = 2 * np.arctan(np.hypot(h, k))
91
+ raan = np.arctan2(k, h) if np.hypot(h, k) > 0 else 0.0
92
+ lon_peri = np.arctan2(g, f) if e > 0 else 0.0
93
+ return np.array([p / (1 - e ** 2), e, i, raan, lon_peri - raan, L - lon_peri])
@@ -0,0 +1,97 @@
1
+ """Accelerations as SymPy vectors.
2
+
3
+ A force model is a function of the position (a SymPy 3-vector, whose entries may be
4
+ symbols or expressions in other states, such as the equinoctial elements) and its
5
+ parameters (numbers or SymPy symbols, so a problem can vary them). Conservative forces
6
+ are written as potentials and differentiated, so the acceleration is the exact
7
+ gradient of the potential, and its Jacobian is exact too.
8
+ """
9
+
10
+ import numpy as np
11
+ import sympy as sp
12
+
13
+
14
+ def norm(r):
15
+ return sp.sqrt(sum(x ** 2 for x in r))
16
+
17
+
18
+ def _gradient_at(potential, r):
19
+ """The gradient of ``potential(X)`` at the position ``r``: differentiated in plain
20
+ symbols, then evaluated at ``r`` (which may be any expressions)."""
21
+ X = sp.symbols("_X _Y _Z", real=True)
22
+ U = potential(sp.Matrix(X))
23
+ grad = sp.Matrix([sp.diff(U, x) for x in X])
24
+ return grad.xreplace(dict(zip(X, r)))
25
+
26
+
27
+ def point_mass(r, mu):
28
+ """``-mu r / |r|^3``."""
29
+ r = sp.Matrix(r)
30
+ return -mu * r / norm(r) ** 3
31
+
32
+
33
+ def zonal_potential(r, mu, radius, J):
34
+ """The zonal harmonics' part of the gravity potential (the acceleration is its
35
+ gradient): ``-(mu/r) sum_n J_n (R/r)^n P_n(z/r)``, ``J`` as ``{n: J_n}``."""
36
+ rn = norm(r)
37
+ s = r[2] / rn
38
+ return -mu / rn * sum(Jn * (radius / rn) ** n * sp.legendre(n, s) for n, Jn in J.items())
39
+
40
+
41
+ def zonal(r, mu, radius, J):
42
+ """The acceleration of the zonal harmonics ``J`` (``{n: J_n}``) at ``r``."""
43
+ return _gradient_at(lambda X: zonal_potential(X, mu, radius, J), r)
44
+
45
+
46
+ class Gravity:
47
+ """A body's gravity: a point mass ``mu`` and, optionally, zonal harmonics.
48
+
49
+ ``mu``, ``radius`` and the ``J`` values may be numbers or SymPy symbols. Use
50
+ :meth:`of` to take them from a :class:`~analytical_astro_prop.constants.Body`."""
51
+
52
+ def __init__(self, mu, radius=None, J=None):
53
+ self.mu, self.radius, self.J = mu, radius, dict(J or {})
54
+ if self.J and radius is None:
55
+ raise ValueError("zonal harmonics need the body's reference radius")
56
+
57
+ @classmethod
58
+ def of(cls, body, degree=2, units=None):
59
+ """``body``'s gravity to zonal ``degree`` (1 for a point mass), in canonical
60
+ ``units`` if given (``mu = 1``)."""
61
+ mu, radius = body.mu, body.radius
62
+ if units is not None:
63
+ mu, radius = 1.0, body.radius / units.length
64
+ return cls(mu, radius, body.zonals(degree) if degree >= 2 else {})
65
+
66
+ def potential(self, r):
67
+ """The potential ``V`` (the acceleration is ``grad V``)."""
68
+ V = self.mu / norm(r)
69
+ if self.J:
70
+ V = V + zonal_potential(r, self.mu, self.radius, self.J)
71
+ return V
72
+
73
+ def perturbation(self, r):
74
+ """The acceleration beyond the point mass (zero vector without harmonics)."""
75
+ if not self.J:
76
+ return sp.zeros(3, 1)
77
+ return zonal(r, self.mu, self.radius, self.J)
78
+
79
+ def acceleration(self, r):
80
+ return point_mass(r, self.mu) + self.perturbation(r)
81
+
82
+
83
+ def rtn_basis(r, v):
84
+ """The radial / transverse / normal unit vectors ``(i_r, i_t, i_n)`` of the orbit
85
+ through ``(r, v)``: ``i_r`` along ``r``, ``i_n`` along ``r x v``, ``i_t = i_n x i_r``."""
86
+ r, v = sp.Matrix(r), sp.Matrix(v)
87
+ ir = r / norm(r)
88
+ hv = r.cross(v)
89
+ i_n = hv / norm(hv)
90
+ return ir, i_n.cross(ir), i_n
91
+
92
+
93
+ def numeric(exprs, symbols):
94
+ """A NumPy function of ``symbols`` (a flat sequence) giving ``exprs`` (a sequence or
95
+ a Matrix) as a float array, compiled with common subexpressions shared."""
96
+ fn = sp.lambdify(list(symbols), list(exprs), modules="numpy", cse=True)
97
+ return lambda *args: np.asarray(fn(*args), dtype=float)
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: analytical-astro-prop
3
+ Version: 0.1.0
4
+ Summary: Satellite orbit propagation with the equations of motion generated symbolically in SymPy, ready for auto-optimal-control
5
+ Author: Ian Mackey
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/idm23/analytical-astro-prop
8
+ Project-URL: Repository, https://github.com/idm23/analytical-astro-prop
9
+ Project-URL: Issues, https://github.com/idm23/analytical-astro-prop/issues
10
+ Keywords: astrodynamics,orbit-propagation,orbital-elements,equinoctial,zonal-harmonics,sympy
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
16
+ Classifier: Topic :: Scientific/Engineering :: Physics
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: numpy>=2.0
21
+ Requires-Dist: sympy>=1.12
22
+ Dynamic: license-file
23
+
24
+ # analytical-astro-prop
25
+
26
+ Satellite orbit propagation with the equations of motion generated
27
+ symbolically in SymPy. Every force model is a SymPy expression, so its
28
+ Jacobian is exact (an indirect method needs it for the costate equations, a
29
+ shooting method for the variational equations) and it compiles to fast
30
+ numerical code. The model that is optimized and the model that checks the
31
+ answer are the same expressions.
32
+
33
+ It is the dynamics layer for orbit problems in
34
+ [auto-optimal-control](https://github.com/idm23/auto-optimal-control) (AOC):
35
+ AOC's low-thrust transfers are written on this package's modified
36
+ equinoctial equations. This package never imports AOC, so it can be used on
37
+ its own.
38
+
39
+ > **Status: pre-alpha.** Two-body and zonal gravity (EGM2008, J2 to J6),
40
+ > Cartesian and modified equinoctial equations of motion with an optional
41
+ > thrust, and element conversions are in place.
42
+
43
+ ## What's in it
44
+
45
+ - `analytical_astro_prop.constants`: bodies (`EARTH`, with EGM2008 zonal
46
+ harmonics) and `CanonicalUnits` (`mu = 1`, lengths in a chosen unit).
47
+ - `analytical_astro_prop.elements`: Keplerian, Cartesian and modified
48
+ equinoctial elements, as NumPy conversions and as SymPy expressions.
49
+ - `analytical_astro_prop.forces`: accelerations as SymPy vectors. Point mass
50
+ and zonal harmonics, the zonals as the exact gradient of their potential,
51
+ and `rtn_basis` for the radial / transverse / normal frame.
52
+ - `analytical_astro_prop.dynamics`: `cartesian` (Newton) and `equinoctial`
53
+ (Gauss's variational equations) equations of motion, with any extra
54
+ acceleration, such as a thrust, added.
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ git clone https://github.com/idm23/analytical-astro-prop
60
+ cd analytical-astro-prop
61
+ uv sync
62
+ uv run pytest
63
+ ```
64
+
65
+ The package is not on PyPI yet.
66
+
67
+ ## Example: an orbit under J2, propagated in equinoctial elements
68
+
69
+ ```python
70
+ import numpy as np
71
+ import sympy as sp
72
+ from scipy.integrate import solve_ivp
73
+
74
+ from analytical_astro_prop import (EARTH, CanonicalUnits, Gravity, equinoctial,
75
+ equinoctial_to_keplerian, keplerian_to_equinoctial,
76
+ numeric)
77
+
78
+ units = CanonicalUnits.of(EARTH) # mu = 1, lengths in Earth radii
79
+ gravity = Gravity.of(EARTH, degree=2, units=units) # point mass + J2
80
+
81
+ mee = sp.symbols("p f g h k L", real=True)
82
+ rates = equinoctial(gravity, mee) # six SymPy expressions
83
+ rhs = numeric(rates, mee) # compiled to NumPy
84
+
85
+ # The ISS's orbit: 420 km, 51.6 deg, for one day.
86
+ x0 = keplerian_to_equinoctial(1 + 420 / EARTH.radius, 0.001, np.radians(51.6), 0.3, 0.0, 0.0)
87
+ sol = solve_ivp(lambda t, x: rhs(*x), (0, 86400 / units.time), x0, rtol=1e-10, atol=1e-12)
88
+ a, e, i, raan, argp, nu = equinoctial_to_keplerian(sol.y[:, -1])
89
+ print(f"the node moved {np.degrees(raan - 0.3):.2f} deg in a day") # about -5 deg
90
+ ```
91
+
92
+ Because `rates` are SymPy expressions, `sp.Matrix(rates).jacobian(mee)` is
93
+ the exact Jacobian, and a thrust is one more argument:
94
+ `equinoctial(gravity, mee, thrust=[0, T, 0])` pushes along the transverse
95
+ direction.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/analytical_astro_prop/__init__.py
5
+ src/analytical_astro_prop/constants.py
6
+ src/analytical_astro_prop/dynamics.py
7
+ src/analytical_astro_prop/elements.py
8
+ src/analytical_astro_prop/forces.py
9
+ src/analytical_astro_prop.egg-info/PKG-INFO
10
+ src/analytical_astro_prop.egg-info/SOURCES.txt
11
+ src/analytical_astro_prop.egg-info/dependency_links.txt
12
+ src/analytical_astro_prop.egg-info/requires.txt
13
+ src/analytical_astro_prop.egg-info/top_level.txt
14
+ tests/test_dynamics.py
@@ -0,0 +1,2 @@
1
+ numpy>=2.0
2
+ sympy>=1.12
@@ -0,0 +1,161 @@
1
+ """Element conversions, force models and equations of motion.
2
+
3
+ The equinoctial equations are checked against the Cartesian ones by integrating the
4
+ same orbit both ways under J2; the Cartesian ones against energy conservation and
5
+ J2's secular drift of the node.
6
+ """
7
+
8
+ import numpy as np
9
+ import pytest
10
+ import sympy as sp
11
+
12
+ from analytical_astro_prop import (EARTH, CanonicalUnits, Gravity, cartesian,
13
+ cartesian_to_equinoctial, equinoctial,
14
+ equinoctial_to_cartesian, equinoctial_to_keplerian,
15
+ keplerian_to_equinoctial, numeric,
16
+ symbolic_equinoctial_to_cartesian)
17
+ from analytical_astro_prop.forces import point_mass
18
+
19
+ scipy_integrate = pytest.importorskip("scipy.integrate")
20
+
21
+ U = CanonicalUnits.of(EARTH)
22
+ ORBITS = [ # a (Earth radii), e, i, raan, argp, nu
23
+ (1.1, 0.0, 0.0, 0.0, 0.0, 0.3),
24
+ (1.2, 0.01, np.radians(28.5), 0.4, 1.0, 2.0),
25
+ (4.0, 0.72, np.radians(7.0), -1.2, 3.0, -0.5), # a GTO
26
+ (6.6, 1e-4, np.radians(0.05), 2.0, -1.0, 1.0), # near GEO
27
+ (1.15, 0.1, np.radians(98.0), 0.1, 0.2, 0.3), # retrograde, sun-synchronous-like
28
+ ]
29
+
30
+
31
+ @pytest.mark.parametrize("orbit", ORBITS)
32
+ def test_elements_round_trip(orbit):
33
+ mee = keplerian_to_equinoctial(*orbit)
34
+ r, v = equinoctial_to_cartesian(mee, 1.0)
35
+ back = cartesian_to_equinoctial(r, v, 1.0)
36
+ assert back[:5] == pytest.approx(mee[:5], abs=1e-12)
37
+ assert np.cos(back[5] - mee[5]) == pytest.approx(1, abs=1e-12)
38
+ a, e, i, *_ = equinoctial_to_keplerian(mee)
39
+ assert (a, e, i) == pytest.approx(orbit[:3], abs=1e-12)
40
+ # the vis-viva energy and the angular momentum
41
+ assert v @ v / 2 - 1 / np.linalg.norm(r) == pytest.approx(-1 / (2 * orbit[0]), rel=1e-12)
42
+ assert np.linalg.norm(np.cross(r, v)) ** 2 == pytest.approx(mee[0], rel=1e-12)
43
+
44
+
45
+ def test_symbolic_and_numeric_conversions_agree():
46
+ els = sp.symbols("p f g h k L", real=True)
47
+ pos, vel = symbolic_equinoctial_to_cartesian(*els, 1)
48
+ fn = numeric([*pos, *vel], els)
49
+ for orbit in ORBITS:
50
+ mee = keplerian_to_equinoctial(*orbit)
51
+ r, v = equinoctial_to_cartesian(mee, 1.0)
52
+ assert fn(*mee) == pytest.approx(np.concatenate([r, v]), abs=1e-13)
53
+
54
+
55
+ def test_earth_constants():
56
+ assert EARTH.J[2] == pytest.approx(1.0826262e-3, rel=1e-7) # EGM2008 (EGM96: 1.0826267e-3)
57
+ assert EARTH.J[3] == pytest.approx(-2.5324e-6, rel=1e-4)
58
+ assert EARTH.J[4] == pytest.approx(-1.6199e-6, rel=1e-4)
59
+ assert U.time == pytest.approx(806.81, rel=1e-4) # s
60
+ assert U.speed == pytest.approx(7.9054, rel=1e-4) # km/s
61
+
62
+
63
+ def test_j2_acceleration_is_the_gradient_of_its_potential_in_closed_form():
64
+ x, y, z = r = sp.symbols("x y z", real=True)
65
+ mu, R, J2 = sp.symbols("mu R J_2", positive=True)
66
+ a = Gravity(mu, R, {2: J2}).perturbation(sp.Matrix(r))
67
+ rn = sp.sqrt(x ** 2 + y ** 2 + z ** 2)
68
+ c = -sp.Rational(3, 2) * J2 * mu * R ** 2 / rn ** 5
69
+ closed = sp.Matrix([c * x * (1 - 5 * z ** 2 / rn ** 2), c * y * (1 - 5 * z ** 2 / rn ** 2),
70
+ c * z * (3 - 5 * z ** 2 / rn ** 2)])
71
+ pt = {x: 0.7, y: -0.4, z: 0.9, mu: 1.3, R: 0.8, J2: 1e-3}
72
+ assert [float(e.subs(pt)) for e in a] == pytest.approx([float(e.subs(pt)) for e in closed], rel=1e-12)
73
+
74
+
75
+ def _cartesian_rhs(gravity):
76
+ r = sp.symbols("x y z", real=True)
77
+ v = sp.symbols("vx vy vz", real=True)
78
+ fn = numeric(cartesian(gravity, r, v), [*r, *v])
79
+ return lambda t, s: fn(*s)
80
+
81
+
82
+ def _equinoctial_rhs(gravity, thrust=None, extra=()):
83
+ els = sp.symbols("p f g h k L", real=True)
84
+ fn = numeric(equinoctial(gravity, els, thrust), [*els, *extra])
85
+ return lambda t, s: fn(*s)
86
+
87
+
88
+ def _integrate(rhs, s0, tf, n=400):
89
+ sol = scipy_integrate.solve_ivp(rhs, (0, tf), s0, method="DOP853", rtol=1e-12, atol=1e-13,
90
+ t_eval=np.linspace(0, tf, n))
91
+ assert sol.success
92
+ return sol.y.T
93
+
94
+
95
+ @pytest.mark.parametrize("orbit", ORBITS[1:4])
96
+ def test_equinoctial_and_cartesian_motion_agree_under_zonal_gravity(orbit):
97
+ """Gauss's equations with the zonal perturbation projected on the RTN frame give the
98
+ same motion as Newton's in Cartesian coordinates (J2 to J4, five orbits)."""
99
+ gravity = Gravity.of(EARTH, degree=4, units=U)
100
+ mee0 = keplerian_to_equinoctial(*orbit)
101
+ r0, v0 = equinoctial_to_cartesian(mee0, 1.0)
102
+ tf = 5 * 2 * np.pi * orbit[0] ** 1.5
103
+ X = _integrate(_cartesian_rhs(gravity), np.concatenate([r0, v0]), tf)
104
+ M = _integrate(_equinoctial_rhs(gravity), mee0, tf)
105
+ for x, m in zip(X, M):
106
+ r, v = equinoctial_to_cartesian(m, 1.0)
107
+ assert np.concatenate([r, v]) == pytest.approx(x, abs=2e-9 * orbit[0])
108
+
109
+
110
+ def test_two_body_equinoctial_elements_are_constant_but_the_longitude():
111
+ mee0 = keplerian_to_equinoctial(*ORBITS[2])
112
+ M = _integrate(_equinoctial_rhs(Gravity(1.0)), mee0, 2 * np.pi * ORBITS[2][0] ** 1.5)
113
+ assert np.abs(M[:, :5] - mee0[:5]).max() < 1e-13
114
+ assert M[-1, 5] - mee0[5] == pytest.approx(2 * np.pi, rel=1e-9)
115
+
116
+
117
+ def test_zonal_gravity_conserves_energy():
118
+ gravity = Gravity.of(EARTH, degree=6, units=U)
119
+ r = sp.symbols("x y z", real=True)
120
+ V = numeric([gravity.potential(sp.Matrix(r))], r)
121
+ mee0 = keplerian_to_equinoctial(*ORBITS[1])
122
+ r0, v0 = equinoctial_to_cartesian(mee0, 1.0)
123
+ X = _integrate(_cartesian_rhs(gravity), np.concatenate([r0, v0]), 30.0)
124
+ E = [s[3:] @ s[3:] / 2 - V(*s[:3])[0] for s in X]
125
+ assert np.ptp(E) < 1e-11
126
+
127
+
128
+ def test_j2_drifts_the_node_at_its_secular_rate():
129
+ """Omega' = -3/2 n J2 (R/p)^2 cos i on average, for the ISS's orbit (420 km, 51.6 deg)
130
+ over a day: about -5 deg/day."""
131
+ gravity = Gravity.of(EARTH, degree=2, units=U)
132
+ a, e, i = 1 + 420 / EARTH.radius, 0.001, np.radians(51.6)
133
+ mee0 = keplerian_to_equinoctial(a, e, i, 0.3, 0.0, 0.0)
134
+ tf = 86400.0 / U.time
135
+ M = _integrate(_equinoctial_rhs(gravity), mee0, tf, n=2000)
136
+ raan = np.unwrap(np.arctan2(M[:, 4], M[:, 3]))
137
+ rate = np.polyfit(np.linspace(0, tf, len(M)), raan, 1)[0]
138
+ p = a * (1 - e ** 2)
139
+ expected = -1.5 * a ** -1.5 * EARTH.J[2] * (1 / p) ** 2 * np.cos(i)
140
+ assert rate == pytest.approx(expected, rel=5e-3)
141
+ assert np.degrees(rate) * 86400 / U.time == pytest.approx(-5.0, abs=0.3) # deg/day
142
+
143
+
144
+ def test_thrust_in_rtn_matches_thrust_in_the_inertial_frame():
145
+ """A constant tangential thrust in Gauss's equations is the same push as its inertial
146
+ vector added to Newton's (J2 included), and it raises the orbit."""
147
+ gravity = Gravity.of(EARTH, degree=2, units=U)
148
+ T = 1e-3
149
+ rhs_m = _equinoctial_rhs(gravity, thrust=[0, T, 0])
150
+ r, v = sp.symbols("x y z", real=True), sp.symbols("vx vy vz", real=True)
151
+ hv = sp.Matrix(r).cross(sp.Matrix(v))
152
+ it = hv.cross(sp.Matrix(r)) / (sp.sqrt(hv.dot(hv)) * sp.sqrt(sum(x ** 2 for x in r)))
153
+ fn = numeric(cartesian(gravity, r, v, thrust=T * it), [*r, *v])
154
+ mee0 = keplerian_to_equinoctial(1.2, 0.05, np.radians(30), 0.5, 0.5, 0.0)
155
+ r0, v0 = equinoctial_to_cartesian(mee0, 1.0)
156
+ tf = 3 * 2 * np.pi * 1.2 ** 1.5
157
+ X = _integrate(lambda t, s: fn(*s), np.concatenate([r0, v0]), tf)
158
+ M = _integrate(rhs_m, mee0, tf)
159
+ rr, vv = equinoctial_to_cartesian(M[-1], 1.0)
160
+ assert np.concatenate([rr, vv]) == pytest.approx(X[-1], abs=1e-9)
161
+ assert M[-1, 0] > mee0[0] + 0.01