Ephemeris Table Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Replace the single-point embedded ephemeris with an interpolatable table of daily positions, giving accurate sun/moon positions and rise/set times throughout the day without loading Astronomy Engine for most visitors.
Architecture: At build time, generate /ephemeris.js containing noon+midnight RA/Dec for a rolling window (7 days past to 30 days future, plus all frontpage publication dates). The JS loads this file on-demand (front page, ?fp= navigation) and interpolates between data points for any given hour. Astronomy Engine is retained for users who share precise location. Default observer latitude changes from 40°N to San Francisco (37.77°N, 122.42°W).
Tech Stack: Python (skyfield, ephemeris.py), JavaScript (celestial.js), Django build pipeline (build_with_distill), Caddy (Caddyfile)
Data Format
The ephemeris table is a JS file that sets window.__ephemerisTable:
window.__ephemerisTable = {
lat: 37.77,
lon: -122.42,
built: "2026-02-21",
astroEngineHash: "d31f6ade4404",
// Map of "YYYY-MM-DD" → [sunRA_noon, sunDec_noon, moonRA_noon, moonDec_noon, eot,
// sunRA_mid, sunDec_mid, moonRA_mid, moonDec_mid,
// moonPhase, moonIllum]
// noon = 12:00 UTC, mid = 00:00 UTC of the NEXT day
dates: {
"2026-02-14": [334.47, -10.58, 19.8, 12.34, -12.2, 334.97, -10.42, 26.5, 14.8, 50.4, 0.181],
"2026-02-15": [...],
...
}
};
Field indices (constants in JS):
SUN_RA_NOON=0, SUN_DEC_NOON=1, MOON_RA_NOON=2, MOON_DEC_NOON=3, EOT=4,
SUN_RA_MID=5, SUN_DEC_MID=6, MOON_RA_MID=7, MOON_DEC_MID=8,
MOON_PHASE=9, MOON_ILLUM=10
Interpolation logic: - Hour ≥ 12 UTC: lerp between today’s noon (indices 0–4) and today’s midnight (indices 5–8), t = (hour − 12) / 12 - Hour < 12 UTC: lerp between yesterday’s midnight (indices 5–8) and today’s noon (indices 0–4), t = hour / 12 - Moon RA uses angle-aware lerp (shortest path around 360°) - Phase/illumination taken from today’s noon value (changes slowly)
Size estimate: ~2.5 KB for 38 days (7 past + 31 future), plus ~50 bytes per additional frontpage date. Typically under 4 KB total, ~1.5 KB gzipped.
Per-Page Embedded Ephemeris
Every page still embeds noon+midnight for its “Official Page Day” inside #article-swap:
| Page type | Embedded date | Format |
|---|---|---|
Front page (/) |
Today (build date) | Same 11-element array, keyed by date |
| Article detail | almanac-day | Same format |
Article via ?fp= |
publication date (from ?fp= param) |
Same format |
| Static pages | page’s almanac-day | Same format |
The embedded data uses the same format as the table (single entry in dates map), so the JS can merge them into a unified lookup.
Tier Cascade (Revised)
- Tier 2 — Astronomy Engine (user shared precise lat/lon): topocentric + refraction, ~1 min accuracy. Loaded on-demand (~412 KB). Unchanged.
- Tier 1 — Interpolated table (default): geocentric RA/Dec interpolated to current hour, converted to alt/az at default lat (37.77°N) + timezone-estimated lon. ~3–6 min accuracy for rise/set.
- Tier 0 — Simplified formulas (table expired or absent): declination from day-of-year, synodic offset for moon. ~30 min accuracy. Fallback for BCE dates, missing data.
The table is consulted first (before Tier 0) for any date within its range. The embedded per-page data covers the page’s own date even if the table hasn’t loaded yet.
Loading Strategy
Load /ephemeris.js when:
1. On the front page (/) — immediately on init
2. ?fp= query parameter present — immediately on init
3. Any page displaying today’s date in the masthead — on init
Don’t load on: - Direct article visits (embedded almanac-day data suffices) - Static pages with their own almanac-day
Loading mechanism: <script> tag injection (same pattern as Astronomy Engine). Async, non-blocking. On load, merge with any embedded data. On error (404 during dev), degrade gracefully.
Caching
/ephemeris.js lives at the web root, outside /static/. The Caddyfile sets Cache-Control: no-cache for it. Caddy’s automatic ETag support means browsers do conditional requests (304 Not Modified) — effectively free revalidation.
During dev (make serve): file doesn’t exist → 404 → JS falls back to embedded data or Tier 0.
Default Observer
Change from 40°N to San Francisco (37.77°N, 122.42°W): - Affects the default latitude used when no geolocation is available - Affects rise/set time computation - The longitude is used as the build-time reference for EoT-based rise/set times - JS still estimates the visitor’s longitude from timezone offset for positioning
Rise/Set Computation Improvement
Currently computeSunTimes() and computeMoonTimes() use a single noon RA/Dec and don’t correct for longitude. With the table:
- Use interpolated RA/Dec at the estimated rise/set hour (one iteration: estimate time → interpolate → recompute)
- Add longitude correction:
noon_clock = 12 − EoT/60 + (standardMeridian − observerLon) / 15 - The standard meridian is derived from the timezone offset:
stdMeridian = −offset / 4(same asestimateLongitude())
This improves moon rise/set from ~15–20 min error to ~3–6 min error.
Tasks
Task 1: Extend ephemeris.py with table generation
Files:
- Modify: src/almnck/ephemeris.py
- Test: src/tests/test_ephemeris.py
Step 1: Write failing tests
Add to test_ephemeris.py:
@skipif_no_ephemeris
class TestEphemerisTable:
"""Test ephemeris table generation for the JS file."""
def test_compute_table_returns_dict_with_dates(self):
from almnck.ephemeris import compute_table
table = compute_table("2026-02-21", days_past=7, days_future=30)
assert "dates" in table
assert "lat" in table
assert "2026-02-21" in table["dates"]
# 7 past + today + 30 future = 38 dates
assert len(table["dates"]) == 38
def test_table_entry_has_eleven_values(self):
from almnck.ephemeris import compute_table
table = compute_table("2026-02-21", days_past=1, days_future=1)
entry = table["dates"]["2026-02-21"]
assert len(entry) == 11
def test_table_noon_matches_single_compute(self):
"""Noon values in the table should match compute() for the same date."""
from almnck.ephemeris import compute, compute_table
single = compute("2026-02-21")
table = compute_table("2026-02-21", days_past=0, days_future=0)
entry = table["dates"]["2026-02-21"]
assert entry[0] == single["sun"]["ra"] # sun RA noon
assert entry[1] == single["sun"]["dec"] # sun dec noon
assert entry[2] == single["moon"]["ra"] # moon RA noon
assert entry[3] == single["moon"]["dec"] # moon dec noon
def test_table_midnight_differs_from_noon(self):
"""Midnight values should differ from noon (especially moon)."""
from almnck.ephemeris import compute_table
table = compute_table("2026-02-21", days_past=0, days_future=0)
entry = table["dates"]["2026-02-21"]
# Moon moves ~6.5° in RA over 12 hours
assert abs(entry[7] - entry[2]) > 3 # moon RA midnight vs noon
def test_table_includes_extra_dates(self):
"""Extra dates (frontpage dates) are included even if outside range."""
from almnck.ephemeris import compute_table
table = compute_table("2026-02-21", days_past=1, days_future=1,
extra_dates=["2026-01-15"])
assert "2026-01-15" in table["dates"]
assert "2026-02-21" in table["dates"]
def test_table_default_lat_is_san_francisco(self):
from almnck.ephemeris import compute_table
table = compute_table("2026-02-21", days_past=0, days_future=0)
assert table["lat"] == 37.77
def test_table_generates_js_source(self):
from almnck.ephemeris import compute_table, table_to_js
table = compute_table("2026-02-21", days_past=1, days_future=1)
js = table_to_js(table)
assert js.startswith("window.__ephemerisTable")
assert "2026-02-21" in js
Step 2: Run tests to verify they fail
Run: python -m pytest src/tests/test_ephemeris.py::TestEphemerisTable -v
Expected: ImportError on compute_table
Step 3: Implement compute_table() and table_to_js()
Add to ephemeris.py:
# Default observer: San Francisco
DEFAULT_LAT = 37.77
DEFAULT_LON = -122.42
def compute_table(today_str, days_past=7, days_future=30, extra_dates=None):
"""Compute an ephemeris table for a range of dates.
Returns a dict with 'lat', 'lon', 'built', 'dates' suitable for
conversion to JS source via table_to_js().
Each date entry is an 11-element list:
[sunRA_noon, sunDec_noon, moonRA_noon, moonDec_noon, eqnOfTime,
sunRA_mid, sunDec_mid, moonRA_mid, moonDec_mid,
moonPhase, moonIllumination]
noon = 12:00 UTC, mid = 00:00 UTC of the following day.
"""
from datetime import date, timedelta
# Parse today
parts = today_str.split("-")
base = date(int(parts[0]), int(parts[1]), int(parts[2]))
# Build date set: continuous range + extras
dates = set()
for offset in range(-days_past, days_future + 1):
d = base + timedelta(days=offset)
dates.add(d.isoformat())
if extra_dates:
for d in extra_dates:
if d and len(d) >= 10:
dates.add(d)
# Compute for each date
result_dates = {}
for date_str in sorted(dates):
entry = _compute_day_entry(date_str)
if entry:
result_dates[date_str] = entry
return {
"lat": DEFAULT_LAT,
"lon": DEFAULT_LON,
"built": today_str,
"dates": result_dates,
}
def _compute_day_entry(date_str):
"""Compute noon and midnight positions for a single date.
Returns 11-element list or None if date is out of range.
"""
_init()
try:
parts = date_str.split("-")
year, month, day = int(parts[0]), int(parts[1]), int(parts[2])
except (ValueError, IndexError):
return None
if year < 1849 or year > 2150:
return None
try:
from skyfield import almanac as skyfield_almanac
# Noon UTC
t_noon = _ts.utc(year, month, day, 12)
sun_noon = _earth.at(t_noon).observe(_sun).apparent()
sun_ra_n, sun_dec_n, _ = sun_noon.radec()
moon_noon = _earth.at(t_noon).observe(_moon).apparent()
moon_ra_n, moon_dec_n, _ = moon_noon.radec()
# Equation of time at noon
gmst = t_noon.gmst
sun_ha = gmst - sun_ra_n.hours
eot = sun_ha * 60
while eot > 720: eot -= 1440
while eot < -720: eot += 1440
# Moon phase at noon
phase = skyfield_almanac.moon_phase(_eph, t_noon).degrees
illumination = (1 - math.cos(math.radians(phase))) / 2
# Midnight UTC (00:00 of next day)
t_mid = _ts.utc(year, month, day + 1, 0)
sun_mid = _earth.at(t_mid).observe(_sun).apparent()
sun_ra_m, sun_dec_m, _ = sun_mid.radec()
moon_mid = _earth.at(t_mid).observe(_moon).apparent()
moon_ra_m, moon_dec_m, _ = moon_mid.radec()
return [
round(sun_ra_n._degrees, 2),
round(sun_dec_n.degrees, 2),
round(moon_ra_n._degrees, 2),
round(moon_dec_n.degrees, 2),
round(eot, 1),
round(sun_ra_m._degrees, 2),
round(sun_dec_m.degrees, 2),
round(moon_ra_m._degrees, 2),
round(moon_dec_m.degrees, 2),
round(phase, 1),
round(illumination, 3),
]
except Exception:
return None
def table_to_js(table):
"""Convert a table dict to JavaScript source code."""
import json
return "window.__ephemerisTable = " + json.dumps(table, separators=(",", ":")) + ";\n"
Step 4: Run tests to verify they pass
Run: python -m pytest src/tests/test_ephemeris.py::TestEphemerisTable -v
Expected: all PASS
Step 5: Commit
git add src/almnck/ephemeris.py src/tests/test_ephemeris.py
git commit -m "feat(ephemeris): add compute_table() for multi-day interpolation"
Task 2: Generate ephemeris table during build
Files:
- Modify: src/almnck/units/management/commands/build_with_distill.py
- Modify: assets/system/Caddyfile
Step 1: Add _generate_ephemeris_table() to build command
In build_with_distill.py, add method and call it after _copy_shared_assets():
def _generate_ephemeris_table(self):
"""Generate /ephemeris.js with interpolatable position data."""
from datetime import datetime
from almnck.ephemeris import compute_table, table_to_js, available
if not available():
self.stdout.write(" Skipping ephemeris table (ephemeris unavailable)")
return
output_dir = Path(settings.DISTILL_DIR)
today = datetime.now().strftime("%Y-%m-%d")
# Collect all frontpage dates for extra coverage
extra_dates = []
for unit in Unit.objects.filter(
unit_type=Unit.UnitType.ARTICLE,
status=Unit.Status.PUBLISHED,
):
for fp_date in unit.frontmatter.get("frontpage", []):
extra_dates.append(fp_date)
table = compute_table(today, days_past=7, days_future=30,
extra_dates=extra_dates)
# Add Astronomy Engine hash for cache-busting
from almnck.units.views import _file_content_hash
table["astroEngineHash"] = _file_content_hash(
"/static/js/vendor/astronomy-engine.js"
)
js_source = table_to_js(table)
output_path = output_dir / "ephemeris.js"
output_path.write_text(js_source)
self.stdout.write(
f" Generated ephemeris.js ({len(table['dates'])} dates, "
f"{len(js_source):,} bytes)"
)
Step 2: Update Caddyfile
:80 {
root * /usr/share/caddy
encode zstd gzip
@static path /static/*
header @static Cache-Control "max-age=31536000, immutable"
@ephemeris path /ephemeris.js
header @ephemeris Cache-Control "no-cache"
file_server
@caddyfile path /Caddyfile
respond @caddyfile 404
}
Step 3: Test the build
Run: make sync && make build
Verify: web/ephemeris.js exists, contains window.__ephemerisTable, has ~38+ dates.
Step 4: Commit
git add src/almnck/units/management/commands/build_with_distill.py assets/system/Caddyfile
git commit -m "feat(build): generate /ephemeris.js table during build"
Task 3: Update per-page embedded ephemeris to new format
Files:
- Modify: src/almnck/ephemeris.py (add compute_page_ephemeris())
- Modify: src/almnck/units/views.py
- Modify: src/almnck/templates/units/index.html
- Modify: src/almnck/templates/units/article.html
- Modify: src/tests/test_index_ephemeris_date.py
The per-page embedded data switches from the old single-point format:
{"date": "2026-02-21", "sun": {"ra": 334.47, "dec": -10.58}, ...}
To the new table-compatible format (single entry in a dates map):
{"lat": 37.77, "dates": {"2026-02-21": [334.47, -10.58, 19.8, 12.34, -12.2, ...]}}
This lets the JS merge the embedded data directly into the table lookup.
Step 1: Add compute_page_ephemeris() to ephemeris.py
def compute_page_ephemeris(date_str):
"""Compute a single-day ephemeris in table format for embedding in HTML.
Returns a dict with 'lat', 'dates' (single entry) or None.
"""
entry = _compute_day_entry(date_str)
if not entry:
return None
return {
"lat": DEFAULT_LAT,
"dates": {date_str: entry},
}
Step 2: Update views.py
Replace all compute_ephemeris(date) calls with compute_page_ephemeris(date).
Remove the astroEngineHash injection (it’s now in the table file).
Index view:
celestial_ephemeris = compute_page_ephemeris(today)
Article detail view:
celestial_ephemeris = compute_page_ephemeris(ephemeris_target) if ephemeris_target else None
Page detail view: same pattern.
Step 3: Update regression test
Adapt test_index_ephemeris_date.py to the new format: check that ephemeris["dates"] contains today’s date key.
Step 4: Run tests
Run: make test-unit
Expected: all pass
Step 5: Commit
git add src/almnck/ephemeris.py src/almnck/units/views.py \
src/almnck/templates/units/index.html \
src/almnck/templates/units/article.html \
src/tests/test_index_ephemeris_date.py
git commit -m "feat(ephemeris): switch per-page embedded data to table format"
Task 4: Update celestial.js — table loading and interpolation
Files:
- Modify: assets/js/celestial.js
- Test: src/tests/test_celestial.py (browser tests)
This is the largest task. The JS changes are:
- Parse new embedded format —
loadEmbeddedEphemeris()returns{lat, dates}instead of the old format - Table loading — async load of
/ephemeris.json front page and?fp= - Interpolation —
interpolateFromTable(dateStr, hourUTC)returns sun/moon RA/Dec - Position functions —
sunPositionEph()andmoonPositionEph()use interpolated values - Almanack info —
computeAlmanackInfo()uses interpolated values with longitude correction - Default latitude — 37.77°N instead of 40°N
Step 1: Add table loading and interpolation functions
// Field indices in the 11-element day entry
var F_SUN_RA_N=0, F_SUN_DEC_N=1, F_MOON_RA_N=2, F_MOON_DEC_N=3, F_EOT=4,
F_SUN_RA_M=5, F_SUN_DEC_M=6, F_MOON_RA_M=7, F_MOON_DEC_M=8,
F_MOON_PHASE=9, F_MOON_ILLUM=10;
var _ephemerisTable = null; // from /ephemeris.js or embedded
var _tableLoading = null;
function loadEphemerisTable() {
if (_ephemerisTable) return Promise.resolve(_ephemerisTable);
if (_tableLoading) return _tableLoading;
_tableLoading = new Promise(function(resolve) {
var script = document.createElement("script");
script.src = "/ephemeris.js";
script.onload = function() {
if (window.__ephemerisTable) {
_mergeTable(window.__ephemerisTable);
}
resolve(_ephemerisTable);
};
script.onerror = function() {
_tableLoading = null;
resolve(null);
};
document.head.appendChild(script);
});
return _tableLoading;
}
function _mergeTable(newData) {
if (!_ephemerisTable) {
_ephemerisTable = { lat: newData.lat || DEFAULT_LAT, dates: {} };
}
if (newData.dates) {
for (var d in newData.dates) {
_ephemerisTable.dates[d] = newData.dates[d];
}
}
}
function lerpAngle(a, b, t) {
var diff = b - a;
if (diff > 180) diff -= 360;
if (diff < -180) diff += 360;
return ((a + t * diff) % 360 + 360) % 360;
}
function interpolateFromTable(dateStr, hourUTC) {
if (!_ephemerisTable || !_ephemerisTable.dates) return null;
var today = _ephemerisTable.dates[dateStr];
if (!today) return null;
if (hourUTC >= 12) {
// Noon → midnight: interpolate within today's entry
var t = (hourUTC - 12) / 12;
return {
sun: { ra: today[F_SUN_RA_N] + t * (today[F_SUN_RA_M] - today[F_SUN_RA_N]),
dec: today[F_SUN_DEC_N] + t * (today[F_SUN_DEC_M] - today[F_SUN_DEC_N]) },
moon: { ra: lerpAngle(today[F_MOON_RA_N], today[F_MOON_RA_M], t),
dec: today[F_MOON_DEC_N] + t * (today[F_MOON_DEC_M] - today[F_MOON_DEC_N]) },
eqnOfTime: today[F_EOT],
moonPhase: today[F_MOON_PHASE],
moonIllumination: today[F_MOON_ILLUM]
};
} else {
// Midnight → noon: need yesterday's midnight values
var yesterday = prevDateStr(dateStr);
var yest = _ephemerisTable.dates[yesterday];
if (!yest) return null; // can't interpolate without yesterday
var t = hourUTC / 12;
return {
sun: { ra: yest[F_SUN_RA_M] + t * (today[F_SUN_RA_N] - yest[F_SUN_RA_M]),
dec: yest[F_SUN_DEC_M] + t * (today[F_SUN_DEC_N] - yest[F_SUN_DEC_M]) },
moon: { ra: lerpAngle(yest[F_MOON_RA_M], today[F_MOON_RA_N], t),
dec: yest[F_MOON_DEC_M] + t * (today[F_MOON_DEC_N] - yest[F_MOON_DEC_M]) },
eqnOfTime: today[F_EOT],
moonPhase: today[F_MOON_PHASE],
moonIllumination: today[F_MOON_ILLUM]
};
}
}
Step 2: Update position functions
sunPositionEph() and moonPositionEph() gain a new tier:
- Tier 2: Astronomy Engine (unchanged)
- Tier 1: interpolateFromTable() → raDecToAltAz() with observer lat + estimated lon
- Tier 0: simplified formulas (unchanged, but default lat → 37.77°N)
Step 3: Update computeAlmanackInfo()
Use interpolated values for rise/set. Add longitude correction:
var stdMeridian = estimateLongitude();
var lonCorrection = (stdMeridian - (_observerLon || stdMeridian)) / 15;
// Apply to transit/noon calculations
Step 4: Update __celestialSetDate()
On date change, check if the table has the new date. If not and the embedded data matches, use that. Otherwise null out for Tier 0 fallback.
Step 5: Trigger table load on init
// In init():
var needsTable = (window.location.pathname === "/" ||
new URLSearchParams(window.location.search).get("fp"));
if (needsTable) loadEphemerisTable().then(function() { doRender(); });
Step 6: Run browser tests
Run: make test-browser
Expected: all pass (positions may shift slightly due to lat change)
Step 7: Commit
git add assets/js/celestial.js
git commit -m "feat(celestial): interpolated ephemeris table, SF default lat"
Task 5: Update default latitude everywhere
Files:
- Modify: assets/js/celestial.js — _observerLat = 37.77 (was 40)
- Modify: assets/js/celestial.js — simplified fallback functions use 37.77
- Modify: doc/03-website/06-celestial-sphere.md — update documentation
The simplified fallback functions (sunPosition(), moonPosition()) have
var lat = 40 * DEG hardcoded. Change to var lat = DEFAULT_LAT * DEG
where DEFAULT_LAT = 37.77.
Step 1: Change default lat
var DEFAULT_LAT = 37.77;
// ...
var _observerLat = DEFAULT_LAT;
Step 2: Update simplified functions
function sunPosition(hour, doy) {
var lat = DEFAULT_LAT * DEG;
// ... rest unchanged
}
Step 3: Update browser tests
Tests that hard-code altitude expectations at lat=40 may need adjustment.
Check test_celestial_interaction.py and test_celestial.py.
Step 4: Update docs
In 06-celestial-sphere.md, change all references from “40°N” to “37.77°N (San Francisco)”.
Step 5: Commit
git add assets/js/celestial.js doc/03-website/06-celestial-sphere.md \
src/tests/test_celestial_interaction.py
git commit -m "feat(celestial): default observer latitude → San Francisco (37.77°N)"
Task 6: Clean up old single-point ephemeris code
Files:
- Modify: src/almnck/ephemeris.py — keep compute() (used by a-celestial) but deprecate
- Modify: src/almnck/units/views.py — remove astroEngineHash injection from views
- Remove: old _ephemeris parsing in celestial.js (replaced by _ephemerisTable)
Step 1: Remove old code paths
In celestial.js, remove the old loadEmbeddedEphemeris() that parsed the
single-point format. The new version parses the table format.
In views.py, remove the astroEngineHash injection from individual view
functions (it’s now in the build-time table).
Step 2: Run all tests
Run: make test-unit && make test-browser
Step 3: Commit
git add -A
git commit -m "refactor: remove old single-point ephemeris code paths"
Task 7: Integration test — full build verification
Step 1: Full build and verify
make sync && make build
Verify:
- web/ephemeris.js exists with ~38+ dates
- web/index.html has new-format embedded ephemeris inside #article-swap
- web/Caddyfile has @ephemeris rule
- Article pages have their almanac-day ephemeris embedded
Step 2: Dev server spot-check
make serve
Visit http://localhost:1969/ — armillary should show today’s sky.
Open browser console — no errors loading /ephemeris.js (404 is OK in dev).
Step 3: Run all test suites
make test-all
Step 4: Final commit and tag
git add -A
git commit -m "feat: ephemeris interpolation table — accurate sky without Astronomy Engine"