Manual
Almnck.
Price: 50ⓐ

JPL Ephemeris & Geolocation: Design Document

Author: CONSENSX
Date: 2026-02-18
Status: Draft


1. What We’re Building

Upgrade the Almanack’s celestial masthead from its current simplified astronomical model to JPL-accurate ephemeris data, with optional browser-based geolocation that adapts the sky to the reader’s actual position on the Earth’s surface.

The system is structured as two tiers of progressive enhancement:

Tier 1 — Build-time ephemeris (default, zero JS cost): At make build time, Python skyfield (reading JPL DE440s) pre-computes geocentric sun and moon positions for each page’s date and embeds them as JSON in the HTML. The existing celestial.js reads these values and converts them to alt/az using a default latitude (40°N). No additional JavaScript is loaded. Positions are accurate to ~1 arcminute — a real almanac, not a decoration.

Tier 2 — Location-aware (Astronomy Engine loaded on demand): If the reader has granted their location (stored in localStorage), the page lazy-loads the Astronomy Engine library (~115KB, ~35KB gzipped) and recomputes topocentric positions for the reader’s actual coordinates. The armillary mode provides a quiet invitation to share location. On subsequent visits, if geolocation permission is still granted, the position is silently refreshed.

What Changes for the Reader

  • Everyone: The sun and moon are now in their correct positions for the page’s date, computed from JPL ephemeris data. Moon phase is accurate to the hour. The equation of time is modelled (solar noon shifts through the year).
  • Readers who share their location: The sky adapts to their latitude. Someone in Buenos Aires sees the sun arc through the north. Someone in Tromsø sees the midnight sun in June. Rise and set times are correct to within ~2 minutes.
  • Readers who don’t: Everything works as before, but with more accurate celestial coordinates at the default 40°N latitude.

What Doesn’t Change

  • The rendering pipeline (renderScene(), canvas drawing, armillary rings, zodiac constellations) is untouched.
  • The interaction model (body click, period click, long-press, drag rotation, Cmd+drag time scrub) is unchanged.
  • The HTMX date navigation animation is unchanged.
  • The public window.__ API contracts are preserved.
  • Mobile behaviour (canvas hidden, zero JS cost) is unchanged.

2. Why

The current model is documented in doc/website/06-celestial-sphere.md as “simplified models (not an ephemeris).” It uses a fixed 40°N latitude, a simple cosine for solar declination, and a synodic offset model for the moon. It’s honest about its limits:

  • Moon position can be off by several degrees in altitude and azimuth.
  • Rise/set times can be 10–30 minutes off.
  • The equation of time is not modelled (solar noon is always 12:00).
  • The southern hemisphere is simply wrong (sun arcs through the south).
  • No atmospheric refraction.

An almanac should be a trustworthy guide to the shape of the year. The JPL ephemeris makes the masthead a real instrument — accurate enough to verify by looking outside. Browser geolocation makes it personal.

3. Architecture

3.1 Overview

BUILD TIME                          RUNTIME (browser)
──────────                          ─────────────────

skyfield + DE440s                   celestial.js reads
        │                           embedded JSON
        ▼                                  │
compute RA/Dec ──embed──▶ <script>  ──────▶ RA/Dec → alt/az
for each page's date     (JSON)            (40°N default)
                                                │
                                           ┌────▼────┐
                                           │ Render   │
                                           │ Scene    │
                                           └────▲────┘
                                                │
                         localStorage ──▶ lazy-load
                         has location?    astronomy-engine.js
                                                │
                                           topocentric
                                           alt/az for
                                           actual lat/lon

3.2 File Structure

New files:

File Role
src/almnck/ephemeris.py Python module: compute positions via skyfield
assets/reference/de440s.bsp JPL DE440s ephemeris (~32MB, gitignored)
assets/js/vendor/astronomy-engine.js Astronomy Engine browser build (~115KB)

Modified files:

