Coverage for core / src / sensorkit / astro / target.py: 86%

317 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 asyncio 

5import collections 

6from abc import ABC, abstractmethod 

7from collections.abc import AsyncIterator, Callable, Sequence 

8from dataclasses import dataclass 

9from datetime import UTC, datetime, timedelta 

10from typing import TYPE_CHECKING, Annotated, Any, Literal, override 

11 

12import astropy.units as u 

13import numpy as np 

14import satkit 

15from astropy.coordinates import ( 

16 CIRS, 

17 GCRS, 

18 ICRS, 

19 ITRS, 

20 TEME, 

21 AltAz, 

22 BaseCoordinateFrame, 

23 CartesianRepresentation, 

24 EarthLocation, 

25 SkyCoord, 

26 UnitSphericalRepresentation, 

27 get_body, 

28 get_sun, 

29) 

30from astropy.coordinates import AltAz as AltAzFrame 

31from astropy.time import Time 

32from loguru import logger 

33from pydantic import BaseModel, Discriminator 

34 

35from sensorkit.astro.common import TLE, ReferenceFrame 

36from sensorkit.astro.coords import ( 

37 Coordinates, 

38 Equatorial, 

39 Geodetic, 

40 Horizontal, 

41 StateVector, 

42) 

43from sensorkit.astro.trajectory import OrbitalTrajectory, TLETrajectory, Trajectory 

44 

45if TYPE_CHECKING: 

46 from sensorkit.astro.observer import EarthObserver 

47 from sensorkit.std.weather import BasicWeather 

48 

49 

50# Frames built from the site-to-target vector, and so unusable without an observer. 

51_OBSERVER_RELATIVE_FRAMES = ( 

52 ReferenceFrame.ALTAZ, 

53 ReferenceFrame.CIRF, 

54 ReferenceFrame.ICRF, 

55) 

56 

57# How far past a requested window a track propagates, so that successive windows are 

58# usually served without propagating again. 

59_PROPAGATION_HORIZON = timedelta(hours=1) 

60 

61# Window covering consumers that ask adapt() for a materialized EphemerisTarget. A track 

62# leaves this choice to the consumer; these apply only where one is not accepted. 

63_ADAPTED_EPHEMERIS_DURATION = timedelta(minutes=1) 

64_ADAPTED_EPHEMERIS_STEP = timedelta(seconds=2) 

65 

66 

67def _topocentric_cartesian(gcrs: GCRS, location: EarthLocation) -> CartesianRepresentation: 

68 """Return the site-to-target vector in GCRS axes. 

69 

70 Relies on *gcrs* carrying the default geocentric origin; a GCRS with a non-zero 

71 obsgeoloc is already observer-relative and would be shifted twice. 

72 """ 

73 obsgeoloc, _ = location.get_gcrs_posvel(gcrs.obstime) 

74 return gcrs.cartesian.without_differentials() - obsgeoloc 

75 

76 

77def _topocentric_icrs(gcrs: GCRS, location: EarthLocation) -> ICRS: 

78 """Return astrometric RA/Dec for the site-to-target direction. 

79 

80 Converting these angular coordinates to AltAz at the same time and location 

81 recovers the geometric direction. No light-time correction is applied. 

82 """ 

83 cirs = _topocentric_cirs(gcrs, location) 

84 return cirs.realize_frame(cirs.represent_as(UnitSphericalRepresentation)).transform_to( 

85 ICRS() 

86 ) 

87 

88 

89def _topocentric_cirs(gcrs: GCRS, location: EarthLocation) -> CIRS: 

90 topo = _topocentric_cartesian(gcrs, location) 

91 cirs = GCRS(topo, obstime=gcrs.obstime).transform_to(CIRS(obstime=gcrs.obstime)) 

92 return CIRS(cirs.cartesian, obstime=gcrs.obstime, location=location) 

93 

94 

95def _output_frame_transform( 

96 frame: ReferenceFrame, 

97 location: EarthLocation | None, 

98 weather: BasicWeather | None, 

99) -> Callable[[GCRS], BaseCoordinateFrame]: 

100 """Return the conversion from GCRS to the requested ephemeris frame. 

101 

102 ICRF, CIRF, and ALTAZ require an observer and use the site-to-target 

103 direction. ICRF output contains astrometric RA/Dec. Other output frames 

104 retain the geocentric origin. 

105 """ 

