@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
@@ -12,21 +12,20 @@
12
12
  * per-state training (a finding either way).
13
13
  *
14
14
  * One registry pass builds the global address-frequency table + a TRAIN-state sample + an
15
- * EVAL-state sample; both are geocoded; the GBT + LR are trained on the train state's pairs and
16
- * used to cluster the eval state's records through the same `resolveEntities` pipeline (FS
17
- * baseline / GBT scorer / LR scorer), best F1 over a fine per-scorer threshold sweep. The metric
18
- * is the dedup benchmark's clustering F1.
15
+ * EVAL-state sample (the SHARED multi-state sample builder); both are geocoded; the GBT + LR are
16
+ * trained on the train state's pairs and used to cluster the eval state's records through the
17
+ * same `resolveEntities` pipeline (FS baseline / GBT scorer / LR scorer), best F1 over a fine
18
+ * per-scorer threshold sweep. The metric is the dedup benchmark's clustering F1.
19
19
  *
20
20
  * Run: `mailwoman registry scorer-eval cross-state [--train-state TX] [--eval-state CA]
21
21
  * [--npis 2000] [--out-md <md>]`
22
22
  */
23
23
 
24
- import { writeFileSync } from "node:fs"
25
-
26
- import { dataRootPath } from "@mailwoman/core/utils"
24
+ import { dataRootPath } from "@mailwoman/core/data-root"
25
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
27
26
  import { block, gbtScore, trainGBT } from "@mailwoman/match"
27
+
28
28
  import {
29
- addressFrequencyKey,
30
29
  buildDefaultModel,
31
30
  createGBTScorer,
32
31
  createMatchFeaturizer,
@@ -34,27 +33,22 @@ import {
34
33
  defaultBlockingKeys,
35
34
  ingestRows,
36
35
  resolveEntities,
37
- streamRows,
38
36
  type ColumnMapping,
39
- type ResolvedEntity,
40
37
  type SourceRecord,
41
- } from "@mailwoman/registry"
42
-
43
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
38
+ } from "#index"
39
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
40
+ import { buildNPPESStateSamples } from "#tools/nppes/sample"
41
+ import { scoreEntities } from "#tools/nppes/scoring"
44
42
  import {
45
- addr,
46
- MIN_GROUP_SIZE,
43
+ bestOver,
47
44
  MIN_MEANINGFUL_F1_DELTA,
48
- norm,
49
- NPPES_COLUMNS as C,
50
- sigmoid,
51
- TRAINING_EPOCHS,
52
- } from "./shared.ts"
53
-
54
- /**
55
- * Highest k swept when scanning cluster counts.
56
- */
57
- const MAX_K = 32
45
+ pct,
46
+ quantileThresholds,
47
+ sgn,
48
+ toArmScore,
49
+ trainLogisticRegression,
50
+ type ArmScore,
51
+ } from "#tools/shared"
58
52
 
59
53
  /**
60
54
  * Options for {@linkcode scorerCrossStateEval}.
@@ -86,62 +80,6 @@ export interface ScorerCrossStateEvalOptions {
86
80
  outMd?: string
87
81
  }
88
82
 
89
- const choose2 = (n: number) => (n * (n - 1)) / 2
90
-
91
- interface MessyRow {
92
- npi: string
93
- name: string
94
- org: string
95
- address: string
96
- }
97
-
98
- /**
99
- * The dedup benchmark's pairwise clustering metric vs the NPI grouping (record.id = NPI).
100
- */
101
- function scoreClusters(entities: ResolvedEntity[]): {
102
- precision: number
103
- recall: number
104
- f1: number
105
- overMerged: number
106
- } {
107
- const npiTotals = new Map<string, number>()
108
- let sumCK = 0
109
- let sumCluster = 0
110
- let overMerged = 0
111
-
112
- for (const e of entities) {
113
- const byNPI = new Map<string, number>()
114
-
115
- for (const rec of e.records) {
116
- byNPI.set(rec.id, (byNPI.get(rec.id) ?? 0) + 1)
117
- }
118
-
119
- sumCluster += choose2(e.records.length)
120
-
121
- if (byNPI.size > 1) {
122
- overMerged++
123
- }
124
-
125
- for (const [npi, c] of byNPI) {
126
- sumCK += choose2(c)
127
- npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + c)
128
- }
129
- }
130
-
131
- let sumClass = 0
132
-
133
- for (const total of npiTotals.values()) {
134
- sumClass += choose2(total)
135
- }
136
-
137
- const tp = sumCK
138
- const precision = sumCluster > 0 ? tp / sumCluster : 0
139
- const recall = sumClass > 0 ? tp / sumClass : 0
140
- const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
141
-
142
- return { precision, recall, f1, overMerged }
143
- }
144
-
145
83
  /**
146
84
  * Learned-scorer cross-state generalization (#603 Tier 2) — see the module doc. Emits the report to stdout.
147
85
  */
