@mailwoman/registry 9.1.0 → 9.2.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 (149) hide show
  1. package/README.md +1 -1
  2. package/geojson.ts +3 -2
  3. package/ingest.ts +2 -1
  4. package/map-html.ts +4 -4
  5. package/out/geojson.d.ts.map +1 -1
  6. package/out/geojson.js +3 -2
  7. package/out/geojson.js.map +1 -1
  8. package/out/ingest.d.ts.map +1 -1
  9. package/out/ingest.js +2 -1
  10. package/out/ingest.js.map +1 -1
  11. package/out/map-html.d.ts +2 -2
  12. package/out/map-html.d.ts.map +1 -1
  13. package/out/map-html.js.map +1 -1
  14. package/out/reconcile.d.ts.map +1 -1
  15. package/out/reconcile.js +2 -1
  16. package/out/reconcile.js.map +1 -1
  17. package/out/resolve.d.ts.map +1 -1
  18. package/out/resolve.js +4 -1
  19. package/out/resolve.js.map +1 -1
  20. package/out/tools/coverage-reconciliation.js +2 -2
  21. package/out/tools/coverage-reconciliation.js.map +1 -1
  22. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  23. package/out/tools/cross-dataset-correlation.js +6 -5
  24. package/out/tools/cross-dataset-correlation.js.map +1 -1
  25. package/out/tools/cross-source-threshold-sweep.js +2 -2
  26. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  27. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  28. package/out/tools/dedup-ceiling.js +2 -3
  29. package/out/tools/dedup-ceiling.js.map +1 -1
  30. package/out/tools/eval-geocoder.d.ts +1 -1
  31. package/out/tools/eval-geocoder.d.ts.map +1 -1
  32. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  33. package/out/tools/geocoder-vs-provided-coords.js +3 -2
  34. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  35. package/out/tools/gold-set-sample.d.ts.map +1 -1
  36. package/out/tools/gold-set-sample.js +4 -3
  37. package/out/tools/gold-set-sample.js.map +1 -1
  38. package/out/tools/index.d.ts +1 -6
  39. package/out/tools/index.d.ts.map +1 -1
  40. package/out/tools/index.js +1 -6
  41. package/out/tools/index.js.map +1 -1
  42. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  43. package/out/tools/learned-scorer-clustering-eval.js +1 -2
  44. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  45. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  46. package/out/tools/learned-scorer-crossstate-eval.js +1 -1
  47. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  48. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  49. package/out/tools/learned-scorer-eval.js +1 -6
  50. package/out/tools/learned-scorer-eval.js.map +1 -1
  51. package/out/tools/matcher-scale.d.ts.map +1 -1
  52. package/out/tools/matcher-scale.js +1 -1
  53. package/out/tools/matcher-scale.js.map +1 -1
  54. package/out/tools/nppes/levers.d.ts +38 -0
  55. package/out/tools/nppes/levers.d.ts.map +1 -0
  56. package/out/tools/nppes/levers.js +79 -0
  57. package/out/tools/nppes/levers.js.map +1 -0
  58. package/out/tools/nppes/org-name.d.ts +24 -0
  59. package/out/tools/nppes/org-name.d.ts.map +1 -0
  60. package/out/tools/nppes/org-name.js +42 -0
  61. package/out/tools/nppes/org-name.js.map +1 -0
  62. package/out/tools/nppes/overmerge-packet.d.ts +39 -0
  63. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  64. package/out/tools/nppes/overmerge-packet.js +55 -0
  65. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  66. package/out/tools/nppes/report.d.ts +93 -0
  67. package/out/tools/nppes/report.d.ts.map +1 -0
  68. package/out/tools/nppes/report.js +188 -0
  69. package/out/tools/nppes/report.js.map +1 -0
  70. package/out/tools/nppes/sample.d.ts +64 -0
  71. package/out/tools/nppes/sample.d.ts.map +1 -0
  72. package/out/tools/nppes/sample.js +113 -0
  73. package/out/tools/nppes/sample.js.map +1 -0
  74. package/out/tools/nppes/scoring.d.ts +36 -0
  75. package/out/tools/nppes/scoring.d.ts.map +1 -0
  76. package/out/tools/nppes/scoring.js +80 -0
  77. package/out/tools/nppes/scoring.js.map +1 -0
  78. package/out/tools/nppes/truth-grains.d.ts +50 -0
  79. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  80. package/out/tools/nppes/truth-grains.js +148 -0
  81. package/out/tools/nppes/truth-grains.js.map +1 -0
  82. package/out/tools/nppes-dedup-benchmark.d.ts +4 -0
  83. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  84. package/out/tools/nppes-dedup-benchmark.js +79 -652
  85. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  86. package/out/tools/shared.d.ts.map +1 -1
  87. package/out/tools/shared.js +5 -4
  88. package/out/tools/shared.js.map +1 -1
  89. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  90. package/out/tools/train-cross-gbt.js +2 -2
  91. package/out/tools/train-cross-gbt.js.map +1 -1
  92. package/out/tools/train-gbt.d.ts.map +1 -1
  93. package/out/tools/train-gbt.js +2 -2
  94. package/out/tools/train-gbt.js.map +1 -1
  95. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  96. package/out/tools/train-org-cross-gbt.js +2 -2
  97. package/out/tools/train-org-cross-gbt.js.map +1 -1
  98. package/out/tools/txhhsc-to-oarow.js +2 -2
  99. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  100. package/out/tools/viz/cross-dataset-map.d.ts +2 -23
  101. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  102. package/out/tools/viz/cross-dataset-map.js +7 -28
  103. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  104. package/out/tools/viz/geocode-first-surface.d.ts +2 -32
  105. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  106. package/out/tools/viz/geocode-first-surface.js +4 -33
  107. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  108. package/out/tools/viz/render.js +1 -1
  109. package/out/tools/viz/render.js.map +1 -1
  110. package/out/tools/viz/source-provenance-map.d.ts +2 -22
  111. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  112. package/out/tools/viz/source-provenance-map.js +7 -26
  113. package/out/tools/viz/source-provenance-map.js.map +1 -1
  114. package/out/types.d.ts +11 -1
  115. package/out/types.d.ts.map +1 -1
  116. package/out/types.js.map +1 -1
  117. package/package.json +78 -9
  118. package/reconcile.ts +2 -1
  119. package/resolve.ts +6 -1
  120. package/tools/coverage-reconciliation.ts +3 -3
  121. package/tools/cross-dataset-correlation.ts +7 -5
  122. package/tools/cross-source-threshold-sweep.ts +3 -3
  123. package/tools/dedup-ceiling.ts +3 -3
  124. package/tools/eval-geocoder.ts +1 -1
  125. package/tools/geocoder-vs-provided-coords.ts +4 -2
  126. package/tools/gold-set-sample.ts +5 -3
  127. package/tools/index.ts +1 -6
  128. package/tools/learned-scorer-clustering-eval.ts +4 -4
  129. package/tools/learned-scorer-crossstate-eval.ts +4 -4
  130. package/tools/learned-scorer-eval.ts +4 -9
  131. package/tools/matcher-scale.ts +2 -1
  132. package/tools/nppes/levers.ts +102 -0
  133. package/tools/nppes/org-name.ts +56 -0
  134. package/tools/nppes/overmerge-packet.ts +96 -0
  135. package/tools/nppes/report.ts +376 -0
  136. package/tools/nppes/sample.ts +197 -0
  137. package/tools/nppes/scoring.ts +114 -0
  138. package/tools/nppes/truth-grains.ts +201 -0
  139. package/tools/nppes-dedup-benchmark.ts +92 -868
  140. package/tools/shared.ts +6 -4
  141. package/tools/train-cross-gbt.ts +6 -5
  142. package/tools/train-gbt.ts +5 -4
  143. package/tools/train-org-cross-gbt.ts +6 -5
  144. package/tools/txhhsc-to-oarow.ts +2 -2
  145. package/tools/viz/cross-dataset-map.ts +12 -34
  146. package/tools/viz/geocode-first-surface.ts +5 -33
  147. package/tools/viz/render.ts +1 -1
  148. package/tools/viz/source-provenance-map.ts +14 -31
  149. package/types.ts +10 -1
