Coverage for core / src / sensorkit / astro / coords.py: 87%

87 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2from __future__ import annotations 

3 

4import functools 

5from dataclasses import dataclass 

6from datetime import UTC, datetime 

7from typing import TYPE_CHECKING 

8 

9import numpy as np 

10 

11from sensorkit.astro.common import ReferenceFrame 

12 

13if TYPE_CHECKING: 

14 from astropy.coordinates import SkyCoord 

15 from astropy.units import Unit 

16 

17 

18@functools.lru_cache 

19def astropy_unit(spec: str | Unit) -> Unit: 

20 """Resolve and cache an Astropy unit specification.""" 

21 from astropy.units import Unit 

22 

23 return Unit(spec) 

24 

25 

26type Coordinates = Horizontal | Equatorial | Geodetic | Cartesian 

27 

28 

29@dataclass(frozen=True, slots=True) 

30class Horizontal: 

31 """Azimuth and altitude, conventionally in degrees.""" 

32 az: float 

33 alt: float 

34 

35 def to_astropy( 

36 self, 

37 units: str | Unit = "deg", 

38 **kwargs, 

39 ): 

40 """Convert to an astropy SkyCoord in the AltAz frame.""" 

41 from astropy import coordinates as ac 

42 

43 units = astropy_unit(units) 

44 return ac.SkyCoord( 

45 az=self.az * units, 

46 alt=self.alt * units, 

47 frame=ReferenceFrame.ALTAZ, 

48 **kwargs, 

49 ) 

50 

51 

52@dataclass(frozen=True, slots=True) 

53class Equatorial: 

54 """Right ascension and declination, conventionally in degrees.""" 

55 ra: float 

56 dec: float 

57 

58 def to_astropy( 

59 self, 

60 units: str | Unit = "deg", 

61 ra_units: str | Unit | None = None, 

62 frame: ReferenceFrame = ReferenceFrame.ICRF, 

63 **kwargs, 

64 ): 

65 """Convert to an astropy SkyCoord in the given equatorial frame.""" 

66 from astropy import coordinates as ac 

67 

68 dec_unit = astropy_unit(units) 

69 ra_unit = astropy_unit(ra_units) if ra_units is not None else dec_unit 

70 return ac.SkyCoord( 

71 ra=self.ra * ra_unit, 

72 dec=self.dec * dec_unit, 

73 frame=frame.to_astropy(), 

74 **kwargs, 

75 ) 

76 

77 @property 

78 def ra_hms(self): 

79 """Right ascension formatted as a `"H M S"` string.""" 

80 ra = self.ra / 15 

81 hr = int(ra) 

82 fractional = abs(ra - hr) 

83 min = int(fractional * 60) 

84 sec = (fractional * 60 - min) * 60 

85 return f"{hr} {min} {sec}" 

86 

87 @property 

88 def dec_dms(self): 

89 """Declination formatted as a `"D M S"` string.""" 

90 deg = int(self.dec) 

91 fractional = abs(self.dec - deg) 

92 arcmin = int(fractional * 60) 

93 arcsec = (fractional * 60 - arcmin) * 60 

94 return f"{deg} {arcmin} {arcsec}" 

95 

96 

97@dataclass(frozen=True, slots=True) 

98class Geodetic: 

99 """Longitude, latitude, and elevation, conventionally in degrees and meters.""" 

100 lon: float 

101 lat: float 

102 elev: float 

103 

104 @functools.cache 

105 def to_astropy(self, angle_units: str | Unit = "deg", distance_units: str | Unit = "m"): 

106 """Convert to an astropy EarthLocation (result is cached).""" 

107 from astropy import coordinates as ac 

108 

109 angle = astropy_unit(angle_units) 

110 distance = astropy_unit(distance_units) 

111 return ac.EarthLocation( 

112 lon=self.lon * angle, 

113 lat=self.lat * angle, 

114 height=self.elev * distance, 

115 ) 

116 

117 

118@dataclass(frozen=True, slots=True) 

119class Cartesian: 

120 """A 3-D Cartesian vector (x, y, z).""" 

121 x: float 

122 y: float 

123 z: float 

124 

125 def __mul__(self, other): 

126 match other: 

127 case float() | int(): 

128 return Cartesian(self.x * other, self.y * other, self.z * other) 

129 case Cartesian(): 

130 return Cartesian(self.x * other.x, self.y * other.y, self.z * other.z) 

131 case _: 

132 raise RuntimeError(f"cannot multiply Cartesian by {type(other)}") 

133 

134 

135@dataclass(frozen=True, slots=True) 

136class StateVector: 

137 """Position and velocity at a specified time.""" 

138 t: datetime 

139 r: Cartesian 

140 v: Cartesian 

141 

142 def to_numpy(self): 

143 """Return a 6-element numpy array `[rx, ry, rz, vx, vy, vz]`.""" 

144 return np.array([self.r.x, self.r.y, self.r.z, self.v.x, self.v.y, self.v.z]) 

145 

146 @classmethod 

147 def from_astropy( 

148 cls, 

149 coord: SkyCoord, 

150 position_units: str | Unit = "m", 

151 velocity_units: str | Unit = "m/s", 

152 ): 

153 """Construct a StateVector from an astropy SkyCoord with Cartesian position and velocity.""" 

154 pos = astropy_unit(position_units) 

155 vel = astropy_unit(velocity_units) 

156 r = coord.cartesian 

157 v = coord.velocity 

158 return cls( 

159 coord.obstime.to_datetime(UTC), 

160 Cartesian( 

161 r.x.to_value(pos), 

162 r.y.to_value(pos), 

163 r.z.to_value(pos), 

164 ), 

165 Cartesian( 

166 v.d_x.to_value(vel), 

167 v.d_y.to_value(vel), 

168 v.d_z.to_value(vel), 

169 ), 

170 ) 

171 

172 def to_astropy( 

173 self, 

174 position_units: str | Unit = "m", 

175 velocity_units: str | Unit = "m/s", 

176 frame: ReferenceFrame = ReferenceFrame.ICRF, 

177 ): 

178 """Convert to an astropy SkyCoord with Cartesian representation and differential.""" 

179 from astropy import coordinates as ac 

180 

181 pos = astropy_unit(position_units) 

182 vel = astropy_unit(velocity_units) 

183 return ac.SkyCoord( 

184 x=self.r.x * pos, 

185 y=self.r.y * pos, 

186 z=self.r.z * pos, 

187 v_x=self.v.x * vel, 

188 v_y=self.v.y * vel, 

189 v_z=self.v.z * vel, 

190 frame=frame.to_astropy(), 

191 representation_type="cartesian", 

192 differential_type="cartesian", 

193 obstime=self.t, 

194 )