@@ -158,96 +96,38 @@ export async function scorerCrossStateEval(
158
96
  const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
159
97
  const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
160
98
 
161
- report?.("[A] streaming other-names…")
162
- const altNames = new Map<string, string[]>()
163
-
164
- for await (const r of streamRows(OTHER_NAMES)) {
165
- const npi = norm(r[C.npi])
166
- const alt = norm(r[C.otherOrg])
167
-
168
- if (!npi || !alt) continue
169
- const list = altNames.get(npi) ?? []
170
-
171
- if (list.length < MIN_GROUP_SIZE) {
172
- list.push(alt)
173
- }
174
-
175
- altNames.set(npi, list)
176
- }
177
-
178
- // ONE registry pass: global address-frequency + a TRAIN-state sample + an EVAL-state sample.
179
- report?.(`[B] registry pass: address-frequency + ${NPIS} ${TRAIN_STATE} (train) + ${NPIS} ${EVAL_STATE} (eval)…`)
180
-
181
- const samples: Record<string, { rows: MessyRow[]; kept: Set<string> }> = {
182
- [TRAIN_STATE]: { rows: [], kept: new Set() },
183
- [EVAL_STATE]: { rows: [], kept: new Set() },
184
- }
185
-
186
- const addrCounts = new Map<string, number>()
187
- let addrTotal = 0
188
- let scanned = 0
189
-
190
- for await (const r of streamRows(REGISTRY)) {
191
- if (++scanned % 1_000_000 === 0) {
192
- report?.(` scanned ${scanned / 1e6}M`)
193
- }
194
-
195
- const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
196
-
197
- if (practice) {
198
- const k = addressFrequencyKey(practice)
199
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
200
-
201
- addrTotal++
202
- }
203
-
204
- const npi = norm(r[C.npi])
205
- const st = norm(r[C.pState]).toUpperCase()
206
- const bucket = samples[st]
207
-
208
- if (bucket && bucket.kept.size < NPIS && npi && !bucket.kept.has(npi) && altNames.has(npi) && practice) {
209
- const isOrg = norm(r[C.entityType]) === "2"
210
- const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
211
-
212
- if (primaryName) {
213
- const org = isOrg ? norm(r[C.orgLegal]) : ""
214
- bucket.kept.add(npi)
215
- bucket.rows.push({ npi, name: primaryName, org, address: practice })
216
-
217
- for (const alt of altNames.get(npi)!) {
218
- bucket.rows.push({ npi, name: alt, org: alt, address: practice })
219
- }
220
-
221
- const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
222
-
223
- if (mailing && mailing !== practice) {
224
- bucket.rows.push({ npi, name: primaryName, org, address: mailing })
225
- }
226
- }
227
- }
228
- }
229
-
230
- const addressFrequency = {
231
- total: addrTotal,
232
- distinct: addrCounts.size,
233
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
234
- }
235
-
236
- report?.(
237
- ` ${TRAIN_STATE}: ${samples[TRAIN_STATE]!.kept.size} NPIs → ${samples[TRAIN_STATE]!.rows.length} records · ` +
238
- `${EVAL_STATE}: ${samples[EVAL_STATE]!.kept.size} NPIs → ${samples[EVAL_STATE]!.rows.length} records`
99
+ // ONE registry pass fills BOTH state buckets (the SHARED multi-state sample builder): the global
100
+ // address-frequency table + a TRAIN-state sample + an EVAL-state sample.
101
+ const { byState, addressFrequency } = await buildNPPESStateSamples(
102
+ {
103
+ registryPath: REGISTRY,
104
+ otherNamesPath: OTHER_NAMES,
105
+ states: [TRAIN_STATE, EVAL_STATE],
106
+ maxNpisPerState: NPIS,
107
+ },
108
+ report
239
109
  )
240
110
 
111
+ const trainSample = byState.get(TRAIN_STATE)!
112
+ const evalSample = byState.get(EVAL_STATE)!
113
+
241
114
  report?.("[C] geocoding both states…")
242
115
  const geocoder = await options.createGeocoder()
243
- const mapping: ColumnMapping = { id: "npi", name: "name", organization: "org", address: "address", source: "nppes" }
244
116
 
245
- const geocodeRows = (rows: MessyRow[]) =>
246
- ingestRows(rows as unknown as Record<string, string>[], mapping, { geocodeAddress: geocoder.seam })
117
+ // `auth`/`taxonomy` ride as attributes so the SHARED featurizer's #625 roll-up features can read the
118
+ // authorized official; the FS arm ignores them (no discriminators configured).
119
+ const mapping: ColumnMapping = {
120
+ id: "npi",
121
+ name: "name",
122
+ organization: "org",
123
+ address: "address",
124
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
125
+ source: "nppes",
126
+ }
247
127
 
248
- const trainRecords = await geocodeRows(samples[TRAIN_STATE]!.rows)
249
- const evalRecords = await geocodeRows(samples[EVAL_STATE]!.rows)
250
- geocoder.close()
128
+ const trainRecords = await ingestRows(trainSample.rows, mapping, { geocodeAddress: geocoder.geocodeAddress })
129
+ const evalRecords = await ingestRows(evalSample.rows, mapping, { geocodeAddress: geocoder.geocodeAddress })
130
+ geocoder[Symbol.dispose]()
251
131
 
252
132
  // Feature basis: the SHARED production featurizer (train ≡ eval ≡ inference, one definition) over the
253
133
  // collapsed-spatial + address-frequency comparison set (the baseline).
@@ -262,100 +142,42 @@ export async function scorerCrossStateEval(
262
142
  const trainW = trainY.map((y) => (y === 1 ? 1 - posRate : posRate))
263
143
  const dim = trainX[0]?.length ?? 0
264
144
  const gbt = trainGBT(trainX, trainY, trainW, { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 })
265
- const w = new Array<number>(dim).fill(0)
266
- let bias = 0
267
-
268
- for (let epoch = 0; epoch < TRAINING_EPOCHS; epoch++) {
269
- const gw = new Array<number>(dim).fill(0)
270
- let gb = 0
271
-
272
- for (let i = 0; i < trainX.length; i++) {
273
- let z = bias
274
-
275
- for (let j = 0; j < dim; j++) {
276
- z += w[j]! * trainX[i]![j]!
277
- }
278
-
279
- const err = (sigmoid(z) - trainY[i]!) * trainW[i]!
280
-
281
- for (let j = 0; j < dim; j++) {
282
- gw[j]! += err * trainX[i]![j]!
283
- }
284
-
285
- gb += err
286
- }
287
145
 
288
- for (let j = 0; j < dim; j++) {
289
- w[j]! -= 0.1 * (gw[j]! / trainX.length + 1e-3 * w[j]!)
290
- }
291
-
292
- bias -= 0.1 * (gb / trainX.length)
293
- }
294
-
295
- const lrSc = (x: number[]) => {
296
- let z = bias
297
-
298
- for (let j = 0; j < x.length; j++) {
299
- z += w[j]! * x[j]!
300
- }
301
-
302
- return z
303
- }
146
+ // LR (batch GD, class-balanced) — the SHARED trainer.
147
+ const lrSc = trainLogisticRegression(trainX, trainY, trainW, dim)
304
148
 
305
149
  const gbtScorer = (a: SourceRecord, b: SourceRecord) => gbtScore(gbt, featurize(a, b))
306
150
  const lrScorer = (a: SourceRecord, b: SourceRecord) => lrSc(featurize(a, b))
307
151
 
308
152
  report?.(`[E] clustering ${EVAL_STATE} records (FS baseline vs GBT vs LR, trained on ${TRAIN_STATE})…`)
309
153
 
310
- interface ArmScore {
311
- precision: number
312
- recall: number
313
- f1: number
314
- overMerged: number
315
- }
316
-
317
- const bestOver = (thresholds: number[], cfg: (t: number) => Parameters<typeof resolveEntities>[1]): ArmScore => {
318
- let best: ArmScore = { precision: 0, recall: 0, f1: -1, overMerged: 0 }
154
+ const npiLabel = (rec: SourceRecord) => rec.id
319
155
 
320
- for (const t of thresholds) {
321
- const s = scoreClusters(resolveEntities(evalRecords, cfg(t)).entities)
322
-
323
- if (s.f1 > best.f1) {
324
- best = s
325
- }
326
- }
327
-
328
- return best
329
- }
156
+ const armOver = (
157
+ thresholds: readonly number[],
158
+ cfg: (t: number) => Parameters<typeof resolveEntities>[1]
159
+ ): ArmScore =>
160
+ bestOver(thresholds, (t) =>
161
+ toArmScore(scoreEntities(resolveEntities(evalRecords, cfg(t)).entities, npiLabel, evalRecords.length))
162
+ )
330
163
 
331
164
  const { pairs: evalPairs } = block(evalRecords, defaultBlockingKeys())
332
165
 
333
- const quantileThresholds = (scores: number[]): number[] => {
334
- const sorted = [...scores].toSorted((p, q) => p - q)
335
- const ts = new Set<number>()
336
-
337
- for (let k = 0; k <= MAX_K; k++) {
338
- ts.add(sorted[Math.floor((0.2 + (0.999 - 0.2) * (k / 32)) * (sorted.length - 1))]!)
339
- }
340
-
341
- return [...ts]
342
- }
343
-
344
- const fs = bestOver(
166
+ const fs = armOver(
345
167
  Array.from({ length: 26 }, (_, i) => i),
346
168
  // learnedScorer:false — the FS baseline is the baseline (the learned scorer is now default-on, so
347
169
  // without this the "FS arm" would silently BE the GBT).
348
170
  (t) => ({ addressFrequency, collapseSpatial: true, trainEM: true, threshold: t, learnedScorer: false })
349
171
  )
350
172
 
351
- const gbtArm = bestOver(quantileThresholds(evalPairs.map(([a, b]) => gbtScorer(a, b))), (t) => ({
173
+ const gbtArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => gbtScorer(a, b))), (t) => ({
352
174
  addressFrequency,
353
175
  collapseSpatial: true,
354
176
  scorer: gbtScorer,
355
177
  threshold: t,
356
178
  }))
357
179
 
358
- const lrArm = bestOver(quantileThresholds(evalPairs.map(([a, b]) => lrScorer(a, b))), (t) => ({
180
+ const lrArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => lrScorer(a, b))), (t) => ({
359
181
  addressFrequency,
360
182
  collapseSpatial: true,
361
183
  scorer: lrScorer,
@@ -367,7 +189,7 @@ export async function scorerCrossStateEval(
367
189
  // caller would get, evaluated on a state it never trained on.
368
190
  const bundledScorer = createGBTScorer({ model: DEDUP_GBT_MODEL, comparisons, addressFrequency })
369
191
 
370
- const bundledArm = bestOver(quantileThresholds(evalPairs.map(([a, b]) => bundledScorer(a, b))), (t) => ({
192
+ const bundledArm = armOver(quantileThresholds(evalPairs.map(([a, b]) => bundledScorer(a, b))), (t) => ({
371
193
  addressFrequency,
372
194
  collapseSpatial: true,
373
195
  scorer: bundledScorer,
@@ -375,11 +197,6 @@ export async function scorerCrossStateEval(
375
197
  }))
376
198
 
377
199
  const dBundled = bundledArm.f1 - fs.f1
378
-
379
- // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
380
- // numerator/denominator contract (call sites append their own "%").
381
- const pct = (x: number) => (100 * x).toFixed(1)
382
- const sgn = (x: number) => (x >= 0 ? "+" : "")
383
200
  const dGbt = gbtArm.f1 - fs.f1
384
201
  const dLr = lrArm.f1 - fs.f1
385
202
 
@@ -399,8 +216,8 @@ export async function scorerCrossStateEval(
399
216
  `# Learned-scorer CROSS-STATE generalization (#603 Tier 2) — train ${TRAIN_STATE}, evaluate ${EVAL_STATE}`,
400
217
  "",
401
218
  `_Generated by \`mailwoman registry scorer-eval cross-state\`. The GBT + LR are trained on ` +
402
- `${samples[TRAIN_STATE]!.kept.size} ${TRAIN_STATE} NPIs (${trainRecords.length} records) and used to cluster ` +
403
- `${samples[EVAL_STATE]!.kept.size} held-out ${EVAL_STATE} NPIs (${evalRecords.length} records) — a state the model ` +
219
+ `${trainSample.keptNpis.size} ${TRAIN_STATE} NPIs (${trainRecords.length} records) and used to cluster ` +
220
+ `${evalSample.keptNpis.size} held-out ${EVAL_STATE} NPIs (${evalRecords.length} records) — a state the model ` +
404
221
  `never saw — through the same \`resolveEntities\` pipeline (FS baseline / GBT scorer / LR scorer), best F1 over a fine ` +
405
222
  `per-scorer threshold sweep. This is the generalization axis the within-state held-out-NPI A/B couldn't cover._`,
406
223
  "",
@@ -451,7 +268,7 @@ export async function scorerCrossStateEval(
451
268
  console.log(md)
452
269
 
453
270
  if (OUT_MD) {
454
- writeFileSync(OUT_MD, md)
271
+ await writeLocalFile(md, OUT_MD)
455
272
  report?.(`[written] ${OUT_MD}`)
456
273
  }
457
274