Files
second-screen/astro.py
T
rickzkmandClaude Opus 5.5 517f0868db Bigger next-pass panel with brightness on the ISS view, deploy on push
The map leaves out the polar caps (75° N to 60° S at the same scale) so the
next visible pass gets a 100 px panel: the time in 48 px type, the date, and
height, direction, estimated magnitude and clouds in 24 px. The magnitude is
the brightest moment of the pass by Matson's formula (standard magnitude -1.8).

A Gitea webhook now makes Coolify deploy every push to main, and Coolify
4.5.3 re-reads docker-compose.yml on each deploy, so no buttons are needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:48:19 +01:00

207 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The sky over Zlín, calculated locally (ephem): sun, moon, planets, bright stars and the ISS. No drawing.
Every time in and out is naive local wall-clock time (BOARD_TZ); ephem itself works in UTC.
"""
import math
from dataclasses import dataclass
from datetime import datetime, timedelta
import ephem
import ephem.stars
from sky_data import Tle
from timeutil import from_utc, to_utc
from weather_data import LAT, LON
ELEVATION_M = 230
DIRECTIONS = ["S", "SV", "V", "JV", "J", "JZ", "Z", "SZ"] # Czech: S = sever (north), J = jih (south)
BODIES = (("Měsíc", ephem.Moon), ("Merkur", ephem.Mercury), ("Venuše", ephem.Venus), ("Mars", ephem.Mars),
("Jupiter", ephem.Jupiter), ("Saturn", ephem.Saturn))
DARK_SUN_ALT = "-18" # astronomical darkness
VISIBLE_SUN_ALT = -6 # a satellite pass is visible once the sky is at least this dark
TRACK_BACK, TRACK_AHEAD = 40, 95 # minutes of ISS ground track around now
ISS_STD_MAG = -1.8 # brightness at 1000 km and a 90° phase angle; observers quote -1.3 to -1.8
PASS_STEP_S = 10 # how finely a pass is sampled to find its brightest moment
@dataclass(frozen=True)
class Body:
name: str
alt: float # degrees above the horizon, negative below
az: float # degrees clockwise from north
rise: datetime | None # next rising, None when it does not rise or set
@dataclass(frozen=True)
class Star:
name: str
mag: float
alt: float
az: float
@dataclass(frozen=True)
class Pass:
start: datetime
max_alt: float
az_from: float
az_to: float
visible: bool # the ISS is sunlit while the sky here is dark
mag: float # estimated magnitude at the brightest moment (lower is brighter)
@dataclass(frozen=True)
class Fix:
lat: float
lon: float
km: float # height above the ground
def direction(az: float) -> str:
return DIRECTIONS[round(az / 45) % 8]
def _observer(when: datetime, horizon: str = "0") -> ephem.Observer:
o = ephem.Observer()
o.lat, o.lon, o.elevation, o.horizon = str(LAT), str(LON), ELEVATION_M, horizon
o.date = to_utc(when)
return o
def _local(date: ephem.Date) -> datetime:
return from_utc(ephem.Date(date).datetime())
def bodies(now: datetime) -> tuple[Body, ...]:
"""Moon first, then the planets in order from the sun."""
out = []
for name, cls in BODIES:
body = cls()
o = _observer(now)
try:
rise = _local(o.next_rising(body))
except (ephem.AlwaysUpError, ephem.NeverUpError):
rise = None
body.compute(_observer(now))
out.append(Body(name, math.degrees(body.alt), math.degrees(body.az), rise))
return tuple(out)
def sun(now: datetime) -> Body:
s = ephem.Sun(_observer(now))
return Body("Slunce", math.degrees(s.alt), math.degrees(s.az), None)
def moon_phase(now: datetime) -> tuple[float, bool]:
"""Illuminated percentage and whether it is waxing."""
moon = ephem.Moon(_observer(now))
utc = to_utc(now)
return moon.phase, ephem.next_full_moon(utc) < ephem.next_new_moon(utc)
def darkness(now: datetime) -> tuple[datetime, datetime] | None:
"""Astronomical darkness of tonight (before noon: of the night now ending); None if the sun never sinks enough."""
evening = now.date() - timedelta(days=1) if now.hour < 12 else now.date()
o = _observer(datetime.combine(evening, datetime.min.time()).replace(hour=12), DARK_SUN_ALT)
sun = ephem.Sun()
try:
start = o.next_setting(sun, use_center=True)
o.date = start
end = o.next_rising(sun, use_center=True)
except (ephem.AlwaysUpError, ephem.NeverUpError):
return None
return _local(start), _local(end)
def stars(now: datetime, brighter_than: float = 3.4) -> tuple[Star, ...]:
"""Named stars above the horizon, brightest first."""
o = _observer(now)
out = []
for name in ephem.stars.stars:
star = ephem.star(name)
star.compute(o)
if star.alt > 0 and star.mag < brighter_than:
out.append(Star(name, star.mag, math.degrees(star.alt), math.degrees(star.az)))
return tuple(sorted(out, key=lambda s: s.mag))
def _iss(tle: Tle) -> ephem.EarthSatellite:
return ephem.readtle(tle.name, tle.line1, tle.line2)
def iss_fix(tle: Tle, when: datetime) -> Fix:
iss = _iss(tle)
iss.compute(to_utc(when))
return Fix(math.degrees(iss.sublat), math.degrees(iss.sublong), iss.elevation / 1000)
def iss_track(tle: Tle, now: datetime) -> tuple[tuple[int, float, float], ...]:
"""(minutes from now, lat, lon) for every minute from TRACK_BACK before to TRACK_AHEAD after now."""
iss = _iss(tle)
track = []
for m in range(-TRACK_BACK, TRACK_AHEAD + 1):
iss.compute(to_utc(now + timedelta(minutes=m)))
track.append((m, math.degrees(iss.sublat), math.degrees(iss.sublong)))
return tuple(track)
def next_visible_pass(tle: Tle, now: datetime, within_hours: float = 72) -> Pass | None:
iss, sun = _iss(tle), ephem.Sun()
o = _observer(now)
limit = ephem.Date(to_utc(now + timedelta(hours=within_hours)))
while o.date < limit:
rise, az_rise, top, top_alt, set_, az_set = o.next_pass(iss)
if rise is None or rise > limit:
return None
o.date = top
iss.compute(o)
sun.compute(o)
if not iss.eclipsed and math.degrees(sun.alt) < VISIBLE_SUN_ALT:
return Pass(_local(rise), math.degrees(top_alt), math.degrees(az_rise), math.degrees(az_set), True,
_brightest(iss, sun, o, rise, set_))
o.date = set_ + ephem.minute
return None
def magnitude(range_km: float, phase: float, std_mag: float = ISS_STD_MAG) -> float:
"""Estimated magnitude of a satellite seen as a diffusely reflecting sphere (Robert Matson's formula).
`phase` is the sun–satellite–observer angle in radians: 0 when fully lit as seen from here, π when only its
unlit side faces us.
"""
lit = max(1e-6, math.sin(phase) + (math.pi - phase) * math.cos(phase))
return std_mag - 15 + 5 * math.log10(range_km) - 2.5 * math.log10(lit)
def _unit(alt: float, az: float) -> tuple[float, float, float]:
return math.cos(alt) * math.sin(az), math.cos(alt) * math.cos(az), math.sin(alt)
def _phase(sat: ephem.EarthSatellite, sun: ephem.Sun) -> float:
"""The sun is so far away that its direction from the satellite is the same as from here."""
cos = -sum(a * b for a, b in zip(_unit(sat.alt, sat.az), _unit(sun.alt, sun.az)))
return math.acos(max(-1.0, min(1.0, cos)))
def _brightest(iss: ephem.EarthSatellite, sun: ephem.Sun, o: ephem.Observer, rise, set_) -> float:
"""The lowest magnitude while the ISS is above the horizon and sunlit."""
best = math.inf
t = rise
while t <= set_:
o.date = t
iss.compute(o)
sun.compute(o)
if iss.alt > 0 and not iss.eclipsed:
best = min(best, magnitude(iss.range / 1000, _phase(iss, sun)))
t += PASS_STEP_S * ephem.second
return best
def subsolar(now: datetime) -> tuple[float, float]:
"""Latitude and longitude where the sun is straight overhead."""
o = ephem.Observer()
o.lat, o.lon, o.date = "0", "0", to_utc(now)
sun = ephem.Sun(o)
lon = math.degrees(sun.ra - o.sidereal_time())
return math.degrees(sun.dec), (lon + 540) % 360 - 180