@mailwoman/registry 9.2.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 (227) hide show
  1. package/README.md +1 -1
  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} +9 -4
  5. package/{index.ts → lib/index.ts} +10 -10
  6. package/{ingest.ts → lib/ingest.ts} +75 -68
  7. package/{learned-scorer.ts → lib/learned-scorer.ts} +1 -1
  8. package/{map-html.ts → lib/map-html.ts} +7 -13
  9. package/{reconcile.ts → lib/reconcile.ts} +7 -23
  10. package/{resolve.ts → lib/resolve.ts} +25 -12
  11. package/{tools → lib/tools}/coverage-reconciliation.ts +12 -14
  12. package/{tools → lib/tools}/cross-dataset-correlation.ts +60 -137
  13. package/{tools → lib/tools}/cross-source-threshold-sweep.ts +20 -31
  14. package/{tools → lib/tools}/dedup-ceiling.ts +33 -144
  15. package/{tools → lib/tools}/eval-geocoder.ts +9 -10
  16. package/{tools → lib/tools}/geocoder-namesake-probe.ts +5 -12
  17. package/{tools → lib/tools}/geocoder-vs-provided-coords.ts +9 -10
  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 +68 -257
  21. package/{tools → lib/tools}/learned-scorer-crossstate-eval.ts +60 -243
  22. package/{tools → lib/tools}/learned-scorer-eval.ts +62 -256
  23. package/{tools → lib/tools}/matcher-scale.ts +4 -5
  24. package/lib/tools/nppes/org-name.ts +23 -0
  25. package/{tools → lib/tools}/nppes/overmerge-packet.ts +5 -7
  26. package/{tools → lib/tools}/nppes/report.ts +22 -25
  27. package/{tools → lib/tools}/nppes/sample.ts +80 -32
  28. package/{tools/nppes/levers.ts → lib/tools/nppes/settings.ts} +10 -10
  29. package/{tools → lib/tools}/nppes/truth-grains.ts +4 -44
  30. package/{tools → lib/tools}/nppes-dedup-benchmark.ts +42 -38
  31. package/lib/tools/shared.ts +763 -0
  32. package/lib/tools/train-cross-gbt.ts +209 -0
  33. package/{tools → lib/tools}/train-gbt.ts +35 -154
  34. package/lib/tools/train-org-cross-gbt.ts +179 -0
  35. package/{tools → lib/tools}/txhhsc-to-oarow.ts +9 -27
  36. package/lib/tools/viz/browser.ts +50 -0
  37. package/{tools → lib/tools}/viz/cross-dataset-map.ts +7 -8
  38. package/{tools → lib/tools}/viz/geocode-first-surface.ts +10 -8
  39. package/{tools → lib/tools}/viz/render-map.ts +10 -23
  40. package/lib/tools/viz/render.ts +98 -0
  41. package/{tools → lib/tools}/viz/source-provenance-map.ts +8 -10
  42. package/{tools → lib/tools}/viz/yardstick-figure.ts +6 -5
  43. package/out/address-key.d.ts +1 -1
  44. package/out/address-key.d.ts.map +1 -1
  45. package/out/address-key.js.map +1 -1
  46. package/out/geocode-handler.d.ts +6 -6
  47. package/out/geocode-handler.d.ts.map +1 -1
  48. package/out/geocode-handler.js +6 -6
  49. package/out/geocode-handler.js.map +1 -1
  50. package/out/geojson.d.ts +7 -2
  51. package/out/geojson.d.ts.map +1 -1
  52. package/out/geojson.js +5 -3
  53. package/out/geojson.js.map +1 -1
  54. package/out/index.d.ts +10 -10
  55. package/out/index.d.ts.map +1 -1
  56. package/out/index.js +10 -10
  57. package/out/index.js.map +1 -1
  58. package/out/ingest.d.ts +64 -46
  59. package/out/ingest.d.ts.map +1 -1
  60. package/out/ingest.js +31 -45
  61. package/out/ingest.js.map +1 -1
  62. package/out/learned-scorer.d.ts +1 -1
  63. package/out/learned-scorer.d.ts.map +1 -1
  64. package/out/learned-scorer.js.map +1 -1
  65. package/out/map-html.d.ts +3 -3
  66. package/out/map-html.d.ts.map +1 -1
  67. package/out/map-html.js +6 -11
  68. package/out/map-html.js.map +1 -1
  69. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -1
  70. package/out/models/crosssource-gbt-en-us.js.map +1 -1
  71. package/out/models/dedup-gbt-en-us.d.ts.map +1 -1
  72. package/out/models/dedup-gbt-en-us.js.map +1 -1
  73. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -1
  74. package/out/models/org-crosssource-gbt-en-us.js.map +1 -1
  75. package/out/reconcile.d.ts +6 -1
  76. package/out/reconcile.d.ts.map +1 -1
  77. package/out/reconcile.js +5 -20
  78. package/out/reconcile.js.map +1 -1
  79. package/out/resolve.d.ts +19 -7
  80. package/out/resolve.d.ts.map +1 -1
  81. package/out/resolve.js +16 -5
  82. package/out/resolve.js.map +1 -1
  83. package/out/tools/coverage-reconciliation.d.ts +1 -1
  84. package/out/tools/coverage-reconciliation.d.ts.map +1 -1
  85. package/out/tools/coverage-reconciliation.js +11 -11
  86. package/out/tools/coverage-reconciliation.js.map +1 -1
  87. package/out/tools/cross-dataset-correlation.d.ts +4 -4
  88. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  89. package/out/tools/cross-dataset-correlation.js +57 -109
  90. package/out/tools/cross-dataset-correlation.js.map +1 -1
  91. package/out/tools/cross-source-threshold-sweep.d.ts +2 -2
  92. package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -1
  93. package/out/tools/cross-source-threshold-sweep.js +19 -27
  94. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  95. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  96. package/out/tools/dedup-ceiling.js +36 -117
  97. package/out/tools/dedup-ceiling.js.map +1 -1
  98. package/out/tools/eval-geocoder.d.ts +8 -12
  99. package/out/tools/eval-geocoder.d.ts.map +1 -1
  100. package/out/tools/eval-geocoder.js +2 -2
  101. package/out/tools/eval-geocoder.js.map +1 -1
  102. package/out/tools/geocoder-namesake-probe.d.ts +2 -2
  103. package/out/tools/geocoder-namesake-probe.d.ts.map +1 -1
  104. package/out/tools/geocoder-namesake-probe.js +4 -8
  105. package/out/tools/geocoder-namesake-probe.js.map +1 -1
  106. package/out/tools/geocoder-vs-provided-coords.d.ts +1 -1
  107. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  108. package/out/tools/geocoder-vs-provided-coords.js +8 -7
  109. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  110. package/out/tools/gold-set-sample.d.ts +5 -5
  111. package/out/tools/gold-set-sample.d.ts.map +1 -1
  112. package/out/tools/gold-set-sample.js +37 -122
  113. package/out/tools/gold-set-sample.js.map +1 -1
  114. package/out/tools/index.d.ts +23 -23
  115. package/out/tools/index.d.ts.map +1 -1
  116. package/out/tools/index.js +23 -23
  117. package/out/tools/index.js.map +1 -1
  118. package/out/tools/learned-scorer-clustering-eval.d.ts +1 -1
  119. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  120. package/out/tools/learned-scorer-clustering-eval.js +35 -169
  121. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  122. package/out/tools/learned-scorer-crossstate-eval.d.ts +5 -5
  123. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  124. package/out/tools/learned-scorer-crossstate-eval.js +44 -166
  125. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  126. package/out/tools/learned-scorer-eval.d.ts +1 -1
  127. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  128. package/out/tools/learned-scorer-eval.js +37 -168
  129. package/out/tools/learned-scorer-eval.js.map +1 -1
  130. package/out/tools/matcher-scale.d.ts.map +1 -1
  131. package/out/tools/matcher-scale.js +4 -4
  132. package/out/tools/matcher-scale.js.map +1 -1
  133. package/out/tools/nppes/org-name.d.ts +2 -5
  134. package/out/tools/nppes/org-name.d.ts.map +1 -1
  135. package/out/tools/nppes/org-name.js +1 -30
  136. package/out/tools/nppes/org-name.js.map +1 -1
  137. package/out/tools/nppes/overmerge-packet.d.ts +3 -3
  138. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -1
  139. package/out/tools/nppes/overmerge-packet.js +3 -3
  140. package/out/tools/nppes/overmerge-packet.js.map +1 -1
  141. package/out/tools/nppes/report.d.ts +5 -5
  142. package/out/tools/nppes/report.d.ts.map +1 -1
  143. package/out/tools/nppes/report.js +17 -19
  144. package/out/tools/nppes/report.js.map +1 -1
  145. package/out/tools/nppes/sample.d.ts +32 -6
  146. package/out/tools/nppes/sample.d.ts.map +1 -1
  147. package/out/tools/nppes/sample.js +44 -26
  148. package/out/tools/nppes/sample.js.map +1 -1
  149. package/out/tools/nppes/scoring.d.ts.map +1 -1
  150. package/out/tools/nppes/scoring.js.map +1 -1
  151. package/out/tools/nppes/{levers.d.ts → settings.d.ts} +8 -8
  152. package/out/tools/nppes/settings.d.ts.map +1 -0
  153. package/out/tools/nppes/{levers.js → settings.js} +8 -8
  154. package/out/tools/nppes/settings.js.map +1 -0
  155. package/out/tools/nppes/truth-grains.d.ts +2 -2
  156. package/out/tools/nppes/truth-grains.d.ts.map +1 -1
  157. package/out/tools/nppes/truth-grains.js +4 -29
  158. package/out/tools/nppes/truth-grains.js.map +1 -1
  159. package/out/tools/nppes-dedup-benchmark.d.ts +4 -4
  160. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  161. package/out/tools/nppes-dedup-benchmark.js +40 -34
  162. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  163. package/out/tools/shared.d.ts +244 -7
  164. package/out/tools/shared.d.ts.map +1 -1
  165. package/out/tools/shared.js +349 -18
  166. package/out/tools/shared.js.map +1 -1
  167. package/out/tools/train-cross-gbt.d.ts +7 -7
  168. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  169. package/out/tools/train-cross-gbt.js +47 -145
  170. package/out/tools/train-cross-gbt.js.map +1 -1
  171. package/out/tools/train-gbt.d.ts +7 -7
  172. package/out/tools/train-gbt.d.ts.map +1 -1
  173. package/out/tools/train-gbt.js +31 -111
  174. package/out/tools/train-gbt.js.map +1 -1
  175. package/out/tools/train-org-cross-gbt.d.ts +7 -5
  176. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  177. package/out/tools/train-org-cross-gbt.js +45 -141
  178. package/out/tools/train-org-cross-gbt.js.map +1 -1
  179. package/out/tools/txhhsc-to-oarow.d.ts +2 -2
  180. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  181. package/out/tools/txhhsc-to-oarow.js +8 -22
  182. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  183. package/out/tools/viz/browser.d.ts +34 -0
  184. package/out/tools/viz/browser.d.ts.map +1 -0
  185. package/out/tools/viz/browser.js +33 -0
  186. package/out/tools/viz/browser.js.map +1 -0
  187. package/out/tools/viz/cross-dataset-map.d.ts +2 -2
  188. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  189. package/out/tools/viz/cross-dataset-map.js +6 -6
  190. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  191. package/out/tools/viz/geocode-first-surface.d.ts +4 -3
  192. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  193. package/out/tools/viz/geocode-first-surface.js +7 -5
  194. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  195. package/out/tools/viz/render-map.d.ts +3 -6
  196. package/out/tools/viz/render-map.d.ts.map +1 -1
  197. package/out/tools/viz/render-map.js +9 -19
  198. package/out/tools/viz/render-map.js.map +1 -1
  199. package/out/tools/viz/render.d.ts +4 -9
  200. package/out/tools/viz/render.d.ts.map +1 -1
  201. package/out/tools/viz/render.js +24 -39
  202. package/out/tools/viz/render.js.map +1 -1
  203. package/out/tools/viz/source-provenance-map.d.ts +2 -2
  204. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  205. package/out/tools/viz/source-provenance-map.js +6 -7
  206. package/out/tools/viz/source-provenance-map.js.map +1 -1
  207. package/out/tools/viz/yardstick-figure.d.ts +2 -2
  208. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  209. package/out/tools/viz/yardstick-figure.js +5 -4
  210. package/out/tools/viz/yardstick-figure.js.map +1 -1
  211. package/out/types.d.ts.map +1 -1
  212. package/out/types.js.map +1 -1
  213. package/package.json +115 -15
  214. package/out/tools/nppes/levers.d.ts.map +0 -1
  215. package/out/tools/nppes/levers.js.map +0 -1
  216. package/tools/gold-set-sample.ts +0 -254
  217. package/tools/index.ts +0 -31
  218. package/tools/nppes/org-name.ts +0 -56
  219. package/tools/shared.ts +0 -162
  220. package/tools/train-cross-gbt.ts +0 -359
  221. package/tools/train-org-cross-gbt.ts +0 -330
  222. package/tools/viz/render.ts +0 -113
  223. /package/{models → lib/models}/crosssource-gbt-en-us.ts +0 -0
  224. /package/{models → lib/models}/dedup-gbt-en-us.ts +0 -0
  225. /package/{models → lib/models}/org-crosssource-gbt-en-us.ts +0 -0
  226. /package/{tools → lib/tools}/nppes/scoring.ts +0 -0
  227. /package/{types.ts → lib/types.ts} +0 -0
