// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The United States' house-venue tuples, sampled from the admitted rows of the per-state situs databases. */ import { dataRootPath } from "@mailwoman/core/data-root" import type { SeededRandom } from "@mailwoman/core/math/random" import { compareByScalarValue } from "@mailwoman/core/strings/compare" import { capitalize, splitWhitespace } from "@mailwoman/core/strings/unicode" import { basename, type PathBuilderLike } from "path-ts" import { Globerator } from "spliterator/node/fs" import { sampleAddressPoints } from "#recipes/address-points" import type { HouseVenueTuple } from "#recipes/house/venue/tuples" import { type RegisterDecisions, registerSourcePermitsTraining } from "#source-register/corpus-inputs" import { readAddressSourceRegister } from "#source-register/register" import { readUSSitusSources, usSitusSourcesPath } from "#us/address-records/rights" /** * The directory holding one database per state, `address-points-us-.db`. */ export function usSitusDirectory() { return dataRootPath("db", "address-points") } const SITUS_PREFIX = "address-points-us-" /** * Probes per requested row. * * A state whose admitted rows are a few percent of its table needs dozens of probes per kept row. */ export const US_SITUS_PROBE_BUDGET = 512 /** * The situs `source` values whose every register row holds a decision permitting transform and train. * * A value the table doesn't map, such as the bare `openaddresses` of the Hawaii database, isn't admitted. * * @throws When the table doesn't exist, naming it. */ export async function admittedSitusSources( register?: RegisterDecisions, path: PathBuilderLike = usSitusSourcesPath() ): Promise> { const table = await readUSSitusSources(path) const registerFile = register ?? (await readAddressSourceRegister()) return new Set( Object.entries(table) .filter(([, rows]) => rows.length > 0 && rows.every((row) => registerSourcePermitsTraining(registerFile, row))) .map(([source]) => source) ) } /** * The state code after `address-points-us-`, ignoring a county suffix such as `il-cook`. */ export function situsStateCode(path: string): string { return basename(path).replace(/\.db$/u, "").slice(SITUS_PREFIX.length).split("-", 1)[0]!.toUpperCase() } const titleCase = (text: string): string => splitWhitespace(text).map(capitalize).join(" ") /** * The state databases in `directory`, in code-point order of their paths. * * @throws When `directory` holds none, naming it, because an empty sample * would read as a country with no rows. */ export async function listSitusDatabases(directory: PathBuilderLike = usSitusDirectory()): Promise { const found: string[] = await Globerator.from(`${SITUS_PREFIX}*.db`, { cwd: directory.toString(), absolute: true, }).toArray() if (!found.length) throw new Error(`No ${SITUS_PREFIX}*.db database in ${directory.toString()}`) return found.toSorted(compareByScalarValue) } /** * Up to `count` tuples across states rather than from one. * * The state databases differ by orders of magnitude in size, so the budget is * split evenly and the state order is shuffled. * A state holding fewer admitted rows than its share passes the shortfall to the states after it. */ export async function sampleUSHouseVenueTuples( count: number, rng: SeededRandom, directory: PathBuilderLike = usSitusDirectory() ): Promise { const stateDatabases = await listSitusDatabases(directory) const admitted = await admittedSitusSources() rng.shuffle(stateDatabases) const tuples: HouseVenueTuple[] = [] for (const [index, path] of stateDatabases.entries()) { if (tuples.length >= count) break const remaining = count - tuples.length const perState = Math.max(1, Math.ceil(remaining / (stateDatabases.length - index))) const state = situsStateCode(path) const sampled = await sampleAddressPoints(path, perState, rng, { sources: admitted, probeBudget: US_SITUS_PROBE_BUDGET, }) for (const [street, number, postcode, locality] of sampled) { if (tuples.length >= count) break tuples.push({ locality: titleCase(locality), region: state, postcode, country: "US", street: titleCase(street), houseNumber: number, }) } } return tuples }