@mailwoman/registry 9.1.0 → 9.3.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 (228) hide show
  1. package/README.md +2 -2
  2. package/{address-key.ts → lib/address-key.ts} +1 -1
  3. package/{geocode-handler.ts → lib/geocode-handler.ts} +7 -7
  4. package/{geojson.ts → lib/geojson.ts} +12 -6
  5. package/{index.ts → lib/index.ts} +10 -10
  6. package/{ingest.ts → lib/ingest.ts} +77 -69
  7. package/{learned-scorer.ts → lib/learned-scorer.ts} +1 -1
  8. package/{map-html.ts → lib/map-html.ts} +10 -16
  9. package/{reconcile.ts → lib/reconcile.ts} +9 -24
  10. package/{resolve.ts → lib/resolve.ts} +31 -13
  11. package/{tools → lib/tools}/coverage-reconciliation.ts +13 -15
  12. package/{tools → lib/tools}/cross-dataset-correlation.ts +64 -139
  13. package/{tools → lib/tools}/cross-source-threshold-sweep.ts +21 -32
  14. package/{tools → lib/tools}/dedup-ceiling.ts +33 -144
  15. package/{tools → lib/tools}/eval-geocoder.ts +10 -11
  16. package/{tools → lib/tools}/geocoder-namesake-probe.ts +5 -12
  17. package/{tools → lib/tools}/geocoder-vs-provided-coords.ts +12 -11
  18. package/lib/tools/gold-set-sample.ts +141 -0
  19. package/lib/tools/index.ts +31 -0
  20. package/{tools → lib/tools}/learned-scorer-clustering-eval.ts +71 -260
  21. package/{tools → lib/tools}/learned-scorer-crossstate-eval.ts +62 -245
  22. package/{tools → lib/tools}/learned-scorer-eval.ts +64 -263
  23. package/{tools → lib/tools}/matcher-scale.ts +5 -5
  24. package/lib/tools/nppes/org-name.ts +23 -0
  25. package/lib/tools/nppes/overmerge-packet.ts +94 -0
  26. package/lib/tools/nppes/report.ts +373 -0
  27. package/lib/tools/nppes/sample.ts +245 -0
  28. package/lib/tools/nppes/scoring.ts +114 -0
  29. package/lib/tools/nppes/settings.ts +102 -0
  30. package/lib/tools/nppes/truth-grains.ts +161 -0
  31. package/lib/tools/nppes-dedup-benchmark.ts +408 -0
  32. package/lib/tools/shared.ts +763 -0
  33. package/lib/tools/train-cross-gbt.ts +209 -0
  34. package/{tools → lib/tools}/train-gbt.ts +38 -156
  35. package/lib/tools/train-org-cross-gbt.ts +179 -0
  36. package/{tools → lib/tools}/txhhsc-to-oarow.ts +10 -28
  37. package/lib/tools/viz/browser.ts +50 -0
  38. package/{tools → lib/tools}/viz/cross-dataset-map.ts +16 -39
  39. package/{tools → lib/tools}/viz/geocode-first-surface.ts +13 -39
  40. package/{tools → lib/tools}/viz/render-map.ts +10 -23
  41. package/lib/tools/viz/render.ts +98 -0
  42. package/{tools → lib/tools}/viz/source-provenance-map.ts +20 -39
  43. package/{tools → lib/tools}/viz/yardstick-figure.ts +6 -5
  44. package/{types.ts → lib/types.ts} +10 -1
  45. package/out/address-key.d.ts +1 -1
  46. package/out/address-key.d.ts.map +1 -1
  47. package/out/address-key.js.map +1 -1
  48. package/out/geocode-handler.d.ts +6 -6
  49. package/out/geocode-handler.d.ts.map +1 -1
  50. package/out/geocode-handler.js +6 -6
  51. package/out/geocode-handler.js.map +1 -1
  52. package/out/geojson.d.ts +7 -2
  53. package/out/geojson.d.ts.map +1 -1
  54. package/out/geojson.js +8 -5
  55. package/out/geojson.js.map +1 -1
  56. package/out/index.d.ts +10 -10
  57. package/out/index.d.ts.map +1 -1
  58. package/out/index.js +10 -10
  59. package/out/index.js.map +1 -1
  60. package/out/ingest.d.ts +64 -46
  61. package/out/ingest.d.ts.map +1 -1
  62. package/out/ingest.js +33 -46
  63. package/out/ingest.js.map +1 -1
  64. package/out/learned-scorer.d.ts +1 -1
  65. package/out/learned-scorer.d.ts.map +1 -1
  66. package/out/learned-scorer.js.map +1 -1
  67. package/out/map-html.d.ts +4 -4
  68. package/out/map-html.d.ts.map +1 -1
  69. package/out/map-html.js +6 -11
  70. package/out/map-html.js.map +1 -1
  71. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -1
  72. package/out/models/crosssource-gbt-en-us.js.map +1 -1
  73. package/out/models/dedup-gbt-en-us.d.ts.map +1 -1
  74. package/out/models/dedup-gbt-en-us.js.map +1 -1
  75. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -1
  76. package/out/models/org-crosssource-gbt-en-us.js.map +1 -1
  77. package/out/reconcile.d.ts +6 -1
  78. package/out/reconcile.d.ts.map +1 -1
  79. package/out/reconcile.js +7 -21
  80. package/out/reconcile.js.map +1 -1
  81. package/out/resolve.d.ts +19 -7
  82. package/out/resolve.d.ts.map +1 -1
  83. package/out/resolve.js +20 -6
  84. package/out/resolve.js.map +1 -1
  85. package/out/tools/coverage-reconciliation.d.ts +1 -1
  86. package/out/tools/coverage-reconciliation.d.ts.map +1 -1
  87. package/out/tools/coverage-reconciliation.js +12 -12
  88. package/out/tools/coverage-reconciliation.js.map +1 -1
  89. package/out/tools/cross-dataset-correlation.d.ts +4 -4
  90. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  91. package/out/tools/cross-dataset-correlation.js +60 -111
  92. package/out/tools/cross-dataset-correlation.js.map +1 -1
  93. package/out/tools/cross-source-threshold-sweep.d.ts +2 -2
  94. package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -1
  95. package/out/tools/cross-source-threshold-sweep.js +19 -27
  96. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  97. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  98. package/out/tools/dedup-ceiling.js +36 -118
  99. package/out/tools/dedup-ceiling.js.map +1 -1
  100. package/out/tools/eval-geocoder.d.ts +9 -13
  101. package/out/tools/eval-geocoder.d.ts.map +1 -1
  102. package/out/tools/eval-geocoder.js +2 -2
  103. package/out/tools/eval-geocoder.js.map +1 -1
  104. package/out/tools/geocoder-namesake-probe.d.ts +2 -2
  105. package/out/tools/geocoder-namesake-probe.d.ts.map +1 -1
  106. package/out/tools/geocoder-namesake-probe.js +4 -8
  107. package/out/tools/geocoder-namesake-probe.js.map +1 -1
  108. package/out/tools/geocoder-vs-provided-coords.d.ts +1 -1
  109. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  110. package/out/tools/geocoder-vs-provided-coords.js +11 -9
  111. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  112. package/out/tools/gold-set-sample.d.ts +5 -5
  113. package/out/tools/gold-set-sample.d.ts.map +1 -1
  114. package/out/tools/gold-set-sample.js +37 -121
  115. package/out/tools/gold-set-sample.js.map +1 -1
  116. package/out/tools/index.d.ts +24 -29
  117. package/out/tools/index.d.ts.map +1 -1
  118. package/out/tools/index.js +24 -29
  119. package/out/tools/index.js.map +1 -1
  120. package/out/tools/learned-scorer-clustering-eval.d.ts +1 -1
  121. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  122. package/out/tools/learned-scorer-clustering-eval.js +35 -170
  123. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  124. package/out/tools/learned-scorer-crossstate-eval.d.ts +5 -5
  125. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  126. package/out/tools/learned-scorer-crossstate-eval.js +44 -166
  127. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  128. package/out/tools/learned-scorer-eval.d.ts +1 -1
  129. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  130. package/out/tools/learned-scorer-eval.js +37 -173
  131. package/out/tools/learned-scorer-eval.js.map +1 -1
  132. package/out/tools/matcher-scale.d.ts.map +1 -1
  133. package/out/tools/matcher-scale.js +5 -5
  134. package/out/tools/matcher-scale.js.map +1 -1
  135. package/out/tools/nppes/org-name.d.ts +21 -0
  136. package/out/tools/nppes/org-name.d.ts.map +1 -0
  137. package/out/tools/nppes/org-name.js +13 -0
  138. package/out/tools/nppes/org-name.js.map +1 -0
  139. package/out/tools/nppes/overmerge-packet.d.ts +39 -0
  140. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  141. package/out/tools/nppes/overmerge-packet.js +55 -0
  142. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  143. package/out/tools/nppes/report.d.ts +93 -0
  144. package/out/tools/nppes/report.d.ts.map +1 -0
  145. package/out/tools/nppes/report.js +186 -0
  146. package/out/tools/nppes/report.js.map +1 -0
  147. package/out/tools/nppes/sample.d.ts +90 -0
  148. package/out/tools/nppes/sample.d.ts.map +1 -0
  149. package/out/tools/nppes/sample.js +131 -0
  150. package/out/tools/nppes/sample.js.map +1 -0
  151. package/out/tools/nppes/scoring.d.ts +36 -0
  152. package/out/tools/nppes/scoring.d.ts.map +1 -0
  153. package/out/tools/nppes/scoring.js +80 -0
  154. package/out/tools/nppes/scoring.js.map +1 -0
  155. package/out/tools/nppes/settings.d.ts +38 -0
  156. package/out/tools/nppes/settings.d.ts.map +1 -0
  157. package/out/tools/nppes/settings.js +79 -0
  158. package/out/tools/nppes/settings.js.map +1 -0
  159. package/out/tools/nppes/truth-grains.d.ts +50 -0
  160. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  161. package/out/tools/nppes/truth-grains.js +123 -0
  162. package/out/tools/nppes/truth-grains.js.map +1 -0
  163. package/out/tools/nppes-dedup-benchmark.d.ts +7 -3
  164. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  165. package/out/tools/nppes-dedup-benchmark.js +106 -673
  166. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  167. package/out/tools/shared.d.ts +244 -7
  168. package/out/tools/shared.d.ts.map +1 -1
  169. package/out/tools/shared.js +353 -21
  170. package/out/tools/shared.js.map +1 -1
  171. package/out/tools/train-cross-gbt.d.ts +7 -7
  172. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  173. package/out/tools/train-cross-gbt.js +47 -145
  174. package/out/tools/train-cross-gbt.js.map +1 -1
  175. package/out/tools/train-gbt.d.ts +7 -7
  176. package/out/tools/train-gbt.d.ts.map +1 -1
  177. package/out/tools/train-gbt.js +31 -111
  178. package/out/tools/train-gbt.js.map +1 -1
  179. package/out/tools/train-org-cross-gbt.d.ts +7 -5
  180. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  181. package/out/tools/train-org-cross-gbt.js +45 -141
  182. package/out/tools/train-org-cross-gbt.js.map +1 -1
  183. package/out/tools/txhhsc-to-oarow.d.ts +2 -2
  184. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  185. package/out/tools/txhhsc-to-oarow.js +9 -23
  186. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  187. package/out/tools/viz/browser.d.ts +34 -0
  188. package/out/tools/viz/browser.d.ts.map +1 -0
  189. package/out/tools/viz/browser.js +33 -0
  190. package/out/tools/viz/browser.js.map +1 -0
  191. package/out/tools/viz/cross-dataset-map.d.ts +4 -25
  192. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  193. package/out/tools/viz/cross-dataset-map.js +12 -33
  194. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  195. package/out/tools/viz/geocode-first-surface.d.ts +6 -35
  196. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  197. package/out/tools/viz/geocode-first-surface.js +10 -37
  198. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  199. package/out/tools/viz/render-map.d.ts +3 -6
  200. package/out/tools/viz/render-map.d.ts.map +1 -1
  201. package/out/tools/viz/render-map.js +9 -19
  202. package/out/tools/viz/render-map.js.map +1 -1
  203. package/out/tools/viz/render.d.ts +4 -9
  204. package/out/tools/viz/render.d.ts.map +1 -1
  205. package/out/tools/viz/render.js +24 -39
  206. package/out/tools/viz/render.js.map +1 -1
  207. package/out/tools/viz/source-provenance-map.d.ts +4 -24
  208. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  209. package/out/tools/viz/source-provenance-map.js +12 -32
  210. package/out/tools/viz/source-provenance-map.js.map +1 -1
  211. package/out/tools/viz/yardstick-figure.d.ts +2 -2
  212. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  213. package/out/tools/viz/yardstick-figure.js +5 -4
  214. package/out/tools/viz/yardstick-figure.js.map +1 -1
  215. package/out/types.d.ts +11 -1
  216. package/out/types.d.ts.map +1 -1
  217. package/out/types.js.map +1 -1
  218. package/package.json +180 -11
  219. package/tools/gold-set-sample.ts +0 -252
  220. package/tools/index.ts +0 -36
  221. package/tools/nppes-dedup-benchmark.ts +0 -1180
  222. package/tools/shared.ts +0 -160
  223. package/tools/train-cross-gbt.ts +0 -358
  224. package/tools/train-org-cross-gbt.ts +0 -329
  225. package/tools/viz/render.ts +0 -113
  226. /package/{models → lib/models}/crosssource-gbt-en-us.ts +0 -0
  227. /package/{models → lib/models}/dedup-gbt-en-us.ts +0 -0
  228. /package/{models → lib/models}/org-crosssource-gbt-en-us.ts +0 -0