@@ -12,22 +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"
28
27
 
29
28
  import {
30
- addressFrequencyKey,
31
29
  buildDefaultModel,
32
30
  createGBTScorer,
33
31
  createMatchFeaturizer,
@@ -35,27 +33,22 @@ import {
35
33
  defaultBlockingKeys,
36
34
  ingestRows,
37
35
  resolveEntities,
38
- streamRows,
39
36
  type ColumnMapping,
40
- type ResolvedEntity,
41
37
  type SourceRecord,
42
38
  } from "#index"
43
-
44
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
39
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
40
+ import { buildNPPESStateSamples } from "#tools/nppes/sample"
41
+ import { scoreEntities } from "#tools/nppes/scoring"
45
42
  import {
46
- addr,
47
- MIN_GROUP_SIZE,
43
+ bestOver,
48
44
  MIN_MEANINGFUL_F1_DELTA,
49
- norm,
50
- NPPES_COLUMNS as C,
51
- sigmoid,
52
- TRAINING_EPOCHS,
53
- } from "./shared.ts"
54
-
55
- /**
56
- * Highest k swept when scanning cluster counts.
57
- */
58
- const MAX_K = 32
45
+ pct,
46
+ quantileThresholds,
47
+ sgn,
48
+ toArmScore,
49
+ trainLogisticRegression,
50
+ type ArmScore,
51
+ } from "#tools/shared"
59
52
 
