JPL Ephemeris & Geolocation Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Replace the celestial masthead’s simplified astronomical model with JPL-accurate ephemeris data, with optional browser geolocation for location-aware sky rendering.
Architecture: Two-tier progressive enhancement. Tier 1: Python skyfield computes geocentric sun/moon positions at build time and embeds them in HTML; celestial.js reads them with zero library cost. Tier 2: If the reader shares their location, lazy-load Astronomy Engine (~35KB gzipped) for full topocentric positions with refraction.
Tech Stack: Python skyfield + JPL DE440s (build time), Astronomy Engine JS (client, on demand), browser Geolocation API, localStorage.
Design doc: doc/process/plans/2026-02-18-jpl-ephemeris-geolocation-design.md
Pre-flight
Before starting, activate the environment:
source bin/a-activate
Confirm existing tests pass:
make test
Task 1: Add skyfield dependency and ephemeris fetch target
Files:
- Modify: pyproject.toml
- Modify: Makefile
- Modify: .gitignore
- Create: assets/reference/.gitkeep (if needed — dir exists)
Step 1: Add skyfield to pyproject.toml
In pyproject.toml, add skyfield to the main dependencies list:
dependencies = [
...existing...,
"skyfield>=1.48",
]
Step 2: Add .gitignore entry for ephemeris file
Append to .gitignore:
# JPL ephemeris data (downloaded, not tracked)
assets/reference/*.bsp
Step 3: Add Makefile target
Add after the install target in Makefile:
.PHONY: ephemeris-fetch
ephemeris-fetch: check-activated
@echo "$(YELLOW)Fetching JPL DE440s ephemeris (~32MB)...$(RESET)"
@mkdir -p $(ALMANACK_ROOT)/assets/reference
@curl -# -o $(ALMANACK_ROOT)/assets/reference/de440s.bsp \
https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de440s.bsp
@echo "$(GREEN)Saved to assets/reference/de440s.bsp$(RESET)"
Step 4: Install dependencies and fetch ephemeris
uv sync
make ephemeris-fetch
Expected: assets/reference/de440s.bsp exists, ~32MB.
Step 5: Commit
git add pyproject.toml Makefile .gitignore
git commit -m "deps: add skyfield, ephemeris fetch target"
Task 2: Write ephemeris.py with unit tests (TDD)
Files:
- Create: src/almnck/ephemeris.py
- Create: src/tests/test_ephemeris.py
Step 1: Write failing tests
Create src/tests/test_ephemeris.py:
"""Tests for JPL ephemeris computation."""
import os
import pytest
from pathlib import Path
def ephemeris_available():
root = os.environ.get("ALMANACK_ROOT", ".")
return (Path(root) / "assets" / "reference" / "de440s.bsp").exists()
skipif_no_ephemeris = pytest.mark.skipif(
not ephemeris_available(),
reason="DE440s ephemeris not downloaded (run: make ephemeris-fetch)",
)
@skipif_no_ephemeris
class TestEphemerisCompute:
"""Test ephemeris.compute() returns accurate positions."""
def test_returns_required_keys(self):
from almnck.ephemeris import compute
result = compute("2026-02-18")
assert result is not None
assert "date" in result
assert "sun" in result
assert "moon" in result
assert "eqnOfTime" in result
assert "ra" in result["sun"]
assert "dec" in result["sun"]
assert "ra" in result["moon"]
assert "dec" in result["moon"]
assert "phase" in result["moon"]
assert "illumination" in result["moon"]
def test_summer_solstice_sun_declination(self):
"""On summer solstice, sun should be near +23.4° declination."""
from almnck.ephemeris import compute
result = compute("2026-06-21")
assert result["sun"]["dec"] > 23.0
assert result["sun"]["dec"] < 24.0
def test_winter_solstice_sun_declination(self):
"""On winter solstice, sun should be near -23.4° declination."""
from almnck.ephemeris import compute
result = compute("2025-12-21")
assert result["sun"]["dec"] < -23.0
assert result["sun"]["dec"] > -24.0
def test_known_full_moon(self):
"""Jan 13 2026 was a full moon — phase should be near 180°."""
from almnck.ephemeris import compute
result = compute("2026-01-13")
assert result["moon"]["phase"] > 160
assert result["moon"]["phase"] < 200
assert result["moon"]["illumination"] > 0.95
def test_known_new_moon(self):
"""Jan 29 2026 was a new moon — phase should be near 0°/360°."""
from almnck.ephemeris import compute
result = compute("2026-01-29")
phase = result["moon"]["phase"]
assert phase < 20 or phase > 340
assert result["moon"]["illumination"] < 0.05
def test_ra_range(self):
"""RA should be 0-360 degrees."""
from almnck.ephemeris import compute
result = compute("2026-02-18")
assert 0 <= result["sun"]["ra"] < 360
assert 0 <= result["moon"]["ra"] < 360
def test_equation_of_time_range(self):
"""Equation of time should be within ±17 minutes."""
from almnck.ephemeris import compute
result = compute("2026-02-18")
assert -17 < result["eqnOfTime"] < 17
def test_equation_of_time_february(self):
"""In mid-February, equation of time should be around -14 minutes."""
from almnck.ephemeris import compute
result = compute("2026-02-12")
assert result["eqnOfTime"] < -10
assert result["eqnOfTime"] > -16
@skipif_no_ephemeris
class TestEphemerisDateRange:
"""Test boundary behaviour for date ranges."""
def test_date_within_range(self):
from almnck.ephemeris import compute
assert compute("2026-02-18") is not None
def test_date_at_lower_bound(self):
"""DE440s starts around 1849."""
from almnck.ephemeris import compute
assert compute("1850-06-15") is not None
def test_date_before_range_returns_none(self):
"""Dates before DE440s range should return None gracefully."""
from almnck.ephemeris import compute
result = compute("-4000-01-01")
assert result is None
def test_date_far_future_returns_none(self):
"""Dates beyond DE440s range should return None gracefully."""
from almnck.ephemeris import compute
result = compute("3000-01-01")
assert result is None
@skipif_no_ephemeris
class TestEphemerisCaching:
"""Test that repeated calls use cache."""
def test_same_date_returns_same_object(self):
from almnck.ephemeris import compute
a = compute("2026-02-18")
b = compute("2026-02-18")
assert a is b # same object from cache
Step 2: Run tests to verify they fail
cd src && python -m pytest tests/test_ephemeris.py -v
Expected: All tests FAIL (ImportError — module doesn’t exist yet).
Step 3: Write the implementation
Create src/almnck/ephemeris.py:
"""JPL ephemeris computation for celestial masthead.
Uses skyfield with JPL DE440s to compute accurate geocentric sun and moon
positions. Results are embedded as JSON in HTML pages at build time.
The DE440s file (~32MB) covers 1849-2150 CE. Dates outside this range
return None, and the client-side JS falls back to simplified formulas.
"""
import os
from functools import lru_cache
from pathlib import Path
_loader = None
_ts = None
_eph = None
_earth = None
_sun = None
_moon = None
def _init():
"""Lazy-init skyfield objects (only when first needed)."""
global _loader, _ts, _eph, _earth, _sun, _moon
if _eph is not None:
return
from skyfield.api import Loader
root = os.environ.get("ALMANACK_ROOT", ".")
data_dir = Path(root) / "assets" / "reference"
_loader = Loader(str(data_dir))
_ts = _loader.timescale()
_eph = _loader("de440s.bsp")
_earth = _eph["earth"]
_sun = _eph["sun"]
_moon = _eph["moon"]
@lru_cache(maxsize=512)
def compute(date_str):
"""Compute geocentric sun/moon positions for a date string.
Args:
date_str: Date in "YYYY-MM-DD" format (or "-YYYY-MM-DD" for BCE).
Returns:
Dict with sun/moon RA/Dec, moon phase/illumination, equation of time.
Returns None for dates outside the DE440s range (1849-2150 CE).
"""
try:
_init()
except Exception:
return None
# Parse date
try:
if date_str.startswith("-"):
parts = date_str[1:].split("-")
year = -int(parts[0])
else:
parts = date_str.split("-")
year = int(parts[0])
month = int(parts[1])
day = int(parts[2])
except (ValueError, IndexError):
return None
# Check range (DE440s covers ~1849-2150)
if year < 1849 or year > 2150:
return None
try:
t = _ts.utc(year, month, day, 12) # noon UTC
# Sun
sun_apparent = _earth.at(t).observe(_sun).apparent()
sun_ra, sun_dec, _ = sun_apparent.radec()
# Moon
moon_apparent = _earth.at(t).observe(_moon).apparent()
moon_ra, moon_dec, _ = moon_apparent.radec()
# Moon phase angle (0° = new, 180° = full)
from skyfield import almanac as skyfield_almanac
phase_angle = skyfield_almanac.moon_phase(_eph, t).degrees
# Moon illumination from phase angle
import math
illumination = (1 - math.cos(math.radians(phase_angle))) / 2
# Equation of time (minutes)
# EoT = apparent solar time - mean solar time
# At noon UTC, the sun's hour angle tells us how far solar noon
# deviates from clock noon.
sun_ra_hours = sun_ra.hours
# Greenwich mean sidereal time at noon UTC
gmst = t.gmst
# Sun's hour angle at Greenwich
sun_ha = gmst - sun_ra_hours # hours
# EoT in minutes (positive = sundial ahead of clock)
eqn_of_time = sun_ha * 60 # convert hours to minutes
# Normalise to ±720 minutes
while eqn_of_time > 720:
eqn_of_time -= 1440
while eqn_of_time < -720:
eqn_of_time += 1440
return {
"date": date_str,
"sun": {
"ra": round(sun_ra._degrees, 2),
"dec": round(sun_dec.degrees, 2),
},
"moon": {
"ra": round(moon_ra._degrees, 2),
"dec": round(moon_dec.degrees, 2),
"phase": round(phase_angle, 1),
"illumination": round(illumination, 3),
},
"eqnOfTime": round(eqn_of_time, 1),
}
except Exception:
return None
Step 4: Run tests to verify they pass
cd src && python -m pytest tests/test_ephemeris.py -v
Expected: All tests PASS (assuming DE440s is downloaded).
Step 5: Commit
git add src/almnck/ephemeris.py src/tests/test_ephemeris.py
git commit -m "feat: ephemeris module with skyfield/DE440s computation
Computes geocentric sun/moon RA/Dec, moon phase and illumination,
and equation of time for dates within the DE440s range (1849-2150).
Results cached per date. Graceful None return outside range."
Task 3: Inject ephemeris JSON into templates
Files:
- Modify: src/almnck/units/views.py — add ephemeris to context in index(), article_detail(), page_detail()
- Modify: src/almnck/templates/base.html — add <script id="celestial-ephemeris"> block
Step 1: Write a test for embedded JSON in built pages
Add to src/tests/test_ephemeris.py:
@skipif_no_ephemeris
@pytest.mark.django_db
class TestEphemerisTemplateInjection:
"""Test that ephemeris data appears in rendered pages."""
def test_compute_returns_json_serialisable(self):
"""Verify compute() output can be JSON-serialised."""
import json
from almnck.ephemeris import compute
result = compute("2026-02-18")
json_str = json.dumps(result)
parsed = json.loads(json_str)
assert parsed["sun"]["ra"] == result["sun"]["ra"]
Run: cd src && python -m pytest tests/test_ephemeris.py::TestEphemerisTemplateInjection -v
Expected: PASS.
Step 2: Add ephemeris to view contexts
In src/almnck/units/views.py, add at top:
import json as _json
from almnck.ephemeris import compute as compute_ephemeris
In the index() function, before the return render(...), add:
# Compute ephemeris for celestial masthead
ephemeris_date = frontpage_date or today
celestial_ephemeris = compute_ephemeris(ephemeris_date)
celestial_ephemeris_json = _json.dumps(celestial_ephemeris) if celestial_ephemeris else None
Add "celestial_ephemeris": celestial_ephemeris_json, to the context dict.
In the article_detail() function, before the return render(...), add:
# Compute ephemeris for celestial masthead
celestial_ephemeris = compute_ephemeris(almanac_day) if almanac_day else None
celestial_ephemeris_json = _json.dumps(celestial_ephemeris) if celestial_ephemeris else None
Add "celestial_ephemeris": celestial_ephemeris_json, to the context dict.
In the page_detail() function, before the return render(...), add:
# Compute ephemeris for celestial masthead
page_almanac_day = unit.frontmatter.get("almanac-day", "")
celestial_ephemeris = compute_ephemeris(page_almanac_day) if page_almanac_day else None
celestial_ephemeris_json = _json.dumps(celestial_ephemeris) if celestial_ephemeris else None
Add "celestial_ephemeris": celestial_ephemeris_json, to the context dict.
Step 3: Add JSON block to base.html
In src/almnck/templates/base.html, add just before the <script src="{% cdnstatic 'js/celestial.js' %}" line:
{% if celestial_ephemeris %}
<script id="celestial-ephemeris" type="application/json">{{ celestial_ephemeris|safe }}</script>
{% endif %}
Step 4: Verify the dev server includes the data
make serve &
sleep 3
curl -s http://localhost:1969/ | grep -o 'celestial-ephemeris.*</script>' | head -1
kill %1
Expected: Shows the JSON data block.
Step 5: Verify existing tests still pass
make test
Step 6: Commit
git add src/almnck/units/views.py src/almnck/templates/base.html src/tests/test_ephemeris.py
git commit -m "feat: embed ephemeris JSON in HTML pages at build time
Views compute JPL-accurate sun/moon positions via skyfield and
inject them as <script type=application/json> in base.html.
Keyed to the page's almanac-day or frontpage date."
Task 4: Modify celestial.js to read embedded ephemeris (Tier 1)
Files:
- Modify: assets/js/celestial.js
This is the core Tier 1 change. The strategy:
1. Read the embedded JSON on init
2. Add a raDecToAltAz() function
3. Add a localSiderealTime() function that uses the equation of time
4. Replace sunPosition() / moonPosition() calls in the main render path with ephemeris-derived values when available
5. Fall back to the existing simplified functions when no embedded data
Step 1: Add ephemeris reading and RA/Dec→alt/az conversion
At the top of celestial.js (after the constants section), add:
// ===== Embedded ephemeris (Tier 1) =====
var _ephemeris = null; // parsed JSON from build-time computation
function loadEmbeddedEphemeris() {
var el = document.getElementById("celestial-ephemeris");
if (!el) return null;
try { return JSON.parse(el.textContent); }
catch (e) { return null; }
}
/**
* Estimate longitude from browser timezone offset.
* getTimezoneOffset() returns minutes west of UTC, so
* longitude (east-positive) ≈ -offset / 4.
*/
function estimateLongitude() {
return -(new Date().getTimezoneOffset()) / 4;
}
/**
* Local sidereal time (degrees) for a given UT hour and day-of-year.
* Uses the equation of time from embedded ephemeris for correction.
*
* lon: observer longitude in degrees (east positive)
* hour: UT hour (fractional)
* eqnOfTime: equation of time in minutes (from ephemeris)
*/
function localSiderealTime(lon, hour, doy, eqnOfTime) {
// Approximate GMST: at vernal equinox (doy ~80), sidereal time ≈ 0h at noon
// LST increases by ~361°/day (one full rotation + ~1° for Earth's orbit)
var daysSinceEquinox = doy - 80;
var gmst = (daysSinceEquinox * 360.9856 + (hour - 12) * 15.04107) % 360;
if (gmst < 0) gmst += 360;
// Apply equation of time correction (convert minutes to degrees: 1 min ≈ 0.25°)
var eot = (eqnOfTime || 0) * 0.25;
return (gmst + lon + eot + 360) % 360;
}
/**
* Convert geocentric RA/Dec to topocentric alt/az.
*
* ra: right ascension in degrees (0-360)
* dec: declination in degrees (-90 to +90)
* lat: observer latitude in degrees
* lst: local sidereal time in degrees
*
* Returns {alt, az} in degrees.
*/
function raDecToAltAz(ra, dec, lat, lst) {
var ha = (lst - ra) * DEG;
var decR = dec * DEG;
var latR = lat * DEG;
var sinAlt = Math.sin(latR) * Math.sin(decR) +
Math.cos(latR) * Math.cos(decR) * Math.cos(ha);
var alt = Math.asin(sinAlt) / DEG;
var cosAz = (Math.sin(decR) - Math.sin(latR) * sinAlt) /
(Math.cos(latR) * Math.cos(Math.asin(sinAlt)));
var az = Math.acos(Math.max(-1, Math.min(1, cosAz))) / DEG;
if (Math.sin(ha) > 0) az = 360 - az;
return { alt: alt, az: az };
}
Step 2: Add location-aware position functions
Add wrapper functions that use the ephemeris when available, falling back to the simplified model:
// ===== Location state =====
var _observerLat = 40; // default: 40°N
var _observerLon = null; // estimated from timezone, or from stored location
/**
* Sun position using ephemeris if available, else simplified model.
*/
function sunPositionEph(hour, doy) {
if (_ephemeris && _ephemeris.sun) {
var lon = _observerLon != null ? _observerLon : estimateLongitude();
var lst = localSiderealTime(lon, hour, doy, _ephemeris.eqnOfTime);
return raDecToAltAz(_ephemeris.sun.ra, _ephemeris.sun.dec, _observerLat, lst);
}
return sunPosition(hour, doy);
}
/**
* Moon position using ephemeris if available, else simplified model.
*/
function moonPositionEph(hour, doy) {
if (_ephemeris && _ephemeris.moon) {
var lon = _observerLon != null ? _observerLon : estimateLongitude();
var lst = localSiderealTime(lon, hour, doy, _ephemeris.eqnOfTime);
var pos = raDecToAltAz(_ephemeris.moon.ra, _ephemeris.moon.dec, _observerLat, lst);
pos.age = (_ephemeris.moon.phase / 360) * SYNODIC_PERIOD;
return pos;
}
return moonPosition(hour, doy);
}
Step 3: Replace sunPosition/moonPosition calls in renderScene
In renderScene(), change:
var sun = sunPosition(hour, doy);
var moon = moonPosition(hour, doy);
to:
var sun = sunPositionEph(hour, doy);
var moon = moonPositionEph(hour, doy);
In drawArmillary(), the diurnal path still uses the simplified functions (they trace the full 24h path which needs per-hour data):
// Sun's diurnal path — use ephemeris-aware function
drawDiurnalPath(ctx, cx, cy, radius, viewRot, sunPositionEph, doy, ...);
// Moon's diurnal path
drawDiurnalPath(ctx, cx, cy, radius, viewRot, moonPositionEph, doy, ...);
Step 4: Initialise ephemeris and location in init()
Near the top of init(), after var currentDateStr = resolvePageDate();:
// Load embedded ephemeris (Tier 1)
_ephemeris = loadEmbeddedEphemeris();
// Estimate longitude from timezone
_observerLon = estimateLongitude();
// Check localStorage for stored location
try {
var stored = localStorage.getItem("almnck-location");
if (stored) {
var loc = JSON.parse(stored);
if (loc && typeof loc.lat === "number" && typeof loc.lon === "number") {
_observerLat = loc.lat;
_observerLon = loc.lon;
}
}
} catch (e) { /* ignore */ }
Step 5: Update moon phase class to use ephemeris phase
In loadCelestialImages(), when computing the fallback moon phase for the default image, use the ephemeris phase if available:
moonImg.onerror = function () {
moonImg.onerror = null;
var phase;
if (_ephemeris && _ephemeris.moon) {
// Use ephemeris phase angle (0=new, 180=full)
var age = (_ephemeris.moon.phase / 360) * SYNODIC_PERIOD;
phase = moonPhaseClass(age);
} else {
var doyVal = dayOfYear(dateStr);
var moon = moonPosition(12, doyVal);
phase = moonPhaseClass(moon.age);
}
moonImg.src = defaultPath + "moon-" + phase + ".png";
};
Step 6: Verify existing tests still pass
make test
Also manually check the dev server — the masthead should render identically (or more accurately, which may be subtly different on position but visually correct).
Step 7: Commit
git add assets/js/celestial.js
git commit -m "feat: celestial.js reads embedded JPL ephemeris (Tier 1)
Reads <script id=celestial-ephemeris> JSON, converts RA/Dec to alt/az
using observer latitude (default 40°N) and timezone-estimated longitude.
Includes equation of time correction. Falls back to simplified model
when no ephemeris data is present."
Task 5: Vendor Astronomy Engine and add lazy loader
Files:
- Create: assets/js/vendor/astronomy-engine.js
- Modify: assets/js/celestial.js — add lazy loader and Tier 2 recomputation
Step 1: Download Astronomy Engine
curl -o assets/js/vendor/astronomy-engine.js \
https://raw.githubusercontent.com/cosinekitty/astronomy/master/source/js/astronomy.browser.js
Verify it’s a valid JS file:
head -5 assets/js/vendor/astronomy-engine.js
wc -c assets/js/vendor/astronomy-engine.js
Expected: ~115KB, starts with a copyright comment.
Step 2: Add lazy loader to celestial.js
Add after the ephemeris section in celestial.js:
// ===== Astronomy Engine (Tier 2, on-demand) =====
var _astronomyEngine = null;
var _astronomyLoading = null;
function loadAstronomyEngine() {
if (_astronomyEngine) return Promise.resolve(_astronomyEngine);
if (_astronomyLoading) return _astronomyLoading;
_astronomyLoading = new Promise(function (resolve) {
var script = document.createElement("script");
// Cache-bust using content hash from ephemeris JSON or data attribute
var canvas = document.querySelector(".horizon-canvas");
var hash = canvas && canvas.getAttribute("data-astro-hash") || "";
script.src = "/static/js/vendor/astronomy-engine.js" + (hash ? "?" + hash : "");
script.onload = function () {
_astronomyEngine = window.Astronomy;
resolve(_astronomyEngine);
};
script.onerror = function () {
_astronomyLoading = null;
resolve(null); // degrade gracefully
};
document.head.appendChild(script);
});
return _astronomyLoading;
}
/**
* Compute sun/moon positions using Astronomy Engine (Tier 2).
* Returns {sun: {alt, az}, moon: {alt, az, age}} or null if engine unavailable.
*/
function computeWithEngine(dateStr, hour, lat, lon) {
if (!_astronomyEngine) return null;
var Astro = _astronomyEngine;
try {
var parts = dateStr.split("-");
var y = parseInt(parts[0], 10), mo = parseInt(parts[1], 10) - 1, d = parseInt(parts[2], 10);
var h = Math.floor(hour), m = Math.round((hour - h) * 60);
var date = new Date(Date.UTC(y, mo, d, h, m, 0));
var time = Astro.MakeTime(date);
var observer = new Astro.Observer(lat, lon, 0);
var sunHoriz = Astro.Horizon(time, observer, Astro.Body.Sun, "normal");
var moonHoriz = Astro.Horizon(time, observer, Astro.Body.Moon, "normal");
var moonIllum = Astro.Illumination(Astro.Body.Moon, time);
var age = (moonIllum.phase_angle / 360) * SYNODIC_PERIOD;
return {
sun: { alt: sunHoriz.altitude, az: sunHoriz.azimuth },
moon: { alt: moonHoriz.altitude, az: moonHoriz.azimuth, age: age }
};
} catch (e) {
return null;
}
}
Step 3: Integrate Tier 2 into position functions
Update sunPositionEph and moonPositionEph to prefer Astronomy Engine when available:
function sunPositionEph(hour, doy) {
if (_astronomyEngine && _observerLat !== 40) {
// Tier 2: full topocentric with refraction
var result = computeWithEngine(
window.__celestialDateStr || resolvePageDate(),
hour, _observerLat, _observerLon || estimateLongitude()
);
if (result) return result.sun;
}
if (_ephemeris && _ephemeris.sun) {
// Tier 1: embedded RA/Dec with local conversion
var lon = _observerLon != null ? _observerLon : estimateLongitude();
var lst = localSiderealTime(lon, hour, doy, _ephemeris.eqnOfTime);
return raDecToAltAz(_ephemeris.sun.ra, _ephemeris.sun.dec, _observerLat, lst);
}
// Fallback: simplified model
return sunPosition(hour, doy);
}
function moonPositionEph(hour, doy) {
if (_astronomyEngine && _observerLat !== 40) {
var result = computeWithEngine(
window.__celestialDateStr || resolvePageDate(),
hour, _observerLat, _observerLon || estimateLongitude()
);
if (result) return result.moon;
}
if (_ephemeris && _ephemeris.moon) {
var lon = _observerLon != null ? _observerLon : estimateLongitude();
var lst = localSiderealTime(lon, hour, doy, _ephemeris.eqnOfTime);
var pos = raDecToAltAz(_ephemeris.moon.ra, _ephemeris.moon.dec, _observerLat, lst);
pos.age = (_ephemeris.moon.phase / 360) * SYNODIC_PERIOD;
return pos;
}
return moonPosition(hour, doy);
}
Step 4: Add cache-bust hash to canvas element
In src/almnck/templates/base.html, modify the canvas element to include the hash. Add a templatetag call:
<canvas class="horizon-canvas" aria-hidden="true" data-astro-hash="{% cdnstatic_hash 'js/vendor/astronomy-engine.js' %}"></canvas>
Alternatively, since cdnstatic_hash doesn’t exist yet, embed the hash in the ephemeris JSON. In src/almnck/units/views.py, after computing ephemeris JSON, add the hash:
from almnck.units.views import _file_content_hash
if celestial_ephemeris:
astro_hash = _file_content_hash("/static/js/vendor/astronomy-engine.js")
celestial_ephemeris["astroEngineHash"] = astro_hash
Then in celestial.js, the loader reads it:
var hash = _ephemeris && _ephemeris.astroEngineHash || "";
script.src = "/static/js/vendor/astronomy-engine.js" + (hash ? "?tag=" + hash : "");
Step 5: Verify
make test
Step 6: Commit
git add assets/js/vendor/astronomy-engine.js assets/js/celestial.js \
src/almnck/units/views.py src/almnck/templates/base.html
git commit -m "feat: vendor Astronomy Engine, add Tier 2 lazy loader
Astronomy Engine (~115KB) vendored for on-demand topocentric computation.
Lazy-loaded only when a stored location exists. Includes atmospheric
refraction and lunar parallax. Cache-busted via content hash in
ephemeris JSON."
Task 6: Armillary location UI
Files:
- Modify: assets/js/celestial.js — add location prompt in armillary mode
Step 1: Add location UI to expand/collapse
In the updateMetaTime() function, extend it to show location status:
function formatLocation() {
var latDir = _observerLat >= 0 ? "N" : "S";
var lonDir = _observerLon >= 0 ? "E" : "W";
return Math.round(Math.abs(_observerLat)) + "\u00B0" + latDir +
", " + Math.round(Math.abs(_observerLon)) + "\u00B0" + lonDir;
}
function locationHasStored() {
try {
return !!localStorage.getItem("almnck-location");
} catch (e) { return false; }
}
function locationDenied() {
try {
return localStorage.getItem("almnck-location-denied") === "true";
} catch (e) { return false; }
}
function updateMetaTime() {
if (!metaLeft) return;
var day = dayNameFromDateStr(currentDateStr);
var time = formatHour(state.hour);
var locationLine = "";
if (locationHasStored()) {
locationLine = "Sky for " + formatLocation() +
' · <a href="#" class="location-update" style="color:rgba(184,137,46,0.7);text-decoration:none">\u2295 Update</a>';
} else if (!locationDenied()) {
locationLine = "Sky for 40\u00B0N" +
' · <a href="#" class="location-prompt" style="color:rgba(184,137,46,0.7);text-decoration:none">\u2295 Use my location</a>';
}
metaLeft.innerHTML = day + ", " + time +
(locationLine ? "<br><small>" + locationLine + "</small>" : "") +
"<br><small>" + MOD_KEY + "+drag for time</small>";
// Attach click handler for location link
var link = metaLeft.querySelector(".location-prompt, .location-update");
if (link) {
link.addEventListener("click", function (e) {
e.preventDefault();
requestGeolocation();
});
}
}
Step 2: Add geolocation request function
function requestGeolocation() {
if (!navigator.geolocation) return;
navigator.geolocation.getCurrentPosition(
function (pos) {
var loc = {
lat: pos.coords.latitude,
lon: pos.coords.longitude,
ts: Math.floor(Date.now() / 1000),
source: "geolocation"
};
try {
localStorage.setItem("almnck-location", JSON.stringify(loc));
localStorage.removeItem("almnck-location-denied");
} catch (e) { /* ignore */ }
_observerLat = loc.lat;
_observerLon = loc.lon;
// Immediate re-render with new lat (Tier 1)
doRender();
updateMetaTime();
// Load Astronomy Engine for Tier 2
loadAstronomyEngine().then(function (engine) {
if (engine) doRender();
});
},
function (err) {
// User denied or error
if (err.code === 1) { // PERMISSION_DENIED
try {
localStorage.setItem("almnck-location-denied", "true");
} catch (e) { /* ignore */ }
}
updateMetaTime();
},
{ enableHighAccuracy: false, timeout: 10000, maximumAge: 300000 }
);
}
Step 3: Add silent permission check on init
In init(), after the localStorage read:
// If we have a stored location and geolocation permission is granted,
// silently refresh the position
if (_observerLat !== 40 && navigator.permissions) {
navigator.permissions.query({ name: "geolocation" }).then(function (result) {
if (result.state === "granted") {
navigator.geolocation.getCurrentPosition(function (pos) {
var loc = {
lat: pos.coords.latitude,
lon: pos.coords.longitude,
ts: Math.floor(Date.now() / 1000),
source: "geolocation"
};
try {
localStorage.setItem("almnck-location", JSON.stringify(loc));
} catch (e) { /* ignore */ }
_observerLat = loc.lat;
_observerLon = loc.lon;
// Load Astronomy Engine and re-render
loadAstronomyEngine().then(function (engine) {
if (engine) doRender();
});
}, function () { /* ignore errors */ },
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 600000 });
}
}).catch(function () { /* permissions API not supported */ });
}
Step 4: Verify
make test
Test manually in browser: open armillary, verify “⊕ Use my location” appears.
Step 5: Commit
git add assets/js/celestial.js
git commit -m "feat: armillary location UI with geolocation prompt
Shows 'Use my location' in armillary meta-left when no location stored.
On grant: stores to localStorage, re-renders with new latitude, lazy-loads
Astronomy Engine. On deny: records denial, never prompts again.
Silent refresh when permission already granted."
Task 7: Regolith latitude bridge
Files:
- Modify: editorial/articles/regolith-with-latitude/assets/figures/latitude-picker.js
Step 1: Add localStorage write to latitude picker
In latitude-picker.js, in the setLatitude() function, after publish.latitude(latitude), add:
// Bridge to celestial masthead: store latitude for sky rendering
try {
var existing = localStorage.getItem('almnck-location');
var loc = existing ? JSON.parse(existing) : {};
loc.lat = latitude;
loc.source = 'manual';
loc.ts = Math.floor(Date.now() / 1000);
if (!loc.lon) loc.lon = -(new Date().getTimezoneOffset()) / 4;
localStorage.setItem('almnck-location', JSON.stringify(loc));
} catch (e) { /* ignore */ }
Step 2: Verify manually
Load the Regolith with Latitude article, drag the latitude picker, check localStorage.getItem('almnck-location') in the console.
Step 3: Commit
git add editorial/articles/regolith-with-latitude/assets/figures/latitude-picker.js
git commit -m "feat: latitude picker bridges to celestial masthead location
Dragging the Regolith latitude picker stores the latitude in
almnck-location localStorage, so the masthead sky adapts."
Task 8: Update documentation
Files:
- Modify: doc/website/06-celestial-sphere.md
- Modify: doc/setup.md (add ephemeris fetch step)
Step 1: Update celestial sphere documentation
In doc/website/06-celestial-sphere.md, update the “Astronomical Model” section. Replace “What Is Accurate”, “What Is Approximate”, and “What Is Not Modelled” with the new reality. Key changes:
- Sun and moon positions are now JPL-accurate (DE440s) when embedded data is present
- Location-awareness: reader’s latitude from geolocation or default 40°N
- Timezone-estimated longitude for equation of time
- Atmospheric refraction modelled when Astronomy Engine loaded
- Lunar parallax modelled when Astronomy Engine loaded
- Simplified model retained as fallback for BCE dates
Add a new “Geolocation” subsection documenting the localStorage schema, the three states (no location, stored, denied), and the silent refresh behaviour.
Update the file table to include ephemeris.py, astronomy-engine.js, and de440s.bsp.
Step 2: Update setup docs
In doc/setup.md, add after the virtualenv step:
### Fetch JPL Ephemeris
The celestial masthead uses JPL DE440s for accurate sun/moon positions:
make ephemeris-fetch
This downloads ~32MB to `assets/reference/de440s.bsp`. Only needed once.
Without it, the build uses simplified astronomical formulas instead.
Step 3: Commit
git add doc/website/06-celestial-sphere.md doc/setup.md
git commit -m "docs: update celestial sphere docs for JPL ephemeris
Document the two-tier architecture, geolocation flow, localStorage
schema, and Astronomy Engine integration. Add ephemeris fetch to
setup instructions."
Task 9: Browser tests for the full flow
Files:
- Modify: src/tests/test_celestial_animation.py — add ephemeris presence test
- Create: src/tests/test_celestial_location.py — geolocation UI tests
Step 1: Test ephemeris JSON presence in pages
Add to an existing test file or create new:
@pytest.mark.browser
class TestCelestialEphemeris:
"""Test that JPL ephemeris data is embedded in pages."""
def test_frontpage_has_ephemeris_json(self, page, dev_server_url):
page.goto(dev_server_url)
el = page.query_selector("#celestial-ephemeris")
assert el is not None, "Ephemeris JSON block not found in frontpage"
import json
data = json.loads(el.text_content())
assert "sun" in data
assert "moon" in data
assert "ra" in data["sun"]
def test_ephemeris_sun_altitude_plausible(self, page, dev_server_url):
"""Sun position from ephemeris should be in a plausible range."""
page.goto(dev_server_url)
# Set hour to noon and check sun position
page.evaluate("window.__celestialSetHour(12)")
sun = page.evaluate("window.__sunPosition")
# At noon on any date at 40°N, sun should be above horizon
assert sun["visible"] is True
Step 2: Test location prompt in armillary
@pytest.mark.browser
class TestCelestialLocation:
"""Test geolocation UI in armillary mode."""
def test_location_prompt_appears_in_armillary(self, page, dev_server_url):
"""When no location is stored, armillary should show location prompt."""
page.goto(dev_server_url)
page.evaluate("localStorage.removeItem('almnck-location')")
page.evaluate("localStorage.removeItem('almnck-location-denied')")
page.evaluate("window.__celestialSetHour(12)")
# Click the period to open armillary
page.click(".fp-period")
page.wait_for_timeout(500)
meta = page.query_selector(".meta-left")
assert meta is not None
text = meta.inner_text()
assert "Use my location" in text or "40°N" in text
def test_location_prompt_hidden_when_denied(self, page, dev_server_url):
"""When user has denied location, prompt should not appear."""
page.goto(dev_server_url)
page.evaluate("localStorage.setItem('almnck-location-denied', 'true')")
page.evaluate("localStorage.removeItem('almnck-location')")
page.reload()
page.evaluate("window.__celestialSetHour(12)")
page.click(".fp-period")
page.wait_for_timeout(500)
meta = page.query_selector(".meta-left")
text = meta.inner_text()
assert "Use my location" not in text
Step 3: Run tests
make test-browser
Step 4: Commit
git add src/tests/test_celestial_location.py src/tests/test_celestial_animation.py
git commit -m "test: browser tests for ephemeris embedding and location UI
Verify ephemeris JSON is present in pages, sun position is plausible,
location prompt appears/hides correctly in armillary mode."
Task 10: Final verification and build test
Step 1: Run full test suite
make test-all
Step 2: Build static site and verify
make sync && make build
Check a built page for the ephemeris block:
grep -l "celestial-ephemeris" web/*/index.html web/*/*/index.html 2>/dev/null | head -5
Step 3: Spot-check a page
grep "celestial-ephemeris" web/index.html | python -m json.tool
Verify the JSON contains plausible RA/Dec values.
Step 4: Final commit
git add -A
git status # review any uncommitted changes
git commit -m "chore: final integration verification for JPL ephemeris"
Summary of Commits
| # | Message | Key Files |
|---|---|---|
| 1 | deps: add skyfield, ephemeris fetch target | pyproject.toml, Makefile, .gitignore |
| 2 | feat: ephemeris module with skyfield/DE440s | ephemeris.py, test_ephemeris.py |
| 3 | feat: embed ephemeris JSON in HTML pages | views.py, base.html |
| 4 | feat: celestial.js reads embedded ephemeris | celestial.js |
| 5 | feat: vendor Astronomy Engine, Tier 2 loader | astronomy-engine.js, celestial.js |
| 6 | feat: armillary location UI with geolocation | celestial.js |
| 7 | feat: latitude picker bridges to masthead | latitude-picker.js |
| 8 | docs: update celestial sphere docs | 06-celestial-sphere.md, setup.md |
| 9 | test: browser tests for ephemeris and location | test_celestial_location.py |
| 10 | chore: final integration verification | — |