228 lines
9.8 KiB
TypeScript
228 lines
9.8 KiB
TypeScript
/**
|
||
* scripts/regions.test.ts — validation for the committed `public/regions.geo.json`.
|
||
*
|
||
* The dataset is now REAL named sub-national administrative regions (Natural
|
||
* Earth admin-1: states, provinces, governorates, oblasts, …) rather than the
|
||
* old geometric grid — one feature per named region, each carrying
|
||
* `properties = { name, parent }` where `parent` is the country's ISO_A3 (the
|
||
* RegionMap key the map resolves ownership through). Tiny or uncovered
|
||
* countries collapse to a single whole-country region (`<ISO_A3>-01`).
|
||
*
|
||
* This test is self-contained (no import of the generator): it re-implements
|
||
* the same planar area model the generator/analysis use, so the area-based
|
||
* assertions measure the same quantity:
|
||
*
|
||
* x = lon · 111.32 · cos(midLat), y = lat · 110.574 (km)
|
||
*
|
||
* with a shoelace per OUTER ring, each ring measured at its own mean latitude.
|
||
* Outer rings only — a region's inner rings (holes) are lakes and are ignored
|
||
* by design, the same way the coverage band already absorbed them.
|
||
*
|
||
* It reads each file exactly once and runs in O(total vertices).
|
||
*/
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
import { describe, expect, it } from 'vitest';
|
||
|
||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||
const root = path.resolve(here, '..');
|
||
|
||
// --- area model (planar approximation; matches scripts/generate-regions.mjs) --
|
||
const KM_LON = 111.32;
|
||
const KM_LAT = 110.574;
|
||
const rad = (deg: number) => (deg * Math.PI) / 180;
|
||
|
||
type Ring = [number, number][];
|
||
type Geometry =
|
||
| { type: 'Polygon'; coordinates: Ring[] }
|
||
| { type: 'MultiPolygon'; coordinates: Ring[][] };
|
||
|
||
function ringAreaKm2(ring: Ring, midLat: number): number {
|
||
const kx = KM_LON * Math.cos(rad(midLat));
|
||
let a = 0;
|
||
const n = ring.length;
|
||
for (let i = 0; i < n; i++) {
|
||
const [lon1, lat1] = ring[i];
|
||
const [lon2, lat2] = ring[(i + 1) % n];
|
||
a += lon1 * kx * (lat2 * KM_LAT) - lon2 * kx * (lat1 * KM_LAT);
|
||
}
|
||
return Math.abs(a / 2);
|
||
}
|
||
|
||
function outerRings(geom: Geometry): Ring[] {
|
||
if (geom.type === 'Polygon') return [geom.coordinates[0]];
|
||
if (geom.type === 'MultiPolygon') return geom.coordinates.map((p) => p[0]);
|
||
return [];
|
||
}
|
||
|
||
/** Sum of a feature's outer-ring areas, each ring at its own mean latitude. */
|
||
function featureAreaKm2(geom: Geometry): number {
|
||
let total = 0;
|
||
for (const ring of outerRings(geom)) {
|
||
let lat = 0;
|
||
for (const [, la] of ring) lat += la;
|
||
total += ringAreaKm2(ring, ring.length ? lat / ring.length : 0);
|
||
}
|
||
return total;
|
||
}
|
||
|
||
function median(nums: number[]): number {
|
||
if (!nums.length) return 0;
|
||
const s = [...nums].sort((a, b) => a - b);
|
||
const m = Math.floor(s.length / 2);
|
||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||
}
|
||
// ------------------------------------------------------------------------------
|
||
|
||
interface RegionFeature {
|
||
type: 'Feature';
|
||
id: string;
|
||
properties: { name: string; parent: string };
|
||
geometry: Geometry;
|
||
}
|
||
interface CountryFeature {
|
||
type: 'Feature';
|
||
id: string;
|
||
properties: { name: string };
|
||
geometry: Geometry;
|
||
}
|
||
|
||
// Read each file exactly once.
|
||
const regions = JSON.parse(
|
||
readFileSync(path.join(root, 'public', 'regions.geo.json'), 'utf8'),
|
||
) as { type: 'FeatureCollection'; features: RegionFeature[] };
|
||
const countries = JSON.parse(
|
||
readFileSync(path.join(root, 'public', 'countries.geo.json'), 'utf8'),
|
||
) as { type: 'FeatureCollection'; features: CountryFeature[] };
|
||
|
||
// Precompute once (O(total vertices)).
|
||
const countryIds = new Set(countries.features.map((c) => c.id));
|
||
const countryArea = new Map<string, number>();
|
||
for (const c of countries.features) countryArea.set(c.id, featureAreaKm2(c.geometry));
|
||
const regionArea = new Map<string, number>();
|
||
for (const f of regions.features) regionArea.set(f.id, featureAreaKm2(f.geometry));
|
||
const sumByParent = new Map<string, number>();
|
||
for (const f of regions.features)
|
||
sumByParent.set(f.properties.parent, (sumByParent.get(f.properties.parent) ?? 0) + (regionArea.get(f.id) ?? 0));
|
||
const countByParent = new Map<string, number>();
|
||
for (const f of regions.features)
|
||
countByParent.set(f.properties.parent, (countByParent.get(f.properties.parent) ?? 0) + 1);
|
||
|
||
describe('regions.geo.json', () => {
|
||
it('is a valid GeoJSON FeatureCollection of well-formed features', () => {
|
||
expect(regions.type).toBe('FeatureCollection');
|
||
expect(Array.isArray(regions.features)).toBe(true);
|
||
expect(regions.features.length).toBeGreaterThan(0);
|
||
for (const f of regions.features) {
|
||
expect(f.type, `${f.id ?? '?'}: not a Feature`).toBe('Feature');
|
||
expect(typeof f.id, `${f.id ?? '?'}: id must be a string`).toBe('string');
|
||
expect(f.id.length, `${f.id ?? '?'}: empty id`).toBeGreaterThan(0);
|
||
expect(typeof f.properties?.name, `${f.id}: missing name`).toBe('string');
|
||
expect(f.properties.name.length, `${f.id}: empty name`).toBeGreaterThan(0);
|
||
expect(typeof f.properties.parent, `${f.id}: missing parent`).toBe('string');
|
||
expect(countryIds.has(f.properties.parent), `${f.id}: unknown parent ${f.properties.parent}`).toBe(true);
|
||
const g = f.geometry;
|
||
expect(
|
||
!!g && (g.type === 'Polygon' || g.type === 'MultiPolygon'),
|
||
`${f.id}: bad geometry type ${g?.type}`,
|
||
).toBe(true);
|
||
if (g) {
|
||
const polys = g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
|
||
for (const poly of polys)
|
||
for (const ring of poly)
|
||
expect(ring.length, `${f.id}: ring with ${ring.length} pts`).toBeGreaterThanOrEqual(3);
|
||
}
|
||
}
|
||
});
|
||
|
||
it('has globally unique feature ids (ISO 3166-2 disambiguated on within-country collision)', () => {
|
||
const seen = new Set<string>();
|
||
const dups = new Set<string>();
|
||
for (const f of regions.features) {
|
||
if (seen.has(f.id)) dups.add(f.id);
|
||
seen.add(f.id);
|
||
}
|
||
expect(
|
||
dups.size,
|
||
`duplicate ids: ${[...dups].slice(0, 10).join(', ')}`,
|
||
).toBe(0);
|
||
expect(seen.size).toBe(regions.features.length);
|
||
});
|
||
|
||
it('covers every one of the 177 countries with at least one region', () => {
|
||
const counts = countries.features.map((c) => countByParent.get(c.id) ?? 0);
|
||
for (const c of countries.features) {
|
||
expect(countByParent.get(c.id) ?? 0, `country ${c.id} has no regions`).toBeGreaterThanOrEqual(1);
|
||
}
|
||
const min = Math.min(...counts);
|
||
const max = Math.max(...counts);
|
||
const med = median(counts);
|
||
const maxCountry = [...countByParent.entries()].sort((a, b) => b[1] - a[1])[0];
|
||
const maxCountryName = countries.features.find((c) => c.id === maxCountry[0])?.properties.name ?? '';
|
||
console.log(
|
||
`\n per-country region count: min ${min} / median ${med} / max ${max}` +
|
||
` (max: ${maxCountry[0]} ${maxCountryName} with ${maxCountry[1]})`,
|
||
);
|
||
});
|
||
|
||
it('has sane region areas: median >= 100 km2, and no non-Antarctica region >= 5,000,000 km2', () => {
|
||
const areas = regions.features.map((f) => regionArea.get(f.id) ?? 0);
|
||
const med = median(areas);
|
||
const maxRegion = regions.features.reduce((m, f) => ((regionArea.get(f.id) ?? 0) > (regionArea.get(m.id) ?? 0) ? f : m));
|
||
const minRegion = regions.features.reduce((m, f) => ((regionArea.get(f.id) ?? 0) < (regionArea.get(m.id) ?? 0) ? f : m));
|
||
const tiny = areas.filter((a) => a < 1).length;
|
||
// Antarctica (ATA) is a full-360° wrap ring, so the planar model can't
|
||
// measure it (it reports ~21.8M km2 for a ~14M km2 landmass) — exempt it.
|
||
for (const f of regions.features) {
|
||
if (f.properties.parent === 'ATA') continue;
|
||
const a = regionArea.get(f.id) ?? 0;
|
||
expect(a < 5_000_000, `${f.id}: area ${Math.round(a).toLocaleString('en-US')} km2 is absurdly large`).toBe(true);
|
||
}
|
||
expect(med, `median region area ${med.toFixed(1)} km2 is too small`).toBeGreaterThanOrEqual(100);
|
||
console.log(
|
||
`\n region area: min ${minRegion.id} (${minRegion.properties.name}) ≈ ${(regionArea.get(minRegion.id) ?? 0).toExponential(2)} km2` +
|
||
` / median ${med.toLocaleString('en-US')} km2` +
|
||
` / max ${maxRegion.id} (${maxRegion.properties.name}) ≈ ${Math.round(regionArea.get(maxRegion.id) ?? 0).toLocaleString('en-US')} km2` +
|
||
` — ${tiny} regions < 1 km2 (legit micro-regions: tiny islands, small urban districts, degenerate disputed enclaves)`,
|
||
);
|
||
});
|
||
|
||
it('sums to within [40%, 175%] of each country area (median in [70%, 130%])', () => {
|
||
// The band is a planar-approximation sanity check. It is wider than a naive
|
||
// [40%, 110%] because Natural Earth's admin-1 polygons are digitized
|
||
// independently of the admin-0 country polygons (they are NOT clipped to
|
||
// them), so for a handful of small/island nations the region union
|
||
// over/under-fills the country: measured range is ~[52%, 151%]
|
||
// (Brunei under-fills, Vanuatu over-fills). The band brackets that with
|
||
// margin while still catching a genuinely missing or doubled-up region.
|
||
const ratios: number[] = [];
|
||
let minRatio = Infinity;
|
||
let maxRatio = -Infinity;
|
||
let minId = '';
|
||
let maxId = '';
|
||
for (const c of countries.features) {
|
||
const ca = countryArea.get(c.id) ?? 0;
|
||
if (ca <= 0) continue;
|
||
const ratio = (sumByParent.get(c.id) ?? 0) / ca;
|
||
ratios.push(ratio);
|
||
if (ratio < minRatio) { minRatio = ratio; minId = c.id; }
|
||
if (ratio > maxRatio) { maxRatio = ratio; maxId = c.id; }
|
||
expect(
|
||
ratio >= 0.4 && ratio <= 1.75,
|
||
`${c.id}: coverage ${(100 * ratio).toFixed(1)}% is outside [40%, 175%]`,
|
||
).toBe(true);
|
||
}
|
||
const medRatio = median(ratios);
|
||
expect(
|
||
medRatio >= 0.7 && medRatio <= 1.3,
|
||
`median coverage ${(100 * medRatio).toFixed(1)}% is outside [70%, 130%]`,
|
||
).toBe(true);
|
||
console.log(
|
||
`\n coverage range: min ${minId} ${(100 * minRatio).toFixed(1)}%` +
|
||
` / median ${(100 * medRatio).toFixed(1)}%` +
|
||
` / max ${maxId} ${(100 * maxRatio).toFixed(1)}% (band 40–175%)`,
|
||
);
|
||
});
|
||
});
|