@mailwoman/entity-resolution 0.0.0-stage → 11.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.
Files changed (227) hide show
  1. package/README.md +114 -2
  2. package/lib/address-key.ts +46 -0
  3. package/lib/geocode-handler.ts +37 -0
  4. package/lib/geojson.ts +72 -0
  5. package/lib/index.ts +23 -0
  6. package/lib/ingest.ts +349 -0
  7. package/lib/learned-scorer.ts +134 -0
  8. package/lib/map-html.ts +287 -0
  9. package/lib/models/crosssource-gbt-en-us.ts +43 -0
  10. package/lib/models/dedup-gbt-en-us.ts +47 -0
  11. package/lib/models/org-crosssource-gbt-en-us.ts +43 -0
  12. package/lib/reconcile.ts +239 -0
  13. package/lib/resolve.ts +569 -0
  14. package/lib/types.ts +110 -0
  15. package/out/address-key.d.ts +34 -0
  16. package/out/address-key.d.ts.map +1 -0
  17. package/out/address-key.js +41 -0
  18. package/out/address-key.js.map +1 -0
  19. package/out/geocode-handler.d.ts +20 -0
  20. package/out/geocode-handler.d.ts.map +1 -0
  21. package/out/geocode-handler.js +29 -0
  22. package/out/geocode-handler.js.map +1 -0
  23. package/out/geojson.d.ts +28 -0
  24. package/out/geojson.d.ts.map +1 -0
  25. package/out/geojson.js +62 -0
  26. package/out/geojson.js.map +1 -0
  27. package/out/index.d.ts +23 -0
  28. package/out/index.d.ts.map +1 -0
  29. package/out/index.js +23 -0
  30. package/out/index.js.map +1 -0
  31. package/out/ingest.d.ts +173 -0
  32. package/out/ingest.d.ts.map +1 -0
  33. package/out/ingest.js +185 -0
  34. package/out/ingest.js.map +1 -0
  35. package/out/learned-scorer.d.ts +61 -0
  36. package/out/learned-scorer.d.ts.map +1 -0
  37. package/out/learned-scorer.js +91 -0
  38. package/out/learned-scorer.js.map +1 -0
  39. package/out/map-html.d.ts +39 -0
  40. package/out/map-html.d.ts.map +1 -0
  41. package/out/map-html.js +220 -0
  42. package/out/map-html.js.map +1 -0
  43. package/out/models/crosssource-gbt-en-us.d.ts +45 -0
  44. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -0
  45. package/out/models/crosssource-gbt-en-us.js +40 -0
  46. package/out/models/crosssource-gbt-en-us.js.map +1 -0
  47. package/out/models/dedup-gbt-en-us.d.ts +44 -0
  48. package/out/models/dedup-gbt-en-us.d.ts.map +1 -0
  49. package/out/models/dedup-gbt-en-us.js +44 -0
  50. package/out/models/dedup-gbt-en-us.js.map +1 -0
  51. package/out/models/org-crosssource-gbt-en-us.d.ts +45 -0
  52. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -0
  53. package/out/models/org-crosssource-gbt-en-us.js +40 -0
  54. package/out/models/org-crosssource-gbt-en-us.js.map +1 -0
  55. package/out/reconcile.d.ts +96 -0
  56. package/out/reconcile.d.ts.map +1 -0
  57. package/out/reconcile.js +127 -0
  58. package/out/reconcile.js.map +1 -0
  59. package/out/resolve.d.ts +264 -0
  60. package/out/resolve.d.ts.map +1 -0
  61. package/out/resolve.js +282 -0
  62. package/out/resolve.js.map +1 -0
  63. package/out/tools/coverage-reconciliation.d.ts +67 -0
  64. package/out/tools/coverage-reconciliation.d.ts.map +1 -0
  65. package/out/tools/coverage-reconciliation.js +113 -0
  66. package/out/tools/coverage-reconciliation.js.map +1 -0
  67. package/out/tools/cross/dataset-correlation.d.ts +61 -0
  68. package/out/tools/cross/dataset-correlation.d.ts.map +1 -0
  69. package/out/tools/cross/dataset-correlation.js +244 -0
  70. package/out/tools/cross/dataset-correlation.js.map +1 -0
  71. package/out/tools/cross/source-threshold-sweep.d.ts +60 -0
  72. package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -0
  73. package/out/tools/cross/source-threshold-sweep.js +264 -0
  74. package/out/tools/cross/source-threshold-sweep.js.map +1 -0
  75. package/out/tools/dedup-ceiling.d.ts +62 -0
  76. package/out/tools/dedup-ceiling.d.ts.map +1 -0
  77. package/out/tools/dedup-ceiling.js +171 -0
  78. package/out/tools/dedup-ceiling.js.map +1 -0
  79. package/out/tools/eval-geocoder.d.ts +68 -0
  80. package/out/tools/eval-geocoder.d.ts.map +1 -0
  81. package/out/tools/eval-geocoder.js +13 -0
  82. package/out/tools/eval-geocoder.js.map +1 -0
  83. package/out/tools/geocoder/namesake-probe.d.ts +33 -0
  84. package/out/tools/geocoder/namesake-probe.d.ts.map +1 -0
  85. package/out/tools/geocoder/namesake-probe.js +60 -0
  86. package/out/tools/geocoder/namesake-probe.js.map +1 -0
  87. package/out/tools/geocoder/vs-provided-coords.d.ts +53 -0
  88. package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -0
  89. package/out/tools/geocoder/vs-provided-coords.js +161 -0
  90. package/out/tools/geocoder/vs-provided-coords.js.map +1 -0
  91. package/out/tools/gold-set-sample.d.ts +67 -0
  92. package/out/tools/gold-set-sample.d.ts.map +1 -0
  93. package/out/tools/gold-set-sample.js +81 -0
  94. package/out/tools/gold-set-sample.js.map +1 -0
  95. package/out/tools/learned/scorer/clustering-eval.d.ts +77 -0
  96. package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -0
  97. package/out/tools/learned/scorer/clustering-eval.js +207 -0
  98. package/out/tools/learned/scorer/clustering-eval.js.map +1 -0
  99. package/out/tools/learned/scorer/crossstate-eval.d.ts +65 -0
  100. package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -0
  101. package/out/tools/learned/scorer/crossstate-eval.js +168 -0
  102. package/out/tools/learned/scorer/crossstate-eval.js.map +1 -0
  103. package/out/tools/learned/scorer/eval.d.ts +64 -0
  104. package/out/tools/learned/scorer/eval.d.ts.map +1 -0
  105. package/out/tools/learned/scorer/eval.js +275 -0
  106. package/out/tools/learned/scorer/eval.js.map +1 -0
  107. package/out/tools/matcher-scale.d.ts +40 -0
  108. package/out/tools/matcher-scale.d.ts.map +1 -0
  109. package/out/tools/matcher-scale.js +111 -0
  110. package/out/tools/matcher-scale.js.map +1 -0
  111. package/out/tools/nppes/dedup-benchmark.d.ts +82 -0
  112. package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -0
  113. package/out/tools/nppes/dedup-benchmark.js +226 -0
  114. package/out/tools/nppes/dedup-benchmark.js.map +1 -0
  115. package/out/tools/nppes/org-name.d.ts +15 -0
  116. package/out/tools/nppes/org-name.d.ts.map +1 -0
  117. package/out/tools/nppes/org-name.js +6 -0
  118. package/out/tools/nppes/org-name.js.map +1 -0
  119. package/out/tools/nppes/overmerge-packet.d.ts +43 -0
  120. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  121. package/out/tools/nppes/overmerge-packet.js +54 -0
  122. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  123. package/out/tools/nppes/report.d.ts +97 -0
  124. package/out/tools/nppes/report.d.ts.map +1 -0
  125. package/out/tools/nppes/report.js +178 -0
  126. package/out/tools/nppes/report.js.map +1 -0
  127. package/out/tools/nppes/sample.d.ts +101 -0
  128. package/out/tools/nppes/sample.d.ts.map +1 -0
  129. package/out/tools/nppes/sample.js +127 -0
  130. package/out/tools/nppes/sample.js.map +1 -0
  131. package/out/tools/nppes/scoring.d.ts +37 -0
  132. package/out/tools/nppes/scoring.d.ts.map +1 -0
  133. package/out/tools/nppes/scoring.js +81 -0
  134. package/out/tools/nppes/scoring.js.map +1 -0
  135. package/out/tools/nppes/settings.d.ts +41 -0
  136. package/out/tools/nppes/settings.d.ts.map +1 -0
  137. package/out/tools/nppes/settings.js +79 -0
  138. package/out/tools/nppes/settings.js.map +1 -0
  139. package/out/tools/nppes/truth-grains.d.ts +63 -0
  140. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  141. package/out/tools/nppes/truth-grains.js +142 -0
  142. package/out/tools/nppes/truth-grains.js.map +1 -0
  143. package/out/tools/shared.d.ts +325 -0
  144. package/out/tools/shared.d.ts.map +1 -0
  145. package/out/tools/shared.js +453 -0
  146. package/out/tools/shared.js.map +1 -0
  147. package/out/tools/train/cross-gbt.d.ts +89 -0
  148. package/out/tools/train/cross-gbt.d.ts.map +1 -0
  149. package/out/tools/train/cross-gbt.js +132 -0
  150. package/out/tools/train/cross-gbt.js.map +1 -0
  151. package/out/tools/train/gbt.d.ts +85 -0
  152. package/out/tools/train/gbt.d.ts.map +1 -0
  153. package/out/tools/train/gbt.js +155 -0
  154. package/out/tools/train/gbt.js.map +1 -0
  155. package/out/tools/train/org-cross-gbt.d.ts +85 -0
  156. package/out/tools/train/org-cross-gbt.d.ts.map +1 -0
  157. package/out/tools/train/org-cross-gbt.js +122 -0
  158. package/out/tools/train/org-cross-gbt.js.map +1 -0
  159. package/out/tools/txhhsc-to-oarow.d.ts +42 -0
  160. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -0
  161. package/out/tools/txhhsc-to-oarow.js +78 -0
  162. package/out/tools/txhhsc-to-oarow.js.map +1 -0
  163. package/out/tools/viz/browser.d.ts +31 -0
  164. package/out/tools/viz/browser.d.ts.map +1 -0
  165. package/out/tools/viz/browser.js +26 -0
  166. package/out/tools/viz/browser.js.map +1 -0
  167. package/out/tools/viz/cross-dataset-map.d.ts +39 -0
  168. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -0
  169. package/out/tools/viz/cross-dataset-map.js +84 -0
  170. package/out/tools/viz/cross-dataset-map.js.map +1 -0
  171. package/out/tools/viz/geocode-first-surface.d.ts +36 -0
  172. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -0
  173. package/out/tools/viz/geocode-first-surface.js +234 -0
  174. package/out/tools/viz/geocode-first-surface.js.map +1 -0
  175. package/out/tools/viz/render/map.d.ts +42 -0
  176. package/out/tools/viz/render/map.d.ts.map +1 -0
  177. package/out/tools/viz/render/map.js +40 -0
  178. package/out/tools/viz/render/map.js.map +1 -0
  179. package/out/tools/viz/render.d.ts +46 -0
  180. package/out/tools/viz/render.d.ts.map +1 -0
  181. package/out/tools/viz/render.js +49 -0
  182. package/out/tools/viz/render.js.map +1 -0
  183. package/out/tools/viz/source-provenance-map.d.ts +57 -0
  184. package/out/tools/viz/source-provenance-map.d.ts.map +1 -0
  185. package/out/tools/viz/source-provenance-map.js +82 -0
  186. package/out/tools/viz/source-provenance-map.js.map +1 -0
  187. package/out/tools/viz/yardstick-figure.d.ts +22 -0
  188. package/out/tools/viz/yardstick-figure.d.ts.map +1 -0
  189. package/out/tools/viz/yardstick-figure.js +106 -0
  190. package/out/tools/viz/yardstick-figure.js.map +1 -0
  191. package/out/types.d.ts +108 -0
  192. package/out/types.d.ts.map +1 -0
  193. package/out/types.js +11 -0
  194. package/out/types.js.map +1 -0
  195. package/package.json +113 -3
  196. package/tools/coverage-reconciliation.ts +192 -0
  197. package/tools/cross/dataset-correlation.ts +380 -0
  198. package/tools/cross/source-threshold-sweep.ts +416 -0
  199. package/tools/dedup-ceiling.ts +225 -0
  200. package/tools/eval-geocoder.ts +77 -0
  201. package/tools/geocoder/namesake-probe.ts +91 -0
  202. package/tools/geocoder/vs-provided-coords.ts +232 -0
  203. package/tools/gold-set-sample.ts +147 -0
  204. package/tools/learned/scorer/clustering-eval.ts +349 -0
  205. package/tools/learned/scorer/crossstate-eval.ts +280 -0
  206. package/tools/learned/scorer/eval.ts +429 -0
  207. package/tools/matcher-scale.ts +185 -0
  208. package/tools/nppes/dedup-benchmark.ts +364 -0
  209. package/tools/nppes/org-name.ts +15 -0
  210. package/tools/nppes/overmerge-packet.ts +98 -0
  211. package/tools/nppes/report.ts +380 -0
  212. package/tools/nppes/sample.ts +250 -0
  213. package/tools/nppes/scoring.ts +115 -0
  214. package/tools/nppes/settings.ts +102 -0
  215. package/tools/nppes/truth-grains.ts +185 -0
  216. package/tools/shared.ts +743 -0
  217. package/tools/train/cross-gbt.ts +214 -0
  218. package/tools/train/gbt.ts +261 -0
  219. package/tools/train/org-cross-gbt.ts +189 -0
  220. package/tools/txhhsc-to-oarow.ts +118 -0
  221. package/tools/viz/browser.ts +41 -0
  222. package/tools/viz/cross-dataset-map.ts +133 -0
  223. package/tools/viz/geocode-first-surface.ts +305 -0
  224. package/tools/viz/render/map.ts +61 -0
  225. package/tools/viz/render.ts +103 -0
  226. package/tools/viz/source-provenance-map.ts +154 -0
  227. package/tools/viz/yardstick-figure.ts +197 -0
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The injected-geocoder interface for the record-matcher tools. The registry package never imports
7
+ * the heavy runtime (neural parser, WOF resolver, per-state extracts), since `mailwoman` depends on
8
+ * `@mailwoman/entity-resolution` and the reverse import would cycle the workspace graph. Each tool instead
9
+ * takes an {@linkcode EvalGeocoderFactory} the CLI command constructs from
10
+ * `mailwoman/geocode-core` (see `mailwoman/commands/registry/run.tsx`).
11
+ */
12
+
13
+ import type { CaseNormalization } from "@mailwoman/core/pipeline"
14
+
15
+ import type { ColumnMapping, GeocodeAddress, SourceRecord } from "#index"
16
+
17
+ /**
18
+ * The raw single-address geocode surface used by the probe tools, mirroring
19
+ * `mailwoman/geocode-core`'s wire shape.
20
+ */
21
+ export interface EvalGeocodeResult {
22
+ lat: number | null
23
+ lon: number | null
24
+ /**
25
+ * Wire key that mirrors `GeocodeResult.resolution_tier`.
26
+ */
27
+ resolution_tier?: string | null
28
+ }
29
+
30
+ /**
31
+ * A constructed geocoder: the matcher's ingest interface, the raw geocode and the handle release.
32
+ */
33
+ export interface EvalGeocoder extends Disposable {
34
+ /**
35
+ * The matcher's ingest interface (parse and geocode to `PostalAddress`),
36
+ * built through `geocodeAddressVia`.
37
+ */
38
+ geocodeAddress: GeocodeAddress
39
+ /**
40
+ * Raw single-address geocode returning lat, lon and resolution tier.
41
+ */
42
+ geocode: (address: string) => Promise<EvalGeocodeResult>
43
+ /**
44
+ * Release the DB handles (extracts + WOF lookup).
45
+ */
46
+ }
47
+
48
+ /**
49
+ * Per-construction toggles a tool may need to control (the command owns model/WOF/data-root wiring).
50
+ */
51
+ export interface EvalGeocoderInit {
52
+ /**
53
+ * All-caps case normalization.
54
+ *
55
+ * `nppes-benchmark --legacy-join` passes `"preserve"` for the A/B.
56
+ *
57
+ * @defaultValue `"title-case"`
58
+ */
59
+ caseNormalization?: CaseNormalization
60
+ }
61
+
62
+ /**
63
+ * Build a geocoder on demand.
64
+ *
65
+ * Tools construct it late and dispose it as soon as geocoding is done.
66
+ */
67
+ export type EvalGeocoderFactory = (init?: EvalGeocoderInit) => Promise<EvalGeocoder>
68
+
69
+ /**
70
+ * The threaded geocode surface (`mailwoman/geocode-stream` behind the interface)
71
+ * for `nppes-dedup-benchmark --parallel-geocode`.
72
+ * It yields enriched records in completion order.
73
+ */
74
+ export type EvalGeocodeStream = (
75
+ records: SourceRecord[],
76
+ opts: { mapping: ColumnMapping; concurrency: number }
77
+ ) => AsyncIterable<SourceRecord>
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Admin-tier wrong-region probe. When no street extract covers an address, the admin cascade can
7
+ * resolve the locality by name and, when the region or postcode constraint is weak, pick the
8
+ * population-dominant foreign namesake instead of the in-state Texas city. This probes a curated
9
+ * set of TX namesake cities, with and without ZIP. It flags any result outside the Texas bounding
10
+ * box.
11
+ *
12
+ * Run: `mailwoman registry scorer-eval namesake-probe`
13
+ */
14
+
15
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
16
+
17
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
18
+ import { inTXBBOX } from "#tools/shared"
19
+
20
+ /**
21
+ * Options for {@linkcode geocoderNamesakeProbe}.
22
+ */
23
+ export interface GeocoderNamesakeProbeOptions {
24
+ /**
25
+ * The injected geocoder factory.
26
+ *
27
+ * The command wires `mailwoman/geocode-core`, as `./eval-geocoder.ts` does.
28
+ */
29
+ createGeocoder: EvalGeocoderFactory
30
+ }
31
+
32
+ /**
33
+ * TX namesake cities with their real Texas coordinates + the famous foreign/other namesake to watch for.
34
+ */
35
+ const CASES: Array<{ city: string; zip: string; tx: [number, number]; namesake: string }> = [
36
+ { city: "Paris", zip: "75460", tx: [33.66, -95.55], namesake: "Paris, France (48.85, 2.35)" },
37
+ { city: "Athens", zip: "75751", tx: [32.2, -95.85], namesake: "Athens, Greece (37.98, 23.72)" },
38
+ { city: "Palestine", zip: "75801", tx: [31.76, -95.63], namesake: "Palestine, Levant (31.9, 35.2)" },
39
+ { city: "Italy", zip: "76651", tx: [32.18, -96.88], namesake: "Italy, the country (~42, 12)" },
40
+ { city: "Naples", zip: "75568", tx: [33.2, -94.68], namesake: "Naples, Italy (40.85, 14.27)" },
41
+ { city: "Dublin", zip: "76446", tx: [32.08, -98.34], namesake: "Dublin, Ireland (53.35, -6.26)" },
42
+ { city: "Nazareth", zip: "79063", tx: [34.54, -102.1], namesake: "Nazareth, Israel (32.7, 35.3)" },
43
+ { city: "Odessa", zip: "79761", tx: [31.85, -102.37], namesake: "Odessa, Ukraine (46.48, 30.72)" },
44
+ ]
45
+
46
+ /**
47
+ * Probe a curated set of TX namesake cities and print one line per variant to stdout.
48
+ */
49
+ export async function geocoderNamesakeProbe(
50
+ options: GeocoderNamesakeProbeOptions,
51
+ report?: (line: string) => void
52
+ ): Promise<{ wrongRegion: number; total: number }> {
53
+ report?.("[A] building the geocoder…")
54
+ const geocoder = await options.createGeocoder()
55
+ const geo = geocoder.geocode
56
+
57
+ report?.("[B] probing TX namesake cities (with ZIP / without ZIP)…\n")
58
+ let wrongRegion = 0
59
+ let total = 0
60
+
61
+ for (const c of CASES) {
62
+ for (const variant of [`${c.city}, TX ${c.zip}`, `${c.city}, TX`, `${c.city}, Texas`]) {
63
+ total++
64
+ const g = await geo(variant)
65
+
66
+ if (g.lat === null || g.lon === null) {
67
+ console.log(` ✗ "${variant}" → UNPLACED`)
68
+
69
+ continue
70
+ }
71
+
72
+ const ok = inTXBBOX(g.lat, g.lon)
73
+ const km = haversine(c.tx[0], c.tx[1], g.lat, g.lon)
74
+
75
+ if (!ok) {
76
+ wrongRegion++
77
+ }
78
+
79
+ console.log(
80
+ ` ${ok ? "✓" : "✗ WRONG-REGION"} "${variant}" → ${g.lat.toFixed(3)},${g.lon.toFixed(3)} ` +
81
+ `[${g.resolution_tier ?? "?"}] ${km > 100 ? `${km.toFixed(0)}km off TX (cf ${c.namesake})` : `${(km * 1000).toFixed(0)}m off`}`
82
+ )
83
+ }
84
+ }
85
+
86
+ geocoder[Symbol.dispose]()
87
+
88
+ console.log(`\n ${wrongRegion}/${total} variants resolved OUTSIDE Texas (wrong-region).`)
89
+
90
+ return { wrongRegion, total }
91
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Geocoder validation against provided coordinates. TX HHSC's nursing-facilities registry ships
7
+ * a `Geo Location` (`lat,lon`) per facility alongside its physical address. Geocode the address
8
+ * with mailwoman's parser and resolver, then measure the great-circle delta to the provided point,
9
+ * broken down by resolution tier.
10
+ *
11
+ * The provided coordinate is treated as ground truth for this eval, with the caveat that it is
12
+ * itself a third-party geocode of unknown provenance. A large delta is a discrepancy to inspect
13
+ * rather than automatically our error.
14
+ *
15
+ * Run: `mailwoman registry scorer-eval vs-provided-coords [--max 1176] [--wof <admin.db>]
16
+ * [--data-root <dir>] [--out-md docs/articles/evals/resolver-geo/<date>-...md]`
17
+ */
18
+
19
+ import { dataRootPath } from "@mailwoman/core/data-root"
20
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
21
+ import { isPresent } from "@mailwoman/core/objects"
22
+ import { percentile } from "@mailwoman/core/stats"
23
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
24
+ import { TextSpliterator } from "spliterator"
25
+
26
+ import { streamRows } from "#index"
27
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
28
+ import { norm } from "#tools/shared"
29
+
30
+ /**
31
+ * Largest absolute latitude in WGS-84 degrees.
32
+ */
33
+ const MAX_ABS_LATITUDE = 90
34
+
35
+ /**
36
+ * Largest absolute longitude in WGS-84 degrees.
37
+ */
38
+ const MAX_ABS_LONGITUDE = 180
39
+
40
+ /**
41
+ * Options for {@linkcode geocoderVsProvidedCoords}.
42
+ */
43
+ export interface GeocoderVsProvidedCoordsOptions {
44
+ /**
45
+ * The injected geocoder factory.
46
+ *
47
+ * The command wires `mailwoman/geocode-core`, as `./eval-geocoder.ts` does.
48
+ */
49
+ createGeocoder: EvalGeocoderFactory
50
+ /**
51
+ * Record-matcher sources directory.
52
+ *
53
+ * @defaultValue `$MAILWOMAN_DATA_ROOT/record-matcher/sources`
54
+ */
55
+ sources?: string
56
+ /**
57
+ * Facilities geocoded.
58
+ *
59
+ * @defaultValue `2000`
60
+ */
61
+ max?: number
62
+ /**
63
+ * Also write the markdown report here.
64
+ */
65
+ outMd?: string
66
+ }
67
+
68
+ /**
69
+ * Parse a `lat,lon` string into a coordinate, or null if malformed or out of range.
70
+ *
71
+ * Deliberately strict and deliberately not `GeoPoint.from()`.
72
+ * The provided coordinate is this eval's ground truth, so a row that cannot be read exactly
73
+ * is dropped (counted in `noCoord`) rather than repaired into something plausible.
74
+ *
75
+ * A silently repaired coordinate lands in the delta distribution as geocoder error.
76
+ *
77
+ * This source writes `latitude,longitude`, while `GeoPoint` reads GeoJSON `[longitude, latitude]`,
78
+ * so `31.5,-89.5` is a Mississippi row here and a South-Atlantic point there.
79
+ * `GeoPoint.from` also maps 0,0 to null.
80
+ *
81
+ * This moves Null Island out of the measured outliers and into the skipped bucket.
82
+ *
83
+ * The report attributes part of its p99/max tail to malformed provided coordinates,
84
+ * so those rows have to stay rejected or measured as-is, never rewritten.
85
+ *
86
+ * Strictness is the measurement rather than an unfinished migration.
87
+ */
88
+ function parseLatLon(raw: string | null | undefined): { latitude: number; longitude: number } | null {
89
+ if (!raw) return null
90
+ const [a, b] = TextSpliterator.from(raw, { delimiter: "," }).map(Number).toArray()
91
+
92
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return null
93
+
94
+ if (Math.abs(a!) > MAX_ABS_LATITUDE || Math.abs(b!) > MAX_ABS_LONGITUDE) return null
95
+
96
+ return { latitude: a!, longitude: b! }
97
+ }
98
+
99
+ // The core nearest-rank `percentile` (q in [0,100]) uses a floor index and clamping.
100
+ // `?? NaN` returns NaN when the percentile helper returns null for an empty sample.
101
+ const quantile = (xs: number[], q: number): number => percentile(xs, q * 100) ?? Number.NaN
102
+
103
+ /**
104
+ * Geocode each facility's physical address and measure the delta to its provided
105
+ * coordinate, then emit the report to stdout.
106
+ */
107
+ export async function geocoderVsProvidedCoords(
108
+ options: GeocoderVsProvidedCoordsOptions,
109
+ report?: (line: string) => void
110
+ ): Promise<{ markdown: string }> {
111
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
112
+ const MAX = options.max ?? 2000
113
+ const OUT_MD = options.outMd || ""
114
+
115
+ const FILE = `${SOURCES}/txhhsc_nursing-facilities_20260611.tsv`
116
+
117
+ report?.("[A] building the geocoder…")
118
+ const geocoder = await options.createGeocoder()
119
+
120
+ report?.(`[B] geocoding ≤${MAX} TX nursing facilities + measuring delta to provided coords…`)
121
+
122
+ interface Row {
123
+ deltaM: number
124
+ tier: string
125
+ }
126
+
127
+ const results: Row[] = []
128
+ let scanned = 0
129
+ let noCoord = 0
130
+ let noPlace = 0
131
+
132
+ for await (const r of streamRows(FILE)) {
133
+ if (results.length >= MAX) break
134
+ const provided = parseLatLon(r["Geo Location"])
135
+ const line = norm(r["Physical Address"])
136
+ const city = norm(r["Physical Address CITY"])
137
+ const state = norm(r["Physical Address State"])
138
+ const zip = norm(r["Physical Address Zipcode"])
139
+
140
+ if (!provided || !line) {
141
+ noCoord++
142
+
143
+ continue
144
+ }
145
+
146
+ scanned++
147
+ const address = [line, city, state, zip].filter(isPresent).join(", ")
148
+ const g = await geocoder.geocode(address)
149
+
150
+ if (g.lat === null || g.lon === null) {
151
+ noPlace++
152
+
153
+ continue
154
+ }
155
+
156
+ const deltaM = haversine(provided.latitude, provided.longitude, g.lat, g.lon) * 1000
157
+ results.push({ deltaM, tier: g.resolution_tier ?? "unknown" })
158
+ }
159
+
160
+ geocoder[Symbol.dispose]()
161
+
162
+ const all = results.map((r) => r.deltaM).toSorted((a, b) => a - b)
163
+ const byTier = new Map<string, number[]>()
164
+
165
+ for (const r of results) {
166
+ const list = byTier.get(r.tier) ?? []
167
+ list.push(r.deltaM)
168
+ byTier.set(r.tier, list)
169
+ }
170
+
171
+ const m = (x: number) => (x >= 1000 ? `${(x / 1000).toFixed(2)} km` : `${Math.round(x)} m`)
172
+
173
+ report?.(
174
+ ` geocoded ${results.length}/${scanned} placed (${noPlace} unplaced, ${noCoord} skipped no-coord/addr); ` +
175
+ `p50 ${m(quantile(all, 0.5))}, p90 ${m(quantile(all, 0.9))}`
176
+ )
177
+
178
+ const lines: string[] = [
179
+ `# Geocoder vs provided coordinates (#619)`,
180
+ "",
181
+ `_Generated by \`mailwoman registry scorer-eval vs-provided-coords\`. Source: TX HHSC ` +
182
+ `nursing-facilities (\`Geo Location\` = provided \`lat,lon\`). We geocode each facility's physical address ` +
183
+ `with mailwoman's parser + resolver and measure the great-circle delta to the provided point. The provided ` +
184
+ `coordinate is a third-party geocode of unknown provenance — a large delta is a discrepancy to inspect, not ` +
185
+ `automatically our error._`,
186
+ "",
187
+ `## Result`,
188
+ "",
189
+ `- facilities geocoded: **${results.length}** of ${scanned} with a usable address + provided coord`,
190
+ `- unplaced by our geocoder: ${noPlace} · skipped (no coord / no address): ${noCoord}`,
191
+ `- **overall delta: p50 ${m(quantile(all, 0.5))}, p90 ${m(quantile(all, 0.9))}, p99 ${m(quantile(all, 0.99))}** ` +
192
+ `(max ${m(all.at(-1) ?? 0)})`,
193
+ "",
194
+ `## By resolution tier`,
195
+ "",
196
+ `| tier | n | p50 | p90 |`,
197
+ `|---|---:|---:|---:|`,
198
+ ]
199
+
200
+ for (const [tier, list] of [...byTier.entries()].toSorted((a, b) => b[1].length - a[1].length)) {
201
+ const s = [...list].toSorted((a, b) => a - b)
202
+ lines.push(`| ${tier} | ${list.length} | ${m(quantile(s, 0.5))} | ${m(quantile(s, 0.9))} |`)
203
+ }
204
+
205
+ lines.push("")
206
+ lines.push(`## Reading`)
207
+ lines.push("")
208
+
209
+ lines.push(
210
+ `Two regimes. **Street-tier placement is excellent** (the address_point + interpolated rows above) — ` +
211
+ `rooftop-to-segment medians, the precision that makes geo-first blocking and the distance evidence ` +
212
+ `trustworthy. The **admin (centroid) tier** is where no street extract covered the address: accuracy is ` +
213
+ `necessarily km-scale, and it carries a catastrophic tail (the p90/p99/max above) from wrong-region admin ` +
214
+ `resolutions and/or malformed provided coordinates — NOT street-tier error. Those extremes are a signal to ` +
215
+ `inspect, and they motivate wider street-extract coverage for rural TX plus an admin-tier sanity bound. The ` +
216
+ `self-reported-vs-independent coordinate discrepancy is itself a data-quality column the reconciliation ` +
217
+ `surfaces (#621).`
218
+ )
219
+
220
+ lines.push("")
221
+
222
+ const md = lines.join("\n")
223
+
224
+ console.log(md)
225
+
226
+ if (OUT_MD) {
227
+ await writeLocalFile(md, OUT_MD)
228
+ report?.(`\n[written] ${OUT_MD}`)
229
+ }
230
+
231
+ return { markdown: md }
232
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Gold-set sampling for adjudication. The programmatic entity truth
7
+ * (`nppes-dedup-benchmark.ts`) collapses only NPPES-flagged subparts (Is-Subpart plus parent
8
+ * LBN/TIN), so it cannot settle the ambiguous co-located collisions: distinct NPIs at
9
+ * one address with near-identical name text and no subpart flag for the same parent.
10
+ * NPI truth and programmatic rules may disagree on these pairs. A frozen
11
+ * adjudicated gold set must cover.
12
+ *
13
+ * This scans the full TX registry without geocoding and writes each pair as a JSONL row containing
14
+ * both records' fields (org name, address, authorized official, taxonomy, subpart and parent
15
+ * flags) plus the programmatic verdict. An adjudicator (human or LLM-as-judge, flagged as such)
16
+ * can then label same real-world entity or not.
17
+ *
18
+ * Run: `mailwoman registry gold-set-sample [--cap 200000] [--state TX] [--tau 0.7] [--n 300]
19
+ * [--out-jsonl <path>]`
20
+ */
21
+
22
+ import { dataRootPath } from "@mailwoman/core/data-root"
23
+ import { writeLocalJSONLFile } from "@mailwoman/core/fs/writers"
24
+ import { stringifyJSON } from "@mailwoman/core/json"
25
+ import { jaccard } from "@mailwoman/match"
26
+
27
+ import { colocatedDistinctPairs, scanColocatedProviders, stateOption } from "#tools/shared"
28
+
29
+ /**
30
+ * Options for {@linkcode goldSetSample}.
31
+ */
32
+ export interface GoldSetSampleOptions {
33
+ /**
34
+ * Record-matcher sources directory.
35
+ *
36
+ * @defaultValue `$MAILWOMAN_DATA_ROOT/record-matcher/sources`
37
+ */
38
+ sources?: string
39
+ /**
40
+ * Providers sampled from the registry.
41
+ *
42
+ * @defaultValue `200000`
43
+ */
44
+ cap?: number
45
+ /**
46
+ * State filter.
47
+ *
48
+ * @defaultValue TX.
49
+ */
50
+ state?: string
51
+ /**
52
+ * Org-name Jaccard collision threshold.
53
+ *
54
+ * @defaultValue `0.7`
55
+ */
56
+ tau?: number
57
+ /**
58
+ * Adjudication sample size.
59
+ *
60
+ * @defaultValue `300`
61
+ */
62
+ n?: number
63
+ /**
64
+ * Write the sampled pairs here as jsonl (otherwise the first 10 print to stdout).
65
+ */
66
+ outJSONL?: string
67
+ }
68
+
69
+ interface HardPair {
70
+ npiA: string
71
+ npiB: string
72
+ orgA: string
73
+ orgB: string
74
+ address: string
75
+ nameJaccard: number
76
+ sameAuthorizedOfficial: boolean
77
+ sameTaxonomy: boolean
78
+ bothSubpartSameParent: boolean
79
+ programmaticVerdict: "same-entity" | "distinct"
80
+ adjudication: null
81
+ }
82
+
83
+ /**
84
+ * Sample the hard co-located name-collision stratum for adjudication.
85
+ */
86
+ export async function goldSetSample(
87
+ options: GoldSetSampleOptions = {},
88
+ report?: (line: string) => void
89
+ ): Promise<{ hardPairs: number; sampled: number }> {
90
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
91
+ const CAP = options.cap ?? 200_000
92
+ const STATE = stateOption(options)
93
+ const TAU = options.tau ?? 0.7
94
+ const N = options.n ?? 300
95
+ const OUT = options.outJSONL || ""
96
+ const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
97
+
98
+ report?.(`[A] streaming ${STATE} org providers (cap ${CAP})…`)
99
+ const { byAddr, kept } = await scanColocatedProviders({ registryPath: REGISTRY, state: STATE, cap: CAP })
100
+ report?.(` ${kept} providers at ${byAddr.size} addresses`)
101
+
102
+ const hard: HardPair[] = []
103
+
104
+ for (const { a, b } of colocatedDistinctPairs(byAddr)) {
105
+ const sim = jaccard(a.tokens, b.tokens)
106
+
107
+ if (sim < TAU) continue
108
+ const sameParent = a.subpart && b.subpart && a.parent === b.parent && a.parent !== "|"
109
+
110
+ if (sameParent) continue
111
+ const sameAuth = a.auth !== "" && a.auth === b.auth
112
+ const sameTax = a.taxonomy !== "" && a.taxonomy === b.taxonomy
113
+
114
+ hard.push({
115
+ npiA: a.npi,
116
+ npiB: b.npi,
117
+ orgA: a.org,
118
+ orgB: b.org,
119
+ address: a.address,
120
+ nameJaccard: Number(sim.toFixed(3)),
121
+ sameAuthorizedOfficial: sameAuth,
122
+ sameTaxonomy: sameTax,
123
+ bothSubpartSameParent: false,
124
+ // The verdict records what an entity-level rule would say, so adjudication can grade it.
125
+ programmaticVerdict: sameAuth ? "same-entity" : "distinct",
126
+ adjudication: null,
127
+ })
128
+ }
129
+
130
+ report?.(` ${hard.length} hard co-located name-collision pairs (non-flagged-subpart)`)
131
+
132
+ // A deterministic stride sample avoids file-order bias in the adjudication set.
133
+ const stride = Math.max(1, Math.floor(hard.length / N))
134
+ const sample = hard.filter((_, i) => i % stride === 0).slice(0, N)
135
+ report?.(` sampling ${sample.length} (stride ${stride}) for adjudication`)
136
+
137
+ if (OUT) {
138
+ await writeLocalJSONLFile(sample, OUT)
139
+ report?.(`[written] ${OUT}`)
140
+ } else {
141
+ for (const p of sample.slice(0, 10)) {
142
+ console.log(stringifyJSON(p))
143
+ }
144
+ }
145
+
146
+ return { hardPairs: hard.length, sampled: sample.length }
147
+ }