@mailwoman/resolver 10.3.0 → 10.4.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/README.md +7 -7
- package/lib/admin/coherence-passes.ts +7 -5
- package/lib/admin/jp-municipality.ts +1 -1
- package/lib/admin/winner.ts +1 -1
- package/lib/backend-capabilities.ts +2 -2
- package/lib/bare-toponym-race.ts +105 -22
- package/lib/decorate-node.ts +7 -0
- package/lib/postcode/shape-coherence.ts +10 -1
- package/lib/rerank.ts +2 -2
- package/lib/resolve/passes.ts +125 -31
- package/lib/resolve.ts +19 -12
- package/lib/span-rescore.ts +4 -4
- package/out/admin/coherence-passes.d.ts +2 -2
- package/out/admin/coherence-passes.d.ts.map +1 -1
- package/out/admin/coherence-passes.js +7 -5
- package/out/admin/coherence-passes.js.map +1 -1
- package/out/admin/jp-municipality.d.ts +1 -1
- package/out/admin/jp-municipality.js +1 -1
- package/out/admin/winner.d.ts +1 -1
- package/out/admin/winner.js +1 -1
- package/out/backend-capabilities.js +2 -2
- package/out/bare-toponym-race.d.ts +31 -0
- package/out/bare-toponym-race.d.ts.map +1 -1
- package/out/bare-toponym-race.js +74 -22
- package/out/bare-toponym-race.js.map +1 -1
- package/out/decorate-node.d.ts.map +1 -1
- package/out/decorate-node.js +5 -0
- package/out/decorate-node.js.map +1 -1
- package/out/postcode/shape-coherence.d.ts.map +1 -1
- package/out/postcode/shape-coherence.js +7 -1
- package/out/postcode/shape-coherence.js.map +1 -1
- package/out/rerank.d.ts +2 -2
- package/out/resolve/passes.d.ts +19 -4
- package/out/resolve/passes.d.ts.map +1 -1
- package/out/resolve/passes.js +95 -25
- package/out/resolve/passes.js.map +1 -1
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +17 -13
- package/out/resolve.js.map +1 -1
- package/out/span-rescore.d.ts +2 -2
- package/out/span-rescore.js +4 -4
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @mailwoman/resolver
|
|
2
2
|
|
|
3
|
-
Walk a parsed `AddressTree` and decide, for each span,
|
|
3
|
+
Walk a parsed `AddressTree` and decide, for each span, the real place it refers to. Then hand back the tree with coordinates, attribution and ancestry stamped on it.
|
|
4
4
|
|
|
5
|
-
This is the half of [mailwoman](https://www.npmjs.com/package/mailwoman) that turns _"the model assigns this run of characters to the locality label"_ into _"this is Springfield, Illinois, at 39.7973/-89.6455, and here is why."_ It owns the ranking, the coherence passes and the ordering rules
|
|
5
|
+
This is the half of [mailwoman](https://www.npmjs.com/package/mailwoman) that turns _"the model assigns this run of characters to the locality label"_ into _"this is Springfield, Illinois, at 39.7973/-89.6455, and here is why."_ It owns the ranking, the coherence passes and the ordering rules, and it owns no data. The gazetteer lives behind a `ResolverBackend` you supply.
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
@@ -22,7 +22,7 @@ const resolver = createWOFResolver(backend)
|
|
|
22
22
|
const decorated = await resolver.resolveTree(tree)
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
`resolveTree` returns a new tree. Nodes that resolved
|
|
25
|
+
`resolveTree` returns a new tree. Nodes that resolved have `lat`/`lon`, a `placeID`, and `resolver_*` metadata. Nodes that did not are returned untouched.
|
|
26
26
|
|
|
27
27
|
## Backend-agnostic on purpose
|
|
28
28
|
|
|
@@ -36,7 +36,7 @@ of looking like a bad result.
|
|
|
36
36
|
|
|
37
37
|
Two rules run through this package, and both exist because their opposites shipped bugs.
|
|
38
38
|
|
|
39
|
-
**A coordinate the gazetteer cannot supply is absent, never `0,0`.** `0,0` is the unlocated sentinel in every WOF-lineage database, and those databases
|
|
39
|
+
**A coordinate the gazetteer cannot supply is absent, never `0,0`.** `0,0` is the unlocated sentinel in every WOF-lineage database, and those databases contain a great deal of it — 48,216 of 142,604 Japanese postcodes, 86,377 GB, 414 US. `decorateNode` leaves `lat`/`lon` unset for such a row, so the place still resolves and identifies itself while stating that it cannot say where it is. A consumer's `lat != null` check then means what it looks like it means.
|
|
40
40
|
|
|
41
41
|
**A missing answer is not a wrong answer.** An unresolvable span is returned as parsed. The resolver invents no centroid to fill a hole.
|
|
42
42
|
|
|
@@ -44,7 +44,7 @@ Two rules run through this package, and both exist because their opposites shipp
|
|
|
44
44
|
|
|
45
45
|
`admin-winner.ts` owns one ordering, and it is the only one whose rungs are not fixed.
|
|
46
46
|
|
|
47
|
-
`PLACETYPE_SPECIFICITY` ranks placetypes by how much ground they cover
|
|
47
|
+
`PLACETYPE_SPECIFICITY` ranks placetypes by how much ground they cover. That measure ranks most placetypes correctly and ranks `postalcode` wrongly. A GB unit postcode covers ~15 addresses and is tighter than any locality centroid. A French _code postal_ can span several communes and be coarser than the one you want. One number cannot be both.
|
|
48
48
|
|
|
49
49
|
So the rank of a resolved postcode is computed, from two independent routes:
|
|
50
50
|
|
|
@@ -60,9 +60,9 @@ const rank = resolvedSpecificity({ placetype: "postalcode", value: "N7 0BT", res
|
|
|
60
60
|
|
|
61
61
|
Either an **exact hit on a unit-grade code** (`@mailwoman/codex`'s `UNIT_GRADE_POSTCODE` — NL PC6, GB unit, CA urban LDU) or an **address system whose area-grade codes are finer than its localities** (`AREA_POSTCODE_FINER_THAN_LOCALITY` — Germany, where a Gemeinde can be the size of Berlin) puts the postcode ahead of the locality. Everything else follows the locality.
|
|
62
62
|
|
|
63
|
-
The two shapes live in one module deliberately. They express one claim and are consumed by different callers, and when they were separate the eval harnesses each froze one arm of the conditional as a constant — every grader correct on half the data and wrong on the other half, unconditionally,
|
|
63
|
+
The two shapes live in one module deliberately. They express one claim and are consumed by different callers, and when they were separate the eval harnesses each froze one arm of the conditional as a constant — every grader correct on half the data and wrong on the other half, unconditionally, until a test compared them. `lib/admin/winner.test.ts` asserts they agree on every arm, and a mutation of either side fails it.
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
A code system joins those tiers by measurement, never by its shape without a measurement. Canada is the worked example. Its urban LDU measures 78 m against rooftop truth and joined the tier, while its rural codes measure 2.08 km and did not. Canada Post already marks the difference with a `0` in the second character, so the code itself identifies its tier before any lookup runs.
|
|
66
66
|
|
|
67
67
|
## Coherence passes
|
|
68
68
|
|
|
@@ -68,8 +68,8 @@ export function applyParentFallbackContradiction(roots: readonly AddressNode[]):
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
/**
|
|
71
|
-
* Re-picks a resolved region and its unresolved child locality as a pair,
|
|
72
|
-
* region candidate that
|
|
71
|
+
* Re-picks a resolved region and its unresolved child locality as a pair,
|
|
72
|
+
* choosing the region candidate that contains a locality with the same name.
|
|
73
73
|
*
|
|
74
74
|
* This recovers cases such as "Portland, ME" where the region was picked in isolation
|
|
75
75
|
* before the locality was known.
|
|
@@ -255,14 +255,16 @@ async function reconcileExplicitCountry(
|
|
|
255
255
|
localityNode: AddressNode,
|
|
256
256
|
backend: ResolverBackend
|
|
257
257
|
): Promise<void> {
|
|
258
|
-
|
|
258
|
+
// A span tagged `country` may hold a constituent country such as `England`.
|
|
259
|
+
// That is a subdivision of GB rather than a sovereign state, and it still fixes the country.
|
|
260
|
+
const iso2 = matchCountry(countryNode.value)?.iso2 ?? matchSubdivision(countryNode.value)?.country
|
|
259
261
|
|
|
260
|
-
if (!
|
|
262
|
+
if (!iso2) return
|
|
261
263
|
|
|
262
264
|
const scoped = await backend.findPlace({
|
|
263
265
|
text: localityNode.value,
|
|
264
266
|
placetype: "locality",
|
|
265
|
-
country:
|
|
267
|
+
country: iso2,
|
|
266
268
|
limit: 3,
|
|
267
269
|
})
|
|
268
270
|
|
|
@@ -73,7 +73,7 @@ function stamp<Pick extends { metadata?: Record<string, unknown> }>(
|
|
|
73
73
|
* the parent fallback withheld, so a namesake ward or town outside the head is never admissible,
|
|
74
74
|
* including one the backend re-admits through its own region-scope fallback (`regionScopeMiss`).
|
|
75
75
|
*
|
|
76
|
-
* A county head
|
|
76
|
+
* A county head can have no key.
|
|
77
77
|
* The tail then probes under the parent the walk already holds.
|
|
78
78
|
* Answers the tail when it hits, else the head, else null.
|
|
79
79
|
*
|
package/lib/admin/winner.ts
CHANGED
|
@@ -95,7 +95,7 @@ export function adminLadderForNodes(nodes: readonly AddressNode[]): ReadonlyArra
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
/**
|
|
98
|
-
* Deliberately non-integer position for an area-grade
|
|
98
|
+
* Deliberately non-integer position for an area-grade postcode on `PLACETYPE_SPECIFICITY`:
|
|
99
99
|
* below the whole locality tier and above `county` (2).
|
|
100
100
|
*/
|
|
101
101
|
export const AREA_GRADE_POSTALCODE_SPECIFICITY = 2.5
|
|
@@ -68,8 +68,8 @@ export function formatCapabilityGaps(gaps: readonly BackendCapabilityGap[]): str
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
/**
|
|
71
|
-
* Backends already reported, so a process that builds
|
|
72
|
-
* harness, the gauntlet, a batch worker — states the gap once rather than once per construction.
|
|
71
|
+
* Backends already reported, so a process that builds more than one resolver over one artifact — the
|
|
72
|
+
* eval harness, the gauntlet, a batch worker — states the gap once rather than once per construction.
|
|
73
73
|
*/
|
|
74
74
|
const reported = new Set<string>()
|
|
75
75
|
|
package/lib/bare-toponym-race.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
|
|
|
15
15
|
import type { AddressNode, AddressTree } from "@mailwoman/core/decoder"
|
|
16
16
|
import { loneValueNode } from "@mailwoman/core/decoder"
|
|
17
17
|
import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
|
|
18
|
+
import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* The tree's single value-containing node when it is locality-tagged, else null.
|
|
@@ -97,11 +98,33 @@ export async function bareCountryCandidate(
|
|
|
97
98
|
backend: ResolverBackend,
|
|
98
99
|
text: string,
|
|
99
100
|
scopedCountry: string | undefined
|
|
101
|
+
): Promise<ResolvedPlace | null> {
|
|
102
|
+
return probeBareRace(backend, text, "country", ["country"], scopedCountry)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The top exact row of one placetype band for a bare toponym, or null.
|
|
107
|
+
*
|
|
108
|
+
* Every side race shares these rules: one row, abbreviation and gloss aliases excluded,
|
|
109
|
+
* the locality query's scope, an exact match, and a located coordinate.
|
|
110
|
+
*
|
|
111
|
+
* The placetype check is required.
|
|
112
|
+
* A backend may ignore the filter, as test stubs or a partial implementation could,
|
|
113
|
+
* and hand a race a locality row that would then demote the real pick.
|
|
114
|
+
*
|
|
115
|
+
* A failed probe returns null, so a side race never aborts the primary lookup.
|
|
116
|
+
*/
|
|
117
|
+
async function probeBareRace(
|
|
118
|
+
backend: ResolverBackend,
|
|
119
|
+
text: string,
|
|
120
|
+
placetype: string,
|
|
121
|
+
accepted: readonly string[],
|
|
122
|
+
scopedCountry: string | undefined
|
|
100
123
|
): Promise<ResolvedPlace | null> {
|
|
101
124
|
try {
|
|
102
125
|
const hits = await backend.findPlace({
|
|
103
126
|
text,
|
|
104
|
-
placetype
|
|
127
|
+
placetype,
|
|
105
128
|
limit: 1,
|
|
106
129
|
excludeNameRoles: BARE_RACE_EXCLUDED_NAME_ROLES,
|
|
107
130
|
...(scopedCountry ? { country: scopedCountry } : {}),
|
|
@@ -109,14 +132,10 @@ export async function bareCountryCandidate(
|
|
|
109
132
|
|
|
110
133
|
const top = hits[0]
|
|
111
134
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
// The repick would then demote the real pick.
|
|
116
|
-
return top && top.placetype === "country" && top.exactMatch !== false ? top : null
|
|
135
|
+
return top && accepted.includes(top.placetype) && top.exactMatch !== false && !(top.lat === 0 && top.lon === 0)
|
|
136
|
+
? top
|
|
137
|
+
: null
|
|
117
138
|
} catch {
|
|
118
|
-
// A failed side race must never abort the primary lookup.
|
|
119
|
-
// The locality answer stands.
|
|
120
139
|
return null
|
|
121
140
|
}
|
|
122
141
|
}
|
|
@@ -143,21 +162,85 @@ export async function bareRegionCandidate(
|
|
|
143
162
|
text: string,
|
|
144
163
|
scopedCountry: string | undefined
|
|
145
164
|
): Promise<ResolvedPlace | null> {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
text,
|
|
149
|
-
placetype: "region",
|
|
150
|
-
limit: 1,
|
|
151
|
-
excludeNameRoles: BARE_RACE_EXCLUDED_NAME_ROLES,
|
|
152
|
-
...(scopedCountry ? { country: scopedCountry } : {}),
|
|
153
|
-
})
|
|
165
|
+
return probeBareRace(backend, text, "region", ["region", "macroregion"], scopedCountry)
|
|
166
|
+
}
|
|
154
167
|
|
|
155
|
-
|
|
168
|
+
/**
|
|
169
|
+
* The sub-locality placetypes {@link bareSublocalityCandidate} probes, coarse to fine:
|
|
170
|
+
* every Who's On First placetype finer than `locality` through `microhood`.
|
|
171
|
+
*/
|
|
172
|
+
export const BARE_SUBLOCALITY_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
|
|
173
|
+
.filter(
|
|
174
|
+
([, rank]) =>
|
|
175
|
+
rank != null && rank > PLACETYPE_SPECIFICITY["locality"]! && rank <= PLACETYPE_SPECIFICITY["microhood"]!
|
|
176
|
+
)
|
|
177
|
+
.toSorted((a, b) => (a[1] as number) - (b[1] as number))
|
|
178
|
+
.map(([placetype]) => placetype)
|
|
156
179
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
180
|
+
/**
|
|
181
|
+
* The best sub-locality row for a bare toponym with no locality row, or null.
|
|
182
|
+
*
|
|
183
|
+
* A whole-input name such as `Buckingham Palace` can be a Who's On First `neighbourhood` row.
|
|
184
|
+
* The locality placetype filter makes that row unreachable.
|
|
185
|
+
*
|
|
186
|
+
* The resolver would otherwise shorten the span and answer a different place.
|
|
187
|
+
*
|
|
188
|
+
* Bands are probed coarse to fine, and the first exact hit with a coordinate wins.
|
|
189
|
+
* The same scope, exact-match and alias-role rules as the country and region races apply.
|
|
190
|
+
*/
|
|
191
|
+
export async function bareSublocalityCandidate(
|
|
192
|
+
backend: ResolverBackend,
|
|
193
|
+
text: string,
|
|
194
|
+
scopedCountry: string | undefined
|
|
195
|
+
): Promise<ResolvedPlace | null> {
|
|
196
|
+
for (const placetype of BARE_SUBLOCALITY_BANDS) {
|
|
197
|
+
const top = await probeBareRace(backend, text, placetype, [placetype], scopedCountry)
|
|
198
|
+
|
|
199
|
+
if (top) return top
|
|
162
200
|
}
|
|
201
|
+
|
|
202
|
+
return null
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The place a bare toponym with no locality row resolves to, or null.
|
|
207
|
+
*
|
|
208
|
+
* It returns the place with the trace check, pick source and node metadata that record the pick.
|
|
209
|
+
*
|
|
210
|
+
* The larger admin namesake from the country and region races wins first.
|
|
211
|
+
* A sub-locality namesake is probed only when neither race hit.
|
|
212
|
+
*/
|
|
213
|
+
export async function emptyLocalityPick(
|
|
214
|
+
backend: ResolverBackend,
|
|
215
|
+
text: string,
|
|
216
|
+
scopedCountry: string | undefined,
|
|
217
|
+
bareCountry: ResolvedPlace | null,
|
|
218
|
+
bareRegion: ResolvedPlace | null
|
|
219
|
+
): Promise<{
|
|
220
|
+
place: ResolvedPlace
|
|
221
|
+
check: string
|
|
222
|
+
source: "empty_admin" | "bare_sublocality"
|
|
223
|
+
metadata: Record<string, boolean>
|
|
224
|
+
} | null> {
|
|
225
|
+
const admin = pickLargerAdmin(bareCountry, bareRegion)
|
|
226
|
+
|
|
227
|
+
if (admin) {
|
|
228
|
+
return {
|
|
229
|
+
place: admin,
|
|
230
|
+
check: "empty_admin_pick",
|
|
231
|
+
source: "empty_admin",
|
|
232
|
+
metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const sublocality = await bareSublocalityCandidate(backend, text, scopedCountry)
|
|
237
|
+
|
|
238
|
+
return sublocality
|
|
239
|
+
? {
|
|
240
|
+
place: sublocality,
|
|
241
|
+
check: "bare_sublocality_pick",
|
|
242
|
+
source: "bare_sublocality",
|
|
243
|
+
metadata: { bare_sublocality_pick: true },
|
|
244
|
+
}
|
|
245
|
+
: null
|
|
163
246
|
}
|
package/lib/decorate-node.ts
CHANGED
|
@@ -85,6 +85,13 @@ export function decorateNode(
|
|
|
85
85
|
node.metadata["resolver_importance"] = resolved.importance
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
// A point-only row stores its coordinate as both corners, so only an extent with area measures the place's size.
|
|
89
|
+
const bbox = resolved.bbox
|
|
90
|
+
|
|
91
|
+
if (bbox && (bbox.minLat !== bbox.maxLat || bbox.minLon !== bbox.maxLon)) {
|
|
92
|
+
node.metadata["resolver_bbox"] = bbox
|
|
93
|
+
}
|
|
94
|
+
|
|
88
95
|
// The postcode pointed to a geographically different place than the parsed city name,
|
|
89
96
|
// surfaced so callers can warn rather than silently trust the resolved point.
|
|
90
97
|
if (resolved.mismatch) {
|
|
@@ -47,7 +47,16 @@ function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
|
|
|
47
47
|
if (n.tag === "country") {
|
|
48
48
|
const matched = matchCountry(n.value)
|
|
49
49
|
|
|
50
|
-
if (!matched)
|
|
50
|
+
if (!matched) {
|
|
51
|
+
// A constituent country such as `England` tagged `country` still fixes its sovereign state.
|
|
52
|
+
const sub = matchSubdivision(n.value)
|
|
53
|
+
|
|
54
|
+
if (sub && SYSTEM_UNIVERSE.has(sub.country.toUpperCase())) {
|
|
55
|
+
out.add(sub.country.toUpperCase())
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
continue
|
|
59
|
+
}
|
|
51
60
|
|
|
52
61
|
const system = isUSStateAbbreviation(matched.iso2) ? "US" : matched.iso2.toUpperCase()
|
|
53
62
|
|
package/lib/rerank.ts
CHANGED
|
@@ -56,7 +56,7 @@ export interface RerankResult<T = unknown> {
|
|
|
56
56
|
*/
|
|
57
57
|
best: RerankedCandidate<T>
|
|
58
58
|
/**
|
|
59
|
-
* True when resolution evidence
|
|
59
|
+
* True when resolution evidence changed the answer from the model's rank-1.
|
|
60
60
|
*/
|
|
61
61
|
changed: boolean
|
|
62
62
|
}
|
|
@@ -69,7 +69,7 @@ export type ResolveTree = (tree: AddressTree) => Promise<AddressTree>
|
|
|
69
69
|
|
|
70
70
|
export interface RerankOpts {
|
|
71
71
|
/**
|
|
72
|
-
* Resolve at most this
|
|
72
|
+
* Resolve at most this number of candidates.
|
|
73
73
|
*
|
|
74
74
|
* Each costs a resolver round-trip, so this is the latency knob.
|
|
75
75
|
*
|
package/lib/resolve/passes.ts
CHANGED
|
@@ -194,7 +194,7 @@ export interface ResolutionState {
|
|
|
194
194
|
defaultCountry: DefaultCountry | null
|
|
195
195
|
|
|
196
196
|
/**
|
|
197
|
-
* The tree's only value
|
|
197
|
+
* The tree's only node with a value when it maps to `locality`, or null otherwise.
|
|
198
198
|
*
|
|
199
199
|
* Its lookup also probes countries and regions of the same name, because the locality
|
|
200
200
|
* placetype filter cannot reach a country that the parser tagged as a locality.
|
|
@@ -206,7 +206,7 @@ export interface ResolutionState {
|
|
|
206
206
|
* The tree's first postcode value.
|
|
207
207
|
*
|
|
208
208
|
* Locality lookups send it to the backend.
|
|
209
|
-
* The backend can then favor
|
|
209
|
+
* The backend can then favor candidates closer to the postcode.
|
|
210
210
|
*/
|
|
211
211
|
postcode?: string | null
|
|
212
212
|
|
|
@@ -366,7 +366,8 @@ export function pickCompletion(candidates: readonly CoincidentLocality[]): Coinc
|
|
|
366
366
|
|
|
367
367
|
/**
|
|
368
368
|
* Returns the first postcode value anywhere in the tree, skipping shape-excluded postcodes.
|
|
369
|
-
*
|
|
369
|
+
*
|
|
370
|
+
* A locality lookup uses it because the postcode node is a sibling in the tree shape this pass expects.
|
|
370
371
|
*/
|
|
371
372
|
export function firstPostcodeValue(roots: readonly AddressNode[]): string | null {
|
|
372
373
|
for (const n of walkNodes(roots)) {
|
|
@@ -480,32 +481,33 @@ async function recoverPostcodeNode(
|
|
|
480
481
|
}
|
|
481
482
|
|
|
482
483
|
/**
|
|
483
|
-
*
|
|
484
|
-
*
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
*
|
|
484
|
+
* Measures each resolved locality and dependent locality against `anchor`,
|
|
485
|
+
* a point the tree places the address at.
|
|
486
|
+
*
|
|
487
|
+
* A node farther than `thresholdKm` is re-picked to its nearest alternative
|
|
488
|
+
* within the threshold when one exists.
|
|
489
|
+
*
|
|
490
|
+
* When no alternative lies within the threshold, `findNear` may return more same-name
|
|
491
|
+
* candidates for the node, and the nearest of those within the threshold is taken instead.
|
|
492
|
+
*
|
|
493
|
+
* Returns each node that lay beyond the threshold, with its distance before any re-pick.
|
|
494
|
+
* The caller decides what an unreconciled node means for its anchor.
|
|
492
495
|
*/
|
|
493
|
-
|
|
496
|
+
async function reconcileLocalitiesToAnchor(
|
|
494
497
|
roots: readonly AddressNode[],
|
|
498
|
+
anchor: { lat: number; lon: number },
|
|
495
499
|
thresholdKm: number,
|
|
496
|
-
|
|
497
|
-
):
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
for (const n of walkNodes(roots)) {
|
|
501
|
-
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
|
|
502
|
-
anchor = { lat: n.lat!, lon: n.lon! }
|
|
503
|
-
|
|
504
|
-
break
|
|
505
|
-
}
|
|
506
|
-
}
|
|
500
|
+
findNear?: (node: AddressNode) => Promise<readonly ResolvedPlace[]>
|
|
501
|
+
): Promise<Array<{ node: AddressNode; gapKm: number; repicked: boolean }>> {
|
|
502
|
+
const far: Array<{ node: AddressNode; gapKm: number; repicked: boolean }> = []
|
|
507
503
|
|
|
508
|
-
|
|
504
|
+
const nearest = (places: readonly ResolvedPlace[]) =>
|
|
505
|
+
places
|
|
506
|
+
.filter((a) => a.lat !== 0 || a.lon !== 0)
|
|
507
|
+
.map((a) => ({ a, d: haversineKm(anchor.lat, anchor.lon, a.lat, a.lon) }))
|
|
508
|
+
.filter((x) => x.d <= thresholdKm)
|
|
509
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
|
|
510
|
+
.sort((x, y) => x.d - y.d)[0]
|
|
509
511
|
|
|
510
512
|
for (const node of walkNodes(roots)) {
|
|
511
513
|
if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
|
|
@@ -516,12 +518,11 @@ export function applyPostcodeConsistency(
|
|
|
516
518
|
|
|
517
519
|
const alts = (node.alternatives as ResolvedPlace[] | null) ?? []
|
|
518
520
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
.filter((
|
|
523
|
-
|
|
524
|
-
.sort((x, y) => x.d - y.d)[0]
|
|
521
|
+
let reconciling = nearest(alts)
|
|
522
|
+
|
|
523
|
+
if (!reconciling && findNear) {
|
|
524
|
+
reconciling = nearest((await findNear(node)).filter((a) => `wof:${a.id}` !== node.placeID))
|
|
525
|
+
}
|
|
525
526
|
|
|
526
527
|
if (reconciling) {
|
|
527
528
|
const displaced: ResolvedPlace = {
|
|
@@ -537,6 +538,99 @@ export function applyPostcodeConsistency(
|
|
|
537
538
|
|
|
538
539
|
const rest = alts.filter((a) => a !== reconciling.a)
|
|
539
540
|
decorateNode(node, reconciling.a, [displaced, ...rest])
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
far.push({ node, gapKm, repicked: !!reconciling })
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
return far
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* The count of same-name localities {@link applyRooftopConsistency} asks the
|
|
551
|
+
* backend for, ranked by distance to the rooftop.
|
|
552
|
+
*/
|
|
553
|
+
const ROOFTOP_NAMESAKE_LIMIT = 25
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Reconciles each resolved locality that lies farther than `thresholdKm` from the street's
|
|
557
|
+
* address-point coordinate, re-picking the nearest alternative within the threshold.
|
|
558
|
+
*
|
|
559
|
+
* The resolved candidates are the most prominent namesakes, so the namesake
|
|
560
|
+
* nearest the rooftop can lie outside them.
|
|
561
|
+
* With a `backend`, the pass asks it for same-name localities ranked by distance
|
|
562
|
+
* to the rooftop and takes the nearest within the threshold.
|
|
563
|
+
*
|
|
564
|
+
* A rooftop row is an observed point, so an unreconciled locality is never moved onto it.
|
|
565
|
+
* The node records the distance as `rooftop_outside_locality_km`, and the result
|
|
566
|
+
* reports the locality as a component the answer did not follow.
|
|
567
|
+
*/
|
|
568
|
+
export async function applyRooftopConsistency(
|
|
569
|
+
roots: readonly AddressNode[],
|
|
570
|
+
thresholdKm: number,
|
|
571
|
+
backend?: ResolverBackend
|
|
572
|
+
): Promise<void> {
|
|
573
|
+
const street = [...walkNodes(roots)].find(
|
|
574
|
+
(n) => n.tag === "street" && n.metadata?.["resolution_tier"] === "address_point"
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
const point = street?.metadata?.["address_point"] as { lat: number; lon: number } | undefined
|
|
578
|
+
|
|
579
|
+
if (!point) return
|
|
580
|
+
|
|
581
|
+
const findNear = backend
|
|
582
|
+
? async (node: AddressNode): Promise<readonly ResolvedPlace[]> => {
|
|
583
|
+
if (node.tag !== "locality") return []
|
|
584
|
+
|
|
585
|
+
const country = node.metadata?.["resolver_country"]
|
|
586
|
+
|
|
587
|
+
return backend.findPlace({
|
|
588
|
+
text: node.value,
|
|
589
|
+
placetype: "locality",
|
|
590
|
+
...(typeof country === "string" ? { country } : {}),
|
|
591
|
+
bias: [point],
|
|
592
|
+
limit: ROOFTOP_NAMESAKE_LIMIT,
|
|
593
|
+
})
|
|
594
|
+
}
|
|
595
|
+
: undefined
|
|
596
|
+
|
|
597
|
+
for (const { node, gapKm, repicked } of await reconcileLocalitiesToAnchor(roots, point, thresholdKm, findNear)) {
|
|
598
|
+
node.metadata = repicked
|
|
599
|
+
? { ...node.metadata, rooftop_repicked: true }
|
|
600
|
+
: { ...node.metadata, rooftop_outside_locality_km: gapKm }
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* The farthest distance, in kilometers, that {@link applyPostcodeConsistency}
|
|
606
|
+
* moves a locality onto its postcode's point.
|
|
607
|
+
*/
|
|
608
|
+
export const DEFAULT_POSTCODE_MAX_MOVE_KM = 300
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Reconciles each resolved locality that lies farther than `thresholdKm` from the tree's
|
|
612
|
+
* resolved postcode point, re-picking the nearest alternative within the threshold and otherwise
|
|
613
|
+
* moving the coordinate there, but skipping the move when the distance exceeds `maxMoveKm`.
|
|
614
|
+
*/
|
|
615
|
+
export async function applyPostcodeConsistency(
|
|
616
|
+
roots: readonly AddressNode[],
|
|
617
|
+
thresholdKm: number,
|
|
618
|
+
maxMoveKm = DEFAULT_POSTCODE_MAX_MOVE_KM
|
|
619
|
+
): Promise<void> {
|
|
620
|
+
let anchor: { lat: number; lon: number } | null = null
|
|
621
|
+
|
|
622
|
+
for (const n of walkNodes(roots)) {
|
|
623
|
+
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
|
|
624
|
+
anchor = { lat: n.lat!, lon: n.lon! }
|
|
625
|
+
|
|
626
|
+
break
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
if (!anchor) return
|
|
631
|
+
|
|
632
|
+
for (const { node, gapKm, repicked } of await reconcileLocalitiesToAnchor(roots, anchor, thresholdKm)) {
|
|
633
|
+
if (repicked) {
|
|
540
634
|
node.metadata = { ...node.metadata, postcode_repicked: true }
|
|
541
635
|
|
|
542
636
|
continue
|
package/lib/resolve.ts
CHANGED
|
@@ -36,9 +36,9 @@ import {
|
|
|
36
36
|
BARE_REGION_DOMINANCE_LOG10,
|
|
37
37
|
bareCountryCandidate,
|
|
38
38
|
bareRegionCandidate,
|
|
39
|
+
emptyLocalityPick,
|
|
39
40
|
logPopulation,
|
|
40
41
|
loneBareLocalityNode,
|
|
41
|
-
pickLargerAdmin,
|
|
42
42
|
} from "#bare-toponym-race"
|
|
43
43
|
import { decorateNode } from "#decorate-node"
|
|
44
44
|
import {
|
|
@@ -50,6 +50,7 @@ import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcod
|
|
|
50
50
|
import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "#postcode/shape-coherence"
|
|
51
51
|
import {
|
|
52
52
|
applyPostcodeConsistency,
|
|
53
|
+
applyRooftopConsistency,
|
|
53
54
|
applySpanRescore,
|
|
54
55
|
createNodeTraceRecorder,
|
|
55
56
|
DIAGNOSTIC_BANDS,
|
|
@@ -255,9 +256,12 @@ class WOFResolver implements Resolver {
|
|
|
255
256
|
await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry?.country ?? null)
|
|
256
257
|
}
|
|
257
258
|
|
|
259
|
+
// The postcode and rooftop passes hold a locality to the same distance from their point.
|
|
260
|
+
const consistencyThresholdKm = opts.postcodeConsistencyThresholdKm ?? 50
|
|
261
|
+
|
|
258
262
|
// Postcode/locality consistency pass (default on).
|
|
259
263
|
if (opts.postcodeConsistency) {
|
|
260
|
-
applyPostcodeConsistency(newRoots,
|
|
264
|
+
await applyPostcodeConsistency(newRoots, consistencyThresholdKm, opts.postcodeConsistencyMaxMoveKm)
|
|
261
265
|
}
|
|
262
266
|
|
|
263
267
|
// Optional exact address-point tier.
|
|
@@ -281,6 +285,11 @@ class WOFResolver implements Resolver {
|
|
|
281
285
|
applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
|
|
282
286
|
}
|
|
283
287
|
|
|
288
|
+
// A rooftop row keyed by locality name can lie in a namesake of the selected locality.
|
|
289
|
+
if (opts.addressPoints && opts.postcodeConsistency) {
|
|
290
|
+
await applyRooftopConsistency(newRoots, consistencyThresholdKm, this.#backend)
|
|
291
|
+
}
|
|
292
|
+
|
|
284
293
|
// Optional street-centroid tier runs last.
|
|
285
294
|
if (opts.streetCentroids) {
|
|
286
295
|
applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
|
|
@@ -587,18 +596,16 @@ class WOFResolver implements Resolver {
|
|
|
587
596
|
const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null
|
|
588
597
|
|
|
589
598
|
if (!candidates.length) {
|
|
590
|
-
// With no locality candidates,
|
|
591
|
-
const
|
|
599
|
+
// With no locality candidates, a bare name takes an admin or sub-locality namesake.
|
|
600
|
+
const pick = isBareRace
|
|
601
|
+
? await emptyLocalityPick(this.#backend, node.value, query.country, bareCountry, bareRegion)
|
|
602
|
+
: null
|
|
592
603
|
|
|
593
|
-
if (
|
|
594
|
-
rec.check(
|
|
595
|
-
rec.emit({ id:
|
|
604
|
+
if (pick) {
|
|
605
|
+
rec.check(pick.check)
|
|
606
|
+
rec.emit({ id: pick.place.id, name: pick.place.name, source: pick.source })
|
|
596
607
|
|
|
597
|
-
return {
|
|
598
|
-
top: admin,
|
|
599
|
-
alternatives: [],
|
|
600
|
-
metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
|
|
601
|
-
}
|
|
608
|
+
return { top: pick.place, alternatives: [], metadata: pick.metadata }
|
|
602
609
|
}
|
|
603
610
|
|
|
604
611
|
rec.emit(null)
|
package/lib/span-rescore.ts
CHANGED
|
@@ -134,8 +134,8 @@ function tokenizeRaw(raw: string): RawTok[] {
|
|
|
134
134
|
}
|
|
135
135
|
|
|
136
136
|
/**
|
|
137
|
-
* The code-shaped (digit-containing) token subset of a postcode string
|
|
138
|
-
*
|
|
137
|
+
* The code-shaped (digit-containing) token subset of a postcode string
|
|
138
|
+
* ("1382 Kožljek" yields "1382"), and an empty string when no token contains a digit.
|
|
139
139
|
*/
|
|
140
140
|
export function postcodeCodeSubset(postcode: string): string {
|
|
141
141
|
return postcode
|
|
@@ -146,8 +146,8 @@ export function postcodeCodeSubset(postcode: string): string {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
/**
|
|
149
|
-
* Over-fetch for the bare-toponym probe: without a country filter the top 5 worldwide bearers of
|
|
150
|
-
* common name
|
|
149
|
+
* Over-fetch for the bare-toponym probe: without a country filter the top 5 worldwide bearers of
|
|
150
|
+
* a common name can all be in one country, with the candidate the soft prior promotes below the fold.
|
|
151
151
|
*/
|
|
152
152
|
const BARE_TOPONYM_FETCH = 20
|
|
153
153
|
|
|
@@ -14,8 +14,8 @@ import type { ResolverBackend } from "@mailwoman/core/resolver";
|
|
|
14
14
|
*/
|
|
15
15
|
export declare function applyParentFallbackContradiction(roots: readonly AddressNode[]): void;
|
|
16
16
|
/**
|
|
17
|
-
* Re-picks a resolved region and its unresolved child locality as a pair,
|
|
18
|
-
* region candidate that
|
|
17
|
+
* Re-picks a resolved region and its unresolved child locality as a pair,
|
|
18
|
+
* choosing the region candidate that contains a locality with the same name.
|
|
19
19
|
*
|
|
20
20
|
* This recovers cases such as "Portland, ME" where the region was picked in isolation
|
|
21
21
|
* before the locality was known.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coherence-passes.d.ts","sourceRoot":"","sources":["../../lib/admin/coherence-passes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAY9E;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,IAAI,CAuCpF;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhH;AA4HD;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,GACtB,OAAO,CAAC,IAAI,CAAC,CAkBf;
|
|
1
|
+
{"version":3,"file":"coherence-passes.d.ts","sourceRoot":"","sources":["../../lib/admin/coherence-passes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAY9E;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,IAAI,CAuCpF;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhH;AA4HD;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,GACtB,OAAO,CAAC,IAAI,CAAC,CAkBf;AAmCD;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAChD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,EACxB,cAAc,EAAE,MAAM,GAAG,IAAI,GAC3B,OAAO,CAAC,IAAI,CAAC,CAuBf"}
|