GNSS Integrity on H3 resolution-4 hexagons, as gpsjam.org

Aircraft are binned into H3 resolution-4 cells (h3-js) and each cell is
drawn as its hexagon instead of a 0.5 degree square. As on gpsjam.org,
every hexagon with an aircraft is shown: the three-aircraft minimum is
gone, and discounting one bad aircraft is the only small-sample guard.
Cells are keyed by their H3 index and carry their centre and boundary.
This commit is contained in:
Sameh Khamis committed 2026-11-15 10:19:59 -08:00
1 parent 574d873e6b
commit 317d06adf6
25 files changed
+331 -154

No files matched your search

+10 -15
View File
@@ -3,10 +3,10 @@ import { formatNumber, msg, t } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
GNSS_LEVEL_COLORS,
GNSS_MIN_AIRCRAFT,
GNSS_WINDOW_MS,
accumulateGnssObservations,
binGnssCells,
gnssCellRing,
gnssProvenance,
pruneGnssObservations,
} from './records.js';
@@ -62,7 +62,7 @@ export function defaultGnssViewAnchor(viewer) {
/**
* Own one GNSS navigation-integrity display: rolling integrity observations
* around the views the user visits, binned into cells coloured by the
* around the views the user visits, binned into H3 hexagons coloured by the
* gpsjam low-accuracy score. Share links retain token 3.
*/
export function createGnssIntegrityLayer({
@@ -185,13 +185,12 @@ export function createGnssIntegrityLayer({
(cell) =>
new Cesium.GeometryInstance({
id: `${layer.id}:${cell.id}`,
geometry: new Cesium.RectangleGeometry({
rectangle: Cesium.Rectangle.fromDegrees(
cell.west,
cell.south,
cell.east,
cell.north,
geometry: new Cesium.PolygonGeometry({
// H3 edges are great-circle arcs, as Cesium's geodesic edges.
polygonHierarchy: new Cesium.PolygonHierarchy(
Cesium.Cartesian3.fromDegreesArray(gnssCellRing(cell)),
),
arcType: Cesium.ArcType.GEODESIC,
vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
}),
attributes: {
@@ -209,7 +208,7 @@ export function createGnssIntegrityLayer({
}),
classificationType: Cesium.ClassificationType.BOTH,
allowPicking: false,
// Retain the compact rectangle descriptors for inspection, not Entity visualizers.
// Retain the compact polygon descriptors for inspection, not Entity visualizers.
releaseGeometryInstances: false,
}),
);
@@ -396,7 +395,7 @@ export function createGnssIntegrityLayer({
}`
: ''),
infoTitle: t(
'Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.',
'Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank areas had no aircraft reporting navigation accuracy in the window.',
),
legend: ['high', 'medium', 'low'].map((level, index) => ({
label: t(LEVEL_LABELS[level]),
@@ -405,11 +404,7 @@ export function createGnssIntegrityLayer({
...(index === 0
? {
blurb: t(
'Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.',
{
aircraft: formatNumber(GNSS_MIN_AIRCRAFT),
minutes: formatNumber(provenance.window.minutes),
},
'Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Navigation-integrity anomalies are not a detection of jamming or spoofing.',
),
}
: {}),
+21 -13
View File
@@ -75,8 +75,8 @@ function harness(
const MIN = 60_000;
const threeHealthy = () => [
row('a1', 1.1, false),
row('a2', 1.2, false),
row('a3', 1.3, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
];
const flush = () => new Promise((resolve) => setImmediate(resolve));
@@ -216,21 +216,25 @@ test('an enabled refresh bins the snapshot into coloured ground cells', async ()
assert.equal(sources[0].show, true);
assert.equal(await layer.update(), true);
const entities = sources[0].get(0).geometryInstances;
assert.equal(entities.length, 1, 'the one-aircraft cell is withheld');
assert.equal(entities[0].id, 'gnss-integrity:280:420');
assert.ok(entities[0].geometry instanceof Cesium.RectangleGeometry);
assert.equal(entities.length, 2, 'a one-aircraft cell is shown too');
assert.deepEqual(
entities.map(({ id }) => id),
['gnss-integrity:841e631ffffffff', 'gnss-integrity:841f6b3ffffffff'],
);
for (const { geometry } of entities)
assert.ok(geometry instanceof Cesium.PolygonGeometry);
assert.equal(sources[0].get(0).allowPicking, false);
const stats = layer.getStats();
assert.equal(stats.count, 1);
assert.equal(stats.count, 2);
assert.equal(stats.error, null);
assert.equal(stats.fallback, false);
const { legend } = layer.getRowControls();
assert.deepEqual(
legend.map(({ count }) => count),
[1, 0, 0],
[1, 0, 1],
);
assert.match(legend[0].blurb, /not a detection/);
assert.match(legend[0].blurb, /need 3 aircraft/);
assert.doesNotMatch(legend[0].blurb, /need \d+ aircraft/);
});
test('the visible layer leads with low navigation accuracy and exposes its provenance', async () => {
@@ -262,10 +266,10 @@ test('the visible layer leads with low navigation accuracy and exposes its prove
assert.deepEqual(layer.provenance.window, {
minutes: 30,
scope: 'visited-view',
cellDeg: 0.5,
minAircraft: 3,
definedBy: 'GEV',
});
assert.equal(layer.provenance.aggregation.grid, 'h3');
assert.equal(layer.provenance.aggregation.h3Resolution, 4);
assert.equal(layer.provenance.interpretation.validated, false);
assert.equal(layer.getStats().provenance, layer.provenance);
});
@@ -277,8 +281,8 @@ test('a failed refresh keeps the last cells and reports the error', async () =>
return {
rows: [
row('a1', 1.1, false),
row('a2', 1.2, false),
row('a3', 1.3, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
],
stale: true,
};
@@ -305,7 +309,11 @@ test('observations expire with the window, and disable aborts the request in fli
layer.enable();
let result = layer.update();
pending.resolve({
rows: [row('a1', 1.1, false), row('a2', 1.2, false), row('a3', 1.3, false)],
rows: [
row('a1', 1.1, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
],
});
assert.equal(await result, true);
assert.equal(layer.getStats().count, 1);
+48 -34
View File
@@ -1,5 +1,5 @@
/**
* Low navigation accuracy reported by ADS-B aircraft, binned into cells.
* Low navigation accuracy reported by ADS-B aircraft, binned into H3 cells.
*
* Aircraft broadcasting DO-260 version 1/2 ADS-B report how much they trust
* their own position: NIC (integrity containment radius) and NACp (position
@@ -16,9 +16,12 @@
* from the US 14 CFR 91.227(c) ADS-B Out performance minima, which are not
* a published interference classifier) or the readsb/tar1090 `gpsOkBefore`
* flag. gpsjam.org does not publish its per-aircraft threshold.
* - Cell aggregation: gpsjam.org's published formula and 2% / 10% bands.
* - Cell aggregation: gpsjam.org's published formula, 2% / 10% bands and
* hex grid (H3 resolution 4). Every cell with an aircraft is shown, as on
* gpsjam.org; the one-aircraft discount is the only small-sample guard.
* - Window: a GEV-defined rolling 30 minutes over the views the user visits.
*/
import { cellToBoundary, cellToLatLng, latLngToCell } from 'h3-js';
/** Position source can switch to MLAT after GPS loss; quality must remain aircraft-reported. */
const QUALIFYING_TYPES = new Set(['adsb_icao', 'mlat']);
@@ -30,10 +33,8 @@ export const GNSS_NIC_THRESHOLD = 7;
export const GNSS_NACP_THRESHOLD = 8;
/** Positions older than this are not current evidence of the local sky. */
const MAX_POSITION_AGE_S = 60;
/** Cell edge in degrees: roughly 55 km north-south, similar in area to an H3 res-4 cell. */
export const GNSS_CELL_DEG = 0.5;
/** Hide sparse one- and two-aircraft cells; the aggregation separately discounts one bad report. */
export const GNSS_MIN_AIRCRAFT = 3;
/** H3 resolution of the cells, gpsjam.org's grid: hexagons of about 1,770 km² (22.6 km edge). */
export const GNSS_H3_RESOLUTION = 4;
/** Rolling window over which aircraft seen in a cell are counted. */
export const GNSS_WINDOW_MS = 30 * 60_000;
/** gpsjam.org band edges, in percent of aircraft (after discounting one). */
@@ -68,14 +69,14 @@ export function gnssProvenance({ windowMs = GNSS_WINDOW_MS } = {}) {
id: 'gpsjam-cell-bands',
formula: '100 * max(0, bad - 1) / total',
bands: Object.freeze([GNSS_MEDIUM_PERCENT, GNSS_HIGH_PERCENT]),
grid: 'h3',
h3Resolution: GNSS_H3_RESOLUTION,
source: 'https://gpsjam.org/faq',
definedBy: 'gpsjam.org',
}),
window: Object.freeze({
minutes: windowMs / 60_000,
scope: 'visited-view',
cellDeg: GNSS_CELL_DEG,
minAircraft: GNSS_MIN_AIRCRAFT,
definedBy: 'GEV',
}),
state: Object.freeze({
@@ -161,11 +162,30 @@ export function normalizeGnssAircraft(payload) {
return rows;
}
/** Stable key of the cell containing a position. */
export function gnssCellKey(lat, lon, cellDeg = GNSS_CELL_DEG) {
const row = Math.floor((Math.min(lat, 89.999999) + 90) / cellDeg);
const col = Math.floor((Math.min(lon, 179.999999) + 180) / cellDeg);
return `${row}:${col}`;
/** Stable key of the cell containing a position: its H3 index. */
export function gnssCellKey(lat, lon, resolution = GNSS_H3_RESOLUTION) {
return latLngToCell(lat, lon, resolution);
}
/**
* The ring to draw for a cell, as flat `[lon, lat, lon, lat, ...]` degrees.
* Longitudes are unwrapped to within 180° of the cell centre, so a cell
* across the antimeridian stays one narrow polygon (some longitudes then lie
* just outside ±180°) instead of spanning the globe. A cell around a pole
* keeps its full turn of longitudes; drawn on the globe it is still small.
*
* @param {{lat: number, lon: number, boundary: {lat: number, lon: number}[]}} cell
* @returns {number[]}
*/
export function gnssCellRing(cell) {
const ring = [];
for (const { lat, lon } of cell.boundary) {
let unwrapped = lon;
while (unwrapped - cell.lon > 180) unwrapped -= 360;
while (unwrapped - cell.lon < -180) unwrapped += 360;
ring.push(unwrapped, lat);
}
return ring;
}
/**
@@ -183,7 +203,7 @@ export function gnssCellKey(lat, lon, cellDeg = GNSS_CELL_DEG) {
* @param {Map<string, {cell: string, seenAt: number, degradedAt: number|null}>} store
* @param {ReturnType<typeof normalizeGnssAircraft>} rows
* @param {number} nowMs
* @param {{windowMs?: number, cellDeg?: number, observedAt?: number}} [options]
* @param {{windowMs?: number, resolution?: number, observedAt?: number}} [options]
* `observedAt` is the snapshot's observation time (defaults to `nowMs`;
* a future time is clamped to `nowMs`, a non-finite one adds nothing).
* @returns {Map} The same store, pruned to the window.
@@ -194,7 +214,7 @@ export function accumulateGnssObservations(
nowMs,
{
windowMs = GNSS_WINDOW_MS,
cellDeg = GNSS_CELL_DEG,
resolution = GNSS_H3_RESOLUTION,
observedAt = nowMs,
} = {},
) {
@@ -202,7 +222,7 @@ export function accumulateGnssObservations(
if (Number.isFinite(at) && nowMs - at <= windowMs) {
for (const row of rows || []) {
if (!Number.isFinite(row?.lat) || !Number.isFinite(row?.lon)) continue;
const cell = gnssCellKey(row.lat, row.lon, cellDeg);
const cell = gnssCellKey(row.lat, row.lon, resolution);
const key = `${row.hex}|${cell}`;
const previous = store.get(key);
const previousDegradedAt = previous?.degradedAt ?? null;
@@ -264,16 +284,16 @@ export function gnssIntegrityLevel(total, degraded) {
}
/**
* Aggregate the observation store into displayable cells. Expects a store
* already pruned to the window by `accumulateGnssObservations` or
* `pruneGnssObservations`.
* Aggregate the observation store into displayable cells, one per H3 cell
* with at least one aircraft (gpsjam.org has no minimum count). Expects a
* store already pruned to the window by `accumulateGnssObservations` or
* `pruneGnssObservations`. `lat`/`lon` is the cell centre and `boundary` its
* vertices in order (six for a hexagon, five for a pentagon), with
* longitudes in -180..180; `gnssCellRing` gives the ring to draw.
*
* @returns {{id: string, south: number, west: number, north: number, east: number, lat: number, lon: number, aircraft: number, degraded: number, percentDegraded: number, level: 'low'|'medium'|'high', state: string, interpretation: string|null}[]}
* @returns {{id: string, lat: number, lon: number, boundary: {lat: number, lon: number}[], aircraft: number, degraded: number, percentDegraded: number, level: 'low'|'medium'|'high', state: string, interpretation: string|null}[]}
*/
export function binGnssCells(
store,
{ cellDeg = GNSS_CELL_DEG, minAircraft = GNSS_MIN_AIRCRAFT } = {},
) {
export function binGnssCells(store) {
const tallies = new Map();
for (const { cell, degradedAt } of store.values()) {
const tally = tallies.get(cell) || { aircraft: 0, degraded: 0 };
@@ -283,22 +303,16 @@ export function binGnssCells(
}
const cells = [];
for (const [id, { aircraft, degraded }] of tallies) {
if (aircraft < minAircraft) continue;
const [row, col] = id.split(':').map(Number);
const south = row * cellDeg - 90;
const west = col * cellDeg - 180;
const [lat, lon] = cellToLatLng(id);
const { percent, level, state, interpretation } = gnssIntegrityLevel(
aircraft,
degraded,
);
cells.push({
id,
south,
west,
north: south + cellDeg,
east: west + cellDeg,
lat: south + cellDeg / 2,
lon: west + cellDeg / 2,
lat,
lon,
boundary: cellToBoundary(id).map(([lat, lon]) => ({ lat, lon })),
aircraft,
degraded,
percentDegraded: Math.round(percent * 10) / 10,
+145 -23
View File
@@ -1,12 +1,17 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getResolution, isPentagon, isValidCell } from 'h3-js';
import {
accumulateGnssObservations,
binGnssCells,
GNSS_CLASSIFIER,
GNSS_H3_RESOLUTION,
GNSS_HIGH_PERCENT,
GNSS_MEDIUM_PERCENT,
GNSS_PROVENANCE,
GNSS_WINDOW_MS,
gnssCellKey,
gnssCellRing,
gnssIntegrityLevel,
gnssProvenance,
normalizeGnssAircraft,
@@ -117,13 +122,87 @@ test('low NIC, low NACp or a readsb GPS-loss flag each mark an aircraft degraded
);
});
test('cell keys are stable half-degree bins, clamped at the poles and antimeridian', () => {
assert.equal(gnssCellKey(50.1, 19.9), gnssCellKey(50.4, 19.6));
assert.notEqual(gnssCellKey(50.1, 19.9), gnssCellKey(50.6, 19.9));
assert.equal(gnssCellKey(90, 180), gnssCellKey(89.9, 179.9));
assert.equal(gnssCellKey(-90, -180), '0:0');
// Just south-west of the origin falls in the last cell before 0°, not cell 0.
assert.equal(gnssCellKey(-0.1, -0.1), '179:359');
test('cell keys are the H3 resolution-4 cells gpsjam.org uses', () => {
assert.equal(GNSS_H3_RESOLUTION, 4);
// Kraków: a known lat/lon lands in its known res-4 hexagon.
assert.equal(gnssCellKey(50.1, 19.9), '841e2e7ffffffff');
assert.equal(getResolution(gnssCellKey(50.1, 19.9)), 4);
// Nearby points share the hexagon; a point ~50 km north does not.
assert.equal(gnssCellKey(50.1, 19.9), gnssCellKey(50.12, 19.95));
assert.notEqual(gnssCellKey(50.1, 19.9), gnssCellKey(50.55, 19.9));
// The poles and both sides of the antimeridian still key valid cells.
for (const [lat, lon] of [
[90, 180],
[-90, -180],
[0, 179.99],
[0, -179.99],
]) {
const key = gnssCellKey(lat, lon);
assert.ok(isValidCell(key), `${lat},${lon} → ${key}`);
assert.equal(getResolution(key), 4);
}
});
const cellAt = (lat, lon) => {
const store = new Map();
accumulateGnssObservations(
store,
[{ hex: 'c1', lat, lon, degraded: false }],
0,
);
return binGnssCells(store)[0];
};
test('a cell carries its H3 centre and hexagon boundary', () => {
const cell = cellAt(50.1, 19.9);
assert.equal(cell.id, '841e2e7ffffffff');
assert.ok(Math.abs(cell.lat - 50.17184) < 1e-4);
assert.ok(Math.abs(cell.lon - 20.12566) < 1e-4);
assert.equal(cell.boundary.length, 6);
for (const { lat, lon } of cell.boundary) {
// Res-4 hexagons are about 45 km across.
assert.ok(Math.abs(lat - cell.lat) < 0.4, `lat ${lat}`);
assert.ok(Math.abs(lon - cell.lon) < 0.6, `lon ${lon}`);
}
for (const key of ['south', 'west', 'north', 'east'])
assert.equal(key in cell, false, `no rectangle field ${key}`);
assert.deepEqual(
gnssCellRing(cell),
cell.boundary.flatMap(({ lat, lon }) => [lon, lat]),
);
});
test('a cell across the antimeridian is drawn as one narrow polygon', () => {
for (const lon of [179.99, -179.99]) {
const cell = cellAt(0, lon);
const lons = cell.boundary.map((vertex) => vertex.lon);
assert.ok(
Math.max(...lons) - Math.min(...lons) > 300,
'the raw boundary straddles ±180°',
);
const drawn = gnssCellRing(cell).filter((_, index) => index % 2 === 0);
const width = Math.max(...drawn) - Math.min(...drawn);
assert.ok(width < 1, `drawn width ${width}° stays narrow`);
for (const value of drawn) assert.ok(Math.abs(value - cell.lon) < 1);
}
});
test('pentagon and polar cells give closed rings', () => {
// 8408001ffffffff is one of the twelve res-4 pentagons.
const pentagon = cellAt(64.7, 10.5);
assert.ok(isPentagon(pentagon.id));
assert.equal(pentagon.boundary.length, 5);
assert.equal(gnssCellRing(pentagon).length, 10);
for (const lat of [89.99, -89.99]) {
const polar = cellAt(lat, 10);
assert.ok(polar.boundary.length >= 6);
for (const vertex of polar.boundary)
assert.ok(Math.abs(vertex.lat) > 89 && Math.abs(vertex.lat) <= 90);
// Unwrapped longitudes stay within half a turn of the centre.
gnssCellRing(polar)
.filter((_, index) => index % 2 === 0)
.forEach((value) => assert.ok(Math.abs(value - polar.lon) <= 180));
}
});
test('integrity level follows the gpsjam.org published cell formula and bands', () => {
@@ -156,8 +235,8 @@ test('the primary state is a navigation-integrity anomaly; interference is only
store,
[
{ hex: 'h1', lat: 10.1, lon: 10.1, degraded: true },
{ hex: 'h2', lat: 10.2, lon: 10.2, degraded: true },
{ hex: 'h3', lat: 10.3, lon: 10.3, degraded: false },
{ hex: 'h2', lat: 10.11, lon: 10.11, degraded: true },
{ hex: 'h3', lat: 10.12, lon: 10.12, degraded: false },
],
0,
);
@@ -182,14 +261,14 @@ test('provenance separates the GEV classifier from the gpsjam aggregation and th
id: 'gpsjam-cell-bands',
formula: '100 * max(0, bad - 1) / total',
bands: [2, 10],
grid: 'h3',
h3Resolution: 4,
source: 'https://gpsjam.org/faq',
definedBy: 'gpsjam.org',
});
assert.deepEqual(GNSS_PROVENANCE.window, {
minutes: 30,
scope: 'visited-view',
cellDeg: 0.5,
minAircraft: 3,
definedBy: 'GEV',
});
assert.equal(GNSS_PROVENANCE.state.id, 'navigation-integrity-anomaly');
@@ -225,14 +304,13 @@ test('observations count each aircraft once per cell and expire after the window
assert.equal(cell.aircraft, 3);
assert.equal(cell.degraded, 1);
assert.equal(cell.level, 'low');
assert.deepEqual(
[cell.south, cell.west, cell.north, cell.east],
[50, 20, 50.5, 20.5],
);
assert.equal(cell.id, gnssCellKey(50.2, 20.1));
accumulateGnssObservations(store, [], 1200, { windowMs: 1000 });
assert.equal(store.size, 1);
assert.deepEqual(binGnssCells(store), []);
[cell] = binGnssCells(store);
assert.equal(cell.aircraft, 1, 'only a1, seen inside the window, remains');
assert.equal(cell.degraded, 0);
});
const MIN = 60_000;
@@ -396,22 +474,66 @@ test('rows without finite coordinates never key a cell', () => {
assert.equal(store.size, 0);
});
test('cells below the minimum aircraft count are withheld', () => {
test('every cell with an aircraft is shown, as on gpsjam.org; only the bad − 1 discount guards small samples', () => {
const store = new Map();
accumulateGnssObservations(
store,
[
{ hex: 'b1', lat: 10.1, lon: 10.1, degraded: true },
{ hex: 'b2', lat: 10.2, lon: 10.2, degraded: true },
],
[{ hex: 'b1', lat: 10.1, lon: 10.1, degraded: true }],
0,
);
assert.deepEqual(binGnssCells(store), []);
const [cell] = binGnssCells(store, { minAircraft: 2 });
let [cell] = binGnssCells(store);
assert.equal(cell.aircraft, 1);
assert.equal(cell.level, 'low', 'one bad aircraft is discounted');
assert.equal(cell.percentDegraded, 0);
accumulateGnssObservations(
store,
[{ hex: 'b2', lat: 10.12, lon: 10.12, degraded: true }],
0,
);
[cell] = binGnssCells(store);
assert.equal(cell.aircraft, 2);
assert.equal(cell.level, 'high');
assert.equal(cell.percentDegraded, 50);
});
test('the gpsjam bands are unchanged by the hex grid', () => {
assert.equal(GNSS_MEDIUM_PERCENT, 2);
assert.equal(GNSS_HIGH_PERCENT, 10);
// [total, bad] → level, at and either side of both band edges.
for (const [total, bad, level] of [
[100, 0, 'low'],
[100, 1, 'low'],
[100, 2, 'low'],
[100, 3, 'medium'],
[50, 2, 'medium'],
[100, 11, 'medium'],
[100, 12, 'high'],
[10, 2, 'medium'],
[10, 3, 'high'],
])
assert.equal(
gnssIntegrityLevel(total, bad).level,
level,
`${bad}/${total}`,
);
// Binned cells band the same way: 3 bad of 10 in one hexagon is high.
const store = new Map();
accumulateGnssObservations(
store,
Array.from({ length: 10 }, (_, index) => ({
hex: `h${index}`,
lat: 50.1,
lon: 19.9,
degraded: index < 3,
})),
0,
);
const [cell] = binGnssCells(store);
assert.equal(cell.id, '841e2e7ffffffff');
assert.equal(cell.level, 'high');
assert.equal(cell.percentDegraded, 20);
});
test('MLAT GPS-loss evidence uses the last good GNSS location and ignores MLAT NIC', () => {
const [row] = normalizeGnssAircraft({
ac: [