60
53
  /**
61
54
  * Options for {@linkcode scorerCrossStateEval}.
@@ -87,62 +80,6 @@ export interface ScorerCrossStateEvalOptions {
87
80
  outMd?: string
88
81
  }
89
82
 
90
- const choose2 = (n: number) => (n * (n - 1)) / 2
91
-
92
- interface MessyRow extends Record<string, string> {
93
- npi: string
94
- name: string
95
- org: string
96
- address: string
97
- }
98
-
99
- /**
100
- * The dedup benchmark's pairwise clustering metric vs the NPI grouping (record.id = NPI).
101
- */
102
- function scoreClusters(entities: ResolvedEntity[]): {
103
- precision: number
104
- recall: number
105
- f1: number
106
- overMerged: number
107
- } {
108
- const npiTotals = new Map<string, number>()
109
- let sumCK = 0
110
- let sumCluster = 0
111
- let overMerged = 0
112
-
113
- for (const e of entities) {
114
- const byNPI = new Map<string, number>()
115
-
116
- for (const rec of e.records) {
117
- byNPI.set(rec.id, (byNPI.get(rec.id) ?? 0) + 1)
118
- }
119
-
120
- sumCluster += choose2(e.records.length)
121
-
122
- if (byNPI.size > 1) {
123
- overMerged++
124
- }
125
-
126
- for (const [npi, c] of byNPI) {
127
- sumCK += choose2(c)
128
- npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + c)
129
- }
130
- }
131
-
132
- let sumClass = 0
133
-
134
- for (const total of npiTotals.values()) {
135
- sumClass += choose2(total)
136
- }
137
-
138
- const tp = sumCK
139
- const precision = sumCluster > 0 ? tp / sumCluster : 0
140
- const recall = sumClass > 0 ? tp / sumClass : 0
141
- const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
142
-
143
- return { precision, recall, f1, overMerged }
144
- }
145
-
146
83
  /**
147
84
  * Learned-scorer cross-state generalization (#603 Tier 2) — see the module doc. Emits the report to stdout.
148
85
  */
