In this section
- Wmm2025 transform · gridatlas / tools/satnav/orientation/wmm2025.mjs lines 1–222
- Wmm2025 Test test · gridatlas / tools/satnav/orientation/wmm2025.test.mjs lines 1–157
- Bristol Browser render · gridatlas / tools/satnav/pedestrian-pilot/bristol-browser.py lines 1–104
- Bristol render · gridatlas / tools/satnav/pedestrian-pilot/bristol.mjs lines 1–165
Wmm2025
A JavaScript module in the orientation folder of GridAtlas that works with decimal year (`decimalYear`) and evaluate field (`evaluateField`) and calculates great-circle distances and planar distances, using SHA-256.
transformgridatlas / tools/satnav/orientation/wmm2025.mjs · lines 1–222 of 222 · Not reached from any entry point (candidate for review)
- What it does
- It calculates its inputs. Defines 9 functions or classes, including index, decimalYear, check, evaluateField, declinationSigmaDeg.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 4 files: Orient17a Reference Wmm (gridatlas); Orient17a V9211 Heading (gridatlas); Orient17a V9212 Heading (gridatlas); Wmm2025 Test (gridatlas).
- What it achieves
- It is built from the index step (`index`), the decimal year helper (`decimalYear`) and the check step (`check`). ORIENT-17A support: World Magnetic Model 2025 (WMM2025) declination evaluator.
- Why it matters
- Imported by Orient17a Reference Wmm, Orient17a V9211 Heading and Orient17a V9212 Heading. Checked by Wmm2025 Test.
- Application
- gridatlas · tools/satnav/orientation · JavaScript module
- Uses
- none found
- Used by
- imported by Orient17a Reference Wmm (import), imported by Orient17a V9211 Heading (import), imported by Orient17a V9212 Heading (import), imported by Wmm2025 Test (import)
- Produces
- WMM2025, WMM2025_COEFFICIENTS, decimalYear, evaluateField, declinationSigmaDeg, declination, magneticToTrue
- Defines here
- index, decimalYear, check, evaluateField, declinationSigmaDeg, declination, normalise, magneticToTrue, fail
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/orientation/wmm2025.mjs:1-222 · blob c29e0dd59b9ab47f0d4d3733af66d30a6dfa21ca · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// SPDX-License-Identifier: Apache-2.0
// ORIENT-17A support: World Magnetic Model 2025 (WMM2025) declination evaluator.
//
// Dependency-free, offline, no network and no location leaves the device.
// Coefficients: NOAA NCEI / BGS WMM2025.COF, header "2025.0 WMM-2025 11/13/2024",
// SHA-256 dfa8597825af4e0b87ff4198a5b4fb661b3c49f4cd090cd0164e0259b075582f.
// The WMM coefficients and source are U.S. Government work in the public domain
// (NCEI: "not licensed or under copyright"). Cite: Chulliat et al. (2025), The
// US/UK World Magnetic Model for 2025-2030: Technical Report, NOAA NCEI,
// https://doi.org/10.25923/prbc-s316. Equations follow report section 1.2.
// Error model (report eq. 43): sigmaD = sqrt(0.26^2 + (5417 / H)^2) degrees, 1 sigma.
// Blackout zone H < 2000 nT (declination unreliable); caution zone 2000 <= H < 6000 nT.
export const WMM2025 = Object.freeze({
model: 'WMM-2025',
epoch: 2025.0,
releaseDate: '2024-11-13',
validFrom: 2025.0,
validUntil: 2030.0, // exclusive: NCEI states validity through 31 December 2029
minAltitudeKm: -1,
maxAltitudeKm: 850,
cofSha256: 'dfa8597825af4e0b87ff4198a5b4fb661b3c49f4cd090cd0164e0259b075582f',
errorModel: Object.freeze({ declinationFloorDeg: 0.26, declinationHScaleNt: 5417 }),
blackoutHNt: 2000,
cautionHNt: 6000,
});
// [n, m, g, h, gDot, hDot] in nT and nT/year, exactly as WMM2025.COF.
export const WMM2025_COEFFICIENTS = Object.freeze([
[1,0,-29351.8,0,12,0],[1,1,-1410.8,4545.4,9.7,-21.5],[2,0,-2556.6,0,-11.6,0],[2,1,2951.1,-3133.6,-5.2,-27.7],[2,2,1649.3,-815.1,-8,-12.1],[3,0,1361,0,-1.3,0],
[3,1,-2404.1,-56.6,-4.2,4],[3,2,1243.8,237.5,0.4,-0.3],[3,3,453.6,-549.5,-15.6,-4.1],[4,0,895,0,-1.6,0],[4,1,799.5,278.6,-2.4,-1.1],[4,2,55.7,-133.9,-6,4.1],
[4,3,-281.1,212,5.6,1.6],[4,4,12.1,-375.6,-7,-4.4],[5,0,-233.2,0,0.6,0],[5,1,368.9,45.4,1.4,-0.5],[5,2,187.2,220.2,0,2.2],[5,3,-138.7,-122.9,0.6,0.4],
[5,4,-142,43,2.2,1.7],[5,5,20.9,106.1,0.9,1.9],[6,0,64.4,0,-0.2,0],[6,1,63.8,-18.4,-0.4,0.3],[6,2,76.9,16.8,0.9,-1.6],[6,3,-115.7,48.8,1.2,-0.4],
[6,4,-40.9,-59.8,-0.9,0.9],[6,5,14.9,10.9,0.3,0.7],[6,6,-60.7,72.7,0.9,0.9],[7,0,79.5,0,-0,0],[7,1,-77,-48.9,-0.1,0.6],[7,2,-8.8,-14.4,-0.1,0.5],
[7,3,59.3,-1,0.5,-0.8],[7,4,15.8,23.4,-0.1,0],[7,5,2.5,-7.4,-0.8,-1],[7,6,-11.1,-25.1,-0.8,0.6],[7,7,14.2,-2.3,0.8,-0.2],[8,0,23.2,0,-0.1,0],
[8,1,10.8,7.1,0.2,-0.2],[8,2,-17.5,-12.6,0,0.5],[8,3,2,11.4,0.5,-0.4],[8,4,-21.7,-9.7,-0.1,0.4],[8,5,16.9,12.7,0.3,-0.5],[8,6,15,0.7,0.2,-0.6],
[8,7,-16.8,-5.2,-0,0.3],[8,8,0.9,3.9,0.2,0.2],[9,0,4.6,0,-0,0],[9,1,7.8,-24.8,-0.1,-0.3],[9,2,3,12.2,0.1,0.3],[9,3,-0.2,8.3,0.3,-0.3],
[9,4,-2.5,-3.3,-0.3,0.3],[9,5,-13.1,-5.2,0,0.2],[9,6,2.4,7.2,0.3,-0.1],[9,7,8.6,-0.6,-0.1,-0.2],[9,8,-8.7,0.8,0.1,0.4],[9,9,-12.9,10,-0.1,0.1],
[10,0,-1.3,0,0.1,0],[10,1,-6.4,3.3,0,0],[10,2,0.2,0,0.1,-0],[10,3,2,2.4,0.1,-0.2],[10,4,-1,5.3,-0,0.1],[10,5,-0.6,-9.1,-0.3,-0.1],
[10,6,-0.9,0.4,0,0.1],[10,7,1.5,-4.2,-0.1,0],[10,8,0.9,-3.8,-0.1,-0.1],[10,9,-2.7,0.9,-0,0.2],[10,10,-3.9,-9.1,-0,-0],[11,0,2.9,0,0,0],
[11,1,-1.5,0,-0,-0],[11,2,-2.5,2.9,0,0.1],[11,3,2.4,-0.6,0,-0],[11,4,-0.6,0.2,0,0.1],[11,5,-0.1,0.5,-0.1,-0],[11,6,-0.6,-0.3,0,-0],
[11,7,-0.1,-1.2,-0,0.1],[11,8,1.1,-1.7,-0.1,-0],[11,9,-1,-2.9,-0.1,0],[11,10,-0.2,-1.8,-0.1,0],[11,11,2.6,-2.3,-0.1,0],[12,0,-2,0,0,0],
[12,1,-0.2,-1.3,0,-0],[12,2,0.3,0.7,-0,0],[12,3,1.2,1,-0,-0.1],[12,4,-1.3,-1.4,-0,0.1],[12,5,0.6,-0,-0,-0],[12,6,0.6,0.6,0.1,-0],
[12,7,0.5,-0.1,-0,-0],[12,8,-0.1,0.8,0,0],[12,9,-0.4,0.1,0,-0],[12,10,-0.2,-1,-0.1,-0],[12,11,-1.3,0.1,-0,0],[12,12,-0.7,0.2,-0.1,-0.1],
].map(Object.freeze));
const NMAX = 12;
const RAD = Math.PI / 180;
const A_WGS84 = 6378.137; // km
const F_WGS84 = 1 / 298.257223563;
const E2 = F_WGS84 * (2 - F_WGS84);
const R_REF = 6371.2; // geomagnetic reference radius, km
const index = (n, m) => n * (n + 1) / 2 + m;
const G = new Float64Array(index(NMAX, NMAX) + 1);
const H = new Float64Array(G.length);
const GD = new Float64Array(G.length);
const HD = new Float64Array(G.length);
for (const [n, m, g, h, gd, hd] of WMM2025_COEFFICIENTS) {
const i = index(n, m);
G[i] = g; H[i] = h; GD[i] = gd; HD[i] = hd;
}
/** Decimal year from a Date or epoch milliseconds (UTC, leap-year aware). */
export function decimalYear(date) {
const ms = date instanceof Date ? date.getTime() : date;
if (!Number.isFinite(ms)) return NaN;
const y = new Date(ms).getUTCFullYear();
const start = Date.UTC(y, 0, 1), end = Date.UTC(y + 1, 0, 1);
return y + (ms - start) / (end - start);
}
function check({ latitude, longitude, altitudeKm, year }) {
if (![latitude, longitude, altitudeKm, year].every(Number.isFinite)) return 'Non-finite input';
if (Math.abs(latitude) > 90 || Math.abs(longitude) > 360) return 'Latitude or longitude out of range';
if (Math.abs(latitude) > 89.9999) return 'Geographic pole: declination undefined';
if (altitudeKm < WMM2025.minAltitudeKm || altitudeKm > WMM2025.maxAltitudeKm) return 'Altitude outside WMM range -1 to 850 km';
if (year < WMM2025.validFrom || year >= WMM2025.validUntil) return 'Date outside WMM2025 validity 2025.0 to 2030.0';
return null;
}
/**
* Full WMM2025 main-field and secular-variation evaluation.
* Inputs: geodetic latitude/longitude (deg, WGS84), altitude above the
* ellipsoid in km, decimal year. Returns null-valued fields with a reason
* when the input is outside the model's validity.
*/
export function evaluateField({ latitude, longitude, altitudeKm = 0, year }) {
const reason = check({ latitude, longitude, altitudeKm, year });
if (reason) return { ok: false, reason };
const phi = latitude * RAD, lambda = longitude * RAD;
const sinPhi = Math.sin(phi), cosPhi = Math.cos(phi);
const rc = A_WGS84 / Math.sqrt(1 - E2 * sinPhi * sinPhi);
const p = (rc + altitudeKm) * cosPhi;
const z = (rc * (1 - E2) + altitudeKm) * sinPhi;
const r = Math.hypot(p, z);
const phiC = Math.asin(z / r);
const cosT = Math.sin(phiC), sinT = Math.cos(phiC); // theta = colatitude
const dt = year - WMM2025.epoch;
// Schmidt semi-normalised associated Legendre functions and d/dtheta.
const P = new Float64Array(G.length), dP = new Float64Array(G.length);
P[0] = 1; dP[0] = 0;
for (let n = 1; n <= NMAX; n++) {
for (let m = 0; m <= n; m++) {
const i = index(n, m);
if (n === m) {
if (n === 1) { P[i] = sinT; dP[i] = cosT; continue; }
const k = Math.sqrt((2 * n - 1) / (2 * n)), j = index(n - 1, n - 1);
P[i] = k * sinT * P[j];
dP[i] = k * (cosT * P[j] + sinT * dP[j]);
} else {
const j1 = index(n - 1, m);
const k1 = (2 * n - 1) / Math.sqrt(n * n - m * m);
P[i] = k1 * cosT * P[j1];
dP[i] = k1 * (cosT * dP[j1] - sinT * P[j1]);
if (n - 2 >= m) {
const j2 = index(n - 2, m);
const k2 = Math.sqrt(((n - 1) * (n - 1) - m * m) / (n * n - m * m));
P[i] -= k2 * P[j2];
dP[i] -= k2 * dP[j2];
}
}
}
}
let xs = 0, ys = 0, zs = 0, xsd = 0, ysd = 0, zsd = 0;
for (let n = 1; n <= NMAX; n++) {
const ratio = Math.pow(R_REF / r, n + 2);
for (let m = 0; m <= n; m++) {
const i = index(n, m);
const cm = Math.cos(m * lambda), sm = Math.sin(m * lambda);
const g = G[i] + dt * GD[i], h = H[i] + dt * HD[i];
const a = g * cm + h * sm, ad = GD[i] * cm + HD[i] * sm;
const b = m * (g * sm - h * cm), bd = m * (GD[i] * sm - HD[i] * cm);
xs += ratio * a * dP[i]; xsd += ratio * ad * dP[i];
ys += ratio * b * P[i]; ysd += ratio * bd * P[i];
zs -= (n + 1) * ratio * a * P[i]; zsd -= (n + 1) * ratio * ad * P[i];
}
}
ys /= sinT; ysd /= sinT;
// Rotate from geocentric spherical to geodetic (ellipsoidal) frame.
const psi = phiC - phi, cp = Math.cos(psi), sp = Math.sin(psi);
const X = xs * cp - zs * sp, Y = ys, Z = xs * sp + zs * cp;
const Xd = xsd * cp - zsd * sp, Yd = ysd, Zd = xsd * sp + zsd * cp;
const Hh = Math.hypot(X, Y), F = Math.hypot(Hh, Z);
const D = Math.atan2(Y, X) / RAD, I = Math.atan2(Z, Hh) / RAD;
const Hd = (X * Xd + Y * Yd) / Hh;
const Fd = (X * Xd + Y * Yd + Z * Zd) / F;
const Dd = (X * Yd - Y * Xd) / (Hh * Hh) / RAD;
const Id = (Hh * Zd - Z * Hd) / (F * F) / RAD;
return { ok: true, reason: null, x: X, y: Y, z: Z, h: Hh, f: F,
declinationDeg: D, inclinationDeg: I,
xDot: Xd, yDot: Yd, zDot: Zd, hDot: Hd, fDot: Fd,
declinationDotDegPerYear: Dd, inclinationDotDegPerYear: Id };
}
/** One-sigma WMM2025 declination uncertainty (degrees) for horizontal intensity hNt. */
export function declinationSigmaDeg(hNt) {
const { declinationFloorDeg: a, declinationHScaleNt: b } = WMM2025.errorModel;
return Number.isFinite(hNt) && hNt > 0 ? Math.sqrt(a * a + (b / hNt) ** 2) : Infinity;
}
/**
* Declination with explicit uncertainty and compass-zone classification.
* `when` may be a Date, epoch ms, or { year } decimal year.
* ok=false in the blackout zone, outside validity, or on invalid input.
*/
export function declination({ latitude, longitude, altitudeKm = 0, when = Date.now() }) {
const year = typeof when === 'object' && when !== null && !(when instanceof Date) ? when.year : decimalYear(when);
const field = evaluateField({ latitude, longitude, altitudeKm: altitudeKm ?? 0, year });
const base = { model: WMM2025.model, year, declinationDeg: null, sigmaDeg: null, zone: null, hNt: null, expectedFieldNt: null };
if (!field.ok) return { ...base, ok: false, reason: field.reason };
const zone = field.h < WMM2025.blackoutHNt ? 'blackout' : field.h < WMM2025.cautionHNt ? 'caution' : 'normal';
const out = { ...base, declinationDeg: field.declinationDeg, sigmaDeg: declinationSigmaDeg(field.h), zone,
hNt: field.h, expectedFieldNt: field.f, inclinationDeg: field.inclinationDeg };
if (zone === 'blackout') return { ...out, ok: false, reason: 'Magnetic blackout zone (H < 2000 nT): compass and declination unreliable' };
return { ...out, ok: true, reason: null };
}
const normalise = d => (d % 360 + 360) % 360;
/**
* Convert a magnetic heading to the true-north heading object expected by
* orient17a-navigation.relativeGuidance(): { reference:'true', degrees,
* accuracyDeg, timestampMs, disturbed }.
*
* heading: { reference, degrees, accuracyDeg, timestampMs, disturbed }
* reference 'true' passes through unchanged; 'magnetic' is corrected;
* 'sensor' (W3C absolute orientation) is corrected ONLY when
* options.sensorIsMagnetic === true, because the W3C specification does not
* say whether its earth frame is magnetic or true north.
* position: { latitude, longitude, altitudeKm? } (WGS84; never transmitted)
* options.sigmaMultiplier: declination sigma multiple added linearly to the
* heading accuracy (default 2, about 95 per cent), matching the linear
* uncertainty sum used by relativeGuidance().
* Returns { heading, declination, reason }; heading is null when unsafe.
*/
export function magneticToTrue(heading, position, { when = heading?.timestampMs ?? Date.now(), sigmaMultiplier = 2, sensorIsMagnetic = false } = {}) {
const fail = (reason, d = null) => ({ heading: null, declination: d, reason });
if (!heading || !Number.isFinite(heading.degrees) || heading.degrees < 0 || heading.degrees > 360) return fail('Heading missing or invalid');
if (heading.reference === 'true') return { heading, declination: null, reason: null };
const magnetic = heading.reference === 'magnetic' || (heading.reference === 'sensor' && sensorIsMagnetic === true);
if (!magnetic) return fail(`Heading reference "${heading.reference}" not known to be magnetic north`);
if (!Number.isFinite(heading.accuracyDeg) || heading.accuracyDeg < 0) return fail('Heading accuracy unknown');
if (!Number.isFinite(sigmaMultiplier) || sigmaMultiplier < 0) return fail('Invalid sigma multiplier');
const d = declination({ latitude: position?.latitude, longitude: position?.longitude, altitudeKm: position?.altitudeKm ?? 0, when });
if (!d.ok) return fail(d.reason, d);
return {
heading: {
reference: 'true',
degrees: normalise(heading.degrees + d.declinationDeg),
accuracyDeg: heading.accuracyDeg + sigmaMultiplier * d.sigmaDeg,
timestampMs: heading.timestampMs,
disturbed: heading.disturbed === true,
source: { from: heading.reference, model: d.model, declinationDeg: d.declinationDeg, sigmaDeg: d.sigmaDeg, zone: d.zone },
},
declination: d,
reason: null,
};
}Wmm2025 Test
A test in the orientation folder of GridAtlas that checks Wmm2025 and Orient17a Reference Wmm, using SHA-256.
testgridatlas / tools/satnav/orientation/wmm2025.test.mjs · lines 1–157 of 157 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Defines here, wrap. Uses libraries node:test, node:assert/strict, node:crypto, node:fs, node:url. Side effects: reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: browser IndexedDB.
- What it achieves
- Defines `here` and `wrap`. It reads `./wmm2025-fixtures/WMM2025_TEST_VALUES.txt`.
- Why it matters
- Guards the behaviour of Wmm2025, Orient17a Reference Wmm and Orient17a Navigation.
- Application
- gridatlas · tools/satnav/orientation · test
- Uses
- Wmm2025 (import), Orient17a Reference Wmm (import), Orient17a Navigation (import), node:test, node:assert/strict, node:crypto, node:fs, node:url
- Used by
- none found
- Produces
- here, wrap
- Defines here
- here, wrap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/orientation/wmm2025.test.mjs:1-157 · blob c9a8fea26aead558abcde7cff90582daf124989a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network, storage · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// SPDX-License-Identifier: Apache-2.0
// Run: node --test tools/satnav/orientation/wmm2025.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
WMM2025, WMM2025_COEFFICIENTS, evaluateField, declination,
declinationSigmaDeg, decimalYear, magneticToTrue,
} from './wmm2025.mjs';
import { trueHeadingFromObservation } from './orient17a-reference-wmm.mjs';
import { relativeGuidance } from './orient17a-navigation.mjs';
const here = p => fileURLToPath(new URL(p, import.meta.url));
const cofBytes = readFileSync(here('./wmm2025-fixtures/WMM2025.COF'));
const testValues = readFileSync(here('./wmm2025-fixtures/WMM2025_TEST_VALUES.txt'), 'utf8')
.split('\n').filter(l => l.trim() && !l.startsWith('#')).map(l => l.trim().split(/\s+/).map(Number));
const wrap = d => ((d + 540) % 360) - 180;
test('coefficient file provenance and embedded table are byte-faithful', () => {
assert.equal(createHash('sha256').update(cofBytes).digest('hex'), WMM2025.cofSha256);
const lines = cofBytes.toString('utf8').split(/\r?\n/);
assert.match(lines[0], /^\s*2025\.0\s+WMM-2025\s+11\/13\/2024\s*$/);
const rows = lines.slice(1).filter(l => l.trim() && !l.startsWith('9999')).map(l => l.trim().split(/\s+/).map(Number));
assert.equal(rows.length, 90);
assert.deepEqual(WMM2025_COEFFICIENTS.map(r => [...r]), rows);
assert.equal(createHash('sha256').update(readFileSync(here('./wmm2025-fixtures/WMM2025_TEST_VALUES.txt'))).digest('hex'),
'e6975b093dddeb6153e0b23cc418425c438167e7c5b1dd795da379cb654f5819');
});
test('100 official WMM2025 full-precision test vectors', () => {
assert.equal(testValues.length, 100);
for (const [year, alt, lat, lon, D, I, Hn, X, Y, Z, F, Dd, Id, Hd, Xd, Yd, Zd, Fd] of testValues) {
const f = evaluateField({ year, altitudeKm: alt, latitude: lat, longitude: lon });
const at = `${year} ${alt} ${lat} ${lon}`;
assert.ok(f.ok, at);
// Published to 2 dp (angles) and 6 dp (nT): tolerances are rounding plus margin.
assert.ok(Math.abs(wrap(f.declinationDeg - D)) <= 0.0051, `D ${at}`);
assert.ok(Math.abs(f.inclinationDeg - I) <= 0.0051, `I ${at}`);
for (const [g, e, k] of [[f.x, X, 'X'], [f.y, Y, 'Y'], [f.z, Z, 'Z'], [f.h, Hn, 'H'], [f.f, F, 'F']])
assert.ok(Math.abs(g - e) <= 0.002, `${k} ${at} ${g} vs ${e}`);
for (const [g, e, k] of [[f.xDot, Xd, 'Xd'], [f.yDot, Yd, 'Yd'], [f.zDot, Zd, 'Zd'], [f.hDot, Hd, 'Hd'], [f.fDot, Fd, 'Fd']])
assert.ok(Math.abs(g - e) <= 1e-5, `${k} ${at}`);
assert.ok(Math.abs(f.declinationDotDegPerYear - Dd) <= 1e-5, `Dd ${at}`);
assert.ok(Math.abs(f.inclinationDotDegPerYear - Id) <= 1e-5, `Id ${at}`);
}
});
test('NCEI WMM2025testvalues.pdf main-field rows (0.1 nT, 0.01 deg)', () => {
const rows = [
[2025.0, 0, 80, 0, 6521.6, 145.9, 54791.5, 1.28], [2025.0, 0, 0, 120, 39677.8, -109.6, -10580.2, -0.16],
[2025.0, 0, -80, 240, 6117.5, 15751.9, -52022.5, 68.78], [2025.0, 100, 80, 0, 6216, 92.4, 52598.8, 0.85],
[2025.0, 100, 0, 120, 37688.6, -96.2, -10152.1, -0.15], [2025.0, 100, -80, 240, 5907.6, 14780.3, -49540.7, 68.21],
[2027.5, 0, 80, 0, 6500.8, 294.5, 54869.4, 2.59], [2027.5, 0, 0, 120, 39701.6, -167.4, -10381.8, -0.24],
[2027.5, 0, -80, 240, 6200.7, 15730.3, -51783.7, 68.49], [2027.5, 100, 80, 0, 6196.7, 233.8, 52670.5, 2.16],
[2027.5, 100, 0, 120, 37711.5, -148.7, -9969.8, -0.23], [2027.5, 100, -80, 240, 5984, 14760.1, -49317.7, 67.93],
];
for (const [year, alt, lat, lon, X, Y, Z, D] of rows) {
const f = evaluateField({ year, altitudeKm: alt, latitude: lat, longitude: lon });
assert.ok(Math.abs(f.x - X) <= 0.051 && Math.abs(f.y - Y) <= 0.051 && Math.abs(f.z - Z) <= 0.051, `${year} ${lat} ${lon}`);
assert.ok(Math.abs(wrap(f.declinationDeg - D)) <= 0.0051, `D ${year} ${lat} ${lon}`);
}
});
test('epoch, altitude and input validity fail closed', () => {
const p = { latitude: 51.75, longitude: -1.26, altitudeKm: 0 };
assert.equal(evaluateField({ ...p, year: 2024.9999 }).ok, false);
assert.equal(evaluateField({ ...p, year: 2025.0 }).ok, true);
assert.equal(evaluateField({ ...p, year: 2029.9999 }).ok, true);
assert.equal(evaluateField({ ...p, year: 2030.0 }).ok, false);
assert.equal(evaluateField({ ...p, year: NaN }).ok, false);
assert.equal(evaluateField({ ...p, year: 2026, altitudeKm: 851 }).ok, false);
assert.equal(evaluateField({ ...p, year: 2026, altitudeKm: -1.01 }).ok, false);
assert.equal(evaluateField({ ...p, year: 2026, latitude: 90 }).ok, false);
assert.equal(evaluateField({ ...p, year: 2026, latitude: 91 }).ok, false);
assert.equal(declination({ ...p, when: Date.UTC(2030, 0, 1) }).ok, false);
assert.equal(declination({ ...p, when: new Date(Date.UTC(2029, 11, 31, 23, 59)) }).ok, true);
assert.equal(declination({ ...p, when: { year: 2026.5 } }).ok, true);
});
test('decimal year is UTC and leap-year aware', () => {
assert.equal(decimalYear(Date.UTC(2025, 0, 1)), 2025);
assert.equal(decimalYear(Date.UTC(2028, 6, 2)), 2028 + 183 / 366); // 2028 is a leap year
assert.equal(decimalYear(new Date(Date.UTC(2027, 6, 2, 12))), 2027 + 182.5 / 365);
assert.ok(Number.isNaN(decimalYear(NaN)));
});
test('uncertainty interface: published error model and compass zones', () => {
assert.equal(declinationSigmaDeg(20000), Math.sqrt(0.26 ** 2 + (5417 / 20000) ** 2));
assert.equal(declinationSigmaDeg(0), Infinity);
// Official vector points: H = 1504 nT (blackout) and 2164 nT (caution).
const blackout = declination({ latitude: 89, longitude: -121, altitudeKm: 28, when: { year: 2025 } });
assert.equal(blackout.ok, false); assert.equal(blackout.zone, 'blackout'); assert.match(blackout.reason, /blackout/);
const caution = declination({ latitude: 80, longitude: -96, altitudeKm: 48, when: { year: 2025 } });
assert.equal(caution.ok, true); assert.equal(caution.zone, 'caution');
const normal = declination({ latitude: 0, longitude: 120, when: { year: 2025 } });
assert.equal(normal.zone, 'normal');
assert.ok(normal.sigmaDeg > 0.26 && normal.sigmaDeg < 0.33);
assert.ok(Math.abs(normal.expectedFieldNt - 41064.3) < 0.05);
});
test('magneticToTrue: reference rules and uncertainty propagation', () => {
const pos = { latitude: 0, longitude: 120 };
const when = Date.UTC(2025, 0, 1);
const mag = { reference: 'magnetic', degrees: 10, accuracyDeg: 5, timestampMs: when };
const d = declination({ ...pos, when });
const r = magneticToTrue(mag, pos, { when });
assert.equal(r.heading.reference, 'true');
assert.ok(Math.abs(r.heading.degrees - (10 + d.declinationDeg)) < 1e-12);
assert.equal(r.heading.accuracyDeg, 5 + 2 * d.sigmaDeg);
assert.equal(magneticToTrue(mag, pos, { when, sigmaMultiplier: 1 }).heading.accuracyDeg, 5 + d.sigmaDeg);
assert.equal(magneticToTrue({ ...mag, degrees: 359.9 }, pos, { when }).heading.degrees < 360, true);
const t = { reference: 'true', degrees: 1, accuracyDeg: 1, timestampMs: when };
assert.equal(magneticToTrue(t, pos).heading, t);
assert.equal(magneticToTrue({ ...mag, reference: 'sensor' }, pos, { when }).heading, null);
assert.equal(magneticToTrue({ ...mag, reference: 'sensor' }, pos, { when, sensorIsMagnetic: true }).heading.reference, 'true');
assert.equal(magneticToTrue({ ...mag, accuracyDeg: null }, pos, { when }).heading, null);
assert.equal(magneticToTrue({ ...mag, degrees: NaN }, pos, { when }).heading, null);
assert.equal(magneticToTrue(mag, { latitude: NaN, longitude: 0 }, { when }).heading, null);
assert.equal(magneticToTrue(mag, pos, { when: Date.UTC(2030, 0, 2) }).heading, null);
assert.equal(magneticToTrue({ ...mag, disturbed: true }, pos, { when }).heading.disturbed, true);
assert.equal(magneticToTrue(mag, { latitude: 89, longitude: -121, altitudeKm: 28 }, { when }).heading, null);
});
test('V9.210 boundary: trueHeadingFromObservation composes with relativeGuidance for eight headings', () => {
const now = Date.UTC(2026, 11, 4, 12);
const fix = { latitude: 0, longitude: 120, accuracyM: 5, timestampMs: now };
const D = declination({ latitude: 0, longitude: 120, when: now }).declinationDeg;
const metrics = { distanceM: 200, bearingDeg: 0, accuracyM: 5, reason: null };
for (let i = 0; i < 8; i++) {
const magnetic = i * 45;
const obs = { reference: 'magnetic', degrees: magnetic, accuracyDeg: 5, timestampMs: now, frame: 0, provenance: 'webkit-magnetic', disturbed: false };
const h = trueHeadingFromObservation(obs, fix, now);
assert.equal(h.reference, 'true');
const g = relativeGuidance(metrics, h, now);
assert.ok(Math.abs(wrap(g.relativeDeg - wrap(0 - (magnetic + D)))) < 1e-9, `heading ${magnetic}`);
assert.equal(g.reason, null);
}
const base = { reference: 'magnetic', degrees: 0, accuracyDeg: 5, timestampMs: now, provenance: 'webkit-magnetic' };
assert.equal(trueHeadingFromObservation({ ...base, provenance: 'unverified-absolute' }, fix, now), null);
assert.equal(trueHeadingFromObservation({ ...base, reference: 'sensor' }, fix, now), null);
assert.equal(trueHeadingFromObservation({ ...base, timestampMs: now + 1 }, fix, now), null);
assert.equal(trueHeadingFromObservation(base, { ...fix, latitude: undefined }, now), null);
assert.equal(trueHeadingFromObservation(null, fix, now), null);
// Unknown accuracy stays fail-closed end to end.
assert.equal(trueHeadingFromObservation({ ...base, accuracyDeg: null }, fix, now), null);
assert.equal(relativeGuidance(metrics, null, now).relativeDeg, null);
});
test('dependency closure: no network, storage or imports beyond the evaluator', () => {
const src = readFileSync(here('./wmm2025.mjs'), 'utf8');
assert.doesNotMatch(src, /\bimport\b|\brequire\(|fetch\(|XMLHttpRequest|WebSocket|sendBeacon|localStorage|indexedDB/);
const adapter = readFileSync(here('./orient17a-reference-wmm.mjs'), 'utf8');
assert.deepEqual([...adapter.matchAll(/from\s+'([^']+)'/g)].map(m => m[1]), ['./wmm2025.mjs']);
assert.doesNotMatch(adapter, /fetch\(|XMLHttpRequest|sendBeacon|localStorage/);
});Bristol Browser
A Python command-line tool in the pedestrian pilot folder of GridAtlas that works with tap endpoint (`tap_endpoint`), covering bristol footpaths.
rendergridatlas / tools/satnav/pedestrian-pilot/bristol-browser.py · lines 1–104 of 104 · Entry point · pattern features (shared by 5 files)
- What it does
- Defines features, tap_endpoint, check_browser. Uses libraries os, playwright.sync_api. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: GeoJSON file bristol-footpaths.geojson.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It checks browser (`check_browser`) and is built from the features step (`features`). Touch acceptance against the combined V4 GridAtlas map and Bristol footpath data.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/satnav/pedestrian-pilot · Python CLI
- Uses
- os, playwright.sync_api
- Used by
- none found
- Produces
- features, tap_endpoint, check_browser
- Defines here
- features, tap_endpoint, check_browser
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/pedestrian-pilot/bristol-browser.py:1-104 · blob 702f91d6670990723a9bd8ac3f18b8b36945b265 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Touch acceptance against the combined V4 GridAtlas map and Bristol footpath data."""
import os
from playwright.sync_api import expect, sync_playwright
SITE = os.environ.get('LINE_TEST_URL', 'http://127.0.0.1:8873/atlas/v/satnav-layout-202611281330/')
def features(page, count):
return page.wait_for_function("""count => {
const data = window.__GRIDATLAS_V9_MAP__?.getSource('satnav-bristol-footpaths')?.serialize()?.data;
return data?.features?.length === count ? data.features : null;
}""", arg=count, timeout=20000).json_value()
def tap_endpoint(page, field, coordinates):
page.locator('#satnav-' + field).tap()
point = page.evaluate("""coordinates => {
const map = window.__GRIDATLAS_V9_MAP__;
const canvas = map.getCanvas();
const box = canvas.getBoundingClientRect();
map.easeTo({center: coordinates, zoom: 17, duration: 0, offset: [.32 * box.width, .18 * box.height]});
const target = map.project(coordinates);
const x = Math.round(box.left + target.x), y = Math.round(box.top + target.y);
return {x, y, onMap: document.elementFromPoint(x, y) === canvas};
}""", coordinates)
assert point['onMap'], point
page.touchscreen.tap(point['x'], point['y'])
def check_browser(browser, label, width, height):
context = browser.new_context(viewport={'width': width, 'height': height}, is_mobile=True, has_touch=True)
try:
page = context.new_page()
page.goto(SITE, wait_until='domcontentloaded')
panel = page.locator('#satnav-bristol')
summary = panel.locator('summary')
summary.wait_for(state='visible', timeout=60000)
summary.tap()
result = panel.get_by_role('status')
example = panel.get_by_role('button', name='Show example')
page.route('**/bristol-footpaths.geojson', lambda request: request.fulfill(status=503), times=1)
example.tap()
expect(result).to_contain_text('could not be loaded')
example.tap()
expect(result).to_contain_text('578 m')
expect(result).to_contain_text('Current access is unverified')
shown = features(page, 12)
paths = {f['properties']['ROUTE_CODE']: f['geometry']['coordinates']
for f in shown if 'ROUTE_CODE' in f['properties']}
assert len(paths) == 11
summary.tap()
expect(panel.locator('.footpath-brief')).to_be_visible()
expect(panel.locator('.footpath-brief')).to_have_text('Example · BCC/21 · 578 m · access unverified')
features(page, 12)
summary.tap()
panel.get_by_role('button', name='Route FROM to TO').tap()
expect(result).to_contain_text('Select FROM and TO')
features(page, 11)
summary.tap()
tap_endpoint(page, 'from', paths['BCC/21/10'][0])
tap_endpoint(page, 'to', paths['BCC/21/30'][-1])
summary.tap()
expect(result).to_contain_text('FROM to TO · BCC/21')
expect(result).to_contain_text('Current access is unverified')
drawn = features(page, 12)
route = next(f for f in drawn if f['properties'].get('role') == 'mapped-footpath')
assert len(route['geometry']['coordinates']) > 10
summary.tap()
tap_endpoint(page, 'to', paths['BCC/38/30'][-1])
expect(panel.locator('.footpath-brief')).to_have_text('Coverage only · no mapped route')
expect(panel.locator('.footpath-brief')).to_be_visible()
summary.tap()
expect(result).to_contain_text('No mapped connection')
features(page, 11)
summary.tap()
west, north = paths['BCC/21/10'][0]
tap_endpoint(page, 'from', [west - .004, north])
summary.tap()
expect(result).to_contain_text('Route unavailable')
features(page, 11)
panel.get_by_role('button', name='Clear footpaths').tap()
features(page, 0)
expect(result).to_have_text('')
print(f'{label} {width}×{height} passed Bristol example, pins, source retry, coverage, disconnection and clear')
finally:
context.close()
if __name__ == '__main__':
with sync_playwright() as pw:
for engine in os.environ.get('LINE_TEST_BROWSERS', 'chromium,webkit').split(','):
options = {'args': ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']} if engine == 'chromium' else {}
browser = getattr(pw, engine).launch(**options)
try:
for dimensions in [(390, 664), (664, 390)]:
check_browser(browser, engine, *dimensions)
finally:
browser.close()Bristol
A JavaScript module in the pedestrian pilot folder of GridAtlas that maps bristol footpaths.
rendergridatlas / tools/satnav/pedestrian-pilot/bristol.mjs · lines 1–165 of 165 · Not reached from any entry point (candidate for review) · pattern showResult (shared by 3 files)
- What it does
- It maps bristol footpaths. Defines 8 functions or classes, including installBristolFootpaths, paint, showResult, refresh, load. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: GeoJSON file bristol-footpaths.geojson.
- What it achieves
- It shows result (`showResult`) and is built from the install bristol footpaths helper (`installBristolFootpaths`) and the refresh step (`refresh`). Defines `installBristolFootpaths`, `paint`, `showResult` and 5 more. It responds to toggle events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/satnav/pedestrian-pilot · JavaScript module
- Uses
- Mapped Footpaths (import)
- Used by
- none found
- Produces
- installBristolFootpaths
- Defines here
- installBristolFootpaths, paint, showResult, refresh, load, points, select, hide
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/pedestrian-pilot/bristol.mjs:1-165 · blob ed43104cd705b945cc2542f956a63c90eb24c610 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// SPDX-License-Identifier: Apache-2.0
import {createBristolFootpathRouter} from '../pedestrian/mapped-footpaths.mjs';
const bundleUrl = new URL('../pedestrian/bristol-footpaths.geojson', import.meta.url);
const sourceId = 'satnav-bristol-footpaths';
const coverageLayer = sourceId + '-coverage';
const routeLayer = sourceId + '-route';
const empty = {type: 'FeatureCollection', features: []};
const unavailable = {
'invalid-point': 'Select FROM and TO on the highlighted footpaths.',
'outside-coverage': 'Route unavailable. Select both pins within 12 m of a highlighted Bristol footpath.',
'no-mapped-connection': 'Route unavailable. No mapped connection joins these pins in this extract.',
'ambiguous-tap': 'Route unavailable. Select a point away from a crossing or overlapping paths.',
'same-position': 'Both pins select the same place on the footpath.',
'excluded-section': 'Route unavailable. A section is excluded.',
};
export function installBristolFootpaths({map, container, maths, getEndpoints}) {
const style = document.createElement('style');
style.textContent = `#satnav-bristol{border-radius:6px;background:#081820ed;color:#e4f7f7}
#satnav-bristol summary{padding:8px;min-height:40px;box-sizing:border-box;cursor:pointer}
#satnav-bristol .footpath-brief{display:block;font-size:11px;color:#c9edce}
#satnav-bristol[open] .footpath-brief,#satnav-bristol .footpath-brief[hidden]{display:none}
#satnav-bristol p,#satnav-bristol small{display:block;margin:0;padding:3px 7px 7px}
#satnav-bristol a{color:#8bf7f7}#satnav-bristol button{margin:2px 0 2px 4px}`;
const details = document.createElement('details');
details.id = 'satnav-bristol';
details.innerHTML = `<summary>Bristol footpaths<span class="footpath-brief" aria-live="polite" hidden></span></summary>
<p>Coverage is limited to council paths BCC/21, BCC/25 and BCC/38. Check signs and current restrictions before walking.</p>
<button type="button" data-bristol="example">Show example</button>
<button type="button" data-bristol="pins">Route FROM to TO</button>
<button type="button" data-bristol="clear" hidden>Clear footpaths</button>
<p role="status" class="footpath-result"></p>
<small>Contains public sector information from <a href="https://www.arcgis.com/home/item.html?id=3716eccf257a423f939a2bf6da435c5c" target="_blank" rel="noopener noreferrer">Bristol City Council</a> licensed under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" target="_blank" rel="noopener noreferrer">Open Government Licence v3.0</a>.</small>`;
container.append(style, details);
const message = details.querySelector('[role="status"]');
const brief = details.querySelector('.footpath-brief');
const clear = details.querySelector('[data-bristol="clear"]');
let bundle, calculate, example, loading;
let mode = null, lastPins = null, displayed = empty, paintedSource, paintedData;
let revision = 0, painting = false;
function paint() {
if (painting || (!mode && !paintedSource)) return;
if (!map.getLayer('l-sat') && !map.isStyleLoaded()) return;
painting = true;
try {
if (!map.getSource(sourceId)) map.addSource(sourceId, {type: 'geojson', data: displayed});
const source = map.getSource(sourceId);
const marker = map.getStyle().layers.find(layer => layer.type === 'circle' && layer.id.includes('satnav'))?.id;
if (!map.getLayer(coverageLayer)) {
map.addLayer({id: coverageLayer, source: sourceId, type: 'line',
filter: ['has', 'ROUTE_CODE'], paint: {'line-color': '#e7d4ff', 'line-width': 4, 'line-dasharray': [2, 1]}}, marker);
}
if (!map.getLayer(routeLayer)) {
map.addLayer({id: routeLayer, source: sourceId, type: 'line',
filter: ['==', ['get', 'role'], 'mapped-footpath'],
paint: {'line-color': '#93f16d', 'line-width': 5}}, marker);
}
if (source !== paintedSource || displayed !== paintedData) source.setData(displayed);
paintedSource = source;
paintedData = displayed;
} finally {
painting = false;
}
}
function showResult(result) {
const features = [...bundle.features];
if (result.status === 'mapped') {
features.push({type: 'Feature', properties: {role: 'mapped-footpath'}, geometry: result.geometry});
const prefix = mode === 'example' ? 'Example' : 'FROM to TO';
message.textContent = `${prefix} · ${result.route} · ${Math.round(result.distanceM)} m on the mapped path. Current access is unverified.`;
brief.textContent = `${prefix} · ${result.route} · ${Math.round(result.distanceM)} m · access unverified`;
if (Math.max(result.fromOffsetM, result.toOffsetM) >= 0.5) {
message.textContent += ` Pins are ${Math.round(result.fromOffsetM)} m and ${Math.round(result.toOffsetM)} m from the path.`;
}
} else {
message.textContent = unavailable[result.reason] || 'A mapped pedestrian route is unavailable.';
brief.textContent = 'Coverage only · no mapped route';
}
brief.hidden = false;
displayed = {type: 'FeatureCollection', features};
paint();
}
function refresh() {
if (mode !== 'pins' || !calculate) return;
const pins = getEndpoints() || [];
const key = JSON.stringify(pins);
if (key === lastPins) return;
lastPins = key;
showResult(calculate(pins[0], pins[1]));
}
async function load() {
const response = await fetch(bundleUrl);
if (!response.ok) throw new Error('Footpaths unavailable');
const data = await response.json();
const route = createBristolFootpathRouter(data, maths);
const points = code => data.features.find(f => f.properties.ROUTE_CODE === code).geometry.coordinates;
const sample = route(points('BCC/21/10')[0], points('BCC/21/30').at(-1));
if (sample.status !== 'mapped') throw new Error('Footpath example unavailable');
bundle = data;
calculate = route;
example = sample;
}
async function select(next) {
const selected = ++revision;
mode = next;
lastPins = null;
clear.hidden = false;
if (!calculate) {
message.textContent = 'Loading Bristol footpaths…';
try {
loading ??= load().finally(() => { loading = null; });
await loading;
} catch {
if (selected === revision) message.textContent = 'Bristol footpaths could not be loaded. Try again when connected.';
return;
}
}
if (selected !== revision) return;
if (mode === 'pins') {
refresh();
return;
}
showResult(example);
const points = bundle.features.flatMap(feature => feature.geometry.coordinates);
const lngs = points.map(p => p[0]), lats = points.map(p => p[1]);
map.fitBounds([[Math.min(...lngs), Math.min(...lats)], [Math.max(...lngs), Math.max(...lats)]],
{padding: 35, maxZoom: 17, duration: 0});
}
function hide() {
revision++;
mode = null;
displayed = empty;
clear.hidden = true;
message.textContent = '';
brief.hidden = true;
brief.textContent = '';
paint();
}
details.querySelector('[data-bristol="example"]').onclick = () => select('example');
details.querySelector('[data-bristol="pins"]').onclick = () => select('pins');
clear.onclick = hide;
details.addEventListener('toggle', () => { if (!details.open && loading) hide(); });
map.on('style.load', paint);
map.on('idle', paint);
return {refresh, destroy() {
revision++;
mode = null;
map.off('style.load', paint);
map.off('idle', paint);
if (map.getLayer(routeLayer)) map.removeLayer(routeLayer);
if (map.getLayer(coverageLayer)) map.removeLayer(coverageLayer);
if (map.getSource(sourceId)) map.removeSource(sourceId);
details.remove();
style.remove();
}};
}