106 if location is None and frame in _OBSERVER_RELATIVE_FRAMES: 

107 raise RuntimeError(f"an observer location is required for {frame}") 

108 

109 match frame: 

110 case ReferenceFrame.ICRF: 

111 return lambda gcrs: _topocentric_icrs(gcrs, location) 

112 case ReferenceFrame.CIRF: 

113 return lambda gcrs: _topocentric_cirs(gcrs, location) 

114 case ReferenceFrame.ALTAZ: 

115 return lambda gcrs: _topocentric_cirs(gcrs, location).transform_to( 

116 AltAz( 

117 obstime=gcrs.obstime, 

118 location=location, 

119 **(weather.to_astropy() if weather else {}), 

120 ) 

121 ) 

122 case _: 

123 output_frame = frame.to_astropy() 

124 

125 if "obstime" in output_frame.frame_attributes: 

126 return lambda gcrs: gcrs.transform_to(output_frame(obstime=gcrs.obstime)) 

127 

128 return lambda gcrs: gcrs.transform_to(output_frame()) 

129 

130 

131def _ephemeris_points(frame: ReferenceFrame, coord: BaseCoordinateFrame) -> list[Coordinates]: 

132 """Pack a sampled coordinate into the point type native to *frame*. 

133 

134 Equatorial frames expose ra/dec directly, but ITRF and TEME carry cartesian data and 

135 have to be resolved first: ITRF to the sub-satellite geodetic point, TEME to the 

136 spherical angles its cartesian representation implies. 

137 """ 

138 match frame: 

139 case ReferenceFrame.ALTAZ: 

140 return [ 

141 Horizontal(az=az, alt=alt) 

142 for az, alt in zip(coord.az.deg, coord.alt.deg, strict=True) 

143 ] 

144 case ReferenceFrame.ITRF: 

145 lons, lats, heights = coord.earth_location.to_geodetic() 

146 return [ 

147 Geodetic(lon=lon, lat=lat, elev=elev) 

148 for lon, lat, elev in zip( 

149 lons.deg, lats.deg, heights.to_value(u.m), strict=True 

150 ) 

151 ] 

152 case ReferenceFrame.TEME: 

153 usph = coord.represent_as(UnitSphericalRepresentation) 

154 return [ 

155 Equatorial(ra=ra, dec=dec) 

156 for ra, dec in zip(usph.lon.deg, usph.lat.deg, strict=True) 

157 ] 

158 case _: 

159 return [ 

160 Equatorial(ra=ra, dec=dec) 

161 for ra, dec in zip(coord.ra.deg, coord.dec.deg, strict=True) 

162 ] 

163 

164 

165class TargetTrack: 

166 """The unbounded on-sky path of a single propagatable target.""" 

167 

168 def __init__( 

169 self, 

170 trajectory: Trajectory, 

171 frame: ReferenceFrame, 

172 *, 

173 observer: EarthObserver | Geodetic | None = None, 

174 weather: BasicWeather | None = None, 

175 propagation_horizon: timedelta = _PROPAGATION_HORIZON, 

176 ): 

177 """Bind *trajectory* to the frame and observing context it is sampled in. 

178 

179 Args: 

180 trajectory: The path to sample, propagated in GCRS. 

181 frame: Reference frame the sampled points are returned in. 

182 observer: Site position. Required for observer-relative frames. 

183 weather: Ambient conditions, applied as refraction in ALTAZ. 

184 propagation_horizon: How far past a requested window to propagate. 

185 """ 

186 self.trajectory = trajectory 

187 self.frame = frame 

188 self.observer = observer 

189 self.weather = weather 

190 self.propagation_horizon = propagation_horizon 

191 self._propagated: Trajectory | None = None 

192 self._propagated_until: datetime | None = None 

193 self._propagating = asyncio.Lock() 

194 

195 async def sample( 

196 self, 

197 start_time: datetime, 

198 duration: timedelta, 

199 step: timedelta, 

200 ) -> tuple[list[float], list[Coordinates]]: 

201 """Sample the track over a window, returning Julian dates and points in `frame`. 

202 

203 The first sample sits one *step* after *start_time*, and samples run to the last 

204 whole *step* within *duration*, which falls short of the full span where the two 

205 do not divide evenly. 

206 """ 

