@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
@@ -28,38 +28,36 @@
28
28
  * [--out-md <md>]`
29
29
  */
30
30
 
31
- import { writeFileSync } from "node:fs"
32
-
33
- import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
31
+ import { dataRootPath } from "@mailwoman/core/data-root"
32
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
33
+ import { makeLcg } from "@mailwoman/core/random"
34
34
  import { block, gbtScore, trainGBT } from "@mailwoman/match"
35
+
35
36
  import {
36
- addressFrequencyKey,
37
37
  buildDefaultModel,
38
38
  createMatchFeaturizer,
39
39
  defaultBlockingKeys,
40
40
  ingestRows,
41
41
  resolveEntities,
42
- streamRows,
43
42
  type ColumnMapping,
44
- type ResolvedEntity,
45
43
  type SourceRecord,
46
- } from "@mailwoman/registry"
47
-
48
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
44
+ } from "#index"
45
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
46
+ import { buildNPPESSample } from "#tools/nppes/sample"
47
+ import { scoreEntities } from "#tools/nppes/scoring"
49
48
  import {
50
- addr,
51
- MIN_GROUP_SIZE,
49
+ bestOver,
50
+ mean,
52
51
  MIN_MEANINGFUL_F1_DELTA,
53
- norm,
54
- NPPES_COLUMNS as C,
55
- sigmoid,
56
- TRAINING_EPOCHS,
57
- } from "./shared.ts"
58
-
59
- /**
60
- * Highest k swept when scanning cluster counts.
61
- */
62
- const MAX_K = 32
52
+ pct,
53
+ quantileThresholds,
54
+ sgn,
55
+ stateOption,
56
+ std,
57
+ toArmScore,
58
+ trainLogisticRegression,
59
+ type ArmScore,
60
+ } from "#tools/shared"
63
61
 
64
62
  /**
65
63
  * Options for {@linkcode scorerClusteringEval}.
@@ -99,61 +97,6 @@ export interface ScorerClusteringEvalOptions {
99
97
  outMd?: string
100
98
  }
101
99
 
102
- interface MessyRow {
103
- npi: string
104
- name: string
105
- org: string
106
- address: string
107
- }
108
-
109
- const choose2 = (n: number) => (n * (n - 1)) / 2
110
-
111
- /**
112
- * The dedup benchmark's pairwise clustering metric vs the NPI grouping (record.id = NPI).
113
- */
114
- function scoreClusters(
115
- entities: ResolvedEntity[],
116
- n: number
117
- ): { precision: number; recall: number; f1: number; overMerged: number } {
118
- const npiTotals = new Map<string, number>()
119
- let sumCK = 0
120
- let sumCluster = 0
121
- let overMerged = 0
122
-
123
- for (const e of entities) {
124
- const byNPI = new Map<string, number>()
125
-
126
- for (const rec of e.records) {
127
- byNPI.set(rec.id, (byNPI.get(rec.id) ?? 0) + 1)
128
- }
129
-
130
- sumCluster += choose2(e.records.length)
131
-
132
- if (byNPI.size > 1) {
133
- overMerged++
134
- }
135
-
136
- for (const [npi, c] of byNPI) {
137
- sumCK += choose2(c)
138
- npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + c)
139
- }
140
- }
141
-
142
- let sumClass = 0
143
-
144
- for (const total of npiTotals.values()) {
145
- sumClass += choose2(total)
146
- }
147
-
148
- void n
149
- const tp = sumCK
150
- const precision = sumCluster > 0 ? tp / sumCluster : 0
151
- const recall = sumClass > 0 ? tp / sumClass : 0
152
- const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
153
-
154
- return { precision, recall, f1, overMerged }
155
- }
156
-
157
100
  /**
158
101
  * Learned-scorer clustering A/B (#603 Tier 2) — see the module doc. Emits the markdown report to stdout.
159
102
  */
@@ -162,7 +105,7 @@ export async function scorerClusteringEval(
162
105
  report?: (line: string) => void
163
106
  ): Promise<{ markdown: string }> {
164
107
  const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
165
- const STATE = (options.state || "TX").toUpperCase()
108
+ const STATE = stateOption(options)
166
109
  const NPIS = options.npis ?? 2000
167
110
  const SPLIT = options.split ?? 0.67
168
111
  const SEED = options.seed ?? 1
@@ -171,93 +114,36 @@ export async function scorerClusteringEval(
171
114
  const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
172
115
  const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
173
116
 
174
- // --- Data-gen: the same NPI-keyed records as the dedup benchmark + the pairwise probe. ---
175
- report?.("[A] streaming other-names…")
176
- const altNames = new Map<string, string[]>()
177
-
178
- for await (const r of streamRows(OTHER_NAMES)) {
179
- const npi = norm(r[C.npi])
180
- const alt = norm(r[C.otherOrg])
181
-
182
- if (!npi || !alt) continue
183
- const list = altNames.get(npi) ?? []
184
-
185
- if (list.length < MIN_GROUP_SIZE) {
186
- list.push(alt)
187
- }
188
-
189
- altNames.set(npi, list)
190
- }
191
-
192
- report?.(`[B] full registry pass: address-frequency table + ${NPIS} ${STATE} sample…`)
193
- const rows: MessyRow[] = []
194
- const kept = new Set<string>()
195
- const addrCounts = new Map<string, number>()
196
- let addrTotal = 0
197
- let scanned = 0
198
-
199
- for await (const r of streamRows(REGISTRY)) {
200
- if (++scanned % 1_000_000 === 0) {
201
- report?.(` scanned ${scanned / 1e6}M, kept ${kept.size}`)
202
- }
203
-
204
- const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
205
-
206
- if (practice) {
207
- const k = addressFrequencyKey(practice)
208
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
209
-
210
- addrTotal++
211
- }
212
-
213
- const npi = norm(r[C.npi])
214
-
215
- if (
216
- kept.size < NPIS &&
217
- npi &&
218
- !kept.has(npi) &&
219
- altNames.has(npi) &&
220
- practice &&
221
- norm(r[C.pState]).toUpperCase() === STATE
222
- ) {
223
- const isOrg = norm(r[C.entityType]) === "2"
224
- const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
225
-
226
- if (primaryName) {
227
- const org = isOrg ? norm(r[C.orgLegal]) : ""
228
- kept.add(npi)
229
- rows.push({ npi, name: primaryName, org, address: practice })
230
-
231
- for (const alt of altNames.get(npi)!) {
232
- rows.push({ npi, name: alt, org: alt, address: practice })
233
- }
234
-
235
- const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
236
-
237
- if (mailing && mailing !== practice) {
238
- rows.push({ npi, name: primaryName, org, address: mailing })
239
- }
240
- }
241
- }
242
- }
243
-
244
- const addressFrequency = {
245
- total: addrTotal,
246
- distinct: addrCounts.size,
247
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
248
- }
249
-
250
- report?.(` ${kept.size} NPIs → ${rows.length} records`)
117
+ // --- Data-gen: the same NPI-keyed records as the dedup benchmark + the pairwise probe (the SHARED
118
+ // sample builder). ---
119
+ const {
120
+ rows,
121
+ keptNpis: kept,
122
+ addressFrequency,
123
+ } = await buildNPPESSample(
124
+ { registryPath: REGISTRY, otherNamesPath: OTHER_NAMES, state: STATE, maxNpis: NPIS },
125
+ report
126
+ )
251
127
 
252
128
  report?.("[C] geocoding…")
253
129
  const geocoder = await options.createGeocoder()
254
- const mapping: ColumnMapping = { id: "npi", name: "name", organization: "org", address: "address", source: "nppes" }
255
130
 
256
- const records = await ingestRows(rows as unknown as Record<string, string>[], mapping, {
257
- geocodeAddress: geocoder.seam,
131
+ // `auth`/`taxonomy` ride as attributes so the SHARED featurizer's #625 roll-up features can read the
132
+ // authorized official; the FS arm ignores them (no discriminators configured).
133
+ const mapping: ColumnMapping = {
134
+ id: "npi",
135
+ name: "name",
136
+ organization: "org",
137
+ address: "address",
138
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
139
+ source: "nppes",
140
+ }
141
+
142
+ const records = await ingestRows(rows, mapping, {
143
+ geocodeAddress: geocoder.geocodeAddress,
258
144
  })
259
145
 
260
- geocoder.close()
146
+ geocoder[Symbol.dispose]()
261
147
 
262
148
  // --- The feature basis: address-frequency + collapsed-spatial model (the baseline). The agreement
263
149
  // pattern is EM-independent, so the same featurize() is consistent at train and inference time. ---
@@ -266,12 +152,7 @@ export async function scorerClusteringEval(
266
152
  const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
267
153
  const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
268
154
 
269
- interface ArmScore {
270
- precision: number
271
- recall: number
272
- f1: number
273
- overMerged: number
274
- }
155
+ const npiLabel = (rec: SourceRecord) => rec.id
275
156
 
276
157
  interface SeedResult {
277
158
  seed: number
@@ -308,94 +189,37 @@ export async function scorerClusteringEval(
308
189
  const dim = trainX[0]?.length ?? 0
309
190
  const gbt = trainGBT(trainX, trainY, trainW, { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 })
310
191
 
311
- // LR (batch GD, class-balanced) — same as the pairwise probe.
312
- const w = new Array<number>(dim).fill(0)
313
- let bias = 0
314
-
315
- for (let epoch = 0; epoch < TRAINING_EPOCHS; epoch++) {
316
- const gw = new Array<number>(dim).fill(0)
317
- let gb = 0
318
-
319
- for (let i = 0; i < trainX.length; i++) {
320
- let z = bias
321
-
322
- for (let j = 0; j < dim; j++) {
323
- z += w[j]! * trainX[i]![j]!
324
- }
325
-
326
- const err = (sigmoid(z) - trainY[i]!) * trainW[i]!
327
-
328
- for (let j = 0; j < dim; j++) {
329
- gw[j]! += err * trainX[i]![j]!
330
- }
331
-
332
- gb += err
333
- }
334
-
335
- for (let j = 0; j < dim; j++) {
336
- w[j]! -= 0.1 * (gw[j]! / trainX.length + 1e-3 * w[j]!)
337
- }
338
-
339
- bias -= 0.1 * (gb / trainX.length)
340
- }
341
-
342
- const lrSc = (x: number[]) => {
343
- let z = bias
344
-
345
- for (let j = 0; j < x.length; j++) {
346
- z += w[j]! * x[j]!
347
- }
348
-
349
- return z
350
- }
192
+ // LR (batch GD, class-balanced) — the SHARED trainer, same as the pairwise probe.
193
+ const lrSc = trainLogisticRegression(trainX, trainY, trainW, dim)
351
194
 
352
195
  const gbtScorer = (a: SourceRecord, b: SourceRecord) => gbtScore(gbt, featurize(a, b))
353
196
  const lrScorer = (a: SourceRecord, b: SourceRecord) => lrSc(featurize(a, b))
354
197
 
355
- const bestOver = (thresholds: number[], cfg: (t: number) => Parameters<typeof resolveEntities>[1]): ArmScore => {
356
- let best: ArmScore = { precision: 0, recall: 0, f1: -1, overMerged: 0 }
357
-
358
- for (const t of thresholds) {
359
- const s = scoreClusters(resolveEntities(evalRecords, cfg(t)).entities, N)
360
-
361
- if (s.f1 > best.f1) {
362
- best = s
363
- }
364
- }
365
-
366
- return best
367
- }
198
+ const armOver = (
199
+ thresholds: readonly number[],
200
+ cfg: (t: number) => Parameters<typeof resolveEntities>[1]
201
+ ): ArmScore =>
202
+ bestOver(thresholds, (t) => toArmScore(scoreEntities(resolveEntities(evalRecords, cfg(t)).entities, npiLabel, N)))
368
203
 
369
- // FS baseline: EM-fit weights in bits, fine grid [0..25]. Learned scorers: a FINE sweep (33 points)
370
- // from each scorer's own eval-pair score distribution, so a coarse grid can't understate them.
204
+ // FS baseline: EM-fit weights in bits, fine grid [0..25]. Learned scorers: a FINE sweep from each
205
+ // scorer's own eval-pair score distribution, so a coarse grid can't understate them.
371
206
  const { pairs: evalPairs } = block(evalRecords, defaultBlockingKeys())
372
207
 
373
- const quantileThresholds = (scores: number[]): number[] => {
374
- const sorted = [...scores].toSorted((p, q) => p - q)
375
- const ts = new Set<number>()
376
-
377
- for (let k = 0; k <= MAX_K; k++) {
378
- ts.add(sorted[Math.floor((0.2 + (0.999 - 0.2) * (k / 32)) * (sorted.length - 1))]!)
379
- }
380
-
381
- return [...ts]
382
- }
383
-
384
- const fs = bestOver(
208
+ const fs = armOver(
385
209
  Array.from({ length: 26 }, (_, i) => i),
386
210
  // learnedScorer:false — the FS baseline is the baseline this A/B measures against (the learned scorer
387
211
  // is now default-on, so without this the "FS arm" would silently BE the GBT).
388
212
  (t) => ({ addressFrequency, collapseSpatial: true, trainEM: true, threshold: t, learnedScorer: false })
389
213
  )
390
214
 
391
- const gbtArm = bestOver(quantileThresholds(evalPairs.map(([a, b]) => gbtScorer(a, b))), (t) => ({
215
+ const gbtArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => gbtScorer(a, b))), (t) => ({
392
216
  addressFrequency,
393
217
  collapseSpatial: true,
394
218
  scorer: gbtScorer,
395
219
  threshold: t,
396
220
  }))
397
221
 
398
- const lrArm = bestOver(quantileThresholds(evalPairs.map(([a, b]) => lrScorer(a, b))), (t) => ({
222
+ const lrArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => lrScorer(a, b))), (t) => ({
399
223
  addressFrequency,
400
224
  collapseSpatial: true,
401
225
  scorer: lrScorer,
@@ -405,18 +229,6 @@ export async function scorerClusteringEval(
405
229
  return { seed, trainN: trainRecords.length, evalN: N, fs, lr: lrArm, gbt: gbtArm }
406
230
  }
407
231
 
408
- // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
409
- // numerator/denominator contract (call sites append their own "%").
410
- const pct = (x: number) => (100 * x).toFixed(1)
411
- const sgn = (x: number) => (x >= 0 ? "+" : "")
412
- const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
413
-
414
- const std = (xs: number[]) => {
415
- const m = mean(xs)
416
-
417
- return Math.sqrt(mean(xs.map((x) => (x - m) ** 2)))
418
- }
419
-
420
232
  const SEEDS = options.seeds ?? 4
421
233
  report?.(`[D-F] ${SEEDS} held-out-NPI splits: FS baseline vs GBT vs LR…`)
422
234
  const results: SeedResult[] = []
@@ -432,27 +244,26 @@ export async function scorerClusteringEval(
432
244
  }
433
245
 
434
246
  const fsF1 = results.map((r) => r.fs.f1)
435
- const lrF1 = results.map((r) => r.lr.f1)
436
247
  const gbtF1 = results.map((r) => r.gbt.f1)
437
248
  const dGbt = results.map((r) => r.gbt.f1 - r.fs.f1)
438
249
  const dLr = results.map((r) => r.lr.f1 - r.fs.f1)
439
250
  const gbtWins = dGbt.filter((d) => d > 0).length
440
- const meanDGbt = mean(dGbt)
251
+ const meanDGbt = mean(dGbt)!
441
252
 
442
253
  const armRow = (label: string, pick: (r: SeedResult) => ArmScore, dArr: number[] | null, bold: boolean) => {
443
254
  const f1s = results.map((r) => pick(r).f1)
444
- const P = mean(results.map((r) => pick(r).precision))
445
- const R = mean(results.map((r) => pick(r).recall))
446
- const om = mean(results.map((r) => pick(r).overMerged))
447
- const d = dArr ? `${sgn(mean(dArr) * 100)}${(mean(dArr) * 100).toFixed(1)}pp` : "—"
448
- const f1cell = `${pct(mean(f1s))}% ± ${pct(std(f1s))}`
255
+ const P = mean(results.map((r) => pick(r).precision))!
256
+ const R = mean(results.map((r) => pick(r).recall))!
257
+ const om = mean(results.map((r) => pick(r).overMerged))!
258
+ const d = dArr ? `${sgn(mean(dArr)! * 100)}${(mean(dArr)! * 100).toFixed(1)}pp` : "—"
259
+ const f1cell = `${pct(mean(f1s)!)}% ± ${pct(std(f1s))}`
449
260
  const cells = `${pct(P)}% | ${pct(R)}% | ${bold ? `**${f1cell}**` : f1cell} | ${bold ? `**${d}**` : d} | ${om.toFixed(0)}`
450
261
 
451
262
  return `| ${bold ? `**${label}**` : label} | ${cells} |`
452
263
  }
453
264
 
454
- const avgEval = Math.round(mean(results.map((r) => r.evalN)))
455
- const avgTrain = Math.round(mean(results.map((r) => r.trainN)))
265
+ const avgEval = Math.round(mean(results.map((r) => r.evalN))!)
266
+ const avgTrain = Math.round(mean(results.map((r) => r.trainN))!)
456
267
 
457
268
  const lines: string[] = [
458
269
  `# Learned-scorer CLUSTERING A/B (#603 Tier 2) — does a learned scorer beat the FS baseline on the assembled output?`,