@@ -159,95 +96,38 @@ export async function scorerCrossStateEval(
159
96
  const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
160
97
  const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
161
98
 
162
- report?.("[A] streaming other-names…")
163
- const altNames = new Map<string, string[]>()
164
-
165
- for await (const r of streamRows(OTHER_NAMES)) {
166
- const npi = norm(r[C.npi])
167
- const alt = norm(r[C.otherOrg])
168
-
169
- if (!npi || !alt) continue
170
- const list = altNames.get(npi) ?? []
171
-
172
- if (list.length < MIN_GROUP_SIZE) {
173
- list.push(alt)
174
- }
175
-
176
- altNames.set(npi, list)
177
- }
178
-
179
- // ONE registry pass: global address-frequency + a TRAIN-state sample + an EVAL-state sample.
180
- report?.(`[B] registry pass: address-frequency + ${NPIS} ${TRAIN_STATE} (train) + ${NPIS} ${EVAL_STATE} (eval)…`)
181
-
182
- const samples: Record<string, { rows: MessyRow[]; kept: Set<string> }> = {
183
- [TRAIN_STATE]: { rows: [], kept: new Set() },
184
- [EVAL_STATE]: { rows: [], kept: new Set() },
185
- }
186
-
187
- const addrCounts = new Map<string, number>()
188
- let addrTotal = 0
189
- let scanned = 0
190
-
191
- for await (const r of streamRows(REGISTRY)) {
192
- if (++scanned % 1_000_000 === 0) {
193
- report?.(` scanned ${scanned / 1e6}M`)
194
- }
195
-
196
- const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
197
-
198
- if (practice) {
199
- const k = addressFrequencyKey(practice)
200
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
201
-
202
- addrTotal++
203
- }
204
-
205
- const npi = norm(r[C.npi])
206
- const st = norm(r[C.pState]).toUpperCase()
207
- const bucket = samples[st]
208
-
209
- if (bucket && bucket.kept.size < NPIS && npi && !bucket.kept.has(npi) && altNames.has(npi) && practice) {
210
- const isOrg = norm(r[C.entityType]) === "2"
211
- const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
212
-
213
- if (primaryName) {
214
- const org = isOrg ? norm(r[C.orgLegal]) : ""
215
- bucket.kept.add(npi)
216
- bucket.rows.push({ npi, name: primaryName, org, address: practice })
217
-
218
- for (const alt of altNames.get(npi)!) {
219
- bucket.rows.push({ npi, name: alt, org: alt, address: practice })
220
- }
221
-
222
- const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
223
-
224
- if (mailing && mailing !== practice) {
225
- bucket.rows.push({ npi, name: primaryName, org, address: mailing })
226
- }
227
- }
228
- }
229
- }
230
-
231
- const addressFrequency = {
232
- total: addrTotal,
233
- distinct: addrCounts.size,
234
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
235
- }
236
-
237
- report?.(
238
- ` ${TRAIN_STATE}: ${samples[TRAIN_STATE]!.kept.size} NPIs → ${samples[TRAIN_STATE]!.rows.length} records · ` +
239
- `${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
240
109
  )
241
110
 
111
+ const trainSample = byState.get(TRAIN_STATE)!
112
+ const evalSample = byState.get(EVAL_STATE)!
113
+
242
114
  report?.("[C] geocoding both states…")
243
115
  const geocoder = await options.createGeocoder()
244
- const mapping: ColumnMapping = { id: "npi", name: "name", organization: "org", address: "address", source: "nppes" }
245
116
 
246
- const geocodeRows = (rows: MessyRow[]) => ingestRows(rows, 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