File Change
src/almnck/views.py or context processor Inject ephemeris JSON into template context
src/almnck/templates/base.html Add <script id="celestial-ephemeris"> block
assets/js/celestial.js Read embedded data, localStorage check, lazy loader
pyproject.toml Add skyfield dependency
.gitignore Add assets/reference/*.bsp
Makefile Add ephemeris-fetch target

3.3 Build-time Computation

The ephemeris module: src/almnck/ephemeris.py

from skyfield.api import Loader
from skyfield import almanac

load = Loader('/path/to/assets/reference')
ts = load.timescale()
eph = load('de440s.bsp')

sun_body = eph['sun']
moon_body = eph['moon']
earth = eph['earth']

def compute(date_str):
    """
    Compute geocentric sun/moon positions for a date string.

    Returns dict suitable for JSON embedding:
    {
        "date": "2026-02-18",
        "sun": {"ra": 332.14, "dec": -11.52},
        "moon": {"ra": 87.31, "dec": 22.15,
                 "phase": 257.3, "illumination": 0.42},
        "eqnOfTime": -13.8
    }
    """
    parts = date_str.split('-')
    year, month, day = int(parts[0]), int(parts[1]), int(parts[2])
    t = ts.utc(year, month, day, 12)  # noon UTC

    # Sun
    sun_astrometric = earth.at(t).observe(sun_body)
    sun_apparent = sun_astrometric.apparent()
    sun_ra, sun_dec, _ = sun_apparent.radec()

    # Moon
    moon_astrometric = earth.at(t).observe(moon_body)
    moon_apparent = moon_astrometric.apparent()
    moon_ra, moon_dec, _ = moon_apparent.radec()

    # Moon phase angle (0° = new, 180° = full)
    phase_angle = almanac.moon_phase(eph, t).degrees

    # Moon illumination
    illumination = moon_illumination(phase_angle)

    # Equation of time (minutes)
    eqn = equation_of_time(sun_ra, t)

    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, 1),
    }

DE440s ephemeris file

The DE440s file (~32MB) covers 1849–2150 CE, which spans all our published articles except extreme historical dates (“The First Assembly” at 4000 BCE).

  • Stored at assets/reference/de440s.bsp
  • Gitignored (too large for the repo)
  • Downloaded once via make ephemeris-fetch: makefile ephemeris-fetch: curl -o assets/reference/de440s.bsp \ https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de440s.bsp
  • Setup documented in doc/setup.md

Date range handling

Date range Source Notes
1849–2150 CE DE440s via skyfield Full JPL accuracy
Outside range No embedded data JS falls back to simplified model

The fallback is graceful — if the <script id="celestial-ephemeris"> block is missing or empty, celestial.js uses its existing sunPosition() and moonPosition() functions unchanged. The masthead is decorative enough that approximate positions for ancient dates are fine.

Template integration

The ephemeris data is injected in the Django template context. When django-distill renders each page, the view (or a context processor) calls ephemeris.compute(almanac_day) if the date is within range.

In base.html:

{% if celestial_ephemeris %}
<script id="celestial-ephemeris" type="application/json">
{{ celestial_ephemeris|safe }}
</script>
{% endif %}

The computation is cached per date — multiple pages with the same almanac_day don’t recompute. With ~10 articles, build-time cost is negligible (skyfield computes a position in <1ms).

3.4 Client-side: Tier 1 (Embedded Ephemeris)

On page load, celestial.js reads the embedded data:

function loadEmbeddedEphemeris() {
    var el = document.getElementById('celestial-ephemeris');
    if (!el) return null;
    try { return JSON.parse(el.textContent); }
    catch (e) { return null; }
}

If present, the embedded RA/Dec replaces the simplified model for the page’s date. The conversion from RA/Dec to alt/az is a lightweight function (~15 lines of trig) that stays in celestial.js:

/**
 * 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 };
}

The local sidereal time (LST) is computed from the clock hour plus the equation of time (supplied in the embedded JSON). This is the same formula the existing code uses implicitly, but now corrected for the equation of time — solar noon will shift through the year as it does in reality.

Time scrubbing: During Cmd+drag time scrub, the embedded RA/Dec remains valid. The sun’s RA changes ~1° per day, so over a 24-hour scrub the error is <1°. The moon shifts ~13°/day (0.5°/hour), which is noticeable over a full day but acceptable for scrubbing. Only when Astronomy Engine is loaded (Tier 2) do we recompute RA/Dec per-hour.

The simplified model is preserved as a fallback:

  • Pages outside the DE440s range (BCE, far future)
  • If the JSON block is missing for any reason
  • Demo/test pages without editorial dates

3.5 Client-side: Tier 2 (Location-aware)

localStorage schema

// Key: 'almnck-location'
// Value: JSON string
{
    "lat": 51.5,          // degrees, positive = north
    "lon": -0.12,         // degrees, positive = east
    "ts": 1708300000,     // Unix timestamp (seconds) when obtained
    "source": "geolocation"  // or "manual" (future)
}

// Key: 'almnck-location-denied'
// Value: "true"
// Set when user explicitly denies the geolocation prompt.
// Prevents re-prompting on every armillary open.

Boot sequence

On page load, after the Tier 1 embedded data is read:

1. location = localStorage.getItem('almnck-location')
2. if location exists:
   a. Parse lat/lon
   b. Re-render Tier 1 with stored lat/lon (still no library load —
      just change the latitude parameter in raDecToAltAz)
   c. Check navigator.permissions.query({name: 'geolocation'})
   d. If 'granted': silently getCurrentPosition(), update stored
      location, lazy-load Astronomy Engine, recompute, re-render
   e. If 'prompt' or 'denied': use stored values, don't ask
3. if no location:
   a. Render with default 40°N
   b. (Location prompt appears only when armillary is opened)

Note step 2b: even before loading Astronomy Engine, we can immediately improve the display by using the stored latitude with the embedded RA/Dec. The latitude correction is pure trig — no library needed. This means a returning reader in Melbourne sees the sun in the north within milliseconds of page load, before the ~115KB library even starts downloading.

Lazy loading Astronomy Engine

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');
        script.src = '/static/js/vendor/astronomy-engine.js?' + ASTRO_HASH;
        script.onload = function() {
            _astronomyEngine = window.Astronomy;
            resolve(_astronomyEngine);
        };
        script.onerror = function() {
            // Degrade gracefully — Tier 1 continues working
            _astronomyLoading = null;
            resolve(null);
        };
        document.head.appendChild(script);
    });
    return _astronomyLoading;
}

ASTRO_HASH is a content hash of astronomy-engine.js, embedded in celestial.js at build time (or via a data attribute on the canvas element) for cache-busting per the project’s static asset policy.

Once loaded

Astronomy Engine provides Astronomy.Horizon() for topocentric alt/az with atmospheric refraction:

function computeWithEngine(astro, date, hour, lat, lon) {
    var observer = new astro.Observer(lat, lon, 0);
    var d = new Date(date + 'T' + hourToISO(hour) + 'Z');
    var time = astro.MakeTime(d);

    var sun = astro.Horizon(time, observer, 0, 0, 'normal');
    // Computes from full VSOP87 + topocentric correction + refraction

    var moon = astro.Horizon(time, observer, 0, 0, 'normal');
    // Includes lunar parallax (~1°) — significant for horizon accuracy

    var moonIllum = astro.Illumination(astro.Body.Moon, time);

    return {
        sun: { alt: sun.altitude, az: sun.azimuth },
        moon: { alt: moon.altitude, az: moon.azimuth,
                illumination: moonIllum.phase_fraction }
    };
}

The 'normal' refraction parameter means bodies near the horizon are shifted upward by ~0.5° — matching what the reader actually sees. This is the first time the masthead will model refraction.

Time scrubbing with Astronomy Engine: When loaded, Cmd+drag recomputes positions per-hour using the library, giving smooth, accurate movement across the full day. The library is fast enough (~0.1ms per position) that this doesn’t affect frame rate.

3.6 Armillary Location UI

The location prompt appears inside the armillary’s existing .meta-left area, styled in the saffron armillary palette. It does not appear in ambient mode — only during armillary interaction.

States

No location stored, no denial recorded:

Wednesday, 1:00 PM
Sky for 40°N · ⊕ Use my location
⌘+drag for time

Location stored:

Wednesday, 1:00 PM
Sky for 51°N, 0°W · ⊕ Update
⌘+drag for time

Location denied:

Wednesday, 1:00 PM
⌘+drag for time

No “Use my location” link is shown. We don’t nag.

Interaction flow

  1. Reader clicks “⊕ Use my location”
  2. Browser geolocation prompt fires
  3. On success:
  4. Store {lat, lon, ts, source: "geolocation"} to localStorage
  5. Re-render immediately with new latitude (Tier 1 trig)
  6. Lazy-load Astronomy Engine in background
  7. On library load: recompute with full topocentric accuracy, re-render
  8. Update meta-left to show actual coordinates
  9. On denial:
  10. Set localStorage['almnck-location-denied'] = 'true'
  11. Hide the prompt
  12. Continue with default 40°N

Coordinate display format

Whole degrees, compass directions. Almanac-style:

  • 51°N, 0°W (London)
  • 34°S, 151°E (Sydney)
  • 40°N, 74°W (New York)

Styling

The “⊕ Use my location” link uses the armillary saffron colour (rgba(184, 137, 46, 0.6)) with a subtle hover brightening. The ⊕ glyph evokes a geodetic survey mark — appropriate for an instrument that’s asking to know where you stand.

3.7 Regolith Latitude Bridge (Future)

The Regolith with Latitude article’s latitude picker (latitude-picker.js) currently communicates via a figure-internal pub/sub system. A future enhancement could have it write to almnck-location in localStorage when the reader drags the latitude, creating a quiet bridge between the article content and the masthead instrument. This is out of scope for this design but noted as a natural extension.

3.8 Cache-busting

Per the project’s static asset caching policy (Cache-Control: max-age= 31536000, immutable), all references to static assets must be cache-busted.

  • astronomy-engine.js is loaded dynamically, so {% cdnstatic %} can’t be used directly. Instead, the content hash is embedded in the page at build time — either as a data attribute on the canvas element or in the ephemeris JSON block: json {"astroEngineHash": "a3f8c2..."}
  • celestial.js itself is referenced via {% cdnstatic %} in templates and auto-hashed in article markdown, as before.

3.9 Privacy

  • No location data is ever sent to any server. All computation happens in the browser.
  • Location is stored only in localStorage — cleared when the reader clears browser data.
  • The geolocation prompt is shown only on explicit user action (clicking “Use my location” in the armillary).
  • Silent re-grab only happens when the browser’s permission state is already 'granted' — we never trigger a prompt without user initiation.
  • No analytics, no tracking, no fingerprinting. The location exists solely to show the reader their sky.

3.10 Mobile

The canvas is hidden on mobile (display: none !important below 640px), and init() exits early. None of this feature’s code executes on mobile. No Astronomy Engine download, no geolocation prompt, no localStorage reads. Zero cost.

When mobile support is eventually added, the same architecture applies — the embedded ephemeris data is in the HTML regardless of viewport size, ready for whenever the mobile celestial display is implemented.

4. Data Flow Summary

┌──────────────────────────────────────────────────────────────┐
│                        BUILD TIME                            │
│                                                              │
│  skyfield + DE440s ──▶ ephemeris.compute(date)               │
│                              │                               │
│                    {sun: {ra, dec}, moon: {ra, dec, phase,   │
│                     illumination}, eqnOfTime}                │
│                              │                               │
│                    embed as <script type="application/json"> │
└──────────────────────┬───────────────────────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────────────────────┐
│                     RUNTIME: TIER 1                          │
│                                                              │
│  celestial.js reads JSON ──▶ raDecToAltAz(ra, dec, 40°N)    │
│                                        │                     │
│                         ┌──────────────┘                     │
│                         ▼                                    │
│  localStorage has lat/lon? ──yes──▶ raDecToAltAz(ra, dec,    │
│         │                           stored lat)              │
│         no                          (still no library!)      │
│         │                                    │               │
│         ▼                                    ▼               │
│    render with 40°N              render with stored lat      │
└──────────────────────────────────────────────────────────────┘
                       │
            (if location stored + permission granted)
                       ▼
┌──────────────────────────────────────────────────────────────┐
│                     RUNTIME: TIER 2                          │
│                                                              │
│  lazy-load astronomy-engine.js (~115KB)                      │
│         │                                                    │
│         ▼                                                    │
│  Astronomy.Horizon(date, observer, ...) ──▶ topocentric      │
│  + atmospheric refraction                   alt/az           │
│  + lunar parallax                              │             │
│  + full VSOP87 solar model                     ▼             │
│                                          re-render with      │
│                                          JPL-grade accuracy  │
└──────────────────────────────────────────────────────────────┘

5. Dependencies

Dependency Where Size Licence
skyfield Python (build time) pip install MIT
de440s.bsp assets/reference/ ~32MB Public domain (NASA)
astronomy-engine assets/js/vendor/ ~115KB (~35KB gz) MIT

skyfield pulls in jplephem, sgp4, and numpy as transitive dependencies. These are build-time only — they don’t affect the static site or the reader’s browser.

6. Testing

Unit tests (Python)

  • test_ephemeris.py: Test that ephemeris.compute() returns sane values for known dates (e.g. summer solstice sun at dec +23.4°, winter at -23.4°, known full moon dates).
  • Test fallback: dates outside DE440s range return None.
  • Test caching: same date returns same result without recomputation.

Unit tests (JS)

  • Test raDecToAltAz() against known values.
  • Test embedded JSON parsing (present, missing, malformed).
  • Test localStorage read/write for location.

Browser tests (Playwright)

  • Test that embedded ephemeris JSON is present in built pages.
  • Test that window.__sunPosition reflects ephemeris data (not just the simplified model) — compare against known noon altitude for page date.
  • Test location prompt appears in armillary mode when no location stored.
  • Test location prompt does not appear when almnck-location-denied set.
  • Test that after mocking navigator.geolocation, positions update.

Regression

  • All existing test_celestial_animation.py and test_celestial_interaction.py tests must continue to pass unchanged. The rendering pipeline is untouched; only the input data changes.

7. Implementation Order

  1. Add skyfield dependency and ephemeris fetch target.
  2. Write ephemeris.py with compute() function and unit tests.
  3. Inject ephemeris JSON into template context and base.html.
  4. Modify celestial.js to read embedded data and use raDecToAltAz(). Verify existing tests still pass.
  5. Add localStorage location support (read stored lat, apply to Tier 1).
  6. Vendor astronomy-engine.js and add lazy loader.
  7. Add armillary location UI (⊕ prompt, geolocation flow, denial handling).
  8. Add Tier 2 recomputation (load library, topocentric positions).
  9. Update doc/website/06-celestial-sphere.md — the “What Is Accurate” section gets much longer, “What Is Not Modelled” gets much shorter.
  10. Browser tests for the full flow.

8. Resolved Questions

  1. Ephemeris file location: assets/reference/de440s.bsp — reference data alongside the project’s other reference assets.

  2. What to embed: Geocentric RA/Dec at noon UTC, plus moon phase, illumination, and equation of time. A small set of numbers (~200 bytes) that the JS converts to alt/az using the observer’s latitude and local clock time.

  3. Time scrubbing accuracy: The embedded noon RA/Dec is valid for scrubbing across a single day. The sun moves <1°/day; the moon moves ~13°/day (0.5°/hour). Acceptable for Tier 1. Tier 2 recomputes per-hour.

  4. Tier 3 (active tracking) dropped: Grabbing location once and storing it is sufficient. If geolocation permission is already 'granted', we silently refresh on each visit. No watchPosition() needed.

  5. Accuracy target: Almanac-grade — positions within ~0.5° (30 arcminutes), rise/set times within ~2 minutes for the reader’s location. Correct enough to verify by looking outside.

  6. Southern hemisphere: Fully supported once a location is provided. The sun arcs through the north, seasons are reversed, moon libration is correct. A reader in Sydney sees their sky, not New York’s.

9. Resolved (Post-Design)

  1. Longitude for Tier 1: Use the browser’s timezone offset as a longitude proxy (new Date().getTimezoneOffset() * -0.25 gives degrees east). This is free, requires no permissions, and improves the equation of time correction meaningfully. Resolved: yes.

  2. Regolith bridge: Include in initial implementation. One localStorage.setItem call in latitude-picker.js when the reader drags the latitude. Resolved: yes, do it now.


This document describes the design only. Implementation plan to follow.