@mailwoman/resolver-wof-sqlite 11.4.0 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/build/candidate.ts +186 -0
- package/lib/build/population-corrections.ts +11 -2
- package/lib/candidate/lookup.ts +159 -15
- package/lib/candidate/name-roles.ts +112 -6
- package/lib/candidate/outcomes.ts +191 -0
- package/lib/candidate/schema.ts +67 -3
- package/lib/geonames/aliases.ts +39 -1
- package/lib/labels/street/normalize.ts +2 -1
- package/lib/landmark.ts +51 -4
- package/lib/lookup/types.ts +25 -0
- package/lib/outcome/memberships.ts +131 -0
- package/lib/outcome/schema.ts +147 -0
- package/lib/poi/schema.ts +2 -1
- package/lib/ranking/primary-preference.ts +14 -6
- package/out/build/candidate.d.ts +41 -0
- package/out/build/candidate.d.ts.map +1 -1
- package/out/build/candidate.js +84 -1
- package/out/build/candidate.js.map +1 -1
- package/out/build/population-corrections.d.ts +2 -2
- package/out/build/population-corrections.d.ts.map +1 -1
- package/out/build/population-corrections.js +10 -2
- package/out/build/population-corrections.js.map +1 -1
- package/out/candidate/lookup.d.ts +14 -3
- package/out/candidate/lookup.d.ts.map +1 -1
- package/out/candidate/lookup.js +101 -9
- package/out/candidate/lookup.js.map +1 -1
- package/out/candidate/name-roles.d.ts +3 -2
- package/out/candidate/name-roles.d.ts.map +1 -1
- package/out/candidate/name-roles.js +75 -5
- package/out/candidate/name-roles.js.map +1 -1
- package/out/candidate/outcomes.d.ts +57 -0
- package/out/candidate/outcomes.d.ts.map +1 -0
- package/out/candidate/outcomes.js +109 -0
- package/out/candidate/outcomes.js.map +1 -0
- package/out/candidate/schema.d.ts +45 -3
- package/out/candidate/schema.d.ts.map +1 -1
- package/out/candidate/schema.js +34 -0
- package/out/candidate/schema.js.map +1 -1
- package/out/geonames/aliases.d.ts +10 -0
- package/out/geonames/aliases.d.ts.map +1 -1
- package/out/geonames/aliases.js +33 -1
- package/out/geonames/aliases.js.map +1 -1
- package/out/labels/street/normalize.d.ts.map +1 -1
- package/out/labels/street/normalize.js +1 -1
- package/out/labels/street/normalize.js.map +1 -1
- package/out/landmark.d.ts +15 -3
- package/out/landmark.d.ts.map +1 -1
- package/out/landmark.js +38 -3
- package/out/landmark.js.map +1 -1
- package/out/lookup/types.d.ts +21 -0
- package/out/lookup/types.d.ts.map +1 -1
- package/out/outcome/memberships.d.ts +58 -0
- package/out/outcome/memberships.d.ts.map +1 -0
- package/out/outcome/memberships.js +83 -0
- package/out/outcome/memberships.js.map +1 -0
- package/out/outcome/schema.d.ts +74 -0
- package/out/outcome/schema.d.ts.map +1 -0
- package/out/outcome/schema.js +63 -0
- package/out/outcome/schema.js.map +1 -0
- package/out/poi/schema.d.ts +2 -1
- package/out/poi/schema.d.ts.map +1 -1
- package/out/poi/schema.js.map +1 -1
- package/out/ranking/primary-preference.d.ts +9 -5
- package/out/ranking/primary-preference.d.ts.map +1 -1
- package/out/ranking/primary-preference.js +11 -3
- package/out/ranking/primary-preference.js.map +1 -1
- package/package.json +15 -15
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { isOfficialLanguage } from "@mailwoman/codex/country"
|
|
9
|
+
import { COUNTRY_WRITTEN_SCRIPTS } from "@mailwoman/codex/country/writing-systems"
|
|
9
10
|
import type { DatabaseClient } from "@mailwoman/sqlite/client"
|
|
10
11
|
import { tableExists } from "@mailwoman/sqlite/introspection"
|
|
11
12
|
|
|
@@ -37,9 +38,56 @@ export const GLOSS_EXCLUDED_PLACETYPES: ReadonlySet<string> = new Set([
|
|
|
37
38
|
"county",
|
|
38
39
|
])
|
|
39
40
|
|
|
41
|
+
const NON_ASCII = /\P{ASCII}/u
|
|
42
|
+
|
|
43
|
+
const foreignScriptRegexCache = new Map<string, RegExp | null>()
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Compiles a Unicode set-subtraction regex matching any letter whose script is neither
|
|
47
|
+
* Common/Inherited, Latin (`Latn`), nor one of `country`'s written scripts.
|
|
48
|
+
*
|
|
49
|
+
* Returns `null` when `COUNTRY_WRITTEN_SCRIPTS` has no entry for `country`.
|
|
50
|
+
*/
|
|
51
|
+
function foreignScriptPatternFor(country: string): RegExp | null {
|
|
52
|
+
const cached = foreignScriptRegexCache.get(country)
|
|
53
|
+
|
|
54
|
+
if (cached !== undefined) return cached
|
|
55
|
+
|
|
56
|
+
const written = COUNTRY_WRITTEN_SCRIPTS[country]
|
|
57
|
+
|
|
58
|
+
if (!written?.length) {
|
|
59
|
+
foreignScriptRegexCache.set(country, null)
|
|
60
|
+
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const allowed = new Set<string>(["Latn", ...written])
|
|
65
|
+
const allowedClass = [...allowed].map((script) => `\\p{sc=${script}}`).join("")
|
|
66
|
+
const pattern = new RegExp(`[\\p{L}--[\\p{sc=Common}\\p{sc=Inherited}${allowedClass}]]`, "v")
|
|
67
|
+
|
|
68
|
+
foreignScriptRegexCache.set(country, pattern)
|
|
69
|
+
|
|
70
|
+
return pattern
|
|
71
|
+
}
|
|
72
|
+
|
|
40
73
|
/**
|
|
41
|
-
*
|
|
42
|
-
*
|
|
74
|
+
* Reports whether `nameKey` contains a non-Latin letter in a script outside `country`'s
|
|
75
|
+
* national and regional written scripts (`COUNTRY_WRITTEN_SCRIPTS`).
|
|
76
|
+
*
|
|
77
|
+
* Latin (`Latn`) is always exempt as the global romanization script, so `moskva` on `RU`,
|
|
78
|
+
* `peking` on `CN`, and `tokio` on `JP` return `false`.
|
|
79
|
+
*/
|
|
80
|
+
function isForeignScriptNameKey(nameKey: string, country: string): boolean {
|
|
81
|
+
if (!NON_ASCII.test(nameKey)) return false
|
|
82
|
+
|
|
83
|
+
const pattern = foreignScriptPatternFor(country)
|
|
84
|
+
|
|
85
|
+
return pattern !== null && pattern.test(nameKey)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Stamp `name_role` on non-primary rows: `abbr` by provenance, `foreign-script` by non-Latin script
|
|
90
|
+
* outside `COUNTRY_WRITTEN_SCRIPTS`, `variant` by own-name verdict, then `gloss` by key-volume anomaly.
|
|
43
91
|
*
|
|
44
92
|
* @returns The stamp counts plus the census the prototype exists to report:
|
|
45
93
|
* how much of the ≥-threshold key tail has any role.
|
|
@@ -53,7 +101,14 @@ export function stampNameRoles(ctx: {
|
|
|
53
101
|
ptcodes: Map<string, number>
|
|
54
102
|
ccodes: Map<string, number>
|
|
55
103
|
progress: (phase: string, message: string) => void
|
|
56
|
-
}): {
|
|
104
|
+
}): {
|
|
105
|
+
roleGloss: number
|
|
106
|
+
roleAbbr: number
|
|
107
|
+
roleVariant: number
|
|
108
|
+
roleForeignScript: number
|
|
109
|
+
keyTailPlaces: number
|
|
110
|
+
keyTailWithRole: number
|
|
111
|
+
} {
|
|
57
112
|
const { src, out, attrs, keyCounts, glossThreshold, progress } = ctx
|
|
58
113
|
progress("roles", "stamping name roles (gloss anomaly + abbr provenance)")
|
|
59
114
|
|
|
@@ -116,7 +171,8 @@ export function stampNameRoles(ctx: {
|
|
|
116
171
|
progress("roles", "source carries no `names` table — abbr detector skipped (gloss still runs)")
|
|
117
172
|
}
|
|
118
173
|
|
|
119
|
-
// Stamp order is precedence: abbr first, then
|
|
174
|
+
// Stamp order is precedence: abbr first, then foreign-script, then the own-name
|
|
175
|
+
// variant verdict, then gloss fills what none of them claimed.
|
|
120
176
|
const roleAbbr = Number(
|
|
121
177
|
out
|
|
122
178
|
.prepare(
|
|
@@ -127,6 +183,55 @@ export function stampNameRoles(ctx: {
|
|
|
127
183
|
.run().changes
|
|
128
184
|
)
|
|
129
185
|
|
|
186
|
+
// Runs before variant and gloss so Cyrillic exonyms on Latin-script namesakes
|
|
187
|
+
// (such as `одесса` on Odessa, US or `лондон` on London, CA) receive `foreign-script` rather
|
|
188
|
+
// than `variant` (whose Cyrillic romanizer would otherwise match their primary name), and so
|
|
189
|
+
// zero-population hamlets with scraped non-Latin exonyms receive `foreign-script` rather than `gloss`.
|
|
190
|
+
// Latin romanizations (`brest` on `Брэст`, `moskva` on `Москва`) and home-script spelling
|
|
191
|
+
// variants (`харків` on `Харьков` in `UA`) stay unstamped here and proceed to `variant`.
|
|
192
|
+
out.exec(
|
|
193
|
+
"CREATE TEMP TABLE foreign_script_key (spr_id INTEGER NOT NULL, name_key TEXT NOT NULL, PRIMARY KEY (spr_id, name_key)) WITHOUT ROWID"
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
const insForeignScriptKey = out.prepare("INSERT OR IGNORE INTO foreign_script_key VALUES (?, ?)")
|
|
197
|
+
let foreignScriptScanned = 0
|
|
198
|
+
|
|
199
|
+
out.exec("BEGIN")
|
|
200
|
+
|
|
201
|
+
for (const r of out
|
|
202
|
+
.prepare("SELECT DISTINCT spr_id, name_key FROM cand_stage WHERE is_primary = 0 AND name_role IS NULL")
|
|
203
|
+
.iterate()) {
|
|
204
|
+
foreignScriptScanned++
|
|
205
|
+
const a = attrs.get(Number(r.spr_id))
|
|
206
|
+
|
|
207
|
+
if (!a) continue
|
|
208
|
+
const iso2 = iso2ByCID.get(a.cid) ?? "??"
|
|
209
|
+
const nameKey = String(r.name_key)
|
|
210
|
+
|
|
211
|
+
if (isForeignScriptNameKey(nameKey, iso2)) {
|
|
212
|
+
insForeignScriptKey.run(Number(r.spr_id), nameKey)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
out.exec("COMMIT")
|
|
217
|
+
|
|
218
|
+
const roleForeignScript = Number(
|
|
219
|
+
out
|
|
220
|
+
.prepare(
|
|
221
|
+
`UPDATE cand_stage SET name_role = 'foreign-script'
|
|
222
|
+
WHERE is_primary = 0 AND name_role IS NULL AND EXISTS (
|
|
223
|
+
SELECT 1 FROM foreign_script_key fsk WHERE fsk.spr_id = cand_stage.spr_id AND fsk.name_key = cand_stage.name_key)`
|
|
224
|
+
)
|
|
225
|
+
.run().changes
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
out.exec("DROP TABLE foreign_script_key")
|
|
229
|
+
|
|
230
|
+
progress(
|
|
231
|
+
"roles",
|
|
232
|
+
`foreign-script: ${roleForeignScript.toLocaleString()} of ${foreignScriptScanned.toLocaleString()} unstamped alias keys use a non-Latin foreign script`
|
|
233
|
+
)
|
|
234
|
+
|
|
130
235
|
// Runs before gloss so the place's own name remains its source name.
|
|
131
236
|
// An uncovered script answers no-verdict.
|
|
132
237
|
out.exec(
|
|
@@ -212,9 +317,10 @@ export function stampNameRoles(ctx: {
|
|
|
212
317
|
|
|
213
318
|
progress(
|
|
214
319
|
"roles",
|
|
215
|
-
`${roleAbbr.toLocaleString()} abbr + ${
|
|
320
|
+
`${roleAbbr.toLocaleString()} abbr + ${roleForeignScript.toLocaleString()} foreign-script + ` +
|
|
321
|
+
`${roleVariant.toLocaleString()} variant + ${roleGloss.toLocaleString()} gloss rows stamped; ` +
|
|
216
322
|
`key tail (>= ${glossThreshold} keys): ${keyTailWithRole.toLocaleString()} of ${keyTailPlaces.toLocaleString()} places carry a role`
|
|
217
323
|
)
|
|
218
324
|
|
|
219
|
-
return { roleGloss, roleAbbr, roleVariant, keyTailPlaces, keyTailWithRole }
|
|
325
|
+
return { roleGloss, roleAbbr, roleVariant, roleForeignScript, keyTailPlaces, keyTailWithRole }
|
|
220
326
|
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compiles the candidate database's outcome tables from one pinned revision of the definitions.
|
|
6
|
+
*
|
|
7
|
+
* `outcome_default` holds every placetype default of the spec.
|
|
8
|
+
* `record_outcome` holds the assertions GeoNames feature codes make beyond a record's defaults.
|
|
9
|
+
*
|
|
10
|
+
* A record's feature code is read from the GeoNames per-country dumps, through the GeoNames
|
|
11
|
+
* range id of a place the GeoNames step added, or a record's `gn:id` concordance.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readUnquotedTSV } from "@mailwoman/core/fs/delimited"
|
|
15
|
+
import { GEONAMES_ID_BASE, GEONAMES_POSTAL_ID_BASE } from "@mailwoman/core/resolver/synthetic-id-ranges"
|
|
16
|
+
import { createOutcomeEvidenceTable } from "@mailwoman/gazetteer/whosonfirst/outcomes/evidence"
|
|
17
|
+
import type { CompiledOutcomeSpec, OutcomeSpecPin } from "@mailwoman/gazetteer/whosonfirst/outcomes/spec"
|
|
18
|
+
import type { DatabaseClient } from "@mailwoman/sqlite/client"
|
|
19
|
+
import { resolvePath, type PathBuilderLike } from "path-ts"
|
|
20
|
+
import { Globerator } from "spliterator/node/fs"
|
|
21
|
+
|
|
22
|
+
import type { PlaceAttrs } from "#candidate/place-attrs"
|
|
23
|
+
import { type OutcomeDatabase, writeOutcomeDefaults } from "#outcome/schema"
|
|
24
|
+
import type { WOFDatabase } from "#schema"
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The outcome inputs of a candidate build.
|
|
28
|
+
*/
|
|
29
|
+
export interface CandidateOutcomeInputs {
|
|
30
|
+
spec: CompiledOutcomeSpec
|
|
31
|
+
pin: OutcomeSpecPin
|
|
32
|
+
/**
|
|
33
|
+
* The GeoNames per-country dump directory, `<CC>.txt` files.
|
|
34
|
+
*/
|
|
35
|
+
geonamesDir: PathBuilderLike
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Counts from {@link stageCandidateOutcomes}.
|
|
40
|
+
*/
|
|
41
|
+
export interface CandidateOutcomeResult {
|
|
42
|
+
defaultRows: number
|
|
43
|
+
/**
|
|
44
|
+
* `record_outcome` rows, one per explicit assertion.
|
|
45
|
+
*/
|
|
46
|
+
recordRows: number
|
|
47
|
+
/**
|
|
48
|
+
* Records with one `record_outcome` row or more.
|
|
49
|
+
*/
|
|
50
|
+
recordsAsserted: number
|
|
51
|
+
contestedRows: number
|
|
52
|
+
/**
|
|
53
|
+
* Records whose GeoNames feature code the dumps gave.
|
|
54
|
+
*/
|
|
55
|
+
recordsWithFeatureCode: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isGeonamesPlaceID(id: number): boolean {
|
|
59
|
+
return id >= GEONAMES_ID_BASE && id < GEONAMES_POSTAL_ID_BASE
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Write the outcome tables into a candidate build in progress.
|
|
64
|
+
*
|
|
65
|
+
* @throws When a place the GeoNames step added has no row in the dumps, because its
|
|
66
|
+
* type field is then unmapped and the build would write an empty set for it.
|
|
67
|
+
*/
|
|
68
|
+
export async function stageCandidateOutcomes(options: {
|
|
69
|
+
src: DatabaseClient<WOFDatabase>
|
|
70
|
+
out: DatabaseClient<OutcomeDatabase>
|
|
71
|
+
/**
|
|
72
|
+
* Each candidate place's attributes, by record id.
|
|
73
|
+
*/
|
|
74
|
+
attrs: ReadonlyMap<number, Pick<PlaceAttrs, "ptid">>
|
|
75
|
+
/**
|
|
76
|
+
* The placetype dictionary, from name to id.
|
|
77
|
+
*/
|
|
78
|
+
ptcodes: ReadonlyMap<string, number>
|
|
79
|
+
inputs: CandidateOutcomeInputs
|
|
80
|
+
progress: (phase: string, message: string) => void
|
|
81
|
+
}): Promise<CandidateOutcomeResult> {
|
|
82
|
+
const { src, out, inputs, progress } = options
|
|
83
|
+
const placetypeNames = new Map([...options.ptcodes].map(([placetype, id]) => [id, placetype]))
|
|
84
|
+
const placetypeOf = new Map([...options.attrs].map(([sid, a]) => [sid, placetypeNames.get(a.ptid) ?? ""]))
|
|
85
|
+
const table = createOutcomeEvidenceTable(inputs.spec)
|
|
86
|
+
|
|
87
|
+
const defaultRows = await writeOutcomeDefaults(out, inputs.spec, inputs.pin)
|
|
88
|
+
|
|
89
|
+
// Each GeoNames number, mapped to the candidate places whose id or concordance holds it.
|
|
90
|
+
const sprOf = new Map<number, number[]>()
|
|
91
|
+
const geonamesPlaces = new Set<number>()
|
|
92
|
+
|
|
93
|
+
const link = (geonameid: number, sprID: number) => {
|
|
94
|
+
const ids = sprOf.get(geonameid)
|
|
95
|
+
|
|
96
|
+
if (ids) {
|
|
97
|
+
if (!ids.includes(sprID)) {
|
|
98
|
+
ids.push(sprID)
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
sprOf.set(geonameid, [sprID])
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
for (const sprID of placetypeOf.keys()) {
|
|
106
|
+
if (isGeonamesPlaceID(sprID)) {
|
|
107
|
+
geonamesPlaces.add(sprID)
|
|
108
|
+
link(sprID - GEONAMES_ID_BASE, sprID)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
for (const row of src.prepare("SELECT id, other_id FROM concordances WHERE other_source = 'gn:id'").iterate()) {
|
|
113
|
+
const sprID = Number(row.id)
|
|
114
|
+
const geonameid = Number(row.other_id)
|
|
115
|
+
|
|
116
|
+
if (placetypeOf.has(sprID) && Number.isSafeInteger(geonameid) && geonameid > 0) {
|
|
117
|
+
link(geonameid, sprID)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
progress("outcomes", `${sprOf.size.toLocaleString()} GeoNames numbers on candidate places; reading feature codes`)
|
|
122
|
+
|
|
123
|
+
const assertionsOf = new Map<number, ReturnType<typeof table.assertionsFor>>()
|
|
124
|
+
const coded = new Set<number>()
|
|
125
|
+
|
|
126
|
+
for await (const path of Globerator.from("[A-Z][A-Z].txt", {
|
|
127
|
+
cwd: resolvePath(inputs.geonamesDir),
|
|
128
|
+
absolute: true,
|
|
129
|
+
})) {
|
|
130
|
+
for await (const f of readUnquotedTSV(path)) {
|
|
131
|
+
const ids = sprOf.get(Number(f[0]))
|
|
132
|
+
|
|
133
|
+
if (!ids) continue
|
|
134
|
+
|
|
135
|
+
const assertions = table.assertionsFor("geonames", `${f[6]}.${f[7]}`)
|
|
136
|
+
|
|
137
|
+
for (const sprID of ids) {
|
|
138
|
+
coded.add(sprID)
|
|
139
|
+
|
|
140
|
+
if (assertions.length) {
|
|
141
|
+
assertionsOf.set(sprID, [...(assertionsOf.get(sprID) ?? []), ...assertions])
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const uncoded = [...geonamesPlaces].filter((id) => !coded.has(id))
|
|
148
|
+
|
|
149
|
+
if (uncoded.length) {
|
|
150
|
+
throw new Error(
|
|
151
|
+
`${uncoded.length.toLocaleString()} places the GeoNames step added have no row in ${inputs.geonamesDir.toString()}, ` +
|
|
152
|
+
`so their feature code is unknown; first ${uncoded.slice(0, 5).join(", ")}.`
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const insert = out.prepare("INSERT INTO record_outcome (spr_id, outcome_id, contested) VALUES (?, ?, ?)")
|
|
157
|
+
let recordRows = 0
|
|
158
|
+
let contestedRows = 0
|
|
159
|
+
let recordsAsserted = 0
|
|
160
|
+
|
|
161
|
+
out.exec("BEGIN")
|
|
162
|
+
|
|
163
|
+
for (const [sprID, assertions] of assertionsOf) {
|
|
164
|
+
const rows = table.recordRows(placetypeOf.get(sprID) ?? null, assertions)
|
|
165
|
+
|
|
166
|
+
for (const row of rows) {
|
|
167
|
+
insert.run(sprID, row.outcomeID, row.contested ? 1 : 0)
|
|
168
|
+
|
|
169
|
+
if (row.contested) {
|
|
170
|
+
contestedRows++
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
recordRows += rows.length
|
|
175
|
+
|
|
176
|
+
if (rows.length) {
|
|
177
|
+
recordsAsserted++
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
out.exec("COMMIT")
|
|
182
|
+
|
|
183
|
+
progress(
|
|
184
|
+
"outcomes",
|
|
185
|
+
`${defaultRows} placetype defaults; ${recordRows.toLocaleString()} assertions on ` +
|
|
186
|
+
`${recordsAsserted.toLocaleString()} records (${contestedRows.toLocaleString()} contested); ` +
|
|
187
|
+
`${coded.size.toLocaleString()} records carry a feature code`
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
return { defaultRows, recordRows, recordsAsserted, contestedRows, recordsWithFeatureCode: coded.size }
|
|
191
|
+
}
|
package/lib/candidate/schema.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { sql, type Kysely } from "kysely"
|
|
|
6
6
|
import type { CandidateAncestorsDatabase } from "#candidate/ancestors/schema"
|
|
7
7
|
import type { CapitalTable } from "#candidate/capital-schema"
|
|
8
8
|
import type { NameKey } from "#labels/street/normalize"
|
|
9
|
+
import type { OutcomeDatabase } from "#outcome/schema"
|
|
9
10
|
import type { OvertureWOFMatchTable } from "#schema/overture-match"
|
|
10
11
|
|
|
11
12
|
/**
|
|
@@ -60,9 +61,8 @@ export interface CandidateTable {
|
|
|
60
61
|
*/
|
|
61
62
|
importance: number | null
|
|
62
63
|
/**
|
|
63
|
-
* The name's detected role on this row (`'abbr'`, `'
|
|
64
|
+
* The name's detected role on this row (`'abbr'`, `'foreign-script'`, `'variant'` or `'gloss'`),
|
|
64
65
|
* or NULL when no role was detected.
|
|
65
|
-
* The column is write-only in this build generation.
|
|
66
66
|
*/
|
|
67
67
|
name_role: string | null
|
|
68
68
|
}
|
|
@@ -83,11 +83,39 @@ export interface PlacetypeCodeTable {
|
|
|
83
83
|
placetype: string
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Wikidata concordance row copied from the source admin database (`other_source = 'wd:id'`).
|
|
88
|
+
*/
|
|
89
|
+
export interface CandidateConcordanceTable {
|
|
90
|
+
id: number
|
|
91
|
+
other_source: string
|
|
92
|
+
other_id: string
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Per-candidate Wikipedia sitelink count joined from Wikidata / landmarks via `wd:id`,
|
|
97
|
+
* providing cross-layer prominence `log10(sitelinks + 1)`.
|
|
98
|
+
*/
|
|
99
|
+
export interface CandidateSitelinksTable {
|
|
100
|
+
spr_id: number
|
|
101
|
+
sitelinks: number
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Table name for {@link CandidateConcordanceTable}.
|
|
106
|
+
*/
|
|
107
|
+
export const CANDIDATE_CONCORDANCES_TABLE = "concordances"
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Table name for {@link CandidateSitelinksTable}.
|
|
111
|
+
*/
|
|
112
|
+
export const CANDIDATE_SITELINKS_TABLE = "candidate_sitelinks"
|
|
113
|
+
|
|
86
114
|
/**
|
|
87
115
|
* The candidate database schema, extending the ancestors sidecar so one typed
|
|
88
116
|
* client covers every table in the artifact.
|
|
89
117
|
*/
|
|
90
|
-
export interface CandidateDatabase extends CandidateAncestorsDatabase {
|
|
118
|
+
export interface CandidateDatabase extends CandidateAncestorsDatabase, OutcomeDatabase {
|
|
91
119
|
/**
|
|
92
120
|
* The clustered `without rowid` lookup table the reader probes.
|
|
93
121
|
*/
|
|
@@ -108,6 +136,14 @@ export interface CandidateDatabase extends CandidateAncestorsDatabase {
|
|
|
108
136
|
* See overture-match-schema.ts.
|
|
109
137
|
*/
|
|
110
138
|
overture_wof_match: OvertureWOFMatchTable
|
|
139
|
+
/**
|
|
140
|
+
* Wikidata (`wd:id`) concordances for candidate `spr_id`s.
|
|
141
|
+
*/
|
|
142
|
+
concordances: CandidateConcordanceTable
|
|
143
|
+
/**
|
|
144
|
+
* Wikipedia sitelink counts per `spr_id` for cross-layer prominence.
|
|
145
|
+
*/
|
|
146
|
+
candidate_sitelinks: CandidateSitelinksTable
|
|
111
147
|
}
|
|
112
148
|
|
|
113
149
|
/**
|
|
@@ -247,3 +283,31 @@ export async function createCandidatePostcodePlaceIndex(
|
|
|
247
283
|
.where(sql<boolean>`placetype_id = ${sql.lit(placetypeID)} AND is_primary = 1`)
|
|
248
284
|
.execute()
|
|
249
285
|
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Create the clustered `without rowid` `concordances` table storing Wikidata
|
|
289
|
+
* (`wd:id`) links for candidate `spr_id`s.
|
|
290
|
+
*/
|
|
291
|
+
export async function createCandidateConcordancesTable(db: Kysely<CandidateDatabase>): Promise<void> {
|
|
292
|
+
await db.schema
|
|
293
|
+
.createTable(CANDIDATE_CONCORDANCES_TABLE)
|
|
294
|
+
.addColumn("id", "integer", (c) => c.notNull())
|
|
295
|
+
.addColumn("other_source", "text", (c) => c.notNull())
|
|
296
|
+
.addColumn("other_id", "text", (c) => c.notNull())
|
|
297
|
+
.addPrimaryKeyConstraint("concordances_pk", ["id", "other_source", "other_id"])
|
|
298
|
+
.modifyEnd(sql`without rowid`)
|
|
299
|
+
.execute()
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Create the clustered `without rowid` `candidate_sitelinks` table storing
|
|
304
|
+
* Wikipedia sitelink counts per candidate `spr_id`.
|
|
305
|
+
*/
|
|
306
|
+
export async function createCandidateSitelinksTable(db: Kysely<CandidateDatabase>): Promise<void> {
|
|
307
|
+
await db.schema
|
|
308
|
+
.createTable(CANDIDATE_SITELINKS_TABLE)
|
|
309
|
+
.addColumn("spr_id", "integer", (c) => c.primaryKey())
|
|
310
|
+
.addColumn("sitelinks", "integer", (c) => c.notNull())
|
|
311
|
+
.modifyEnd(sql`without rowid`)
|
|
312
|
+
.execute()
|
|
313
|
+
}
|
package/lib/geonames/aliases.ts
CHANGED
|
@@ -253,9 +253,20 @@ function addAdminRows(
|
|
|
253
253
|
return { countryID, adminMap }
|
|
254
254
|
}
|
|
255
255
|
|
|
256
|
+
/**
|
|
257
|
+
* The GeoNames feature codes of a populated place that no longer exists: abandoned (`PPLQ`),
|
|
258
|
+
* destroyed (`PPLW`), historical (`PPLH`) and a historical capital (`PPLCH`).
|
|
259
|
+
*
|
|
260
|
+
* A row with one of these codes is left out, because every row this step writes is a current locality.
|
|
261
|
+
* WOF marks its own record of such a place as ceased.
|
|
262
|
+
*/
|
|
263
|
+
export const FORMER_PLACE_FEATURE_CODES: ReadonlySet<string> = new Set(["PPLQ", "PPLW", "PPLH", "PPLCH"])
|
|
264
|
+
|
|
256
265
|
/**
|
|
257
266
|
* Purges the GeoNames alias id range, then adds GeoNames `P`-class places
|
|
258
267
|
* and their alternate names for `countries` to `db`.
|
|
268
|
+
*
|
|
269
|
+
* A place of {@link FORMER_PLACE_FEATURE_CODES} is left out.
|
|
259
270
|
* It returns the number of places ingested.
|
|
260
271
|
*
|
|
261
272
|
* The caller must then rebuild `place_search` with `buildPlaceSearchFTS(db, { drop: true })`
|
|
@@ -310,6 +321,31 @@ export async function ingestGeonamesAliases(
|
|
|
310
321
|
|
|
311
322
|
const populationInsert = db.prepare(`INSERT OR REPLACE INTO place_population (id, population) VALUES (?, ?)`)
|
|
312
323
|
|
|
324
|
+
const recordedPopulation = db.prepare(`SELECT 1 FROM place_population WHERE id = ? AND population > 0`)
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The population this run wrote onto each matched record that had none.
|
|
328
|
+
*/
|
|
329
|
+
const populationsAdded = new Map<number, number>()
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Writes a matched place's population onto its record when the record's own sources gave it none.
|
|
333
|
+
*
|
|
334
|
+
* A record with a population of its own keeps it.
|
|
335
|
+
* A record with none takes the largest population among the GeoNames places that matched it,
|
|
336
|
+
* so a suburb read before its city doesn't decide the city record's value.
|
|
337
|
+
*/
|
|
338
|
+
const addPopulation = (id: number, population: number): void => {
|
|
339
|
+
const added = populationsAdded.get(id)
|
|
340
|
+
|
|
341
|
+
if (population <= (added ?? 0)) return
|
|
342
|
+
|
|
343
|
+
if (added == null && recordedPopulation.get(id)) return
|
|
344
|
+
|
|
345
|
+
populationInsert.run(id, population)
|
|
346
|
+
populationsAdded.set(id, population)
|
|
347
|
+
}
|
|
348
|
+
|
|
313
349
|
const ancestorInsert = db.prepare(
|
|
314
350
|
`INSERT INTO ancestors (id, ancestor_id, ancestor_placetype, lastmodified) VALUES (?, ?, ?, 0)`
|
|
315
351
|
)
|
|
@@ -382,7 +418,7 @@ export async function ingestGeonamesAliases(
|
|
|
382
418
|
: { countryID: -1, adminMap: new Map<string, number>() }
|
|
383
419
|
|
|
384
420
|
for await (const f of readUnquotedTSV(file)) {
|
|
385
|
-
if (f[6] !== "P") continue
|
|
421
|
+
if (f[6] !== "P" || FORMER_PLACE_FEATURE_CODES.has(f[7] ?? "")) continue
|
|
386
422
|
const lat = Number(f[4])
|
|
387
423
|
const lon = Number(f[5])
|
|
388
424
|
|
|
@@ -408,6 +444,8 @@ export async function ingestGeonamesAliases(
|
|
|
408
444
|
if (matched) {
|
|
409
445
|
claim(matched, name)
|
|
410
446
|
|
|
447
|
+
addPopulation(matched.id, Number(f[14]) || 0)
|
|
448
|
+
|
|
411
449
|
for (const raw of alternates) {
|
|
412
450
|
const alt = cleanAlias(raw)
|
|
413
451
|
|
|
@@ -504,7 +504,7 @@ export function withoutApostropheLikeMarks(key: NameKey): NameKey {
|
|
|
504
504
|
* The tatweel (U+0640), the short-vowel and shadda marks (U+064B–U+065F) and the superscript
|
|
505
505
|
* alef (U+0670), with the hamza and madda that NFKD splits off `أ`, `إ`, `آ`, `ؤ` and `ئ`.
|
|
506
506
|
*/
|
|
507
|
-
const ARABIC_MARKS =
|
|
507
|
+
const ARABIC_MARKS = /\u0640|[\u064B-\u065F\u0670]/gu
|
|
508
508
|
|
|
509
509
|
/**
|
|
510
510
|
* The key with the Arabic letters that writers interchange folded together, so `الاسماعيليه`
|
|
@@ -665,6 +665,7 @@ export function directionalRelaxedKeys(key: StreetKey): StreetKey[] {
|
|
|
665
665
|
if (words.length < 2) return []
|
|
666
666
|
|
|
667
667
|
const base = words.join(" ")
|
|
668
|
+
|
|
668
669
|
const forms = [
|
|
669
670
|
base,
|
|
670
671
|
...KEY_DIRECTIONALS.flatMap((directional) => [`${directional} ${base}`, `${base} ${directional}`]),
|
package/lib/landmark.ts
CHANGED
|
@@ -8,14 +8,18 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { LandmarkHit, LandmarkLookup } from "@mailwoman/core/resolver"
|
|
11
|
+
import { OutcomeLayer, type OutcomeQuery, refuseMissingOutcomeTables } from "@mailwoman/core/resolver/outcome"
|
|
12
|
+
import { allRows } from "@mailwoman/core/utils"
|
|
11
13
|
import { DatabaseClient } from "@mailwoman/sqlite/client"
|
|
12
14
|
import { sql, type Kysely } from "kysely"
|
|
13
15
|
import type { PathBuilderLike } from "path-ts"
|
|
14
16
|
|
|
15
17
|
import { LANDMARK_BY_NAME_SQL, landmarkHitsFromRows, landmarkNameKey, type LandmarkNameTable } from "#landmark/rows"
|
|
18
|
+
import { missingOutcomeTablesIn, OutcomeMembershipReader, outcomeAdmitPredicate } from "#outcome/memberships"
|
|
19
|
+
import type { LandmarkOutcomeDatabase } from "#outcome/schema"
|
|
16
20
|
import { prepareAll, type PreparedAll } from "#sqlite-utils"
|
|
17
21
|
|
|
18
|
-
export interface LandmarkDatabase {
|
|
22
|
+
export interface LandmarkDatabase extends LandmarkOutcomeDatabase {
|
|
19
23
|
landmark_name: LandmarkNameTable
|
|
20
24
|
}
|
|
21
25
|
|
|
@@ -78,14 +82,57 @@ export class LandmarkSqliteLookup implements LandmarkLookup, Disposable {
|
|
|
78
82
|
|
|
79
83
|
readonly #byName: PreparedAll<[nameKey: string], LandmarkNameTable>
|
|
80
84
|
|
|
81
|
-
|
|
85
|
+
readonly #layer: string
|
|
86
|
+
readonly #missingOutcomeTables: readonly string[]
|
|
87
|
+
readonly #outcomes: OutcomeMembershipReader | null
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* `layer` names the database in each outcome member's source and in a refusal:
|
|
91
|
+
* `landmarks` for the Wikidata layer, `openstreetmap` for the OpenStreetMap place layer.
|
|
92
|
+
*/
|
|
93
|
+
constructor(path: PathBuilderLike, layer: string = OutcomeLayer.Landmarks) {
|
|
82
94
|
this.#db = new DatabaseClient<LandmarkDatabase>(path, { readOnly: true })
|
|
83
95
|
|
|
84
96
|
this.#byName = prepareAll(this.#db, LANDMARK_BY_NAME_SQL)
|
|
97
|
+
this.#layer = layer
|
|
98
|
+
this.#missingOutcomeTables = missingOutcomeTablesIn(this.#db)
|
|
99
|
+
this.#outcomes = OutcomeMembershipReader.open(this.#db, { recordColumn: "qid", layer })
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* With `outcome`, each hit holds its outcome set, and `admit` is a predicate of the read.
|
|
104
|
+
*
|
|
105
|
+
* @throws {OutcomeRequestError} For an outcome query against a database without the outcome tables.
|
|
106
|
+
*/
|
|
107
|
+
find(name: string, outcome?: OutcomeQuery): LandmarkHit[] {
|
|
108
|
+
const key = landmarkNameKey(name)
|
|
109
|
+
|
|
110
|
+
if (!outcome) return landmarkHitsFromRows(this.#byName(key), name)
|
|
111
|
+
|
|
112
|
+
refuseMissingOutcomeTables(`the ${this.#layer} database`, this.#missingOutcomeTables)
|
|
113
|
+
|
|
114
|
+
const rows = outcome.admit ? this.#admittedRows(key, outcome.admit) : this.#byName(key)
|
|
115
|
+
|
|
116
|
+
// A landmark row's defaults are keyed by its `kind`, as a candidate row's are by its placetype.
|
|
117
|
+
return landmarkHitsFromRows(rows, name).map((hit) => ({
|
|
118
|
+
...hit,
|
|
119
|
+
outcomes: this.#outcomes!.read(hit.qid, hit.kind, outcome),
|
|
120
|
+
}))
|
|
85
121
|
}
|
|
86
122
|
|
|
87
|
-
|
|
88
|
-
return
|
|
123
|
+
missingOutcomeTables(): readonly string[] {
|
|
124
|
+
return this.#missingOutcomeTables
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
#admittedRows(key: string, admit: readonly number[]): LandmarkNameTable[] {
|
|
128
|
+
const predicate = outcomeAdmitPredicate(admit, "qid", "landmark_name.qid", "landmark_name.kind")
|
|
129
|
+
const [select, order] = LANDMARK_BY_NAME_SQL.split(" ORDER BY ")
|
|
130
|
+
|
|
131
|
+
return allRows<LandmarkNameTable>(
|
|
132
|
+
this.#db.prepare(`${select} AND ${predicate.sql} ORDER BY ${order}`),
|
|
133
|
+
key,
|
|
134
|
+
...predicate.params
|
|
135
|
+
)
|
|
89
136
|
}
|
|
90
137
|
|
|
91
138
|
[Symbol.dispose](): void {
|
package/lib/lookup/types.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import type { ScoreUnmeasuredReason } from "@mailwoman/core/resolver"
|
|
10
|
+
import type { OutcomeMembership, OutcomeQuery } from "@mailwoman/core/resolver/outcome"
|
|
10
11
|
import type { LatLon, LatLonBounds } from "@mailwoman/spatial"
|
|
11
12
|
|
|
12
13
|
/**
|
|
@@ -125,6 +126,22 @@ export interface PlaceCandidate {
|
|
|
125
126
|
* Set when the input matched an alias of this place, by the candidate-table backend only.
|
|
126
127
|
*/
|
|
127
128
|
matchedAlias?: true | null
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The matched row's `name_role` (`"abbr"`, `"variant"`, `"foreign-script"`, `"gloss"`),
|
|
132
|
+
* or `null` when unstamped or primary, by the candidate-table backend only.
|
|
133
|
+
*/
|
|
134
|
+
nameRole?: string | null
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The place's effective outcome set, read only for a query with `outcome`.
|
|
138
|
+
*/
|
|
139
|
+
outcomes?: readonly OutcomeMembership[] | null
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The place's `wd:id` concordance, read only for a query with `outcome`, when the artifact records one.
|
|
143
|
+
*/
|
|
144
|
+
wikidata?: string | null
|
|
128
145
|
}
|
|
129
146
|
|
|
130
147
|
/**
|
|
@@ -220,6 +237,14 @@ export interface FindPlaceQuery {
|
|
|
220
237
|
*/
|
|
221
238
|
bbox?: LatLonBounds
|
|
222
239
|
|
|
240
|
+
/**
|
|
241
|
+
* Reads each candidate's outcome set, and with `admit` keeps only the rows that
|
|
242
|
+
* hold an admitted id, as a predicate of the fetch.
|
|
243
|
+
*
|
|
244
|
+
* A backend whose artifact lacks the outcome tables throws an `OutcomeRequestError`.
|
|
245
|
+
*/
|
|
246
|
+
outcome?: OutcomeQuery
|
|
247
|
+
|
|
223
248
|
/**
|
|
224
249
|
* The maximum number of candidates to return, defaulting to 10.
|
|
225
250
|
*/
|