@@ -0,0 +1,408 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The #617 NPPES dedup benchmark — the measurable proof of the record-matcher hypothesis.
7
+ *
8
+ * NPPES is NPI-keyed, so the NPI is a ground-truth entity id. We build a deliberately varied
9
+ * multi-record set per NPI from REAL data — the registry's primary record, each alternate
10
+ * organization name (`nppes_other-names`, NAME drift at the same place), and the mailing address
11
+ * where it differs from the practice location (ADDRESS variation) — then run the matcher BLIND to
12
+ * the NPI (geocode → block → Fellegi-Sunter + EM → cluster) and score the recovered clusters
13
+ * against the NPI grouping (pairwise P/R/F1 + adjusted Rand).
14
+ *
15
+ * Honest reading (per the epic): NPI-as-truth is CONSERVATIVE. A cluster that merges two NPIs is a
16
+ * candidate "same entity, two NPIs" surfaced for review, not an error we adjudicate; and a single
17
+ * NPI split across two genuinely-distant addresses is geo-first behaving correctly, counted here
18
+ * as a recall miss. We resolve and report; interpretation is the consumer's.
19
+ *
20
+ * Sample: a tractable, variation-rich slice — providers in one state (default TX) that have ≥1
21
+ * alternate name, so every entity has ≥2 records and the dedup is non-trivial. Streams the 4.8 GB
22
+ * registry via `streamRows` (#616), so nothing loads whole.
23
+ *
24
+ * The stages live in `./nppes/`: the sample, the scorer, the truth grains, the setting progression,
25
+ * the adjudication packet, and the report. This file is the orchestration — read it for the order
26
+ * of operations, the modules for what each stage does.
27
+ *
28
+ * Run: `mailwoman registry scorer-eval nppes-benchmark [--state TX] [--max-npis 300]
29
+ * [--wof <admin.db>] [--data-root <dir>] [--no-train-em]
30
+ * [--out-md docs/articles/evals/matcher-dedup/<date>-nppes-dedup-benchmark.md]`
31
+ */
32
+
33
+ import { dataRootPath } from "@mailwoman/core/data-root"
34
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
35
+ import { pathToFileURL } from "@mailwoman/core/module/file-url"
36
+ import type { GBT } from "@mailwoman/match"
37
+ import { resolvePath } from "path-ts"
38
+
39
+ import {
40
+ ingestRows,
41
+ resolveEntities,
42
+ type ColumnMapping,
43
+ type GeocodeAddress,
44
+ type ResolvedEntity,
45
+ type SourceRecord,
46
+ } from "#index"
47
+ import type { EvalGeocodeStream, EvalGeocoderFactory } from "#tools/eval-geocoder"
48
+ import { writeOvermergePacket } from "#tools/nppes/overmerge-packet"
49
+ import { renderNPPESDedupReport, type SweepArm } from "#tools/nppes/report"
50
+ import { buildNPPESSample } from "#tools/nppes/sample"
51
+ import { scoreEntities, type Score } from "#tools/nppes/scoring"
52
+ import { buildSettings } from "#tools/nppes/settings"
53
+ import {
54
+ buildOrgNameCoordGrain,
55
+ buildOrgNameGrain,
56
+ buildOrgNameH3Grain,
57
+ collectPrimaryCoordinates,
58
+ type TruthLabel,
59
+ } from "#tools/nppes/truth-grains"
60
+ import { stateOption } from "#tools/shared"
61
+
62
+ /**
63
+ * Options for {@linkcode nppesDedupBenchmark}.
64
+ */
65
+ export interface NPPESDedupBenchmarkOptions {
66
+ /**
67
+ * The injected geocoder factory (the command wires `mailwoman/geocode-core`; see `./eval-geocoder.ts`). Model-swap
68
+ * overrides (`--model`/`--tokenizer`/`--model-card`) are the COMMAND's factory config, not tool options.
69
+ */
70
+ createGeocoder: EvalGeocoderFactory
71
+ /**
72
+ * The threaded geocode surface — required when {@linkcode parallelGeocode} is set.
73
+ */
74
+ geocodeStream?: EvalGeocodeStream
75
+ /**
76
+ * Record-matcher sources directory. Default `$MAILWOMAN_DATA_ROOT/record-matcher/sources`.
77
+ */
78
+ sources?: string
79
+ /**
80
+ * State filter. Default TX.
81
+ */
82
+ state?: string
83
+ /**
84
+ * NPIs sampled. Default 300.
85
+ */
86
+ maxNpis?: number
87
+ /**
88
+ * EM-train the FS arms (label-free). Default true; `--no-train-em` uses the seeds.
89
+ */
90
+ trainEm?: boolean
91
+ /**
92
+ * #694 A/B: reproduce the pre-flip ingest (space-joined address columns + normalizeCase OFF). Default off (the
93
+ * validated flip: comma-join + #690 all-caps normalization). Same data + GBT, only the flip toggled — so a delta here
94
+ * is attributable to the flip.
95
+ */
96
+ legacyJoin?: boolean
97
+ /**
98
+ * Optional A/B: a path to a trained dedup-gbt TS module (exports DEDUP_GBT_MODEL + DEDUP_GBT_META) to score alongside
99
+ * the shipped GBT at both truth levels — e.g. grade the #625 corroboration candidate.
100
+ */
101
+ candidate?: string
102
+ /**
103
+ * Write the #625 gold-set adjudication packet (org-name-grain over-merged clusters) here.
104
+ */
105
+ dumpOvermerges?: string
106
+ /**
107
+ * H3 resolution for the org-name-h3 truth grain. Default 11 (≈25 m edge).
108
+ */
109
+ h3Res?: number
110
+ /**
111
+ * Geocode the sample across a worker pool ({@linkcode geocodeStream}) instead of the serial in-process path. Heavy
112
+ * per-row work (ONNX parse + WOF SQLite) → threading pays; measured ~1.5× at 2 workers, coordinates identical.
113
+ */
114
+ parallelGeocode?: boolean
115
+ /**
116
+ * Worker-pool concurrency for {@linkcode parallelGeocode}. Default 2 (geocode is I/O-bound).
117
+ */
118
+ geoConcurrency?: number
119
+ /**
120
+ * Also write the markdown report here.
121
+ */
122
+ outMd?: string
123
+ }
124
+
125
+ /**
126
+ * The #617 NPPES dedup benchmark — see the module doc. Emits the markdown report to stdout.
127
+ */
128
+ export async function nppesDedupBenchmark(
129
+ options: NPPESDedupBenchmarkOptions,
130
+ report?: (line: string) => void
131
+ ): Promise<{ markdown: string }> {
132
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
133
+ const STATE = stateOption(options)
134
+ const MAX_NPIS = options.maxNpis ?? 300
135
+ const OUT_MD = options.outMd || ""
136
+ const TRAIN_EM = options.trainEm ?? true
137
+ const LEGACY = options.legacyJoin ?? false
138
+ const CANDIDATE = options.candidate || ""
139
+ const PARALLEL_GEOCODE = options.parallelGeocode ?? false
140
+ const GEO_CONC = options.geoConcurrency ?? 2
141
+
142
+ // --- Phases A + B: the variation-rich sample plus the corpus-wide address-frequency table. ---
143
+ const { rows, keptNpis, npiPrimary, addressFrequency } = await buildNPPESSample(
144
+ {
145
+ registryPath: `${SOURCES}/nppes_npi-registry_20260607.tsv`,
146
+ otherNamesPath: `${SOURCES}/nppes_other-names_20260607.tsv`,
147
+ state: STATE,
148
+ maxNpis: MAX_NPIS,
149
+ },
150
+ report
151
+ )
152
+
153
+ // --- Phase C: geocode + ingest (the NPI rides on record.id as the held-out label). The heavy
154
+ // geocoder is injected (see ./eval-geocoder.ts); model-swap for a multi-version curve rides the
155
+ // command's factory config (--model/--tokenizer/--model-card; modelCardPath is MANDATORY when
156
+ // modelPath is set — without it a STAGE3 model silently mis-decodes into empty parses). ---
157
+ report?.("[C] building the geocoder + geocoding records…")
158
+
159
+ const mapping: ColumnMapping = {
160
+ id: "npi",
161
+ name: "name",
162
+ organization: "org",
163
+ address: "address",
164
+ // `entityTruth` rides as an attribute purely for scoring (NOT a discriminator → never used in
165
+ // matching); it carries the site-level entity-level label alongside the NPI (record.id).
166
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy", entityTruth: "entityID" },
167
+ source: "nppes",
168
+ }
169
+
170
+ let geo = 0
171
+ let records: SourceRecord[]
172
+
173
+ if (PARALLEL_GEOCODE) {
174
+ // Threaded geocode: normalize on the main thread, then hand records to a worker pool that each rebuild the
175
+ // classifier/resolver/extracts from config. `address` is a single pre-joined column here, so `--legacy-join`
176
+ // (a separator toggle) is a no-op for this path; `normalizeCase` follows the worker default (on).
177
+ if (!options.geocodeStream) {
178
+ throw new Error("parallelGeocode requires the injected geocodeStream (see ./eval-geocoder.ts)")
179
+ }
180
+
181
+ const normalized = await ingestRows(rows, mapping)
182
+ const order = new Map(normalized.map((r, i) => [r.id, i]))
183
+ const geocoded: SourceRecord[] = []
184
+
185
+ for await (const rec of options.geocodeStream(normalized, { mapping, concurrency: GEO_CONC })) {
186
+ geocoded.push(rec)
187
+
188
+ if (rec.address?.geocode) {
189
+ geo++
190
+ }
191
+ }
192
+
193
+ // geocodeStream yields in completion order; restore input order so downstream cluster tie-breaks are byte-stable.
194
+ geocoded.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))
195
+ records = geocoded
196
+ } else {
197
+ const geocoder = await options.createGeocoder({ normalizeCase: !LEGACY })
198
+
199
+ // Count placements at the boundary (parity with the retired in-script counter).
200
+ const countedGeocodeForIngest: GeocodeAddress = async (raw) => {
201
+ const g = await geocoder.geocodeAddress(raw)
202
+
203
+ if (g?.geocode) {
204
+ geo++
205
+ }
206
+
207
+ return g
208
+ }
209
+
210
+ records = await ingestRows(rows, mapping, {
211
+ geocodeAddress: countedGeocodeForIngest,
212
+ addressSeparator: LEGACY ? " " : ", ",
213
+ })
214
+
215
+ geocoder[Symbol.dispose]()
216
+ }
217
+
218
+ report?.(` geocoded ${geo}/${rows.length} (${((100 * geo) / rows.length).toFixed(1)}%)`)
219
+
220
+ // --- Phase E: score recovered clusters against each truth grain (record.id = the held-out NPI). ---
221
+ const N = records.length
222
+
223
+ // Every grain scores against the SAME record population, so the ARI expectation is fixed for the run.
224
+ const score = (entities: readonly ResolvedEntity[], labelOf: TruthLabel): Score => scoreEntities(entities, labelOf, N)
225
+
226
+ // Truth labels: NPI-level (the conservative held-out NPI = record.id) and entity-level (the
227
+ // site-level subpart-collapsed id that rides on attributes.entityTruth). Scoring the SAME clusters
228
+ // both ways isolates how much of the apparent over-merge is NPI over-segmentation, not model error.
229
+ const npiLabel = (rec: SourceRecord) => rec.id
230
+ const entityLabel = (rec: SourceRecord) => rec.attributes?.["entityTruth"] ?? rec.id
231
+ const orgNameLabel = buildOrgNameGrain(npiPrimary)
232
+
233
+ const npiCoord = collectPrimaryCoordinates(records)
234
+ const orgNameCoordLabel = buildOrgNameCoordGrain(npiPrimary, npiCoord)
235
+ const geocodedNpis = [...npiPrimary.keys()].filter((n) => npiCoord.has(n)).length
236
+
237
+ const H3_RES = options.h3Res ?? 11 // res 11 ≈ 25 m edge; res 10 ≈ 65 m (block scale)
238
+ const orgNameH3Label = buildOrgNameH3Grain(npiPrimary, npiCoord, H3_RES)
239
+
240
+ // --- Phase D: the comparison-model setting progression — toggle each setting ON in turn at the default
241
+ // threshold to isolate its marginal effect, then sweep the link threshold on the best config (geocode
242
+ // once, resolve many — config is cheap). ---
243
+ report?.(`[D] resolving the setting progression${TRAIN_EM ? " (EM-trained)" : ""}…`)
244
+
245
+ // learnedScorer:false throughout — this benchmark studies the FS COMPARISON-MODEL settings (#617/#625).
246
+ // The learned scorer is now default-on, so it must be pinned off here or every row would silently be the
247
+ // GBT; the learned scorer is measured separately (learned-scorer-clustering-eval / -crossstate-eval).
248
+ const progression = buildSettings(addressFrequency).map((l) => {
249
+ const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0, ...l.config })
250
+
251
+ return { ...l, res, score: score(res.entities, npiLabel) }
252
+ })
253
+
254
+ const bestSetting = progression.at(-1)! // the full setting stack
255
+
256
+ // The SHIPPED out-of-box default (#86): no setting config at all → resolveEntities auto-computes an
257
+ // input-scoped address-frequency table + collapsed spatial. On this deliberately-sub-sampled corpus the
258
+ // auto table is sparse (few repeats), so the inverse-frequency signal is near-inert and F1 collapses to
259
+ // ≈baseline — NOT a regression, just the honest truth that IDF is a corpus statistic you can't synthesize
260
+ // from a slice. On a FULL-dataset dedup the input IS the corpus and this default reaches the baseline; the
261
+ // CLI passes a corpus-wide table built from the full source files so even a geocoded sub-sample benefits.
262
+ const defaultRes = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0 })
263
+ const defaultOutOfBox = score(defaultRes.entities, npiLabel)
264
+
265
+ const THRESHOLDS = [0, 4, 8, 12, 16, 20]
266
+
267
+ const sweep: SweepArm[] = THRESHOLDS.map((t) => {
268
+ const res = resolveEntities(records, {
269
+ learnedScorer: false,
270
+ trainEM: TRAIN_EM,
271
+ threshold: t,
272
+ ...bestSetting.config,
273
+ })
274
+
275
+ return { t, res, score: score(res.entities, npiLabel) }
276
+ })
277
+
278
+ const base = sweep[0]! // threshold 0, full setting stack
279
+ let best = sweep[0]!
280
+
281
+ for (const arm of sweep) {
282
+ if (arm.score.f1 > best.score.f1) {
283
+ best = arm
284
+ }
285
+ }
286
+
287
+ report?.(
288
+ ` progression @ threshold 0: ${progression.map((p) => `${(100 * p.score.f1).toFixed(1)}%`).join(" → ")} F1`
289
+ )
290
+
291
+ report?.(
292
+ ` default F1 ${(100 * base.score.f1).toFixed(1)}% → best F1 ${(100 * best.score.f1).toFixed(1)}% @ threshold ${best.t}`
293
+ )
294
+
295
+ // --- Phase F: NPI-level vs ENTITY-level truth. Score the SAME clusters against both yardsticks to
296
+ // reveal how much of the apparent over-merge is NPI over-segmentation (one org / many subpart-NPIs,
297
+ // where merging is CORRECT) rather than model error. Two production configs: the FS full setting stack
298
+ // and the shipped default (GBT, default-on) — each fed the corpus-wide address-frequency table. ---
299
+ const entityCount = new Set(records.map((r) => entityLabel(r))).size
300
+ const orgCount = new Set(records.map((r) => orgNameLabel(r))).size
301
+ const fsNPI = bestSetting.score
302
+ const fsEntity = score(bestSetting.res.entities, entityLabel)
303
+ const fsOrg = score(bestSetting.res.entities, orgNameLabel)
304
+ const gbtRes = resolveEntities(records, { addressFrequency, trainEM: TRAIN_EM }) // GBT default-on (production)
305
+ const gbtNPI = score(gbtRes.entities, npiLabel)
306
+ const gbtEntity = score(gbtRes.entities, entityLabel)
307
+ const gbtOrg = score(gbtRes.entities, orgNameLabel)
308
+ // Tier 2D: the coordinate-co-location org-name truth (tighter lower bound).
309
+ const orgCoordCount = new Set(records.map((r) => orgNameCoordLabel(r))).size
310
+ const fsOrgCoord = score(bestSetting.res.entities, orgNameCoordLabel)
311
+ const gbtOrgCoord = score(gbtRes.entities, orgNameCoordLabel)
312
+ // #109: the H3-cell co-location truth — a robustness check on the haversine coord-grain.
313
+ const orgH3Count = new Set(records.map((r) => orgNameH3Label(r))).size
314
+ const gbtOrgH3 = score(gbtRes.entities, orgNameH3Label)
315
+
316
+ // The adjudication packet grades the SHIPPED (GBT) clusters, because the residual over-merge is small and
317
+ // approaching the measured ~1.6% irreducible ceiling — per-pair human adjudication (same entity? distinct
318
+ // co-located?) is the only instrument left that can separate model error from yardstick error.
319
+ const DUMP_OVERMERGES = options.dumpOvermerges || ""
320
+
321
+ if (DUMP_OVERMERGES) {
322
+ const clusters = await writeOvermergePacket(DUMP_OVERMERGES, {
323
+ state: STATE,
324
+ entities: gbtRes.entities,
325
+ rows,
326
+ recordCount: records.length,
327
+ maxNpis: MAX_NPIS,
328
+ orgNameLabel,
329
+ })
330
+
331
+ report?.(` adjudication packet: ${clusters} over-merged clusters -> ${DUMP_OVERMERGES}`)
332
+ }
333
+
334
+ // Optional candidate A/B (--candidate): score a trained GBT module at both levels, at its own
335
+ // recommendedThreshold, alongside the shipped GBT — grades a new model (e.g. corroboration features).
336
+ let cand: { label: string; npi: Score; entity: Score } | null = null
337
+
338
+ if (CANDIDATE) {
339
+ const mod = (await import(pathToFileURL(resolvePath(CANDIDATE)).href)) as {
340
+ DEDUP_GBT_MODEL: GBT
341
+ DEDUP_GBT_META?: { recommendedThreshold?: number; features?: number; costNegative?: number }
342
+ }
343
+
344
+ const t = mod.DEDUP_GBT_META?.recommendedThreshold ?? 0
345
+
346
+ const res = resolveEntities(records, {
347
+ addressFrequency,
348
+ trainEM: TRAIN_EM,
349
+ learnedScorer: mod.DEDUP_GBT_MODEL,
350
+ threshold: t,
351
+ })
352
+
353
+ const cost = mod.DEDUP_GBT_META?.costNegative ?? 1
354
+
355
+ cand = {
356
+ label: `GBT candidate (${mod.DEDUP_GBT_META?.features ?? "?"}-feat${cost !== 1 ? `, cost ×${cost}` : ""})`,
357
+ npi: score(res.entities, npiLabel),
358
+ entity: score(res.entities, entityLabel),
359
+ }
360
+
361
+ report?.(
362
+ ` candidate ${CANDIDATE}: NPI ${(100 * cand.npi.f1).toFixed(1)}% / entity ${(100 * cand.entity.f1).toFixed(1)}%`
363
+ )
364
+ }
365
+
366
+ report?.(
367
+ ` truth-grains — GBT NPI ${(100 * gbtNPI.f1).toFixed(1)}% → site ${(100 * gbtEntity.f1).toFixed(1)}% → org-name ${(100 * gbtOrg.f1).toFixed(1)}% → org-name-coord ${(100 * gbtOrgCoord.f1).toFixed(1)}% → org-name-h3 ${(100 * gbtOrgH3.f1).toFixed(1)}% (res ${H3_RES}); ` +
368
+ `FS: NPI ${(100 * fsNPI.f1).toFixed(1)}% / entity ${(100 * fsEntity.f1).toFixed(1)}% / org-coord ${(100 * fsOrgCoord.f1).toFixed(1)}%`
369
+ )
370
+
371
+ const md = renderNPPESDedupReport({
372
+ state: STATE,
373
+ keptNpis: keptNpis.size,
374
+ recordCount: N,
375
+ geocoded: geo,
376
+ trainEM: TRAIN_EM,
377
+ addressFrequency,
378
+ progression,
379
+ defaultOutOfBox,
380
+ sweep,
381
+ best,
382
+ entityCount,
383
+ orgCount,
384
+ orgCoordCount,
385
+ orgH3Count,
386
+ fsNPI,
387
+ fsEntity,
388
+ fsOrg,
389
+ fsOrgCoord,
390
+ gbtNPI,
391
+ gbtEntity,
392
+ gbtOrg,
393
+ gbtOrgCoord,
394
+ gbtOrgH3,
395
+ candidate: cand,
396
+ h3Res: H3_RES,
397
+ geocodedNpis,
398
+ })
399
+
400
+ console.log(md)
401
+
402
+ if (OUT_MD) {
403
+ await writeLocalFile(md, OUT_MD)
404
+ report?.(`\n[written] ${OUT_MD}`)
405
+ }
406
+
407
+ return { markdown: md }
408
+ }