@mailwoman/registry 9.2.0 → 9.4.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 +63 -257
  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 +761 -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 +36 -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 +38 -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 +243 -7
  164. package/out/tools/shared.d.ts.map +1 -1
  165. package/out/tools/shared.js +348 -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
@@ -35,24 +35,16 @@
35
35
  * [--data-root <dir>] [--seed 1] [--out-md <md>]`
36
36
  */
37
37
 
38
- import { writeFileSync } from "node:fs"
39
-
40
- import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
38
+ import { dataRootPath } from "@mailwoman/core/data-root"
39
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
40
+ import { makeLcg } from "@mailwoman/core/random"
41
+ import { mean } from "@mailwoman/core/utils"
41
42
  import { agreementPattern, block, estimateParameters, gbtScore, scorePair, trainGBT } from "@mailwoman/match"
42
43
 
43
- import {
44
- addressFrequencyKey,
45
- buildDefaultModel,
46
- defaultBlockingKeys,
47
- ingestRows,
48
- streamRows,
49
- type ColumnMapping,
50
- type SourceRecord,
51
- } from "#index"
52
-
53
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
54
- import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C, TRAINING_EPOCHS } from "./shared.ts"
55
-
44
+ import { buildDefaultModel, createMatchFeaturizer, defaultBlockingKeys, ingestRows, type ColumnMapping } from "#index"
45
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
46
+ import { buildNPPESSample } from "#tools/nppes/sample"
47
+ import { pct, sgn, stateOption, std, trainLogisticRegression } from "#tools/shared"
56
48
  /**
57
49
  * Smallest mean gap counted as a real difference rather than seed noise.
58
50
  */
@@ -112,115 +104,6 @@ export interface ScorerPairwiseEvalOptions {
112
104
  outMd?: string
113
105
  }
114
106
 
115
- interface MessyRow extends Record<string, string> {
116
- npi: string
117
- name: string
118
- org: string
119
- address: string
120
- }
121
-
122
- /**
123
- * The address-frequency table the collapsed-spatial model needs: how common each normalized address is.
124
- */
125
- interface AddressFrequency {
126
- total: number
127
- distinct: number
128
- frequency: (v: string) => number
129
- }
130
-
131
- /**
132
- * One full registry pass: the NPI-keyed messy rows (primary name + every other-name alias + the mailing address when it
133
- * differs) and the address-frequency table, built together because both want the same scan. Same generation the dedup
134
- * benchmark uses — the two evals must see identical inputs to be comparable.
135
- */
136
- async function generateMessyRows(paths: {
137
- registry: string
138
- otherNames: string
139
- state: string
140
- npis: number
141
- report?: (line: string) => void
142
- }): Promise<{ rows: MessyRow[]; keptNPIs: Set<string>; addressFrequency: AddressFrequency }> {
143
- const { registry: REGISTRY, otherNames: OTHER_NAMES, state: STATE, npis: NPIS, report } = paths
144
- report?.("[A] streaming other-names…")
145
- const altNames = new Map<string, string[]>()
146
-
147
- for await (const r of streamRows(OTHER_NAMES)) {
148
- const npi = norm(r[C.npi])
149
- const alt = norm(r[C.otherOrg])
150
-
151
- if (!npi || !alt) continue
152
- const list = altNames.get(npi) ?? []
153
-
154
- if (list.length < MIN_GROUP_SIZE) {
155
- list.push(alt)
156
- }
157
-
158
- altNames.set(npi, list)
159
- }
160
-
161
- report?.(`[B] full registry pass: address-frequency table + ${NPIS} ${STATE} sample…`)
162
- const rows: MessyRow[] = []
163
- const kept = new Set<string>()
164
- const addrCounts = new Map<string, number>()
165
- let addrTotal = 0
166
- let scanned = 0
167
-
168
- for await (const r of streamRows(REGISTRY)) {
169
- if (++scanned % 1_000_000 === 0) {
170
- report?.(` scanned ${scanned / 1e6}M, kept ${kept.size}`)
171
- }
172
-
173
- const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
174
-
175
- if (practice) {
176
- const k = addressFrequencyKey(practice)
177
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
178
-
179
- addrTotal++
180
- }
181
-
182
- const npi = norm(r[C.npi])
183
-
184
- if (
185
- kept.size < NPIS &&
186
- npi &&
187
- !kept.has(npi) &&
188
- altNames.has(npi) &&
189
- practice &&
190
- norm(r[C.pState]).toUpperCase() === STATE
191
- ) {
192
- const isOrg = norm(r[C.entityType]) === "2"
193
- const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
194
-
195
- if (primaryName) {
196
- const org = isOrg ? norm(r[C.orgLegal]) : ""
197
- kept.add(npi)
198
- rows.push({ npi, name: primaryName, org, address: practice })
199
-
200
- for (const alt of altNames.get(npi)!) {
201
- rows.push({ npi, name: alt, org: alt, address: practice })
202
- }
203
-
204
- const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
205
-
206
- if (mailing && mailing !== practice) {
207
- rows.push({ npi, name: primaryName, org, address: mailing })
208
- }
209
- }
210
- }
211
- }
212
-
213
- const addressFrequency = {
214
- total: addrTotal,
215
- distinct: addrCounts.size,
216
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
217
- }
218
-
219
- report?.(` ${kept.size} NPIs → ${rows.length} records`)
220
-
221
- return { rows, keptNPIs: kept, addressFrequency }
222
- }
223
-
224
107
  /**
225
108
  * Learned-scorer pairwise probe (#603) — see the module doc. Emits the markdown report to stdout.
226
109
  */
@@ -229,7 +112,7 @@ export async function scorerPairwiseEval(
229
112
  report?: (line: string) => void
230
113
  ): Promise<{ markdown: string }> {
231
114
  const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
232
- const STATE = (options.state || "TX").toUpperCase()
115
+ const STATE = stateOption(options)
233
116
  const NPIS = options.npis ?? 1500
234
117
  const SEED = options.seed ?? 1
235
118
  const OUT_MD = options.outMd || ""
@@ -237,24 +120,31 @@ export async function scorerPairwiseEval(
237
120
  const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
238
121
  const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
239
122
 
240
- // --- Data-gen: same NPI-keyed records as the dedup benchmark. ---
241
- const { rows, keptNPIs, addressFrequency } = await generateMessyRows({
242
- registry: REGISTRY,
243
- otherNames: OTHER_NAMES,
244
- state: STATE,
245
- npis: NPIS,
246
- report,
247
- })
123
+ // --- Data-gen: the same NPI-keyed records as the dedup benchmark (the SHARED sample builder). ---
124
+ const { rows, keptNpis, addressFrequency } = await buildNPPESSample(
125
+ { registryPath: REGISTRY, otherNamesPath: OTHER_NAMES, state: STATE, maxNpis: NPIS },
126
+ report
127
+ )
248
128
 
249
129
  report?.("[C] geocoding…")
250
130
  const geocoder = await options.createGeocoder()
251
- const mapping: ColumnMapping = { id: "npi", name: "name", organization: "org", address: "address", source: "nppes" }
131
+
132
+ // `auth`/`taxonomy` ride as attributes so the SHARED featurizer's #625 roll-up features can read the
133
+ // authorized official; the FS arm ignores them (no discriminators configured).
134
+ const mapping: ColumnMapping = {
135
+ id: "npi",
136
+ name: "name",
137
+ organization: "org",
138
+ address: "address",
139
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
140
+ source: "nppes",
141
+ }
252
142
 
253
143
  const records = await ingestRows(rows, mapping, {
254
- geocodeAddress: geocoder.seam,
144
+ geocodeAddress: geocoder.geocodeAddress,
255
145
  })
256
146
 
257
- geocoder.close()
147
+ geocoder[Symbol.dispose]()
258
148
 
259
149
  // --- Block + feature extraction. The model (collapsed spatial + address-frequency) defines the
260
150
  // comparisons; EM-fit it for the FS baseline. ---
@@ -264,44 +154,8 @@ export async function scorerPairwiseEval(
264
154
  const patterns = pairs.map(([a, b]) => agreementPattern(model.comparisons, a, b))
265
155
  const fsModel = estimateParameters(model, patterns).model
266
156
 
267
- // Level counts per comparison (for one-hot). Index -1 (missing) → all-zero block.
268
- const levelCounts = model.comparisons.map((c) => c.levels.length)
269
- const compIndex = Object.fromEntries(model.comparisons.map((c, i) => [c.name, i]))
270
- const spatialI = compIndex["spatial"]!
271
- const givenI = compIndex["given"]!
272
- const familyI = compIndex["family"]!
273
- const orgI = compIndex["organization"]!
274
- const lastLevel = (i: number) => levelCounts[i]! - 1
275
-
276
- // the "different"/"far" catch-all level
277
-
278
- /**
279
- * Feature vector for a pair: one-hot agreement levels + the over-merge interactions + address crowdedness.
280
- */
281
- function features(pat: number[], a: SourceRecord): number[] {
282
- const f: number[] = []
283
-
284
- for (let i = 0; i < pat.length; i++) {
285
- const lvl = pat[i]!
286
-
287
- for (let l = 0; l < levelCounts[i]!; l++) {
288
- f.push(lvl === l ? 1 : 0)
289
- }
290
- }
291
-
292
- // Interaction: co-located (spatial exact = level 0) AND the names/org disagree (catch-all level).
293
- const spatialExact = pat[spatialI] === 0 ? 1 : 0
294
- const nameDisagree = pat[givenI] === lastLevel(givenI) && pat[familyI] === lastLevel(familyI) ? 1 : 0
295
- const orgDisagree = pat[orgI] === lastLevel(orgI) ? 1 : 0
296
- f.push(spatialExact * nameDisagree) // the over-merge signature: same place, names disagree
297
- f.push(spatialExact * orgDisagree)
298
- // Address crowdedness (how shared this address is) — high → "same address" is weak evidence.
299
- const freq = a.address?.raw ? addressFrequency.frequency(a.address.raw) : 0
300
- f.push(Math.min(1, freq * 1000))
301
-
302
- // scale into a usable range
303
- return f
304
- }
157
+ // The SHARED production featurizer (createMatchFeaturizer) — train ≡ eval ≡ inference, one definition.
158
+ const featurize = createMatchFeaturizer({ comparisons: model.comparisons, addressFrequency })
305
159
 
306
160
  interface Sample {
307
161
  x: number[]
@@ -323,8 +177,6 @@ export async function scorerPairwiseEval(
323
177
  gbtScored: Scored[]
324
178
  }
325
179
 
326
- const sigmoid = (z: number) => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
327
-
328
180
  /**
329
181
  * One train/test split (by NPI): train the L2 logistic regression on the train pairs, then score the held-out test
330
182
  * pairs with both the LR and the EM-fitted FS scorer. The FS model is seed-independent (fit unsupervised on ALL
@@ -334,14 +186,14 @@ export async function scorerPairwiseEval(
334
186
  const rnd = makeLcg(seed || 1)
335
187
  const npiSplit = new Map<string, "train" | "test">()
336
188
 
337
- for (const npi of keptNPIs) {
189
+ for (const npi of keptNpis) {
338
190
  npiSplit.set(npi, rnd() < TRAIN_SPLIT_FRACTION ? "train" : "test")
339
191
  }
340
192
 
341
193
  const train: Sample[] = []
342
194
  const test: Sample[] = []
343
195
 
344
- pairs.forEach(([a, b], i) => {
196
+ pairs.forEach(([a, b]) => {
345
197
  const sa = npiSplit.get(a.id)
346
198
  const sb = npiSplit.get(b.id)
347
199
 
@@ -349,7 +201,7 @@ export async function scorerPairwiseEval(
349
201
 
350
202
  // cross-split or unknown → drop (no leakage)
351
203
  const sample: Sample = {
352
- x: features(patterns[i]!, a),
204
+ x: featurize(a, b),
353
205
  y: a.id === b.id ? 1 : 0,
354
206
  fs: scorePair(fsModel, a, b).weight,
355
207
  }
@@ -357,58 +209,23 @@ export async function scorerPairwiseEval(
357
209
  })
358
210
 
359
211
  const dim = train[0]?.x.length ?? 0
360
-
361
- // L2-regularized logistic regression (batch gradient descent), rare class up-weighted.
362
- const w = new Array<number>(dim).fill(0)
363
- let bias = 0
364
- const lrate = 0.1
365
- const l2 = 1e-3
366
212
  const posWeight = train.filter((s) => s.y === 1).length / Math.max(1, train.length)
213
+ const sampleWeights = train.map((s) => (s.y === 1 ? 1 - posWeight : posWeight))
367
214
 
368
- for (let epoch = 0; epoch < TRAINING_EPOCHS; epoch++) {
369
- const gw = new Array<number>(dim).fill(0)
370
- let gb = 0
371
-
372
- for (const s of train) {
373
- let z = bias
374
-
375
- for (let j = 0; j < dim; j++) {
376
- z += w[j]! * s.x[j]!
377
- }
378
-
379
- const p = sigmoid(z)
380
- const sampleW = s.y === 1 ? 1 - posWeight : posWeight
381
- const err = (p - s.y) * sampleW
382
-
383
- for (let j = 0; j < dim; j++) {
384
- gw[j]! += err * s.x[j]!
385
- }
386
-
387
- gb += err
388
- }
389
-
390
- for (let j = 0; j < dim; j++) {
391
- w[j]! -= lrate * (gw[j]! / train.length + l2 * w[j]!)
392
- }
393
-
394
- bias -= lrate * (gb / train.length)
395
- }
396
-
397
- const lrScore = (x: number[]) => {
398
- let z = bias
399
-
400
- for (let j = 0; j < x.length; j++) {
401
- z += w[j]! * x[j]!
402
- }
403
-
404
- return z
405
- }
215
+ // L2-regularized logistic regression (batch gradient descent), rare class up-weighted — the
216
+ // SHARED trainer.
217
+ const lrScore = trainLogisticRegression(
218
+ train.map((s) => s.x),
219
+ train.map((s) => s.y),
220
+ sampleWeights,
221
+ dim
222
+ )
406
223
 
407
224
  // Gradient-boosted trees on the SAME train pairs + class weights — the non-linear arm.
408
225
  const gbt = trainGBT(
409
226
  train.map((s) => s.x),
410
227
  train.map((s) => s.y),
411
- train.map((s) => (s.y === 1 ? 1 - posWeight : posWeight)),
228
+ sampleWeights,
412
229
  { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
413
230
  )
414
231
 
@@ -488,13 +305,6 @@ export async function scorerPairwiseEval(
488
305
  report?.("[E] training across seeds…")
489
306
  const SEEDS = options.seeds ?? 8
490
307
  const splits = Array.from({ length: SEEDS }, (_, k) => runSplit(SEED + k))
491
- const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
492
-
493
- const std = (xs: number[]) => {
494
- const m = mean(xs)
495
-
496
- return Math.sqrt(mean(xs.map((x) => (x - m) ** 2)))
497
- }
498
308
 
499
309
  const fsAucs = splits.map((r) => auc(r.fsScored))
500
310
  const lrAucs = splits.map((r) => auc(r.lrScored))
@@ -502,12 +312,12 @@ export async function scorerPairwiseEval(
502
312
  const fsF1s = splits.map((r) => bestF1(r.fsScored).f1)
503
313
  const lrF1s = splits.map((r) => bestF1(r.lrScored).f1)
504
314
  const lrWins = deltas.filter((d) => d > 0).length
505
- const meanDelta = mean(deltas)
506
- const avgTestN = mean(splits.map((r) => r.testN))
507
- const avgTestPos = mean(splits.map((r) => r.lrScored.filter((d) => d.y === 1).length))
315
+ const meanDelta = mean(deltas)!
316
+ const avgTestN = mean(splits.map((r) => r.testN))!
317
+ const avgTestPos = mean(splits.map((r) => r.lrScored.filter((d) => d.y === 1).length))!
508
318
  const seMean = std(deltas) / Math.sqrt(SEEDS) // standard error of the mean ΔAUC
509
319
  const zScore = seMean > 0 ? meanDelta / seMean : 0 // ΔAUC in standard errors above zero
510
- const f1Delta = mean(lrF1s) - mean(fsF1s) // operating-point F1 gain (LR − FS)
320
+ const f1Delta = mean(lrF1s)! - mean(fsF1s)! // operating-point F1 gain (LR − FS)
511
321
  const unanimous = lrWins === SEEDS
512
322
  // GBT (non-linear) arm.
513
323
  const gbtAucs = splits.map((r) => auc(r.gbtScored))
@@ -515,9 +325,9 @@ export async function scorerPairwiseEval(
515
325
  const gbtVsFs = splits.map((_, i) => gbtAucs[i]! - fsAucs[i]!)
516
326
  const gbtVsLr = splits.map((_, i) => gbtAucs[i]! - lrAucs[i]!)
517
327
  const gbtBeatsLr = gbtVsLr.filter((d) => d > 0).length
518
- const meanGbtVsFs = mean(gbtVsFs)
519
- const meanGbtVsLr = mean(gbtVsLr)
520
- const f1DeltaGbt = mean(gbtF1s) - mean(fsF1s)
328
+ const meanGbtVsFs = mean(gbtVsFs)!
329
+ const meanGbtVsLr = mean(gbtVsLr)!
330
+ const f1DeltaGbt = mean(gbtF1s)! - mean(fsF1s)!
521
331
 
522
332
  // operating-point F1 gain (GBT − FS)
523
333
  for (const r of splits) {
@@ -532,21 +342,17 @@ export async function scorerPairwiseEval(
532
342
  }
533
343
 
534
344
  report?.(
535
- ` mean/${SEEDS} — FS ${mean(fsAucs).toFixed(4)} LR ${mean(lrAucs).toFixed(4)} (Δ${meanDelta >= 0 ? "+" : ""}${meanDelta.toFixed(4)}) ` +
536
- `GBT ${mean(gbtAucs).toFixed(4)} (Δ${meanGbtVsFs >= 0 ? "+" : ""}${meanGbtVsFs.toFixed(4)} vs FS, ` +
345
+ ` mean/${SEEDS} — FS ${mean(fsAucs)!.toFixed(4)} LR ${mean(lrAucs)!.toFixed(4)} (Δ${meanDelta >= 0 ? "+" : ""}${meanDelta.toFixed(4)}) ` +
346
+ `GBT ${mean(gbtAucs)!.toFixed(4)} (Δ${meanGbtVsFs >= 0 ? "+" : ""}${meanGbtVsFs.toFixed(4)} vs FS, ` +
537
347
  `${meanGbtVsLr >= 0 ? "+" : ""}${meanGbtVsLr.toFixed(4)} vs LR)`
538
348
  )
539
349
 
540
- // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
541
- // numerator/denominator contract (call sites append their own "%").
542
- const pct = (x: number) => (100 * x).toFixed(1)
543
350
  const f4 = (x: number) => x.toFixed(4)
544
- const sgn = (x: number) => (x >= 0 ? "+" : "")
545
351
 
546
352
  const lines: string[] = [
547
353
  `# Learned-scorer probe (#603) — does a model beat Fellegi-Sunter on the FS feature vector?`,
548
354
  "",
549
- `_Generated by \`mailwoman registry scorer-eval pairwise\`. ${keptNPIs.size} ${STATE} NPIs → ${records.length} ` +
355
+ `_Generated by \`mailwoman registry scorer-eval pairwise\`. ${keptNpis.size} ${STATE} NPIs → ${records.length} ` +
550
356
  `records, geocoded. Candidate pairs are split BY NPI into train/test (no NPI's records cross the split), repeated ` +
551
357
  `over ${SEEDS} seeds to bound split variance. Two learned scorers over the FS agreement pattern + over-merge ` +
552
358
  `interaction features (spatial-exact × name-disagree, spatial-exact × org-disagree, address crowdedness) — features ` +
@@ -559,15 +365,15 @@ export async function scorerPairwiseEval(
559
365
  "",
560
366
  `| scorer | ROC-AUC (mean±std) | ΔAUC vs FS | best F1 (mean) |`,
561
367
  `|---|---:|---:|---:|`,
562
- `| Fellegi-Sunter (EM-fit) | ${f4(mean(fsAucs))} ± ${f4(std(fsAucs))} | — | ${pct(mean(fsF1s))}% |`,
563
- `| logistic regression (linear) | ${f4(mean(lrAucs))} ± ${f4(std(lrAucs))} | ${sgn(meanDelta)}${f4(meanDelta)} | ${pct(mean(lrF1s))}% |`,
564
- `| **gradient-boosted trees** | **${f4(mean(gbtAucs))} ± ${f4(std(gbtAucs))}** | **${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}** | **${pct(mean(gbtF1s))}%** |`,
368
+ `| Fellegi-Sunter (EM-fit) | ${f4(mean(fsAucs)!)} ± ${f4(std(fsAucs))} | — | ${pct(mean(fsF1s)!)}% |`,
369
+ `| logistic regression (linear) | ${f4(mean(lrAucs)!)} ± ${f4(std(lrAucs))} | ${sgn(meanDelta)}${f4(meanDelta)} | ${pct(mean(lrF1s)!)}% |`,
370
+ `| **gradient-boosted trees** | **${f4(mean(gbtAucs)!)} ± ${f4(std(gbtAucs))}** | **${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}** | **${pct(mean(gbtF1s)!)}%** |`,
565
371
  "",
566
372
  `**ΔAUC (LR − FS): ${sgn(meanDelta)}${f4(meanDelta)} ± ${f4(std(deltas))}, LR > FS in ${lrWins}/${SEEDS} seeds.**`,
567
373
  "",
568
374
  `Robustness: the ΔAUC is small but **consistent** — std ${f4(std(deltas))} across seeds, SE ±${f4(seMean)} → ` +
569
375
  `≈${zScore.toFixed(1)}σ above zero, ${lrWins}/${SEEDS} seeds in LR's favour. At the operating point the gap is ` +
570
- `larger: **ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp** (${pct(mean(fsF1s))}% → ${pct(mean(lrF1s))}%), ` +
376
+ `larger: **ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp** (${pct(mean(fsF1s)!)}% → ${pct(mean(lrF1s)!)}%), ` +
571
377
  `because the interaction features sharpen the hard co-located band near the decision boundary even where overall ` +
572
378
  `ranking barely moves.`,
573
379
  "",
@@ -590,7 +396,7 @@ export async function scorerPairwiseEval(
590
396
  `Because the key over-merge interactions are ALREADY hand-engineered into the feature vector, the tree's main ` +
591
397
  `advantage — auto-discovering interactions — is largely pre-empted; it neither extends nor erases the linear ` +
592
398
  `gain. The signal in this feature set is close to linearly saturated, so a production GBM should budget for the ` +
593
- `SAME modest margin the LR shows, not a step change — its real value is generalizing the #625 levers, not ` +
399
+ `SAME modest margin the LR shows, not a step change — its real value is generalizing the #625 changes, not ` +
594
400
  `finding hidden non-linear structure here.`
595
401
 
596
402
  lines.push(treeVerdict)
@@ -609,13 +415,13 @@ export async function scorerPairwiseEval(
609
415
  const verdict =
610
416
  unanimous && (meanDelta > CLEAR_WIN_DELTA || f1Delta > CLEAR_WIN_F1_DELTA)
611
417
  ? `The LR beats FS **consistently** — it wins ${lrWins}/${SEEDS} seeds and lifts the operating-point F1 by ` +
612
- `${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp (${pct(mean(fsF1s))}% → ${pct(mean(lrF1s))}%). The ΔAUC is ` +
613
- `small (+${f4(meanDelta)}) only because FS already ranks well (${f4(mean(fsAucs))}); the gain concentrates at the ` +
418
+ `${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp (${pct(mean(fsF1s)!)}% → ${pct(mean(lrF1s)!)}%). The ΔAUC is ` +
419
+ `small (+${f4(meanDelta)}) only because FS already ranks well (${f4(mean(fsAucs)!)}); the gain concentrates at the ` +
614
420
  `decision boundary, exactly where the interaction features (which FS structurally can't express) bite. ` +
615
421
  `**This greenlights the #603 learned scorer:** a GBM — non-linear over the same features — is the principled ` +
616
- `generalization of the hand-tuned #625 levers and should extend this linear gain. Honest framing: the linear ` +
422
+ `generalization of the hand-tuned #625 changes and should extend this linear gain. Honest framing: the linear ` +
617
423
  `headroom is modest, so the GBM's job is to *widen a real-but-small margin*, not to unlock a step change past the ` +
618
- `64.7% dedup plateau on its own — the reliable secondary identifier (#625) is still the larger lever.`
424
+ `64.7% dedup plateau on its own — the reliable secondary identifier (#625) is still the larger gain.`
619
425
  : unanimous && zScore >= STRONG_EVIDENCE_Z
620
426
  ? `The LR beats FS by a **small but statistically robust** margin (ΔAUC +${f4(meanDelta)}, ≈${zScore.toFixed(1)}σ, ` +
621
427
  `${lrWins}/${SEEDS} seeds; ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp). The interaction features ` +
@@ -636,7 +442,7 @@ export async function scorerPairwiseEval(
636
442
  lines.push("")
637
443
 
638
444
  lines.push(
639
- `In-domain (${STATE} only), ${keptNPIs.size} NPIs, PAIRWISE ranking (not the assembled clustering metric the dedup ` +
445
+ `In-domain (${STATE} only), ${keptNpis.size} NPIs, PAIRWISE ranking (not the assembled clustering metric the dedup ` +
640
446
  `benchmark reports against the 64.7% baseline — a better pairwise scorer need not translate 1:1 to cluster F1). The GBT ` +
641
447
  `is a compact pure-Node implementation (120 boosting rounds, depth 3), a faithful stand-in for an offline ` +
642
448
  `XGBoost/LightGBM but not tuned. The split is by NPI so there's no record-level leakage, but the address-frequency ` +
@@ -654,7 +460,7 @@ export async function scorerPairwiseEval(
654
460
  console.log(md)
655
461
 
656
462
  if (OUT_MD) {
657
- writeFileSync(OUT_MD, md)
463
+ await writeLocalFile(md, OUT_MD)
658
464
  report?.(`[written] ${OUT_MD}`)
659
465
  }
660
466
 
@@ -16,9 +16,8 @@
16
16
  * [--em] [--out-md <md>]`
17
17
  */
18
18
 
19
- import { writeFileSync } from "node:fs"
20
-
21
- import { makeLcg } from "@mailwoman/core/utils"
19
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
20
+ import { makeLcg } from "@mailwoman/core/random"
22
21
 
23
22
  import { resolveEntities, type SourceRecord } from "#index"
24
23
 
@@ -171,7 +170,7 @@ export async function matcherScale(
171
170
  lines.push(
172
171
  `RSS is the shared-process high-water mark across the sweep (each size reuses the heap), so it is an upper ` +
173
172
  `bound, not a per-N working set. The largest size that fits is bounded by the record objects + the link array; ` +
174
- `beyond that, shard by geography (each cell is independent) — the same partition the blocking already implies.`
173
+ `beyond that, extract by geography (each cell is independent) — the same partition the blocking already implies.`
175
174
  )
176
175
 
177
176
  lines.push("")
@@ -190,7 +189,7 @@ export async function matcherScale(
190
189
  console.log(md)
191
190
 
192
191
  if (OUT_MD) {
193
- writeFileSync(OUT_MD, md)
192
+ await writeLocalFile(md, OUT_MD)
194
193
  report?.(`[written] ${OUT_MD}`)
195
194
  }
196
195
 
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file Org-name similarity primitives for the NPPES benchmark's org-name entity truth.
6
+ */
7
+
8
+ export { orgTokens } from "#tools/shared"
9
+
10
+ /**
11
+ * Jaccard floor at or above which two {@linkcode orgTokens} sets count as the same organization — the gold-set
12
+ * threshold.
13
+ */
14
+ export const ORG_TAU = 0.7
15
+
16
+ /**
17
+ * An NPI's primary registry identity: the org-name token set plus the address key of its practice location. Every grain
18
+ * of the org-name truth blocks on a location and filters on the tokens.
19
+ */
20
+ export interface NPIPrimary {
21
+ tokens: Set<string>
22
+ addrKey: string
23
+ }
@@ -6,14 +6,12 @@
6
6
  * formatted for human review.
7
7
  */
8
8
 
9
- import { writeFileSync } from "node:fs"
10
-
9
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers"
11
10
  import { isPresent } from "@mailwoman/core/objects"
12
11
 
13
12
  import type { ResolvedEntity, SourceRecord } from "#index"
14
-
15
- import type { MessyRow } from "./sample.ts"
16
- import type { TruthLabel } from "./truth-grains.ts"
13
+ import type { MessyRow } from "#tools/nppes/sample"
14
+ import type { TruthLabel } from "#tools/nppes/truth-grains"
17
15
 
18
16
  /**
19
17
  * Everything the packet reads.
@@ -43,7 +41,7 @@ export interface OvermergePacketInput {
43
41
  * truth says belong to different entities. Per-pair human adjudication is the only instrument that separates model
44
42
  * error from yardstick error once the residual is near the measured irreducible ceiling.
45
43
  */
46
- export function writeOvermergePacket(path: string, input: OvermergePacketInput): number {
44
+ export async function writeOvermergePacket(path: string, input: OvermergePacketInput): Promise<number> {
47
45
  const { entities, rows, recordCount, maxNpis, state, orgNameLabel } = input
48
46
  const rowByID = new Map(rows.map((r) => [r.npi, r]))
49
47
 
@@ -90,7 +88,7 @@ export function writeOvermergePacket(path: string, input: OvermergePacketInput):
90
88
  out.push("")
91
89
  })
92
90
 
93
- writeFileSync(path, out.join("\n"))
91
+ await writeLocalTextFile(out.join("\n"), path)
94
92
 
95
93
  return n
96
94
  }