@@ -480,16 +291,16 @@ export async function scorerClusteringEval(
480
291
  const verdict =
481
292
  meanDGbt > MIN_MEANINGFUL_F1_DELTA && gbtWins >= SEEDS - 1
482
293
  ? `**The learned scorer beats the FS baseline on the assembled clustering output** — GBT clustering F1 ` +
483
- `${pct(mean(gbtF1))}% vs FS ${pct(mean(fsF1))}% (${sgn(meanDGbt * 100)}${(meanDGbt * 100).toFixed(1)}pp mean, ${gbtWins}/${SEEDS} ` +
484
- `seeds), driven by a large PRECISION gain that cuts the over-merge — the #625 problem. The pairwise gain (#640) ` +
485
- `DOES translate to the entity-resolution metric. This confirms the #603 GBM as a real dedup lever and justifies the ` +
294
+ `${pct(mean(gbtF1)!)}% vs FS ${pct(mean(fsF1)!)}% (${sgn(meanDGbt * 100)}${(meanDGbt * 100).toFixed(1)}pp mean, ${gbtWins}/${SEEDS} ` +
295
+ `seeds), driven by a large PRECISION gain that reduces the over-merge — the #625 problem. The pairwise gain (#640) ` +
296
+ `DOES translate to the entity-resolution metric. This confirms the #603 GBM as a real dedup change and justifies the ` +
486
297
  `production build (offline XGBoost/LightGBM → tree JSON, the \`scorer\` hook for inference). The honest next axis is ` +
487
298
  `cross-STATE generalization (train-TX / eval-other-state) and a tuned GBM on more features.`
488
299
  : meanDGbt < -MIN_MEANINGFUL_F1_DELTA
489
- ? `**The learned scorer does NOT beat the FS baseline on clustering** (GBT ${pct(mean(gbtF1))}% vs FS ${pct(mean(fsF1))}%, ` +
300
+ ? `**The learned scorer does NOT beat the FS baseline on clustering** (GBT ${pct(mean(gbtF1)!)}% vs FS ${pct(mean(fsF1)!)}%, ` +
490
301
  `${(meanDGbt * 100).toFixed(1)}pp). The pairwise ranking gain (#640) does not survive the threshold + ` +
491
302
  `connected-components assembly — clustering, not ranking, is the binding constraint. FS stays the baseline.`
492
- : `**The learned scorer roughly TIES the FS baseline on clustering** (GBT ${pct(mean(gbtF1))}% vs FS ${pct(mean(fsF1))}%, ` +
303
+ : `**The learned scorer roughly TIES the FS baseline on clustering** (GBT ${pct(mean(gbtF1)!)}% vs FS ${pct(mean(fsF1)!)}%, ` +
493
304
  `${sgn(meanDGbt * 100)}${(meanDGbt * 100).toFixed(1)}pp, ${gbtWins}/${SEEDS} seeds). The pairwise ranking gain (#640) is ` +
494
305
  `real but largely washes out through the threshold + connected-components assembly. A learned scorer is not a free ` +
495
306
  `dedup win; pairing it with a clustering change or a more distinctive identifier (#625) is the path.`
@@ -526,7 +337,7 @@ export async function scorerClusteringEval(
526
337
  console.log(md)
527
338
 
528
339
  if (OUT_MD) {
529
- writeFileSync(OUT_MD, md)
340
+ await writeLocalFile(md, OUT_MD)
530
341
  report?.(`[written] ${OUT_MD}`)
531
342
  }
532
343