simulate and animate a satellite orbit using sgp4 in python

To simulate and animate a satellite orbit using sgp4 in Python, you can follow the below steps:

  1. Import necessary libraries - sgp4 for satellite orbit propagation and mpl_toolkits for 3D animation
  2. Define the necessary parameters - like satellite TLE, time range, step size, etc.
  3. Generate orbit positions using sgp4 - this will give you the position of satellite in the form of (x, y, z) coordinates for each step.
  4. Create a 3D plot and animate the trajectory using mpl_toolkits - this step involves creating a 3D plot and animating the orbit positions obtained in step 3.

Here's the sample code that demonstrates the above steps:

main.py
# Import necessary libraries
from sgp4.api import Satrec
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation

# Define necessary parameters
satellite_tle = "ISS (ZARYA)              \n1 25544U 98067A   21203.54571327  .00001191  00000-0  32519-4 0  9999\n2 25544  51.6450 125.0793 0004062  25.0073  74.9941 15.48943159317145"
satellite = Satrec.twoline2rv(*satellite_tle.split("\n"))
jd_start, jd_end, step = 2459449.5, 2459450.5, 60
time_range = np.arange(jd_start, jd_end, step * 60)

# Generate orbit positions using sgp4
positions = []
for t in time_range:
    e, r, v = satellite.sgp4(t)
    positions.append(list(r))

# Create 3D plot and animate the trajectory
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim([-6e3,6e3])
ax.set_ylim([-6e3,6e3])
ax.set_zlim([-6e3,6e3])
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")

def animate(i):
    ax.view_init(elev=45., azim=4 * i)
    ax.plot([positions[0][0]], [positions[0][1]], [positions[0][2]], marker='o', markersize=3, color="green")
    ax.plot([positions[i][0]], [positions[i][1]], [positions[i][2]], marker='o', markersize=3, color="red")

anim = FuncAnimation(fig, animate, frames=len(positions), interval=50)
plt.show()
1302 chars
37 lines

In the above code, we first import the necessary libraries - sgp4 for satellite orbit propagation, numpy and matplotlib for numerical computations and plotting and mpl_toolkits for 3D animation. Next, we define the necessary parameters like satellite TLE, time range, step size, etc. Then, we generate the orbit positions using sgp4 library which gives us the position of satellite in the form of (x, y, z) coordinates for each step. Finally, we create a 3D plot and animate the trajectory using mpl_toolkits. The animate function is called for each frame and updates the plot accordingly.

gistlibby LogSnag