// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Reads GeoNames physical features (seas and undersea terrain, water, landforms, parks and vegetation) * and class `S` transit stations from a country dump and emits rows that label each feature's name as `venue`. * * A search for `Mariana Trench`, `Lake Tahoe, California`, or `Heathrow Airport` asks for a place that has a name * and no address. The corpus held no such rows before this source (#2897), so the parser had never read a bare * physical-feature name. Each feature renders bare and with its region where GeoNames records one, and one feature in * {@linkcode GEONAMES_FEATURES_WITH_COUNTRY_DIVISOR} also renders with its own country. * * The dump holds 5,076,239 physical features in 16,318 (country, feature code) cells on 2026-11-02, and 991,667 of them * are streams (feature code `STM`). A cell keeps at most {@linkcode GEONAMES_FEATURES_PER_CELL} features, chosen by the lowest hash of their * geonameid, so every feature code of every country is represented and no one class dominates. */ import { componentsPresentIn } from "@mailwoman/codex/address/format" import { hashFNV1a } from "@mailwoman/core/coarse-placer/fnv-hash" import { readUnquotedTSV } from "@mailwoman/core/fs/delimited" import { isDirectory } from "@mailwoman/core/fs/readers/stat" import { compareByScalarValue } from "@mailwoman/core/strings/compare" import { PathBuilder } from "path-ts" import { Globerator } from "spliterator/node/fs" import { GEONAMES_DEFAULT_LICENSE, GEONAMES_MAIN_COLUMNS as COL, loadAdmin1, loadCountries, } from "#adapters/geonames/adapter" import { type CapitalSeats, DualRoleBasis, dualRoleKey, type DualRolePair, dualRoleRowRule, readCapitalSeats, } from "#adapters/wof/admin/json/dual-role" import { SourceRegister } from "#registers" import { AddressRole, type AdapterOptions, type CanonicalRow, type CorpusAdapter, SurfaceOrigin } from "#types" /** * The source ID on rows from this adapter. */ export const GEONAMES_FEATURES_ADAPTER_ID = "geonames-features" /** * The GeoNames feature classes this adapter reads unconditionally: undersea (`U`), water (`H`), * terrain (`T`), parks and areas (`L`, which includes ports `PRT`) and vegetation (`V`). */ export const GEONAMES_FEATURE_CLASSES: ReadonlySet = new Set(["U", "H", "T", "L", "V"]) /** * The GeoNames transit feature codes this adapter admits from class `S` (spots/buildings/facilities): * airports (`AIRP`), rail stations (`RSTN`), metro stations (`MTRO`), bus stations (`BUSTN`), * ports (`PRT`, also present under class `L`), and ferries (`FY`). * * `packages/mailwoman/tools/training/outcomes/masks.ts` routes these codes to the `transit` * outcome reading using `geonames_transit_codes` in `packages/trainer/data/outcome_readings.json`. */ const GEONAMES_TRANSIT_FEATURE_CODES: ReadonlySet = new Set(["AIRP", "RSTN", "MTRO", "BUSTN", "PRT", "FY"]) function isSelectedGeonamesFeature(featureClass: string, featureCode: string): boolean { return ( GEONAMES_FEATURE_CLASSES.has(featureClass) || (featureClass === "S" && GEONAMES_TRANSIT_FEATURE_CODES.has(featureCode)) ) } /** * The most features one (country, feature code) cell contributes. * * At 25 the dump yields 176,158 features, about 528,000 rows, against 95,086 * features at 10 and 272,765 at 50. */ export const GEONAMES_FEATURES_PER_CELL = 25 /** * The divisor of the features that render with their country: a feature renders with it * when the hash of its geonameid is divisible by this value. * * `, ` is the shape of a locality query as well as a feature query, and the * corpus holds far fewer locality–country rows than this source writes feature–country rows. * With every feature rendered with its country, v0.8.11 held 171,416 `venue -> country` * base rows against 58,892 `locality -> country`, and models trained on it read * `Mount Washington, United States` as a venue. * * One in four brings the feature rows below the locality rows in all. * The bare and region renderings are unchanged. */ export const GEONAMES_FEATURES_WITH_COUNTRY_DIVISOR = 4 /** * Historical, abandoned, or destroyed populated-place feature codes skipped * when detecting dual-role regions. */ const NON_CURRENT_PPL = new Set(["PPLH", "PPLQ", "PPLW", "PPLCH"]) /** * GeoNames feature codes for national capitals and admin-1 seats. */ const ADMIN1_SEAT_CODES = new Set(["PPLC", "PPLA"]) /** * One feature the cap kept. */ interface KeptFeature { hash: number geonameid: string } /** * Result of pass 1 over one GeoNames dump: the capped feature IDs and the dual-role * `(country, admin1)` pairs whose homonymous city-region name stays out of `region` (#3504). */ interface ScannedDump { kept: Set dualRolePairs: DualRolePair[] } /** * Scans one GeoNames dump in a single pass to collect: * 1. The {@linkcode GEONAMES_FEATURES_PER_CELL} lowest-hashed feature geonameids * per `(country, featureCode)` cell. * 2. The dual-role admin-1 pairs where a current populated place in `(cc, admin1)` * shares the folded name of that admin-1 unit and is either a capital/admin-1 seat * or the unit's most populous locality. * When a country has no populated-place rows in the dump (as in features-only fixtures), * the committed capitals reference decides seats. */ async function scanDump( input: PathBuilder, country: string | undefined, admin1: ReadonlyMap, seats: CapitalSeats ): Promise { const cells = new Map() const countriesWithPPL = new Set() const largestByAdmin1 = new Map() const candidates: Array<{ admin1Key: string cc: string regionName: string localityID: number isSeat: boolean }> = [] for await (const rec of readUnquotedTSV(input)) { const cls = rec[COL.featureClass] ?? "" const code = (rec[COL.featureCode] ?? "").trim() const cc = (rec[COL.country] ?? "").trim() if (!cc || (country && cc !== country)) continue const geonameid = (rec[COL.geonameid] ?? "").trim() const name = (rec[COL.name] ?? "").trim() if (!geonameid || !name) continue if (cls === "P" && !NON_CURRENT_PPL.has(code)) { countriesWithPPL.add(cc) const admin1Code = (rec[COL.admin1] ?? "").trim() const admin1Key = `${cc}.${admin1Code}` const regionName = admin1.get(admin1Key) if (regionName) { const id = Number.parseInt(geonameid, 10) || 0 const population = Number.parseInt(rec[COL.population] ?? "0", 10) || 0 const prev = largestByAdmin1.get(admin1Key) if ( population > 0 && (!prev || population > prev.population || (population === prev.population && id < prev.id)) ) { largestByAdmin1.set(admin1Key, { id, population }) } const regionFolded = dualRoleKey(regionName) const asciiName = (rec[COL.asciiname] ?? "").trim() if (dualRoleKey(name) === regionFolded || (asciiName && dualRoleKey(asciiName) === regionFolded)) { const isSeat = ADMIN1_SEAT_CODES.has(code) || seats.has(`${cc}|${regionFolded}`) candidates.push({ admin1Key, cc, regionName, localityID: id, isSeat }) } } } if (!isSelectedGeonamesFeature(cls, code)) continue const key = `${cc}\t${code}` const kept = cells.get(key) ?? [] const hash = hashFNV1a(geonameid) if (kept.length < GEONAMES_FEATURES_PER_CELL) { kept.push({ hash, geonameid }) cells.set(key, kept) } else { let highest = 0 for (let i = 1; i < kept.length; i++) if (kept[i]!.hash > kept[highest]!.hash) { highest = i } if (hash < kept[highest]!.hash) { kept[highest] = { hash, geonameid } } } } const pairsByRegion = new Map() for (const candidate of candidates) { const basis = candidate.isSeat ? DualRoleBasis.seat : largestByAdmin1.get(candidate.admin1Key)?.id === candidate.localityID ? DualRoleBasis.largest : null if (basis && !pairsByRegion.has(candidate.admin1Key)) { pairsByRegion.set(candidate.admin1Key, { regionID: 0, localityID: candidate.localityID, country: candidate.cc, name: candidate.regionName, basis, }) } } // Fallback for features-only dumps that omit populated-place rows: check admin1 names against the capitals reference. for (const [admin1Key, regionName] of admin1) { const cc = admin1Key.split(".")[0] ?? "" if (!cc || (country && cc !== country) || countriesWithPPL.has(cc) || pairsByRegion.has(admin1Key)) continue if (seats.has(`${cc}|${dualRoleKey(regionName)}`)) { pairsByRegion.set(admin1Key, { regionID: 0, localityID: 0, country: cc, name: regionName, basis: DualRoleBasis.seat, }) } } return { kept: new Set([...cells.values()].flatMap((kept) => kept.map((feature) => feature.geonameid))), dualRolePairs: [...pairsByRegion.values()], } } /** * Creates the GeoNames physical-feature adapter. */ export function createGeonamesFeaturesAdapter(): CorpusAdapter { return { id: GEONAMES_FEATURES_ADAPTER_ID, defaultLicense: GEONAMES_DEFAULT_LICENSE, // A natural feature is no premise, office or facility, and it stays out of the premise street index. addressRole: AddressRole.Other, register: SourceRegister.GeoNames, surface: SurfaceOrigin.Rendered, description: "GeoNames physical and transit features (CC-BY-4.0): seas, undersea terrain, water bodies, landforms, parks, forests, and transit hubs (airports, rail/metro/bus stations, ports, ferries), labeled as venue.", async *rows(opts: AdapterOptions): AsyncIterable { // The input is one dump (`allCountries.txt`) or a directory of country dumps (`US.txt`, `MP.txt`). const input = PathBuilder.from(opts.inputPath) const inputIsDirectory = await isDirectory(input) const dir = inputIsDirectory ? input : input.dirname() const dumps = inputIsDirectory ? ( await Globerator.from(opts.country ? `${opts.country}.txt` : "[A-Z][A-Z].txt", { cwd: input.toString(), }).toArray() ) .toSorted(compareByScalarValue) .map((name: string) => input(name)) : [input] const [admin1, countries, seats] = await Promise.all([loadAdmin1(dir), loadCountries(dir), readCapitalSeats()]) let emitted = 0 for (const dump of dumps) { yield* rowsOf(dump) } async function* rowsOf(dump: PathBuilder): AsyncIterable { const { kept, dualRolePairs } = await scanDump(dump, opts.country, admin1, seats) const dualRole = dualRoleRowRule(GEONAMES_FEATURES_ADAPTER_ID, dualRolePairs) for await (const rec of readUnquotedTSV(dump)) { if (opts.signal?.aborted) break if (typeof opts.limit === "number" && emitted >= opts.limit) break const geonameid = (rec[COL.geonameid] ?? "").trim() if (!kept.has(geonameid)) continue const cc = (rec[COL.country] ?? "").trim() const venue = (rec[COL.name] ?? "").trim() const region = admin1.get(`${cc}.${(rec[COL.admin1] ?? "").trim()}`) const country = countries.get(cc) const variants: Array<{ slot: string; comp: CanonicalRow["components"]; raw: string }> = [ { slot: "v", comp: { venue }, raw: venue }, ] if (country && hashFNV1a(`${geonameid}:vc`) % GEONAMES_FEATURES_WITH_COUNTRY_DIVISOR === 0) { variants.push({ slot: "vc", comp: { venue, country }, raw: `${venue}, ${country}` }) } if (region && region !== venue) { variants.push({ slot: "vr", comp: { venue, region }, raw: `${venue}, ${region}` }) } for (const variant of variants) { if (typeof opts.limit === "number" && emitted >= opts.limit) break const aligned = componentsPresentIn(variant.comp, variant.raw) if (!aligned.venue) continue const row: CanonicalRow = { raw: variant.raw, components: aligned, country: cc, source: GEONAMES_FEATURES_ADAPTER_ID, source_id: `${GEONAMES_FEATURES_ADAPTER_ID}-${geonameid}-${variant.slot}`, license: GEONAMES_DEFAULT_LICENSE, } if (dualRole.drops(row)) continue yield row emitted++ } } } }, } } /** * The adapter instance registered with the corpus builder. */ export const geonamesFeaturesAdapter = createGeonamesFeaturesAdapter()