@mailwoman/entity-resolution 0.0.0-stage → 10.8.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,349 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Learned-scorer clustering A/B. A better pairwise scorer need not lift the assembled clustering F1,
7
+ * because that F1 depends on the threshold and connected components. This measures the clustering F1
8
+ * directly. It splits the NPIs into train and eval, trains a GBT and an LR on train pairs labeled by
9
+ * same NPI, then clusters the eval records three ways through the same `resolveEntities` pipeline
10
+ * (FS baseline, GBT scorer, LR scorer), sweeping the link threshold for each.
11
+ *
12
+ * The FS arm is the benchmark baseline (same model: address-frequency plus collapsed spatial,
13
+ * EM-fit), and the split is in-domain, held out by NPI rather than by state.
14
+ *
15
+ * Run: `mailwoman registry scorer-eval clustering [--npis 2000] [--split 0.67] [--seed 1]
16
+ * [--out-md <md>]`
17
+ */
18
+
19
+ import { dataRootPath } from "@mailwoman/core/data-root"
20
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
21
+ import { makeLcg } from "@mailwoman/core/random"
22
+ import { mean } from "@mailwoman/core/utils"
23
+ import { block, gbtScore, trainGBT } from "@mailwoman/match"
24
+
25
+ import {
26
+ buildDefaultModel,
27
+ createMatchFeaturizer,
28
+ defaultBlockingKeys,
29
+ ingestRows,
30
+ resolveEntities,
31
+ type ColumnMapping,
32
+ type SourceRecord,
33
+ } from "#index"
34
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
35
+ import { buildNPPESSample } from "#tools/nppes/sample"
36
+ import { scoreEntities } from "#tools/nppes/scoring"
37
+ import {
38
+ bestOver,
39
+ MIN_MEANINGFUL_F1_DELTA,
40
+ pct,
41
+ quantileThresholds,
42
+ sgn,
43
+ stateOption,
44
+ std,
45
+ toArmScore,
46
+ trainLogisticRegression,
47
+ type ArmScore,
48
+ } from "#tools/shared"
49
+
50
+ /**
51
+ * Options for {@linkcode scorerClusteringEval}.
52
+ */
53
+ export interface ScorerClusteringEvalOptions {
54
+ /**
55
+ * The injected geocoder factory.
56
+ *
57
+ * The command wires `mailwoman/geocode-core`, as `./eval-geocoder.ts` does.
58
+ */
59
+ createGeocoder: EvalGeocoderFactory
60
+ /**
61
+ * Record-matcher sources directory.
62
+ *
63
+ * @defaultValue `$MAILWOMAN_DATA_ROOT/record-matcher/sources`
64
+ */
65
+ sources?: string
66
+ /**
67
+ * State filter.
68
+ *
69
+ * @defaultValue TX.
70
+ */
71
+ state?: string
72
+ /**
73
+ * NPIs sampled.
74
+ *
75
+ * @defaultValue `2000`
76
+ */
77
+ npis?: number
78
+ /**
79
+ * Train fraction of the NPI split.
80
+ *
81
+ * @defaultValue `0.67`
82
+ */
83
+ split?: number
84
+ /**
85
+ * Base prng seed.
86
+ *
87
+ * @defaultValue `1`
88
+ */
89
+ seed?: number
90
+ /**
91
+ * Held-out-NPI splits averaged.
92
+ *
93
+ * @defaultValue `4`
94
+ */
95
+ seeds?: number
96
+ /**
97
+ * Also write the markdown report here.
98
+ */
99
+ outMd?: string
100
+ }
101
+
102
+ /**
103
+ * Cluster the eval records with the FS baseline, GBT and LR.
104
+ * Emit the markdown report to stdout.
105
+ */
106
+ export async function scorerClusteringEval(
107
+ options: ScorerClusteringEvalOptions,
108
+ report?: (line: string) => void
109
+ ): Promise<{ markdown: string }> {
110
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
111
+ const STATE = stateOption(options)
112
+ const NPIS = options.npis ?? 2000
113
+ const SPLIT = options.split ?? 0.67
114
+ const SEED = options.seed ?? 1
115
+ const OUT_MD = options.outMd || ""
116
+
117
+ const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
118
+ const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
119
+
120
+ const {
121
+ rows,
122
+ keptNpis: kept,
123
+ addressFrequency,
124
+ } = await buildNPPESSample(
125
+ { registryPath: REGISTRY, otherNamesPath: OTHER_NAMES, state: STATE, maxNpis: NPIS },
126
+ report
127
+ )
128
+
129
+ report?.("[C] geocoding…")
130
+ const geocoder = await options.createGeocoder()
131
+
132
+ // `auth` and `taxonomy` ride as attributes so the shared featurizer's roll-up
133
+ // features can read the authorized official.
134
+ // The FS arm ignores them, since no discriminators are configured.
135
+ const mapping: ColumnMapping = {
136
+ id: "npi",
137
+ name: "name",
138
+ organization: "org",
139
+ address: "address",
140
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
141
+ source: "nppes",
142
+ }
143
+
144
+ const records = await ingestRows(rows, mapping, {
145
+ geocodeAddress: geocoder.geocodeAddress,
146
+ })
147
+
148
+ geocoder[Symbol.dispose]()
149
+
150
+ // The collapsed-spatial and address-frequency comparison set is the benchmark feature basis.
151
+ // The shared production featurizer keeps train, eval and inference on one definition.
152
+ // The agreement pattern is independent of EM, so features stay consistent at train and inference time.
153
+ const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
154
+ const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
155
+
156
+ const npiLabel = (rec: SourceRecord) => rec.id
157
+
158
+ interface SeedResult {
159
+ seed: number
160
+ trainN: number
161
+ evalN: number
162
+ fs: ArmScore
163
+ lr: ArmScore
164
+ gbt: ArmScore
165
+ }
166
+
167
+ /**
168
+ * One held-out-NPI split: train the GBT and LR on train pairs, then cluster
169
+ * the eval records three ways through the same `resolveEntities` pipeline,
170
+ * sweeping the link threshold for each and taking best F1.
171
+ *
172
+ * The geocode is shared across seeds.
173
+ * Only the split, trained scorers and the eval subset move with the seed.
174
+ */
175
+ function runSeed(seed: number): SeedResult {
176
+ const rnd = makeLcg(seed || 1)
177
+ const npiSplit = new Map<string, "train" | "eval">()
178
+
179
+ for (const npi of kept) {
180
+ npiSplit.set(npi, rnd() < SPLIT ? "train" : "eval")
181
+ }
182
+
183
+ const trainRecords = records.filter((r) => npiSplit.get(r.id) === "train")
184
+ const evalRecords = records.filter((r) => npiSplit.get(r.id) === "eval")
185
+ const N = evalRecords.length
186
+
187
+ const { pairs: trainPairs } = block(trainRecords, defaultBlockingKeys())
188
+ const trainX = trainPairs.map(([a, b]) => featurize(a, b))
189
+ const trainY = trainPairs.map(([a, b]) => (a.id === b.id ? 1 : 0))
190
+ const posRate = trainY.reduce<number>((s, v) => s + v, 0) / Math.max(1, trainY.length)
191
+ const trainW = trainY.map((y) => (y === 1 ? 1 - posRate : posRate))
192
+ const dim = trainX[0]?.length ?? 0
193
+ const gbt = trainGBT(trainX, trainY, trainW, { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 })
194
+
195
+ // LR (batch GD, class-balanced) through the shared trainer.
196
+ const lrSc = trainLogisticRegression(trainX, trainY, trainW, dim)
197
+
198
+ const gbtScorer = (a: SourceRecord, b: SourceRecord) => gbtScore(gbt, featurize(a, b))
199
+ const lrScorer = (a: SourceRecord, b: SourceRecord) => lrSc(featurize(a, b))
200
+
201
+ const armOver = (
202
+ thresholds: readonly number[],
203
+ cfg: (t: number) => Parameters<typeof resolveEntities>[1]
204
+ ): ArmScore =>
205
+ bestOver(thresholds, (t) => toArmScore(scoreEntities(resolveEntities(evalRecords, cfg(t)).entities, npiLabel, N)))
206
+
207
+ // The FS baseline uses EM-fit weights in bits over a fine grid.
208
+ // Each learned scorer sweeps its own eval-pair score distribution,
209
+ // so a coarse grid cannot understate it.
210
+ const { pairs: evalPairs } = block(evalRecords, defaultBlockingKeys())
211
+
212
+ const fs = armOver(
213
+ Array.from({ length: 26 }, (_, i) => i),
214
+ // learnedScorer false keeps the FS baseline.
215
+ // The learned scorer is default-on, so without this the FS arm would silently be the GBT.
216
+ (t) => ({ addressFrequency, collapseSpatial: true, trainEM: true, threshold: t, learnedScorer: false })
217
+ )
218
+
219
+ const gbtArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => gbtScorer(a, b))), (t) => ({
220
+ addressFrequency,
221
+ collapseSpatial: true,
222
+ scorer: gbtScorer,
223
+ threshold: t,
224
+ }))
225
+
226
+ const lrArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => lrScorer(a, b))), (t) => ({
227
+ addressFrequency,
228
+ collapseSpatial: true,
229
+ scorer: lrScorer,
230
+ threshold: t,
231
+ }))
232
+
233
+ return { seed, trainN: trainRecords.length, evalN: N, fs, lr: lrArm, gbt: gbtArm }
234
+ }
235
+
236
+ const SEEDS = options.seeds ?? 4
237
+ report?.(`[D-F] ${SEEDS} held-out-NPI splits: FS baseline vs GBT vs LR…`)
238
+ const results: SeedResult[] = []
239
+
240
+ for (let k = 0; k < SEEDS; k++) {
241
+ const r = runSeed(SEED + k)
242
+ results.push(r)
243
+
244
+ report?.(
245
+ ` seed ${r.seed}: ${r.trainN}tr/${r.evalN}ev FS ${pct(r.fs.f1)} LR ${pct(r.lr.f1)} (${sgn(r.lr.f1 - r.fs.f1)}${pct(r.lr.f1 - r.fs.f1)}) ` +
246
+ `GBT ${pct(r.gbt.f1)} (${sgn(r.gbt.f1 - r.fs.f1)}${pct(r.gbt.f1 - r.fs.f1)})`
247
+ )
248
+ }
249
+
250
+ const fsF1 = results.map((r) => r.fs.f1)
251
+ const gbtF1 = results.map((r) => r.gbt.f1)
252
+ const dGbt = results.map((r) => r.gbt.f1 - r.fs.f1)
253
+ const dLr = results.map((r) => r.lr.f1 - r.fs.f1)
254
+ const gbtWins = dGbt.filter((d) => d > 0).length
255
+ const meanDGbt = mean(dGbt)!
256
+
257
+ const armRow = (label: string, pick: (r: SeedResult) => ArmScore, dArr: number[] | null, bold: boolean) => {
258
+ const f1s = results.map((r) => pick(r).f1)
259
+ const P = mean(results.map((r) => pick(r).precision))!
260
+ const R = mean(results.map((r) => pick(r).recall))!
261
+ const om = mean(results.map((r) => pick(r).overMerged))!
262
+ const d = dArr ? `${sgn(mean(dArr)! * 100)}${(mean(dArr)! * 100).toFixed(1)}pp` : "—"
263
+ const f1cell = `${pct(mean(f1s)!)}% ± ${pct(std(f1s))}`
264
+ const cells = `${pct(P)}% | ${pct(R)}% | ${bold ? `**${f1cell}**` : f1cell} | ${bold ? `**${d}**` : d} | ${om.toFixed(0)}`
265
+
266
+ return `| ${bold ? `**${label}**` : label} | ${cells} |`
267
+ }
268
+
269
+ const avgEval = Math.round(mean(results.map((r) => r.evalN))!)
270
+ const avgTrain = Math.round(mean(results.map((r) => r.trainN))!)
271
+
272
+ const lines: string[] = [
273
+ `# Learned-scorer CLUSTERING A/B (#603 Tier 2) — does a learned scorer beat the FS baseline on the assembled output?`,
274
+ "",
275
+ `_Generated by \`mailwoman registry scorer-eval clustering\`. ${kept.size} ${STATE} NPIs → ` +
276
+ `${records.length} records, geocoded and split by NPI into ~${avgTrain} train / ~${avgEval} eval records over ${SEEDS} ` +
277
+ `seeds (the GBT/LR never see an eval NPI's records). The held-out EVAL records are clustered three ways through the ` +
278
+ `SAME \`resolveEntities\` pipeline (block → score → connected-components): the FS baseline (address-frequency + ` +
279
+ `collapsed-spatial, EM-fit), the GBT as the link scorer (the new \`ResolveConfig.scorer\` hook), and the LR. Best F1 ` +
280
+ `over a fine per-scorer link-threshold sweep, averaged across seeds. This is the dedup benchmark's clustering metric ` +
281
+ `— the definitive test the pairwise probe (#637/#640) deferred._`,
282
+ "",
283
+ `## Result — eval clustering F1 (best over threshold, mean ± std over ${SEEDS} seeds, ~${avgEval} held-out records)`,
284
+ "",
285
+ `| scorer | precision | recall | F1 | ΔF1 vs FS | over-merged clusters |`,
286
+ `|---|---:|---:|---:|---:|---:|`,
287
+ armRow("FS baseline (EM-fit)", (r) => r.fs, null, false),
288
+ armRow("logistic regression", (r) => r.lr, dLr, false),
289
+ armRow("gradient-boosted trees", (r) => r.gbt, dGbt, true),
290
+ "",
291
+ `**ΔF1 (GBT − FS): ${sgn(meanDGbt * 100)}${(meanDGbt * 100).toFixed(1)}pp mean, GBT > FS in ${gbtWins}/${SEEDS} seeds.**`,
292
+ "",
293
+ ]
294
+
295
+ const verdict =
296
+ meanDGbt > MIN_MEANINGFUL_F1_DELTA && gbtWins >= SEEDS - 1
297
+ ? `**The learned scorer beats the FS baseline on the assembled clustering output** — GBT clustering F1 ` +
298
+ `${pct(mean(gbtF1)!)}% vs FS ${pct(mean(fsF1)!)}% (${sgn(meanDGbt * 100)}${(meanDGbt * 100).toFixed(1)}pp mean, ${gbtWins}/${SEEDS} ` +
299
+ `seeds), driven by a large PRECISION gain that reduces the over-merge — the #625 problem. The pairwise gain (#640) ` +
300
+ `DOES translate to the entity-resolution metric. This confirms the #603 GBM as a real dedup change and justifies the ` +
301
+ `production build (offline XGBoost/LightGBM → tree JSON, the \`scorer\` hook for inference). The honest next axis is ` +
302
+ `cross-STATE generalization (train-TX / eval-other-state) and a tuned GBM on more features.`
303
+ : meanDGbt < -MIN_MEANINGFUL_F1_DELTA
304
+ ? `**The learned scorer does NOT beat the FS baseline on clustering** (GBT ${pct(mean(gbtF1)!)}% vs FS ${pct(mean(fsF1)!)}%, ` +
305
+ `${(meanDGbt * 100).toFixed(1)}pp). The pairwise ranking gain (#640) does not survive the threshold + ` +
306
+ `connected-components assembly — clustering, not ranking, is the binding constraint. FS stays the baseline.`
307
+ : `**The learned scorer roughly TIES the FS baseline on clustering** (GBT ${pct(mean(gbtF1)!)}% vs FS ${pct(mean(fsF1)!)}%, ` +
308
+ `${sgn(meanDGbt * 100)}${(meanDGbt * 100).toFixed(1)}pp, ${gbtWins}/${SEEDS} seeds). The pairwise ranking gain (#640) is ` +
309
+ `real but largely washes out through the threshold + connected-components assembly. A learned scorer is not a free ` +
310
+ `dedup win; pairing it with a clustering change or a more distinctive identifier (#625) is the path.`
311
+
312
+ lines.push(verdict)
313
+ lines.push("")
314
+ lines.push(`### Per-seed F1`)
315
+ lines.push("")
316
+ lines.push(`| seed | eval records | FS | LR | GBT |`)
317
+ lines.push(`|---:|---:|---:|---:|---:|`)
318
+
319
+ for (const r of results) {
320
+ lines.push(`| ${r.seed} | ${r.evalN} | ${pct(r.fs.f1)}% | ${pct(r.lr.f1)}% | ${pct(r.gbt.f1)}% |`)
321
+ }
322
+
323
+ lines.push("")
324
+ lines.push(`## Honest caveats`)
325
+ lines.push("")
326
+
327
+ lines.push(
328
+ `In-domain (${STATE}), a held-out-NPI split (NOT a held-out STATE — cross-state generalization is the next axis, ` +
329
+ `the #603 train-TX/eval-other-state design). The FS arm IS the benchmark baseline (same model), so the comparison is ` +
330
+ `fair. The GBT is a compact pure-Node implementation (120 rounds, depth 3), not a tuned XGBoost/LightGBM — a real ` +
331
+ `GBM with more NPIs/features could move the number further. Thresholds are swept per scorer (FS in bits, learned ` +
332
+ `scorers in logits), each at its own best operating point — note a 300-NPI smoke MISLED (FS ahead): too few ` +
333
+ `co-located collisions to exhibit the over-merge. It only bites at scale. Therefore, trust the larger eval. NPI-as-truth ` +
334
+ `is conservative (a cross-NPI merge is a candidate, not necessarily an error)._`
335
+ )
336
+
337
+ lines.push("")
338
+
339
+ const md = lines.join("\n")
340
+
341
+ console.log(md)
342
+
343
+ if (OUT_MD) {
344
+ await writeLocalFile(md, OUT_MD)
345
+ report?.(`[written] ${OUT_MD}`)
346
+ }
347
+
348
+ return { markdown: md }
349
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Learned-scorer cross-state generalization, the next axis after the held-out-NPI A/B. The
7
+ * within-state A/B showed the GBT beats the FS baseline on clustering, so this trains on one state and
8
+ * evaluates clustering F1 on a different state the model never saw.
9
+ *
10
+ * One registry pass builds the global address-frequency table, a train-state sample and an
11
+ * eval-state sample. Both samples are geocoded. The GBT and LR train on the train state's pairs and
12
+ * cluster the eval state's records through the same `resolveEntities` pipeline, with best F1 over a
13
+ * fine per-scorer threshold sweep.
14
+ *
15
+ * Run: `mailwoman registry scorer-eval cross-state [--train-state TX] [--eval-state CA]
16
+ * [--npis 2000] [--out-md <md>]`
17
+ */
18
+
19
+ import { dataRootPath } from "@mailwoman/core/data-root"
20
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
21
+ import { block, gbtScore, trainGBT } from "@mailwoman/match"
22
+
23
+ import {
24
+ buildDefaultModel,
25
+ createGBTScorer,
26
+ createMatchFeaturizer,
27
+ DEDUP_GBT_MODEL,
28
+ defaultBlockingKeys,
29
+ ingestRows,
30
+ resolveEntities,
31
+ type ColumnMapping,
32
+ type SourceRecord,
33
+ } from "#index"
34
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
35
+ import { buildNPPESStateSamples } from "#tools/nppes/sample"
36
+ import { scoreEntities } from "#tools/nppes/scoring"
37
+ import {
38
+ bestOver,
39
+ MIN_MEANINGFUL_F1_DELTA,
40
+ pct,
41
+ quantileThresholds,
42
+ sgn,
43
+ toArmScore,
44
+ trainLogisticRegression,
45
+ type ArmScore,
46
+ } from "#tools/shared"
47
+
48
+ /**
49
+ * Options for {@linkcode scorerCrossStateEval}.
50
+ */
51
+ export interface ScorerCrossStateEvalOptions {
52
+ /**
53
+ * The injected geocoder factory.
54
+ *
55
+ * The command wires `mailwoman/geocode-core`, as `./eval-geocoder.ts` does.
56
+ */
57
+ createGeocoder: EvalGeocoderFactory
58
+ /**
59
+ * Record-matcher sources directory.
60
+ *
61
+ * @defaultValue `$MAILWOMAN_DATA_ROOT/record-matcher/sources`
62
+ */
63
+ sources?: string
64
+ /**
65
+ * State the GBT/LR train on.
66
+ *
67
+ * @defaultValue TX.
68
+ */
69
+ trainState?: string
70
+ /**
71
+ * Held-out state clustered.
72
+ *
73
+ * @defaultValue CA.
74
+ */
75
+ evalState?: string
76
+ /**
77
+ * NPIs sampled per state.
78
+ *
79
+ * @defaultValue `2000`
80
+ */
81
+ npis?: number
82
+ /**
83
+ * Also write the markdown report here.
84
+ */
85
+ outMd?: string
86
+ }
87
+
88
+ /**
89
+ * Train on one state and cluster a different state's records.
90
+ * Emit the report to stdout.
91
+ */
92
+ export async function scorerCrossStateEval(
93
+ options: ScorerCrossStateEvalOptions,
94
+ report?: (line: string) => void
95
+ ): Promise<{ markdown: string }> {
96
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
97
+ const TRAIN_STATE = (options.trainState || "TX").toUpperCase()
98
+ const EVAL_STATE = (options.evalState || "CA").toUpperCase()
99
+ const NPIS = options.npis ?? 2000
100
+ const OUT_MD = options.outMd || ""
101
+
102
+ const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
103
+ const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
104
+
105
+ const { byState, addressFrequency } = await buildNPPESStateSamples(
106
+ {
107
+ registryPath: REGISTRY,
108
+ otherNamesPath: OTHER_NAMES,
109
+ states: [TRAIN_STATE, EVAL_STATE],
110
+ maxNpisPerState: NPIS,
111
+ },
112
+ report
113
+ )
114
+
115
+ const trainSample = byState.get(TRAIN_STATE)!
116
+ const evalSample = byState.get(EVAL_STATE)!
117
+
118
+ report?.("[C] geocoding both states…")
119
+ const geocoder = await options.createGeocoder()
120
+
121
+ // `auth` and `taxonomy` ride as attributes so the shared featurizer's roll-up
122
+ // features can read the authorized official.
123
+ // The FS arm ignores them, since no discriminators are configured.
124
+ const mapping: ColumnMapping = {
125
+ id: "npi",
126
+ name: "name",
127
+ organization: "org",
128
+ address: "address",
129
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
130
+ source: "nppes",
131
+ }
132
+
133
+ const trainRecords = await ingestRows(trainSample.rows, mapping, { geocodeAddress: geocoder.geocodeAddress })
134
+ const evalRecords = await ingestRows(evalSample.rows, mapping, { geocodeAddress: geocoder.geocodeAddress })
135
+ geocoder[Symbol.dispose]()
136
+
137
+ // The shared production featurizer keeps train, eval and inference on one definition,
138
+ // over the collapsed-spatial and address-frequency comparison set.
139
+ const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
140
+ const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
141
+
142
+ report?.(`[D] training GBT + LR on ${TRAIN_STATE} pairs…`)
143
+ const { pairs: trainPairs } = block(trainRecords, defaultBlockingKeys())
144
+ const trainX = trainPairs.map(([a, b]) => featurize(a, b))
145
+ const trainY = trainPairs.map(([a, b]) => (a.id === b.id ? 1 : 0))
146
+ const posRate = trainY.reduce<number>((s, v) => s + v, 0) / Math.max(1, trainY.length)
147
+ const trainW = trainY.map((y) => (y === 1 ? 1 - posRate : posRate))
148
+ const dim = trainX[0]?.length ?? 0
149
+ const gbt = trainGBT(trainX, trainY, trainW, { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 })
150
+
151
+ // LR (batch GD, class-balanced) through the shared trainer.
152
+ const lrSc = trainLogisticRegression(trainX, trainY, trainW, dim)
153
+
154
+ const gbtScorer = (a: SourceRecord, b: SourceRecord) => gbtScore(gbt, featurize(a, b))
155
+ const lrScorer = (a: SourceRecord, b: SourceRecord) => lrSc(featurize(a, b))
156
+
157
+ report?.(`[E] clustering ${EVAL_STATE} records (FS baseline vs GBT vs LR, trained on ${TRAIN_STATE})…`)
158
+
159
+ const npiLabel = (rec: SourceRecord) => rec.id
160
+
161
+ const armOver = (
162
+ thresholds: readonly number[],
163
+ cfg: (t: number) => Parameters<typeof resolveEntities>[1]
164
+ ): ArmScore =>
165
+ bestOver(thresholds, (t) =>
166
+ toArmScore(scoreEntities(resolveEntities(evalRecords, cfg(t)).entities, npiLabel, evalRecords.length))
167
+ )
168
+
169
+ const { pairs: evalPairs } = block(evalRecords, defaultBlockingKeys())
170
+
171
+ const fs = armOver(
172
+ Array.from({ length: 26 }, (_, i) => i),
173
+ // learnedScorer false keeps the FS baseline.
174
+ // The learned scorer is default-on, so without this the FS arm would silently be the GBT.
175
+ (t) => ({ addressFrequency, collapseSpatial: true, trainEM: true, threshold: t, learnedScorer: false })
176
+ )
177
+
178
+ const gbtArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => gbtScorer(a, b))), (t) => ({
179
+ addressFrequency,
180
+ collapseSpatial: true,
181
+ scorer: gbtScorer,
182
+ threshold: t,
183
+ }))
184
+
185
+ const lrArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => lrScorer(a, b))), (t) => ({
186
+ addressFrequency,
187
+ collapseSpatial: true,
188
+ scorer: lrScorer,
189
+ threshold: t,
190
+ }))
191
+
192
+ // The bundled DEDUP_GBT_MODEL is the shipped artifact every caller receives,
193
+ // evaluated here on a state it never trained on.
194
+ const bundledScorer = createGBTScorer({ model: DEDUP_GBT_MODEL, comparisons, addressFrequency })
195
+
196
+ const bundledArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => bundledScorer(a, b))), (t) => ({
197
+ addressFrequency,
198
+ collapseSpatial: true,
199
+ scorer: bundledScorer,
200
+ threshold: t,
201
+ }))
202
+
203
+ const dBundled = bundledArm.f1 - fs.f1
204
+ const dGbt = gbtArm.f1 - fs.f1
205
+ const dLr = lrArm.f1 - fs.f1
206
+
207
+ report?.(
208
+ ` FS ${pct(fs.f1)}% · LR ${pct(lrArm.f1)}% (${sgn(dLr)}${pct(dLr)}) · GBT ${pct(gbtArm.f1)}% (${sgn(dGbt)}${pct(dGbt)})` +
209
+ ` · BUNDLED ${pct(bundledArm.f1)}% (${sgn(dBundled)}${pct(dBundled)})`
210
+ )
211
+
212
+ const row = (label: string, a: ArmScore, d: number | null, bold: boolean) => {
213
+ const dCell = d === null ? "—" : `${sgn(d * 100)}${(d * 100).toFixed(1)}pp`
214
+ const f1 = bold ? `**${pct(a.f1)}%**` : `${pct(a.f1)}%`
215
+
216
+ return `| ${bold ? `**${label}**` : label} | ${pct(a.precision)}% | ${pct(a.recall)}% | ${f1} | ${bold ? `**${dCell}**` : dCell} | ${a.overMerged} |`
217
+ }
218
+
219
+ const lines: string[] = [
220
+ `# Learned-scorer CROSS-STATE generalization (#603 Tier 2) — train ${TRAIN_STATE}, evaluate ${EVAL_STATE}`,
221
+ "",
222
+ `_Generated by \`mailwoman registry scorer-eval cross-state\`. The GBT + LR are trained on ` +
223
+ `${trainSample.keptNpis.size} ${TRAIN_STATE} NPIs (${trainRecords.length} records) and used to cluster ` +
224
+ `${evalSample.keptNpis.size} held-out ${EVAL_STATE} NPIs (${evalRecords.length} records) — a state the model ` +
225
+ `never saw — through the same \`resolveEntities\` pipeline (FS baseline / GBT scorer / LR scorer), best F1 over a fine ` +
226
+ `per-scorer threshold sweep. This is the generalization axis the within-state held-out-NPI A/B couldn't cover._`,
227
+ "",
228
+ `## Result — ${EVAL_STATE} clustering F1 (GBT/LR trained on ${TRAIN_STATE})`,
229
+ "",
230
+ `| scorer | precision | recall | F1 | ΔF1 vs FS | over-merged |`,
231
+ `|---|---:|---:|---:|---:|---:|`,
232
+ row("FS baseline (EM-fit)", fs, null, false),
233
+ row("logistic regression", lrArm, dLr, false),
234
+ row(`GBT (fresh ${TRAIN_STATE} fit)`, gbtArm, dGbt, false),
235
+ row("SHIPPED bundled model (default-on candidate)", bundledArm, dBundled, true),
236
+ "",
237
+ `The **bundled** row is the actual shipped \`DEDUP_GBT_MODEL\` (the default-on candidate), evaluated on ` +
238
+ `${EVAL_STATE} — a state it never trained on. The "fresh ${TRAIN_STATE} fit" row retrains per run for comparison.`,
239
+ "",
240
+ ]
241
+
242
+ const verdict =
243
+ dGbt > MIN_MEANINGFUL_F1_DELTA
244
+ ? `**The GBT win GENERALIZES across states** — trained on ${TRAIN_STATE}, it still beats the FS baseline on ${EVAL_STATE} ` +
245
+ `clustering F1 (${pct(gbtArm.f1)}% vs ${pct(fs.f1)}%, ${sgn(dGbt * 100)}${(dGbt * 100).toFixed(1)}pp). The learned scorer ` +
246
+ `isn't fitting ${TRAIN_STATE}-specific structure. The over-merge signal it learns transfers. This is the strongest ` +
247
+ `evidence yet for the #603 production GBM — one model, trained once, helps a state it never saw.`
248
+ : dGbt < -MIN_MEANINGFUL_F1_DELTA
249
+ ? `**The GBT win does NOT generalize** — trained on ${TRAIN_STATE}, it is WORSE than the FS baseline on ${EVAL_STATE} ` +
250
+ `(${pct(gbtArm.f1)}% vs ${pct(fs.f1)}%, ${(dGbt * 100).toFixed(1)}pp). The within-state gain was state-specific ` +
251
+ `structure; a production GBM would need per-state (or much broader) training. Important caveat for #603.`
252
+ : `**The GBT roughly TIES the FS baseline cross-state** (${pct(gbtArm.f1)}% vs ${pct(fs.f1)}%, ` +
253
+ `${sgn(dGbt * 100)}${(dGbt * 100).toFixed(1)}pp). The within-state win attenuates across states — partial ` +
254
+ `generalization. A production GBM likely needs broader/multi-state training to recover the full within-state margin.`
255
+
256
+ lines.push(verdict)
257
+ lines.push("")
258
+ lines.push(`## Honest caveats`)
259
+ lines.push("")
260
+
261
+ lines.push(
262
+ `A single train/eval state pair (${TRAIN_STATE}→${EVAL_STATE}), one geocoded sample each, a compact pure-Node GBT ` +
263
+ `(120 rounds, depth 3). The FS arm is the benchmark baseline (same model), so the comparison is fair. Absolute F1 ` +
264
+ `differs from the within-state A/B because the eval population + over-merge density differ by state. NPI-as-truth is ` +
265
+ `conservative. The within-state held-out-NPI A/B (\`scorer-eval clustering\`) is the companion; together ` +
266
+ `they bound the generalization question a production GBM must answer._`
267
+ )
268
+
269
+ lines.push("")
270
+ const md = lines.join("\n")
271
+
272
+ console.log(md)
273
+
274
+ if (OUT_MD) {
275
+ await writeLocalFile(md, OUT_MD)
276
+ report?.(`[written] ${OUT_MD}`)
277
+ }
278
+
279
+ return { markdown: md }
280
+ }