207 trajectory = await self._propagate_through(start_time + duration) 

208 location = self.observer.to_astropy() if self.observer else None 

209 transform_to_output_frame = _output_frame_transform(self.frame, location, self.weather) 

210 

211 def _sample_series(): 

212 epochs = [start_time + (i + 1) * step for i in range(duration // step)] 

213 

214 if not epochs: 

215 return [], [] 

216 

217 gcrs = trajectory.sample(epochs) 

218 coord = transform_to_output_frame(gcrs) 

219 jds = list(gcrs.obstime.jd) 

220 points = _ephemeris_points(self.frame, coord) 

221 logger.debug(f"sampled track ending at {points[-1]}") 

222 

223 return jds, points 

224 

225 return await asyncio.to_thread(_sample_series) 

226 

227 async def stream( 

228 self, 

229 *, 

230 window: timedelta, 

231 step: timedelta, 

232 lead: timedelta, 

233 ) -> AsyncIterator[tuple[list[float], list[Coordinates]]]: 

234 """Yield consecutive windows of the track, indefinitely. 

235 

236 Each iteration yields the next *window* of samples, then waits until *lead* 

237 remains before that window elapses. A consumer therefore always holds samples 

238 reaching at least *lead* into the future, and both producing the next window 

239 and acting on it have to fit within *lead*. 

240 

241 Args: 

242 window: Time span covered by each batch of samples. 

243 step: Interval between samples within a batch. 

244 lead: How long before a window elapses to produce the next one. 

245 

246 Raises: 

247 ValueError: If *lead* leaves no time to consume a window. 

248 """ 

249 # A window that is not a whole number of steps is covered only as far as its 

250 # last sample, which is what the next window has to be timed against. 

251 covered = (window // step) * step 

252 

253 if lead >= covered - step: 

254 raise ValueError("lead must leave at least one step of the window to consume") 

255 

256 while True: 

257 start = datetime.now(UTC) - step 

258 yield await self.sample(start, window, step) 

259 

260 delay = (start + covered - lead - datetime.now(UTC)).total_seconds() 

261 

262 if delay > 0: 

263 await asyncio.sleep(delay) 

264 

265 async def _propagate_through(self, until: datetime) -> Trajectory: 

266 """Return a trajectory propagated at least as far as *until*.""" 

267 async with self._propagating: 

268 if self._propagated is not None and until <= self._propagated_until: 

269 return self._propagated 

270 

271 horizon = until + self.propagation_horizon 

272 # Propagate from the original trajectory rather than the last result, which 

273 # would accumulate error over a long-running track. 

274 propagated = await self.trajectory.propagate(horizon) 

275 

276 # Record the reach only once it is backed by a result, so a failed 

277 # propagation leaves the previous one in place to be retried. 

278 self._propagated = propagated 

279 self._propagated_until = horizon 

280 

281 return propagated 

282 

283 

284def _accepted_frame( 

285 accepted: type, 

286 supported: dict[type, list[ReferenceFrame]], 

287 observer: EarthObserver | Geodetic | None, 

288) -> ReferenceFrame: 

289 """Return the single frame requested for *accepted*, rejecting an unusable request.""" 

290 frames = supported[accepted] 

291 

292 if len(frames) != 1: 

293 raise RuntimeError(f"exactly one reference frame is required for {accepted.__name__}") 

294 

295 frame = frames[0] 

296 

297 if observer is None and frame in _OBSERVER_RELATIVE_FRAMES: 

298 raise RuntimeError(f"an observer location is required for {frame}") 

299 

300 return frame 

301 

302 

303class BaseTarget(BaseModel, ABC): 

304 """Abstract base for all target types; discriminated on `target_type`.""" 

305 target_type: Literal[None] 

306 

307 async def adapt( 

308 self, 

309 *accepts: type[BaseTarget | TargetTrack] | tuple, 

310 observer: EarthObserver | Geodetic | None = None, 

311 weather: BasicWeather | None = None, 

312 _catalog: Any = None, 

313 ) -> BaseTarget | TargetTrack: 

314 """Convert this target to the best matching type from *accepts*, propagating as needed.""" 

315 mytype = type(self) 

316 supported: dict[type[BaseTarget | TargetTrack], list[ReferenceFrame]] = collections.defaultdict(list) 

317 

318 for val in accepts: 

319 match val: 

320 case (obj, *frames): 

321 supported[obj].extend(frames) 

322 case obj: 

323 supported[obj].clear() 

324 

325 # Check whether this target is directly supported. 

326 if mytype in supported: 

327 # If it has a reference frame, check that too. 

328 if not supported[mytype] or self.frame in supported[mytype]: 

329 return self 

330 

331 if mytype is CatalogTarget: 

332 # TODO: Do catalog lookup. 

333 raise NotImplementedError("Catalog lookup is not yet supported") 

334 

335 # Fixed and rate targets have no trajectory and fall through to the error below. 

336 trajectory = self.to_trajectory() 

337 

338 # Prefer a track over a materialized ephemeris where both are accepted. 

339 if trajectory is not None and TargetTrack in supported: 

340 frame = _accepted_frame(TargetTrack, supported, observer) 

341 

342 logger.debug(f"adapting {mytype.__name__} to TargetTrack in {frame}") 

343 return TargetTrack(trajectory, frame, observer=observer, weather=weather) 

344 

345 if trajectory is not None and EphemerisTarget in supported: 

346 frame = _accepted_frame(EphemerisTarget, supported, observer) 

347 

348 logger.debug(f"adapting {mytype.__name__} to EphemerisTarget in {frame}") 

349 return await self.to_ephemeris_target( 

350 start_time=datetime.now(UTC), 

351 duration=_ADAPTED_EPHEMERIS_DURATION, 

352 step=_ADAPTED_EPHEMERIS_STEP, 

353 frame=frame, 

354 observer=observer, 

355 weather=weather, 

356 ) 

357 

358 raise RuntimeError("Could not adapt target to a supported type") 

359 

360 def to_trajectory(self) -> Trajectory | None: 

361 """Return a Trajectory for this target, or None if it cannot be propagated.""" 

362 return None 

363 

364 def to_track( 

365 self, 

366 frame: ReferenceFrame = ReferenceFrame.GCRF, 

367 observer: EarthObserver | Geodetic | None = None, 

368 weather: BasicWeather | None = None, 

369 ) -> TargetTrack: 

370 """Return a TargetTrack sampling this target in the given frame. 

371 

372 Raises: 

373 TypeError: If this target cannot be propagated. 

374 """ 

375 trajectory = self.to_trajectory() 

376 

377 if trajectory is None: 

378 raise TypeError(f"{type(self).__name__} cannot be propagated") 

379 

380 return TargetTrack(trajectory, frame, observer=observer, weather=weather) 

381 

382 async def to_ephemeris_target( 

383 self, 

384 start_time: datetime, 

385 duration: timedelta, 

386 step: timedelta, 

387 frame: ReferenceFrame = ReferenceFrame.GCRF, 

388 observer: EarthObserver | Geodetic | None = None, 

389 weather: BasicWeather | None = None, 

390 ) -> EphemerisTarget: 

391 """Propagate this target into a pre-computed EphemerisTarget over the given time window.""" 

392 track = self.to_track(frame, observer, weather) 

393 jds, points = await track.sample(start_time, duration, step) 

394 

395 return EphemerisTarget( 

396 frame=frame, 

397 jds=jds, 

398 points=points, 

399 ) 

400 

401 

402class CompositeTarget(BaseTarget): 

403 """A sequence of targets. 

404 

405 The timing semantics of constituent targets are undefined. 

406 """ 

407 target_type: Literal["composite"] = "composite" 

408 sequence: Sequence[BaseTarget] 

409 

410 

411class FrameTarget(BaseTarget): 

412 """An unspecified target in a particular reference frame. 

413 

414 An object of type `FrameTarget` (as opposed to one of its subclasses) does not specify the 

415 position within the target reference frame. The default semantics in this case are that the 

416 target refers to the previous position in the user context converted to the target reference 

417 frame. If there is no previous position in this context, use of this target is considered an 

418 error. 

419 """ 

420 target_type: Literal["frame"] = "frame" 

421 frame: ReferenceFrame 

422 

423 

424class FixedTarget[T: Coordinates](FrameTarget, ABC): 

425 """A target at a fixed position in the given reference frame.""" 

426 target_type: Literal["fixed"] = "fixed" 

427 coords: T 

428 

429 @abstractmethod 

430 def to_astropy(self, **kwargs) -> SkyCoord: 

431 """Convert this fixed target to an astropy SkyCoord.""" 

432 ... 

433 

434 

435class AltAzTarget(FixedTarget[Horizontal]): 

436 """A target at a fixed position in the alt-azimuth frame.""" 

437 frame: Literal[ReferenceFrame.ALTAZ] = ReferenceFrame.ALTAZ 

438 

439 @override 

440 def to_astropy( 

441 self, 

442 time: Time | None = None, 

443 observer: EarthObserver | Geodetic | None = None, 

444 weather: BasicWeather | None = None, 

445 wavelength: float | None = None, 

446 ): 

447 return self.coords.to_astropy( 

448 obstime=time, 

449 location=EarthLocation(observer.to_astropy()) if observer else None, 

450 obswl=wavelength, 

451 **(weather.to_astropy() if weather else {}), 

452 ) 

453 

454 

455class ICRSTarget(FixedTarget[Equatorial]): 

456 """A target at a fixed position in the International Celestial Reference Frame.""" 

457 frame: Literal[ReferenceFrame.ICRF] = ReferenceFrame.ICRF 

458 

459 @override 

460 def to_astropy( 

461 self, 

462 time: Time | None = None, 

463 ): 

464 return self.coords.to_astropy(frame=self.frame, obstime=time) 

465 

466 

467class RateTarget(FrameTarget): 

468 """A target moving at a fixed rate relative to an initial position.""" 

469 target_type: Literal["rate"] = "rate" 

470 rates: Coordinates 

471 initial_time: datetime 

472 initial_frame: ReferenceFrame 

473 initial_coords: Coordinates 

474 

475 

476class EphemerisTarget(FrameTarget): 

477 """A target moving according to a precomputed ephemeris. 

478 

479 ICRF points contain astrometric RA/Dec for the observing site. Use the 

480 sample time and the same site when converting them to local pointing 

481 coordinates. 

482 """ 

483 target_type: Literal["ephemeris"] = "ephemeris" 

484 jds: Sequence[float] 

485 points: Sequence[Coordinates] 

486 # FIXME: Needs velocity too. 

487 

488 

489class TLETarget(FrameTarget): 

490 """A target moving according to the input Two-Line Element set.""" 

491 target_type: Literal["tle"] = "tle" 

492 frame: Literal[ReferenceFrame.TEME] = ReferenceFrame.TEME 

493 tle: TLE 

494 

495 @override 

496 def to_trajectory(self): 

497 return TLETrajectory(self.tle) 

498 

499 

500class StateVectorTarget(FrameTarget): 

501 """A target moving according to the input state vector. 

502 

503 Position units must be meters, and velocity units must be meters per second. 

504 """ 

505 target_type: Literal["state_vector"] = "state_vector" 

506 sv: StateVector 

507 

508 @override 

509 def to_trajectory(self): 

510 return OrbitalTrajectory(self.sv_gcrf()) 

511 

512 def sv_gcrf(self): 

513 """Return the state vector converted to GCRF, transforming if necessary.""" 

514 if self.frame == ReferenceFrame.GCRF: 

515 return self.sv 

516 

517 return StateVector.from_astropy( 

518 self.sv.to_astropy(frame=self.frame).transform_to("gcrs") 

519 ) 

520 

521 

522class CatalogTarget(BaseTarget): 

523 """A target identified by name in an astronomical catalog.""" 

524 target_type: Literal["catalog"] = "catalog" 

525 object: str 

526 

527 

528Target = Annotated[ 

529 Annotated[AltAzTarget | ICRSTarget, Discriminator("frame")] 

530 | RateTarget 

531 | EphemerisTarget 

532 | TLETarget 

533 | StateVectorTarget 

534 | CatalogTarget 

535 | FrameTarget, 

536 Discriminator("target_type"), 

537] 

538 

539 

540@dataclass 

541class ObserveWindow: 

542 """A time window for observability calculations, sampled at *step_seconds* intervals.""" 

543 start_time: datetime 

544 end_time: datetime 

545 step_seconds: int = 60 

546 

547 

548def time_grid(win: ObserveWindow) -> list[datetime]: 

549 """Return a list of timezone-aware datetimes spanning the window at the configured step.""" 

550 if win.start_time.tzinfo is None or win.end_time.tzinfo is None: 

551 raise ValueError("start_time and end_time must be timezone-aware (UTC).") 

552 if win.end_time < win.start_time: 

553 raise ValueError("end_time must be >= start_time.") 

554 if win.step_seconds <= 0: 

555 raise ValueError("step_seconds must be > 0.") 

556 

557 t = win.start_time 

558 out: list[datetime] = [] 

559 while t <= win.end_time: 

560 out.append(t) 

561 t += timedelta(seconds=win.step_seconds) 

562 return out 

563 

564 

565def make_altaz_frame(loc: EarthLocation, obstime: Time) -> AltAzFrame: 

566 """Return an astropy AltAz frame for the given location and time.""" 

567 return AltAzFrame(obstime=obstime, location=loc) 

568 

569def norm_az_deg(az_deg: float) -> float: 

570 """Normalize an azimuth value to the [0, 360) degree range.""" 

571 return az_deg % 360.0 

572 

573 

574def sample_altaz_series( 

575 target: Target, 

576 loc: EarthLocation, 

577 times: list[datetime], 

578) -> list[tuple[float, float]]: 

579 """Return `(altitude_deg, azimuth_deg)` for the target at each time. 

580 

581 TLE samples give the geometric site-to-satellite direction. 

582 ICRF coordinates are interpreted as astrometric RA/Dec. 

583 ICRF ephemerides must use *loc* as their observing site. 

584 """ 

585 out: list[tuple[float, float]] = [] 

586 

587 match target: 

588 case ICRSTarget(): 

589 sc = SkyCoord( 

590 ra=target.coords.ra * u.deg, 

591 dec=target.coords.dec * u.deg, 

592 frame=ICRS(), 

593 ) 

594 for dt in times: 

595 t_ast = Time(dt, scale="utc") 

596 a = sc.transform_to(make_altaz_frame(loc, t_ast)) 

597 out.append((a.alt.deg, norm_az_deg(a.az.deg))) 

598 return out 

599 

600 case AltAzTarget(): 

601 az = norm_az_deg(target.coords.az) 

602 return [(target.coords.alt, az) for _ in times] 

603 

604 case TLETarget(): 

605 tle = satkit.TLE.from_lines(target.tle.to_list()) 

606 if isinstance(tle, list): 

607 tle = tle[0] 

608 for dt in times: 

609 t_ast = Time(dt, scale="utc") 

610 t_sk = satkit.time.from_datetime(dt) 

611 try: 

612 teme_p, _teme_v = satkit.sgp4(tle, t_sk) 

613 except Exception: 

614 out.append((-90.0, 0.0)) 

615 continue 

616 teme = TEME(x=teme_p[0]*u.m, y=teme_p[1]*u.m, z=teme_p[2]*u.m, obstime=t_ast) 

617 

618 # Form the site-to-satellite vector explicitly to avoid stellar 

619 # aberration changes during the geocentric-to-topocentric transform. 

620 itrs = teme.transform_to(ITRS(obstime=t_ast)) 

621 topo = ITRS( 

622 itrs.cartesian - loc.get_itrs(t_ast).cartesian, 

623 obstime=t_ast, 

624 location=loc, 

625 ) 

626 a = topo.transform_to(make_altaz_frame(loc, t_ast)) 

627 out.append((a.alt.deg, norm_az_deg(a.az.deg))) 

628 return out 

629 

630 case EphemerisTarget(frame=ReferenceFrame.ICRF): 

631 if not target.jds: 

632 raise ValueError("EphemerisTarget has no samples") 

633 jds = np.asarray(target.jds, dtype=float) 

634 for dt in times: 

635 t_ast = Time(dt, scale="utc") 

636 i = int(np.argmin(np.abs(jds - t_ast.jd))) 

637 pt = target.points[i] 

638 sc = SkyCoord(ra=pt.ra * u.deg, dec=pt.dec * u.deg, frame=ICRS()) 

639 a = sc.transform_to(make_altaz_frame(loc, t_ast)) 

640 out.append((a.alt.deg, norm_az_deg(a.az.deg))) 

641 return out 

642 

643 raise TypeError(f"Unsupported target type: {type(target)}") 

644 

645 

646def altitude_mask(altaz: list[tuple[float, float]], *, min_altitude_deg: float) -> np.ndarray: 

647 """Return a boolean mask that is True where altitude >= *min_altitude_deg*.""" 

648 return np.array([alt >= min_altitude_deg for alt, _ in altaz], dtype=bool) 

649 

650def darkness_mask( 

651 times: list[datetime], 

652 loc: EarthLocation, 

653 max_sun_alt_deg: float, 

654) -> np.ndarray: 

655 """Return a boolean mask that is True where the Sun is at or below *max_sun_alt_deg*.""" 

656 mask = np.zeros(len(times), dtype=bool) 

657 for i, dt in enumerate(times): 

658 t_ast = Time(dt, scale="utc") 

659 sun_alt = get_sun(t_ast).transform_to(make_altaz_frame(loc, t_ast)).alt.deg 

660 mask[i] = (sun_alt <= max_sun_alt_deg) 

661 return mask 

662 

663 

664def sun_avoidance_mask( 

665 altaz: list[tuple[float, float]], 

666 times: list[datetime], 

667 loc: EarthLocation, 

668 min_sun_sep_deg: float, 

669) -> np.ndarray: 

670 """Return a boolean mask that is True where the target is at least *min_sun_sep_deg* from the Sun.""" 

671 mask = np.zeros(len(times), dtype=bool) 

672 for i, dt in enumerate(times): 

673 alt_deg, az_deg = altaz[i] 

674 t_ast = Time(dt, scale="utc") 

675 frame = make_altaz_frame(loc, t_ast) 

676 tgt = SkyCoord(AltAzFrame(az=az_deg * u.deg, alt=alt_deg * u.deg, obstime=t_ast, location=loc)) 

677 sun = get_sun(t_ast).transform_to(frame) 

678 mask[i] = tgt.separation(sun).deg >= min_sun_sep_deg 

679 return mask 

680 

681def moon_avoidance_mask( 

682 altaz: list[tuple[float, float]], 

683 times: list[datetime], 

684 loc: EarthLocation, 

685 min_moon_sep_deg: float, 

686) -> np.ndarray: 

687 """Return a boolean mask that is True where the target is at least *min_moon_sep_deg* from the Moon.""" 

688 mask = np.zeros(len(times), dtype=bool) 

689 for i, dt in enumerate(times): 

690 alt_deg, az_deg = altaz[i] 

691 t_ast = Time(dt, scale="utc") 

692 frame = make_altaz_frame(loc, t_ast) 

693 tgt = SkyCoord(AltAzFrame(az=az_deg * u.deg, alt=alt_deg * u.deg, obstime=t_ast, location=loc)) 

694 moon = get_body("moon", t_ast, location=loc).transform_to(frame) 

695 mask[i] = tgt.separation(moon).deg >= min_moon_sep_deg 

696 return mask 

697 

698def is_observable( 

699 target: Target, 

700 site: Geodetic, 

701 start_time: datetime, 

702 end_time: datetime, 

703 step_seconds: int = 10, 

704 min_altitude_deg: float | None = None, 

705 sun_max_altitude_deg: float | None = None, 

706 sun_separation_deg: float | None = None, 

707 moon_separation_deg: float | None = None, 

708) -> bool: 

709 """Return True if the target satisfies all supplied observability constraints throughout the window.""" 

710 win = ObserveWindow(start_time, end_time, step_seconds) 

711 

712 times = time_grid(win) 

713 if not times: 

714 return False 

715 

716 loc = EarthLocation(site.to_astropy()) 

717 

718 try: 

719 altaz = sample_altaz_series(target, loc, times) 

720 except TypeError: 

721 logger.warning(f"Observability check for {type(target).__name__} is not implemented!") 

722 return True 

723 

724 mask = np.ones(len(times), dtype=bool) 

725 

726 if min_altitude_deg is not None: 

727 mask &= altitude_mask(altaz, min_altitude_deg=min_altitude_deg) 

728 

729 if sun_max_altitude_deg is not None: 

730 mask &= darkness_mask(times, loc, max_sun_alt_deg=sun_max_altitude_deg) 

731 

732 if sun_separation_deg is not None: 

733 mask &= sun_avoidance_mask(altaz, times, loc, min_sun_sep_deg=sun_separation_deg) 

734 

735 if moon_separation_deg is not None: 

736 mask &= moon_avoidance_mask(altaz, times, loc, min_moon_sep_deg=moon_separation_deg) 

737 

738 return np.all(mask) 

739 

740