@@ -0,0 +1,376 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file The NPPES dedup benchmark's markdown report. Pure: every figure comes from the input, because eval figures are
6
+ * never hand-typed into docs.
7
+ */
8
+
9
+ import type { TermFrequencyTable } from "@mailwoman/match"
10
+
11
+ import type { ResolveResult } from "#index"
12
+
13
+ import { ORG_TAU } from "./org-name.ts"
14
+ import type { Score } from "./scoring.ts"
15
+ import { COLOCATION_KM } from "./truth-grains.ts"
16
+
17
+ /**
18
+ * F1 gap within which two blocking strategies are treated as equivalent.
19
+ */
20
+ const BLOCKING_PARITY_TOLERANCE = 0.015
21
+
22
+ /**
23
+ * One row of the lever progression, scored at the default threshold.
24
+ */
25
+ export interface LeverScore {
26
+ label: string
27
+ score: Score
28
+ }
29
+
30
+ /**
31
+ * One arm of the link-threshold sweep.
32
+ */
33
+ export interface SweepArm {
34
+ /**
35
+ * Link threshold, in bits.
36
+ */
37
+ t: number
38
+ res: Pick<ResolveResult, "candidatePairs" | "droppedBlocks">
39
+ score: Score
40
+ }
41
+
42
+ /**
43
+ * Everything the report reads.
44
+ */
45
+ export interface NPPESReportInput {
46
+ state: string
47
+ /**
48
+ * Sampled NPIs — the true-entity count at the NPI grain.
49
+ */
50
+ keptNpis: number
51
+ recordCount: number
52
+ /**
53
+ * Records whose address placed.
54
+ */
55
+ geocoded: number
56
+ trainEM: boolean
57
+ /**
58
+ * The corpus-wide table the progression was fed; only its `total`/`distinct` are reported.
59
+ */
60
+ addressFrequency: TermFrequencyTable
61
+ /**
62
+ * The lever progression in order. The first row is the bare baseline, the last the full stack.
63
+ */
64
+ progression: readonly LeverScore[]
65
+ /**
66
+ * Zero-config `resolveEntities(records)` — reported apart from the progression because its address-frequency table is
67
+ * input-scoped, which on a sub-sample is intentionally sparse.
68
+ */
69
+ defaultOutOfBox: Score
70
+ sweep: readonly SweepArm[]
71
+ /**
72
+ * The best-F1 arm. Must be an element of {@linkcode sweep} — the table stars it by identity.
73
+ */
74
+ best: SweepArm
75
+ entityCount: number
76
+ orgCount: number
77
+ orgCoordCount: number
78
+ orgH3Count: number
79
+ fsNPI: Score
80
+ fsEntity: Score
81
+ fsOrg: Score
82
+ fsOrgCoord: Score
83
+ gbtNPI: Score
84
+ gbtEntity: Score
85
+ gbtOrg: Score
86
+ gbtOrgCoord: Score
87
+ gbtOrgH3: Score
88
+ /**
89
+ * The optional `--candidate` A/B row.
90
+ */
91
+ candidate: { label: string; npi: Score; entity: Score } | null
92
+ h3Res: number
93
+ /**
94
+ * Sampled NPIs whose primary practice address placed — the population the coordinate grain can act on.
95
+ */
96
+ geocodedNpis: number
97
+ }
98
+
99
+ /**
100
+ * Render the run's markdown report.
101
+ */
102
+ export function renderNPPESDedupReport(input: NPPESReportInput): string {
103
+ const {
104
+ state: STATE,
105
+ keptNpis,
106
+ recordCount: N,
107
+ geocoded: geo,
108
+ trainEM: TRAIN_EM,
109
+ addressFrequency,
110
+ progression,
111
+ defaultOutOfBox,
112
+ sweep,
113
+ best,
114
+ entityCount,
115
+ orgCount,
116
+ orgCoordCount,
117
+ orgH3Count,
118
+ fsNPI,
119
+ fsEntity,
120
+ fsOrg,
121
+ fsOrgCoord,
122
+ gbtNPI,
123
+ gbtEntity,
124
+ gbtOrg,
125
+ gbtOrgCoord,
126
+ gbtOrgH3,
127
+ candidate: cand,
128
+ h3Res: H3_RES,
129
+ geocodedNpis,
130
+ } = input
131
+
132
+ const baseline = progression[0]! // no levers — the prior-prior behaviour
133
+ // The LAST progression row — the whole A1–A5 stack, never compared on F1 against the others. Named for what it
134
+ // is: a row called `best` invites reading a stack-wide delta as one lever's marginal effect, which is how the
135
+ // authorized-official sentence below came to quote a five-lever number.
136
+ const fullStack = progression.at(-1)!
137
+ const base = sweep[0]! // threshold 0, full lever stack
138
+
139
+ // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
140
+ // numerator/denominator contract (call sites append their own "%").
141
+ const pct = (x: number) => (100 * x).toFixed(1)
142
+ const signed = (x: number) => `${x >= 0 ? "+" : ""}${x.toFixed(1)}pp`
143
+
144
+ const lines: string[] = [
145
+ `# NPPES NPI dedup benchmark (#617)`,
146
+ "",
147
+ `_Generated by \`mailwoman registry scorer-eval nppes-benchmark\`. Sample: ${keptNpis} ${STATE} NPIs with ≥1 ` +
148
+ `alternate name → ${N} records (${(N / keptNpis).toFixed(1)}/NPI) from real registry + other-names + ` +
149
+ `mailing-vs-practice variation. Matcher run BLIND to the NPI${TRAIN_EM ? ", EM-trained (label-free)" : ""}; ` +
150
+ `geocoded ${pct(geo / N)}% of addresses. The NPI is held-out ground truth._`,
151
+ "",
152
+ `**Headline — org-name truth (the honest grain):** the shipped ` +
153
+ `matcher resolves these records at **F1 ${pct(gbtOrg.f1)}%** against org-name entity-truth — not the NPI-level ` +
154
+ `${pct(gbtNPI.f1)}%, which mostly measures NPI over-segmentation (one organization holds many subpart NPIs, so ` +
155
+ `correct co-located merges are scored as errors). Same clusters, three rulers: ` +
156
+ `**NPI ${pct(gbtNPI.f1)}% → site ${pct(gbtEntity.f1)}% → org-name ${pct(gbtOrg.f1)}%** ` +
157
+ `(${keptNpis} NPI → ${entityCount} site → ${orgCount} org-name classes); the climb is the yardstick getting honest, ` +
158
+ `not the model changing — gold-set validated (120/120 hard pairs = same org). Details in "Three truth grains" below.`,
159
+ "",
160
+ `## The comparison-model levers (each toggled on, at the default threshold)`,
161
+ "",
162
+ `| model | precision | recall | F1 | ΔF1 | ARI | over-merged |`,
163
+ `|---|---:|---:|---:|---:|---:|---:|`,
164
+ ]
165
+
166
+ progression.forEach((p, i) => {
167
+ const delta = i === 0 ? "—" : signed(100 * (p.score.f1 - progression[i - 1]!.score.f1))
168
+ const bold = i === progression.length - 1
169
+ const w = (s: string) => (bold ? `**${s}**` : s)
170
+
171
+ lines.push(
172
+ `| ${w(p.label)} | ${w(pct(p.score.precision) + "%")} | ${w(pct(p.score.recall) + "%")} | ${w(pct(p.score.f1) + "%")} | ${delta} | ${w(p.score.ari.toFixed(3))} | ${w(String(p.score.overMergedClusters))} |`
173
+ )
174
+ })
175
+
176
+ lines.push("")
177
+
178
+ lines.push(
179
+ `Inverse-frequency weighting uses the corpus-wide table (${addressFrequency.distinct.toLocaleString()} distinct addresses ` +
180
+ `over ${addressFrequency.total.toLocaleString()} providers) to down-weight a crowded shared address; collapsing the redundant ` +
181
+ `address-key + distance comparisons into one spatial signal (A1) removes the double-count that let a shared address ` +
182
+ `over-vote a disagreeing name. The address-frequency + A1 baseline is F1 ${pct(progression[2]!.score.f1)}% at the ` +
183
+ `default threshold; the **authorized-official discriminator** is roughly neutral there (${signed(100 * (progression[3]!.score.f1 - progression[2]!.score.f1))}) ` +
184
+ `but enables a higher cutoff — it holds recall where the baseline alone collapses, reaching **${pct(best.score.f1)}%** at ` +
185
+ `threshold ${best.t} (below), the first config past the baseline (#625).`
186
+ )
187
+
188
+ lines.push("")
189
+
190
+ lines.push(
191
+ `**Out-of-the-box (zero-config \`resolveEntities(records)\`, levers default-on #86):** F1 ` +
192
+ `**${pct(defaultOutOfBox.f1)}%** on this sample — essentially the baseline. The default auto-computes the ` +
193
+ `address-frequency table over the INPUT records, and this benchmark deliberately sub-samples ${N} records, so ` +
194
+ `that table is too sparse to carry the inverse-frequency signal (a corpus statistic you can't synthesize from a ` +
195
+ `slice). It's **not a regression** (≥ baseline, no over-merge added) — it's the honest floor when the input isn't ` +
196
+ `corpus-scale. Fed the corpus-wide table (the \`+ inverse-address-frequency\` row above, what the CLI builds from ` +
197
+ `the full source files) the SAME default reaches the **${pct(progression[2]!.score.f1)}%** baseline. On a full-dataset ` +
198
+ `dedup the input IS the corpus, so zero-config reaches the baseline on its own.`
199
+ )
200
+
201
+ lines.push("")
202
+ lines.push(`## With all levers on, across the link threshold (the secondary lever)`)
203
+ lines.push("")
204
+ lines.push(`| link threshold (bits) | precision | recall | F1 | ARI | clusters | over-merged |`)
205
+ lines.push(`|---:|---:|---:|---:|---:|---:|---:|`)
206
+
207
+ for (const s of sweep) {
208
+ const star = s === best ? " ⭐" : ""
209
+
210
+ lines.push(
211
+ `| ${s.t}${s.t === 0 ? " (default)" : ""} | ${pct(s.score.precision)}% | ${pct(s.score.recall)}% | **${pct(s.score.f1)}%**${star} | ${s.score.ari.toFixed(3)} | ${s.score.clusters} | ${s.score.overMergedClusters} |`
212
+ )
213
+ }
214
+
215
+ lines.push("")
216
+
217
+ lines.push(
218
+ best.t === 0
219
+ ? `Best F1 is at the **default threshold** (${pct(base.score.f1)}%): raising it only trades recall away faster ` +
220
+ `than it buys precision. So the threshold knob alone can't separate co-located distinct providers — the ` +
221
+ `over-merge is structural, in the comparison model, not the cutoff.`
222
+ : `Best F1 **${pct(best.score.f1)}%** (ARI ${best.score.ari.toFixed(3)}) at threshold ${best.t}, vs **${pct(base.score.f1)}%** at the ` +
223
+ `default — the threshold knob moves it ${(100 * (best.score.f1 - base.score.f1)).toFixed(0)}pp. Higher thresholds trade recall for precision.`
224
+ )
225
+
226
+ lines.push("")
227
+ lines.push(`## Shape + where the errors are (at the default threshold)`)
228
+ lines.push("")
229
+ lines.push(`- records: ${N} · true entities (NPIs): ${keptNpis} · recovered clusters: ${base.score.clusters}`)
230
+
231
+ lines.push(
232
+ `- candidate pairs blocked: ${base.res.candidatePairs}${base.res.droppedBlocks.length ? ` · oversized blocks skipped: ${base.res.droppedBlocks.length}` : ""}`
233
+ )
234
+
235
+ lines.push(
236
+ `- **Over-merge (precision):** ${base.score.overMergedClusters} clusters fuse ≥2 distinct NPIs (largest fuses ` +
237
+ `${base.score.maxNpisFused}; ${base.score.recordsInOverMerged} records) — **co-located providers sharing a clinic / ` +
238
+ `billing address**, linked by address agreement despite different names.`
239
+ )
240
+
241
+ lines.push(
242
+ `- **Under-merge (recall):** ${base.score.splitNpis}/${keptNpis} NPIs split across >1 cluster — records at distant ` +
243
+ `addresses (mailing vs practice) or with strong name drift the score didn't bridge.`
244
+ )
245
+
246
+ lines.push("")
247
+ lines.push(`## Three truth grains — NPI → site → org-name (the over-segmentation correction)`)
248
+ lines.push("")
249
+
250
+ lines.push(
251
+ `NPI-as-truth OVER-SEGMENTS: one org holds many NPIs, so the matcher's correct co-located merges are scored as ` +
252
+ `errors. Three yardsticks, same clusters: **NPI** (one entity per registration), **site** (subpart-flagged ` +
253
+ `collapse + split an NPI's distinct addresses), and **org-name** — the gold-set-validated truth: same NPI ⇒ ` +
254
+ `same entity (recall preserved) PLUS collapse co-located NPIs whose primary org names match (Jaccard ≥ ${ORG_TAU}), ` +
255
+ `with NO reliance on the subpart flag (the gold set showed it misses 37%). The same ${N} records carry ` +
256
+ `**${keptNpis} NPI** → **${entityCount} site** → **${orgCount} org-name** classes. The org-name number is the ` +
257
+ `honest one: it stops charging the matcher for the same-org merges the gold set proved are correct.`
258
+ )
259
+
260
+ lines.push("")
261
+ lines.push(`| config | truth | precision | recall | F1 | ΔF1 vs NPI | ARI | over-merged |`)
262
+ lines.push(`|---|---|---:|---:|---:|---:|---:|---:|`)
263
+
264
+ const dualRow = (label: string, truth: string, s: Score, delta?: number) =>
265
+ lines.push(
266
+ `| ${label} | ${truth} | ${pct(s.precision)}% | ${pct(s.recall)}% | **${pct(s.f1)}%** | ${delta === undefined ? "—" : signed(100 * delta)} | ${s.ari.toFixed(3)} | ${s.overMergedClusters} |`
267
+ )
268
+
269
+ dualRow("FS full stack", "NPI", fsNPI)
270
+ dualRow("FS full stack", "site", fsEntity, fsEntity.f1 - fsNPI.f1)
271
+ dualRow("FS full stack", "**org-name**", fsOrg, fsOrg.f1 - fsNPI.f1)
272
+ dualRow("FS full stack", "org-name (coord)", fsOrgCoord, fsOrgCoord.f1 - fsNPI.f1)
273
+ dualRow("GBT (shipped default)", "NPI", gbtNPI)
274
+ dualRow("GBT (shipped default)", "site", gbtEntity, gbtEntity.f1 - gbtNPI.f1)
275
+ dualRow("GBT (shipped default)", "**org-name**", gbtOrg, gbtOrg.f1 - gbtNPI.f1)
276
+ dualRow("GBT (shipped default)", "**org-name (coord)**", gbtOrgCoord, gbtOrgCoord.f1 - gbtNPI.f1)
277
+ dualRow("GBT (shipped default)", `org-name (H3 res ${H3_RES})`, gbtOrgH3, gbtOrgH3.f1 - gbtNPI.f1)
278
+
279
+ if (cand) {
280
+ dualRow(cand.label, "NPI", cand.npi)
281
+ dualRow(cand.label, "**entity**", cand.entity, cand.entity.f1 - cand.npi.f1)
282
+ }
283
+
284
+ lines.push("")
285
+
286
+ lines.push(
287
+ `The F1 **climbs as the yardstick gets honest**: GBT **${pct(gbtNPI.f1)}% (NPI) → ${pct(gbtEntity.f1)}% (site) → ` +
288
+ `${pct(gbtOrg.f1)}% (org-name)**, the over-merge collapsing (${gbtNPI.overMergedClusters} → ${gbtOrg.overMergedClusters}) ` +
289
+ `and precision rising (${pct(gbtNPI.precision)}% → ${pct(gbtOrg.precision)}%). The clusters are IDENTICAL across the three ` +
290
+ `columns — the climb is purely the ruler ceasing to charge the matcher for the correct same-org merges the gold set proved ` +
291
+ `(\`2026-06-16-dedup-gold-set-tx120.md\`: 120/120 same org, 0 genuine over-merges).`
292
+ )
293
+
294
+ lines.push("")
295
+
296
+ lines.push(
297
+ `**Tier 2D — tightening the org-name ruler with the geocode coordinate.** The org-name truth above blocks by the address ` +
298
+ `STRING (\`addressFrequencyKey\`), so two records at one building whose text differs — \`1504 Taub LOOP\` vs ` +
299
+ `\`1504 Taub LP STE 100\` — key apart and the merge is still charged as an error. Block by the GEOCODED BUILDING instead ` +
300
+ `(union co-located NPIs within ${COLOCATION_KM * 1000} m whose org names agree, same Jaccard gate) and the truth tightens ` +
301
+ `further: GBT **org-name ${pct(gbtOrg.f1)}% → org-name-coord ${pct(gbtOrgCoord.f1)}%** ` +
302
+ `(${signed(100 * (gbtOrgCoord.f1 - gbtOrg.f1))}), ${orgCount} → ${orgCoordCount} classes, over ${geocodedNpis}/${keptNpis} ` +
303
+ `geocoded NPIs. The string org-name F1 is a conservative LOWER bound; the coordinate one is tighter (the Jaccard gate ` +
304
+ `still blocks distinct co-located orgs). Both are honest — the coordinate is the geocode-first key.`
305
+ )
306
+
307
+ lines.push("")
308
+
309
+ lines.push(
310
+ `**H3-cell robustness check (#109).** Re-keying the same building-grain co-location on an H3 cell ` +
311
+ `(res ${H3_RES}) instead of the 50 m haversine radius — the deterministic, O(n) "geocode-first cell" the issue ` +
312
+ `suggested — gives GBT **org-name-h3 ${pct(gbtOrgH3.f1)}%** (${orgH3Count} classes), vs the haversine ` +
313
+ `${pct(gbtOrgCoord.f1)}% (${orgCoordCount}). ${
314
+ Math.abs(gbtOrgH3.f1 - gbtOrgCoord.f1) < BLOCKING_PARITY_TOLERANCE
315
+ ? "Within noise of the haversine grain — the ~" +
316
+ pct(gbtOrgCoord.f1) +
317
+ "% coord-grain F1 is robust to the co-location method, not an artifact of the 50 m threshold."
318
+ : "The two co-location methods differ by " +
319
+ signed(100 * (gbtOrgH3.f1 - gbtOrgCoord.f1)) +
320
+ " — the cell-vs-radius boundary handling shifts the count (a hard H3 boundary can split a same-building pair into adjacent cells)."
321
+ }`
322
+ )
323
+
324
+ lines.push("")
325
+
326
+ lines.push(
327
+ `**Takeaways:** (1) The dedup model's REAL quality is the **org-name F1 ~${pct(gbtOrg.f1)}%**, not the NPI-level ` +
328
+ `${pct(gbtNPI.f1)}% — the difference was NPI over-segmentation, not model error. (2) The #625 lever was the YARDSTICK, ` +
329
+ `not the scorer: the corroboration-feature experiment (reverted) couldn't move precision because the over-merge was ` +
330
+ `mostly correct. (3) The remaining org-name over-merge (${gbtOrg.overMergedClusters} clusters) is the genuine frontier — ` +
331
+ `small, approaching the ceiling's ~1.6% irreducible (\`2026-06-16-dedup-ceiling.md\`). (4) Trust the large eval: a 50-NPI ` +
332
+ `smoke misled on the site delta (+5–7pp vs this run's ±2pp).`
333
+ )
334
+
335
+ lines.push("")
336
+
337
+ lines.push(
338
+ `Caveats: the programmatic site-truth is CONSERVATIVE (collapses only NPPES-flagged subparts; unflagged same-org pairs still ` +
339
+ `read as over-merge), so it understates the subpart correction. A hand-adjudicated gold set on the ambiguous co-located + ` +
340
+ `two-site slice is the next refinement (#625).`
341
+ )
342
+
343
+ lines.push("")
344
+ lines.push(`## Reading`)
345
+ lines.push("")
346
+
347
+ lines.push(
348
+ `The geocode-first **foundation works**: **${pct(geo / N)}%** of addresses placed, blocking + clustering clean — the ` +
349
+ `geocoding (the Pelias/Nominatim-can't-do-this part) is not the bottleneck. The comparison-model levers reach the ` +
350
+ `address-frequency + A1 baseline at F1 **${pct(progression[2]!.score.f1)}%** (${signed(100 * (progression[2]!.score.f1 - baseline.score.f1))} over baseline): ` +
351
+ `inverse-frequency weighting restores full weight to a *rare* shared address (stitching a provider's name-drifted ` +
352
+ `records together — mostly recall) while down-weighting a *crowded* one, and the collapsed spatial signal (A1) drops ` +
353
+ `the address+distance double-count. What remains is **precision / over-merge** — ${fullStack.score.overMergedClusters} ` +
354
+ `clusters still fuse distinct co-located providers, because even one down-weighted spatial agreement can outvote a ` +
355
+ `disagreeing name. The lever search (#625) — two negatives, then the first positive: a name/org/phone ` +
356
+ `**corroboration gate** (A2/A3) — phone is an unreliable secondary identifier on NPPES (shared institutional ` +
357
+ `switchboard lines), so it over-links and falsely corroborates co-phone distinct providers; and **average-linkage ` +
358
+ `clustering** (A4) — the over-merged clusters are joined by STRONG shared-address edges, not weak bridges, so ` +
359
+ `average-linkage can't split them and only trades away name-drift recall. The over-merge is a **scoring** problem ` +
360
+ `this data can't resolve, not a clustering-topology one. The **authorized-official discriminator** is the first lever to beat the baseline — a reliable secondary identifier holds recall so a higher threshold separates the co-located providers; a still-more-distinctive identifier ` +
361
+ `(taxonomy / license) or a learned scorer over the FS feature vector (#603) goes further. Config ` +
362
+ `dominates the model (the pre-registered finding) — tracked as #625 / the selective-model work (#602 / #603).`
363
+ )
364
+
365
+ lines.push("")
366
+
367
+ lines.push(
368
+ `NPI-as-truth is **conservative**: a cluster fusing two NPIs is a candidate "same entity, two NPIs" surfaced for ` +
369
+ `review, not an adjudicated error; an NPI split across genuinely-distant addresses is geo-first behaving correctly, ` +
370
+ `counted here as a recall miss. We resolve and report; interpretation is the consumer's.`
371
+ )
372
+
373
+ lines.push("")
374
+
375
+ return lines.join("\n")
376
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file The NPPES benchmark's input sample: the variation-rich multi-record set per NPI, plus the corpus-wide
6
+ * address-frequency table built in the same pass.
7
+ */
8
+
9
+ import { isPresent } from "@mailwoman/core/objects"
10
+ import type { TermFrequencyTable } from "@mailwoman/match"
11
+
12
+ import { addressFrequencyKey, streamRows } from "#index"
13
+
14
+ import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C } from "../shared.ts"
15
+ import { orgTokens, type NPIPrimary } from "./org-name.ts"
16
+
17
+ /**
18
+ * One synthetic input row for the matcher; `npi` is the hidden NPI-level truth, `entityID` the site-level entity-level
19
+ * truth (subpart-collapsed).
20
+ */
21
+ export interface MessyRow extends Record<string, string> {
22
+ npi: string
23
+ name: string
24
+ org: string
25
+ address: string
26
+ auth: string
27
+ /**
28
+ * Whitespace-joined taxonomy-code set (up to 15 slots) — the #625 code-set discriminator.
29
+ */
30
+ taxonomy: string
31
+ entityID: string
32
+ }
33
+
34
+ /**
35
+ * What the sample pass yields.
36
+ */
37
+ export interface NPPESSample {
38
+ rows: MessyRow[]
39
+ /**
40
+ * The sampled NPIs — the true-entity count at the NPI grain.
41
+ */
42
+ keptNpis: Set<string>
43
+ /**
44
+ * Per-NPI primary org name + practice address key, the basis for the org-name entity truths.
45
+ */
46
+ npiPrimary: Map<string, NPIPrimary>
47
+ /**
48
+ * Corpus-wide address-frequency table — the inverse-frequency signal. Counted over EVERY practice address in the
49
+ * registry, not just the sample, so the sharing structure is a corpus statistic rather than a slice artifact.
50
+ */
51
+ addressFrequency: TermFrequencyTable
52
+ }
53
+
54
+ /**
55
+ * Where the sample comes from and how much of it to take.
56
+ */
57
+ export interface NPPESSampleOptions {
58
+ registryPath: string
59
+ otherNamesPath: string
60
+ /**
61
+ * Already upper-cased; compared against the practice-location state column.
62
+ */
63
+ state: string
64
+ maxNpis: number
65
+ }
66
+
67
+ /**
68
+ * Build the benchmark's input records from the real registry.
69
+ *
70
+ * Two passes over two files, and the SECOND one cannot break early: the address-frequency table needs every registry
71
+ * row even after the sample is full, so the `kept.size < maxNpis` test gates only the sample branch.
72
+ */
73
+ export async function buildNPPESSample(
74
+ options: NPPESSampleOptions,
75
+ report?: (line: string) => void
76
+ ): Promise<NPPESSample> {
77
+ const { registryPath, otherNamesPath, state, maxNpis } = options
78
+
79
+ // --- Phase A: the variation set — NPIs that carry ≥1 alternate organization name. ---
80
+ report?.("[A] streaming other-names…")
81
+ const altNames = new Map<string, string[]>()
82
+
83
+ for await (const r of streamRows(otherNamesPath)) {
84
+ const npi = norm(r[C.npi])
85
+ const alt = norm(r[C.otherOrg])
86
+
87
+ if (!npi || !alt) continue
88
+ const list = altNames.get(npi) ?? []
89
+
90
+ if (list.length < MIN_GROUP_SIZE) {
91
+ list.push(alt)
92
+ }
93
+
94
+ // cap fan-out per NPI
95
+ altNames.set(npi, list)
96
+ }
97
+
98
+ report?.(` ${altNames.size} NPIs with ≥1 alternate name`)
99
+
100
+ // --- Phase B: ONE full registry pass — build the GLOBAL address-frequency table (every practice
101
+ // address, so the sharing structure is corpus-wide, not sample-biased) AND collect the sample. ---
102
+ report?.(`[B] full registry pass: address-frequency table + ${maxNpis} ${state} sample…`)
103
+ const rows: MessyRow[] = []
104
+ const kept = new Set<string>()
105
+ // Per-NPI primary org name + practice address key — the basis for the ORG-NAME entity-truth.
106
+ const npiPrimary = new Map<string, NPIPrimary>()
107
+ const addrCounts = new Map<string, number>()
108
+ let addrTotal = 0
109
+ let scanned = 0
110
+
111
+ for await (const r of streamRows(registryPath)) {
112
+ if (++scanned % 1_000_000 === 0) {
113
+ report?.(` scanned ${scanned / 1e6}M rows, kept ${kept.size}`)
114
+ }
115
+
116
+ const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
117
+
118
+ // Global address-frequency: count every practice address (one row ≈ one distinct NPI).
119
+ if (practice) {
120
+ const k = addressFrequencyKey(practice)
121
+ addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
122
+
123
+ addrTotal++
124
+ }
125
+
126
+ // Sample: in-state NPIs with ≥1 alternate name, up to maxNpis — NO early break (the table needs the full pass).
127
+ const npi = norm(r[C.npi])
128
+
129
+ if (
130
+ kept.size < maxNpis &&
131
+ npi &&
132
+ !kept.has(npi) &&
133
+ altNames.has(npi) &&
134
+ practice &&
135
+ norm(r[C.pState]).toUpperCase() === state
136
+ ) {
137
+ const isOrg = norm(r[C.entityType]) === "2"
138
+ const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
139
+
140
+ if (primaryName) {
141
+ const org = isOrg ? norm(r[C.orgLegal]) : ""
142
+ const auth = `${norm(r[C.authFirst])} ${norm(r[C.authLast])}`.trim()
143
+
144
+ // the NPI's registrant — shared across its records
145
+ // #625: the taxonomy-code set (up to 15 slots), whitespace-joined — identical across the NPI's
146
+ // records by construction (it's a per-NPI registry attribute), so it NEVER splits one entity;
147
+ // it only separates co-located DISTINCT providers whose sets are disjoint.
148
+ const taxonomy = C.taxonomy
149
+ .map((col) => norm(r[col]))
150
+ .filter(isPresent)
151
+ .join(" ")
152
+
153
+ // Entity-level (site) truth: same org + same physical address. Subparts (NPPES
154
+ // "Is Organization Subpart" + parent LBN/TIN) collapse to their PARENT, so the matcher isn't
155
+ // charged for correctly fusing one org's many subpart-NPIs at a site; an NPI's mailing-vs-
156
+ // practice records stay DISTINCT sites. orgKey = parent identity for subparts, else the NPI
157
+ // (independent orgs sharing an address stay distinct — the conservative choice).
158
+ const isSubpart = norm(r[C.isSubpart]).toUpperCase() === "Y"
159
+ const parentKey = `${norm(r[C.parentLBN])}|${norm(r[C.parentTIN])}`.toLowerCase()
160
+ const orgKey = isSubpart && parentKey !== "|" ? `p:${parentKey}` : `n:${npi}`
161
+ const eid = (a: string) => `${addressFrequencyKey(a)}|${orgKey}`
162
+
163
+ if (org) {
164
+ npiPrimary.set(npi, { tokens: orgTokens(org), addrKey: addressFrequencyKey(practice) })
165
+ }
166
+
167
+ kept.add(npi)
168
+ rows.push({ npi, name: primaryName, org, address: practice, auth, taxonomy, entityID: eid(practice) })
169
+
170
+ // primary
171
+ for (const alt of altNames.get(npi)!) {
172
+ rows.push({ npi, name: alt, org: alt, address: practice, auth, taxonomy, entityID: eid(practice) })
173
+ }
174
+
175
+ // name drift
176
+ const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
177
+
178
+ if (mailing && mailing !== practice) {
179
+ rows.push({ npi, name: primaryName, org, address: mailing, auth, taxonomy, entityID: eid(mailing) })
180
+ } // address variation
181
+ }
182
+ }
183
+ }
184
+
185
+ // Corpus-wide address-frequency table — the inverse-frequency signal (#617 fix per the DeepSeek consult).
186
+ const addressFrequency: TermFrequencyTable = {
187
+ total: addrTotal,
188
+ distinct: addrCounts.size,
189
+ frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
190
+ }
191
+
192
+ report?.(
193
+ ` ${kept.size} NPIs → ${rows.length} records; address table: ${addrCounts.size} distinct over ${addrTotal} rows`
194
+ )
195
+
196
+ return { rows, keptNpis: kept, npiPrimary, addressFrequency }
197
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file Pairwise cluster scoring for the NPPES benchmark — precision/recall/F1 and adjusted Rand of recovered clusters
6
+ * against a truth labelling, plus the over-merge / under-merge shape counts.
7
+ */
8
+
9
+ import type { ResolvedEntity, SourceRecord } from "#index"
10
+
11
+ /**
12
+ * Pairs within a group of `n`.
13
+ */
14
+ export const choose2 = (n: number): number => (n * (n - 1)) / 2
15
+
16
+ /**
17
+ * One clustering scored against one truth labelling.
18
+ */
19
+ export interface Score {
20
+ precision: number
21
+ recall: number
22
+ f1: number
23
+ ari: number
24
+ clusters: number
25
+ singletons: number
26
+ overMergedClusters: number
27
+ recordsInOverMerged: number
28
+ maxNpisFused: number
29
+ splitNpis: number
30
+ }
31
+
32
+ /**
33
+ * Score recovered clusters against a truth labelling.
34
+ *
35
+ * Pairwise, not set-matching: a true pair is two records carrying the same `labelOf`, a predicted pair is two records
36
+ * in the same entity. `totalRecords` is the labelled population and only feeds the adjusted-Rand expectation, so it
37
+ * must be the whole record set rather than the clustered subset — a smaller value inflates ARI.
38
+ */
39
+ export function scoreEntities(
40
+ entities: readonly ResolvedEntity[],
41
+ labelOf: (rec: SourceRecord) => string,
42
+ totalRecords: number
43
+ ): Score {
44
+ const npiTotals = new Map<string, number>()
45
+ const npiClusters = new Map<string, Set<number>>()
46
+ let sumCK = 0 // Σ C(n_ck, 2)
47
+ let sumCluster = 0 // Σ_c C(|c|, 2)
48
+ let singletons = 0
49
+ let overMergedClusters = 0
50
+ let recordsInOverMerged = 0
51
+ let maxNpisFused = 0
52
+
53
+ entities.forEach((e, ci) => {
54
+ const byNPI = new Map<string, number>()
55
+
56
+ for (const rec of e.records) {
57
+ const lbl = labelOf(rec)
58
+ byNPI.set(lbl, (byNPI.get(lbl) ?? 0) + 1)
59
+ }
60
+
61
+ sumCluster += choose2(e.records.length)
62
+
63
+ if (e.records.length === 1) {
64
+ singletons++
65
+ }
66
+
67
+ if (byNPI.size > 1) {
68
+ overMergedClusters++
69
+ recordsInOverMerged += e.records.length
70
+ maxNpisFused = Math.max(maxNpisFused, byNPI.size)
71
+ }
72
+
73
+ for (const [npi, n] of byNPI) {
74
+ sumCK += choose2(n)
75
+ npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + n)
76
+ }
77
+
78
+ for (const rec of e.records) {
79
+ const lbl = labelOf(rec)
80
+ const s = npiClusters.get(lbl) ?? new Set<number>()
81
+ s.add(ci)
82
+ npiClusters.set(lbl, s)
83
+ }
84
+ })
85
+
86
+ let sumClass = 0
87
+
88
+ // Σ_k C(|k|, 2)
89
+ for (const total of npiTotals.values()) {
90
+ sumClass += choose2(total)
91
+ }
92
+
93
+ const tp = sumCK
94
+ const precision = tp + (sumCluster - tp) > 0 ? tp / sumCluster : 0
95
+ const recall = sumClass > 0 ? tp / sumClass : 0
96
+ const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
97
+ const expected = (sumCluster * sumClass) / choose2(totalRecords)
98
+ const maxIndex = (sumCluster + sumClass) / 2
99
+ const ari = maxIndex - expected !== 0 ? (tp - expected) / (maxIndex - expected) : 1
100
+ const splitNpis = [...npiClusters.values()].filter((s) => s.size > 1).length
101
+
102
+ return {
103
+ precision,
104
+ recall,
105
+ f1,
106
+ ari,
107
+ clusters: entities.length,
108
+ singletons,
109
+ overMergedClusters,
110
+ recordsInOverMerged,
111
+ maxNpisFused,
112
+ splitNpis,
113
+ }
114
+ }