import numpy as np
from datetime import datetime, timezone
# --- Part 1: Fundamental Rotation Matrices and Constants ---
# Astronomical constants
ARCSECONDS_TO_RADIANS = np.pi / (180 * 3600)
MICROARCSECONDS_TO_RADIANS = np.pi / (180 * 3600 * 1e6)
SECONDS_PER_DAY = 86400.0
def rotation_matrix_x(angle_rad):
"""Creates a rotation matrix around the X-axis."""
c = np.cos(angle_rad)
s = np.sin(angle_rad)
return np.array([
[1, 0, 0],
[0, c, s],
[0, -s, c]
])
def rotation_matrix_y(angle_rad):
"""Creates a rotation matrix around the Y-axis."""
c = np.cos(angle_rad)
s = np.sin(angle_rad)
return np.array([
[c, 0, -s],
[0, 1, 0],
[s, 0, c]
])
def rotation_matrix_z(angle_rad):
"""Creates a rotation matrix around the Z-axis."""
c = np.cos(angle_rad)
s = np.sin(angle_rad)
return np.array([
[c, s, 0],
[-s, c, 0],
[0, 0, 1]
])
# --- Part 2: Time Scale Conversions ---
def datetime_to_jd(dt_utc):
"""Converts a Python datetime object (UTC) to Julian Date."""
if dt_utc.tzinfo is None or dt_utc.tzinfo.utcoffset(dt_utc) is None:
raise ValueError("Input datetime must be timezone-aware (UTC).")
# Formula from Astronomical Almanac
year, month, day = dt_utc.year, dt_utc.month, dt_utc.day
hour, minute, second = dt_utc.hour, dt_utc.minute, dt_utc.second + dt_utc.microsecond / 1e6
if month <= 2:
year -= 1
month += 12
A = int(year / 100)
B = 2 - A + int(A / 4)
jd = (int(365.25 * (year + 4716)) +
int(30.6001 * (month + 1)) +
day + B - 1524.5 +
(hour + minute / 60 + second / 3600) / 24)
return jd
def get_leap_seconds(jd_utc):
"""
Returns the number of leap seconds for a given Julian Date.
This is a hardcoded table based on IERS data. A real application
would use an up-to-date source.
"""
# (Julian Date of introduction, Cumulative Leap Seconds)
leap_seconds_table = [
(2459945.5, 37), # 2023-01-01
(2457754.5, 37), # 2017-01-01
(2457204.5, 36), # 2015-07-01
(2456109.5, 35), # 2012-07-01
(2454832.5, 34), # 2009-01-01
(2453736.5, 33), # 2006-01-01
(2451179.5, 32), # 1999-01-01
(2441317.5, 10), # 1972-01-01 (start of UTC)
]
for jd_limit, seconds in leap_seconds_table:
if jd_utc >= jd_limit:
return seconds
return 0
def get_eop_values(jd_utc):
"""
Returns Earth Orientation Parameters (EOP).
*** CRITICAL SIMPLIFICATION ***
These values are MEASURED, not calculated. They are published by the IERS.
For this "from scratch" function, we are using recent, constant, representative
values. A high-accuracy system MUST fetch and interpolate EOP data.
Returns:
xp_rad (float): Polar motion x-component in radians.
yp_rad (float): Polar motion y-component in radians.
dut1_sec (float): UT1 - UTC in seconds.
"""
# Representative values for early 2024
# xp and yp are in arcseconds, dUT1 is in seconds.
xp_arcsec = 0.106 # arcseconds
yp_arcsec = 0.355 # arcseconds
dut1_sec = -0.09 # seconds
xp_rad = xp_arcsec * ARCSECONDS_TO_RADIANS
yp_rad = yp_arcsec * ARCSECONDS_TO_RADIANS
return xp_rad, yp_rad, dut1_sec
# --- Part 3: Precession-Nutation Model (IAU 2000A, simplified) ---
def calculate_fundamental_arguments(t_tt):
"""
Calculates the fundamental arguments of nutation for a given time t_tt.
t_tt is Julian centuries since J2000.0.
Formulas from IERS Conventions (2010).
"""
t2 = t_tt * t_tt
t3 = t2 * t_tt
# Mean Anomaly of the Moon
l = np.deg2rad(134.96340251 + 1717915923.2178 * t_tt + 31.8792 * t2 + 0.051635 * t3)
# Mean Anomaly of the Sun
l_prime = np.deg2rad(357.52910918 + 129596581.0481 * t_tt - 0.5532 * t2 + 0.000136 * t3)
# Mean Argument of the Latitude of the Moon
F = np.deg2rad(93.27209062 + 1739527262.8478 * t_tt - 12.7512 * t2 - 0.001037 * t3)
# Mean Elongation of the Moon from the Sun
D = np.deg2rad(297.85019547 + 1602961601.2090 * t_tt - 6.3706 * t2 + 0.006593 * t3)
# Mean Longitude of the Moon's Ascending Node
Omega = np.deg2rad(125.04455501 - 6962890.5431 * t_tt + 7.4722 * t2 + 0.007702 * t3)
return l, l_prime, F, D, Omega
def calculate_cip_cio(t_tt):
"""
Calculates the Celestial Intermediate Pole (CIP) coordinates (X, Y)
and the Celestial Intermediate Origin (CIO) locator 's'.
*** CRITICAL SIMPLIFICATION ***
This is a highly truncated version of the IAU 2000A nutation model.
It includes only the largest terms for demonstration purposes.
The full model is necessary for high accuracy.
Returns:
X_rad (float): CIP x-coordinate in radians.
Y_rad (float): CIP y-coordinate in radians.
s_rad (float): CIO locator 's' in radians.
"""
l, l_prime, F, D, Omega = calculate_fundamental_arguments(t_tt)
# --- Precession terms (polynomial parts of X, Y, s) ---
X = -0.016617 + 2004.191898 * t_tt - 0.4297829 * t_tt**2
Y = -0.006951 - 0.025896 * t_tt - 22.4072747 * t_tt**2
s = -0.000047 * t_tt
# --- Nutation terms (largest periodic terms for dX and dY) ---
# Coefficients are in microarcseconds (uas)
dX = (
(-17206424.0 * np.sin(Omega)) +
(-1318721.0 * np.sin(2 * F - 2 * D + 2 * Omega)) +
(-227343.0 * np.sin(2 * Omega)) +
(206222.0 * np.sin(2 * F - 2 * D + Omega))
)
dY = (
(9202613.0 * np.cos(Omega)) +
(573582.0 * np.cos(2 * F - 2 * D + 2 * Omega)) +
(97769.0 * np.cos(2 * Omega)) +
(-89658.0 * np.cos(2 * F - 2 * D + Omega))
)
X_uas = X + dX / 1000.0 # dX is 1000x larger in tables
Y_uas = Y + dY / 1000.0
X_rad = X_uas * MICROARCSECONDS_TO_RADIANS
Y_rad = Y_uas * MICROARCSECONDS_TO_RADIANS
s_rad = s * ARCSECONDS_TO_RADIANS # s precession is in arcseconds
return X_rad, Y_rad, s_rad
# --- Part 4: Earth Rotation Angle (ERA) ---
def calculate_era(jd_ut1):
"""
Calculates the Earth Rotation Angle (ERA) for a given UT1 Julian Date.
The ERA is the angle between the CIO and the TIO (Terrestrial Intermediate Origin).
Formula from IERS Conventions (2010).
"""
t_ut1 = jd_ut1 - 2451545.0
era_rad = 2 * np.pi * (0.7790572732640 + 1.00273781191135448 * t_ut1)
# Return value in range [0, 2*pi]
return era_rad % (2 * np.pi)
# --- Part 5: The Main Conversion Function ---
def icrf_to_itrf(icrf_pos, dt_utc):
"""
Converts ICRF (International Celestial Reference Frame) coordinates to
ITRF (International Terrestrial Reference Frame) coordinates for a given date.
This function implements the IAU 2006/2000A transformation chain from scratch,
with simplifications for EOP and the nutation model as documented.
Args:
icrf_pos (np.ndarray): A 3-element numpy array with ICRF coordinates (x, y, z) in meters.
dt_utc (datetime): A timezone-aware Python datetime object (in UTC).
Returns:
np.ndarray: A 3-element numpy array with ITRF coordinates (x, y, z) in meters.
"""
# --- Step 1: Time Calculations ---
jd_utc = datetime_to_jd(dt_utc)
# Get Earth Orientation Parameters (simplified)
xp_rad, yp_rad, dut1_sec = get_eop_values(jd_utc)
# Calculate other time scales
# UT1 = UTC + dUT1
jd_ut1 = jd_utc + dut1_sec / SECONDS_PER_DAY
# TAI = UTC + Leap Seconds
leap_seconds = get_leap_seconds(jd_utc)
jd_tai = jd_utc + leap_seconds / SECONDS_PER_DAY
# TT = TAI + 32.184s
jd_tt = jd_tai + 32.184 / SECONDS_PER_DAY
# Julian centuries since J2000.0 for TT
t_tt = (jd_tt - 2451545.0) / 36525.0
# --- Step 2: Calculate Transformation Matrices ---
# 2a. GCRF to CIRS (Precession-Nutation) Matrix: C(t)
# r_cirs = C(t) * r_gcrs
# C(t) = Rz(-s) * Ry(X) * Rx(-Y)
X_cip, Y_cip, s_cio = calculate_cip_cio(t_tt)
# The matrix that transforms from GCRF to CIRS is the transpose of the matrix
# that transforms the basis vectors. The rotation is R3(s)R2(-X)R1(Y)
# for the coordinate transformation. Let's build it directly.
# Note on signs/convention: This is a frequent point of confusion.
# The transformation of a vector from GCRF to CIRS is:
# r_cirs = R1(Y_cip) @ R2(-X_cip) @ R3(s_cio) @ r_gcrf - Incorrect
# IERS Conventions 2010 (5.20) uses r_cirs = Q(t) r_gcrf where Q = R3(-s)R2(X)R1(-Y)
# This aligns with SOFA.
C_matrix = rotation_matrix_z(-s_cio) @ rotation_matrix_y(X_cip) @ rotation_matrix_x(-Y_cip)
# 2b. CIRS to TIRS (Earth Rotation) Matrix: R(t)
# r_tirs = R(t) * r_cirs, where TIRS is the Terrestrial Intermediate Ref System.
# This is a simple rotation around the z-axis (the CIP) by the ERA.
era = calculate_era(jd_ut1)
R_matrix = rotation_matrix_z(era)
# 2c. TIRS to ITRF (Polar Motion) Matrix: W(t)
# r_itrf = W(t) * r_tirs
# This matrix aligns the CIP with the ITRF pole.
# W(t) = Rz(-sp) * Ry(xp) * Rx(yp) where sp is tiny and often neglected.
# A common and accurate form is W(t) = Ry(-xp) Rx(-yp)
W_matrix = rotation_matrix_y(-xp_rad) @ rotation_matrix_x(-yp_rad)
# --- Step 3: Apply the Full Transformation ---
# The full transformation matrix P = W * R * C
P_matrix = W_matrix @ R_matrix @ C_matrix
# Apply the transformation to the ICRF position vector
itrf_pos = P_matrix @ icrf_pos
return itrf_pos
# --- Example Usage ---
if __name__ == '__main__':
# Example: Position of a geostationary satellite.
# In an inertial frame (ICRF), it traces a circle.
# In the Earth-fixed frame (ITRF), it should be nearly stationary.
# A typical GEO satellite radius is ~42,164 km.
# Let's place one on the equator at the Prime Meridian (0 longitude).
r_geo = 42164 * 1000.0 # meters
icrf_position_geo = np.array([r_geo, 0, 0])
# Pick a date and time
# Let's use January 1, 2024 at 12:00:00 UTC
example_datetime = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
print(f"--- ICRF to ITRF Conversion Example ---")
print(f"Input Datetime (UTC): {example_datetime}")
print(f"Input ICRF Position (m): {icrf_position_geo}")
# Perform the conversion
itrf_position_geo = icrf_to_itrf(icrf_position_geo, example_datetime)
print(f"\nCalculated ITRF Position (m): {itrf_position_geo}")
# To verify, let's calculate the longitude and latitude from the ITRF coordinates
x, y, z = itrf_position_geo
longitude_rad = np.arctan2(y, x)
latitude_rad = np.arctan2(z, np.sqrt(x**2 + y**2))
longitude_deg = np.rad2deg(longitude_rad)
latitude_deg = np.rad2deg(latitude_rad)
print(f"\nDerived Geodetic Coordinates:")
print(f" Longitude: {longitude_deg:.6f} degrees")
print(f" Latitude: {latitude_deg:.6f} degrees")
print("\n--- Verification ---")
print("The input ICRF position corresponds to a satellite over the Prime Meridian at t=0 of an inertial frame.")
print("The Earth rotates, so at 12:00 UTC, the Prime Meridian has rotated approximately 180 degrees.")
print("Therefore, we expect the satellite's ITRF longitude to be around -180 (or +180) degrees.")
print("The small latitude value is due to the slight tilt of the Earth's axis (modeled by Precession-Nutation and Polar Motion).")