@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
package/tools/shared.ts DELETED
@@ -1,160 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Shared helpers for the `registry/tools` probe battery.
7
- *
8
- * The rule: anything reused by two or more probes belongs here; anything a single probe needs
9
- * stays with that probe.
10
- */
11
-
12
- import type { ColumnMapping } from "../ingest.ts"
13
-
14
- export interface SourceSpec {
15
- source: string
16
- path: string
17
- mapping: ColumnMapping
18
- inState: (row: Record<string, string>) => boolean
19
- }
20
-
21
- /**
22
- * Trim, treating `undefined` as empty — the shape every probe's raw CSV columns arrive in.
23
- */
24
- export const norm = (s: string | undefined): string => (s ?? "").trim()
25
-
26
- /**
27
- * Join the four US address columns into one line, dropping blanks.
28
- */
29
- export const addr = (line: string, city: string, st: string, zip: string): string =>
30
- [norm(line), norm(city), norm(st), norm(zip)].filter(Boolean).join(", ")
31
-
32
- /**
33
- * Arithmetic mean; `0` on an empty sample rather than `NaN`, because these feed report tables that print a number per
34
- * row.
35
- */
36
- export const mean = (xs: readonly number[]): number => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
37
-
38
- /**
39
- * Logistic function with the input clamped to +/-30 — past that `Math.exp` underflows to 0 and the gradient step
40
- * silently becomes a no-op.
41
- */
42
- export const sigmoid = (z: number): number => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
43
-
44
- /**
45
- * NPPES registry column headers, by the short name the probes read them under.
46
- *
47
- * The NPI registry export is a ~330-column TSV with headers this long, so every probe that touches it needs this map,
48
- * and five of them had grown their own copy. The copies were a NESTED SUPERSET chain, not a disagreement -- each new
49
- * probe took the previous one's map and appended what it additionally read -- so this is the widest of the five, and no
50
- * consumer loses a column. Reading extra keys costs nothing: they are inert strings, and nothing enumerates this object
51
- * (checked: no `Object.keys`/`values`/`entries`/spread over it anywhere in `tools/`), so adding a column can never
52
- * change a probe's behavior.
53
- */
54
- export const NPPES_COLUMNS = {
55
- npi: "NPI",
56
- entityType: "Entity Type Code",
57
- orgLegal: "Provider Organization Name (Legal Business Name)",
58
- last: "Provider Last Name (Legal Name)",
59
- first: "Provider First Name",
60
- pAddr: "Provider First Line Business Practice Location Address",
61
- pCity: "Provider Business Practice Location Address City Name",
62
- pState: "Provider Business Practice Location Address State Name",
63
- pZip: "Provider Business Practice Location Address Postal Code",
64
- mAddr: "Provider First Line Business Mailing Address",
65
- mCity: "Provider Business Mailing Address City Name",
66
- mState: "Provider Business Mailing Address State Name",
67
- mZip: "Provider Business Mailing Address Postal Code",
68
- otherOrg: "Provider Other Organization Name",
69
- authLast: "Authorized Official Last Name",
70
- authFirst: "Authorized Official First Name",
71
- isSubpart: "Is Organization Subpart",
72
- parentLBN: "Parent Organization LBN",
73
- parentTIN: "Parent Organization TIN",
74
- // #625 taxonomy discriminator: the 15 taxonomy slots; collected as a set (any shared code = agreement).
75
- taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
76
- }
77
-
78
- /**
79
- * Groups below this size are too small for a held-out split to mean anything.
80
- */
81
- export const MIN_GROUP_SIZE = 5
82
-
83
- /**
84
- * Gradient-boosting rounds. Fixed rather than early-stopped so seeds stay comparable.
85
- */
86
- export const TRAINING_EPOCHS = 400
87
-
88
- /**
89
- * Smallest mean F1 gap counted as a real difference between models rather than seed noise. Verdicts inside ±this are
90
- * reported as a tie.
91
- */
92
- export const MIN_MEANINGFUL_F1_DELTA = 0.02
93
-
94
- /**
95
- * `n + 1` evenly-spaced order statistics of an already-sorted sample, de-duplicated — the candidate split thresholds a
96
- * GBT node considers. `[0]` for an empty sample so a degenerate feature still yields one (useless but well-formed)
97
- * threshold rather than an empty split set.
98
- */
99
- export function uniqueQuantiles(sorted: readonly number[], n: number): number[] {
100
- if (!sorted.length) return [0]
101
- const ts = new Set<number>()
102
-
103
- for (let k = 0; k <= n; k++) {
104
- ts.add(sorted[Math.floor((k / n) * (sorted.length - 1))]!)
105
- }
106
-
107
- return [...ts]
108
- }
109
-
110
- /**
111
- * The TX facility source specs two probes reconcile against each other. `cross-dataset-correlation` deliberately keeps
112
- * its own longer list — it correlates a wider set than these two reconcile.
113
- */
114
- export const buildSpecs = (S: string, STATE: string): SourceSpec[] => [
115
- {
116
- source: "txhhsc-nursing",
117
- path: `${S}/txhhsc_nursing-facilities_20260611.tsv`,
118
- mapping: {
119
- id: "Facility ID",
120
- organization: "Facility Name",
121
- address: ["Physical Address", "Physical Address CITY", "Physical Address State", "Physical Address Zipcode"],
122
- phone: "Facility Phone Number",
123
- source: "txhhsc-nursing",
124
- },
125
- inState: (r) => norm(r["Physical Address State"]).toUpperCase() === STATE,
126
- },
127
- {
128
- source: "fcc-rhc",
129
- path: `${S}/fcc-rhc_posted-services_form461-465_20260615.tsv`,
130
- mapping: {
131
- id: "HCP Number",
132
- organization: "HCP Name",
133
- address: ["Site Address Line 1", "Site City", "Site State", "Site ZIP Code"],
134
- phone: "Contact Phone",
135
- email: "Contact E-mail",
136
- source: "fcc-rhc",
137
- },
138
- inState: (r) => norm(r["Site State"]).toUpperCase() === STATE,
139
- },
140
- {
141
- source: "nppes",
142
- path: `${S}/nppes_npi-registry_20260607.tsv`,
143
- mapping: {
144
- id: "NPI",
145
- organization: "Provider Organization Name (Legal Business Name)",
146
- address: [
147
- "Provider First Line Business Practice Location Address",
148
- "Provider Business Practice Location Address City Name",
149
- "Provider Business Practice Location Address State Name",
150
- "Provider Business Practice Location Address Postal Code",
151
- ],
152
- phone: "Provider Business Practice Location Address Telephone Number",
153
- source: "nppes",
154
- },
155
- inState: (r) =>
156
- norm(r["Provider Business Practice Location Address State Name"]).toUpperCase() === STATE &&
157
- norm(r["Entity Type Code"]) === "2" &&
158
- !!norm(r["Provider Organization Name (Legal Business Name)"]),
159
- },
160
- ]
@@ -1,358 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Train the CROSS-SOURCE link scorer (#655 option 2 — unblocked 2026-07-06). The dedup GBT (#603)
7
- * is trained on within-NPPES labels, so its strongest feature (`spatial-exact × name-disagree`)
8
- * REJECTS the prototypical cross-source pair ("same provider, different operational text across
9
- * registries") — the reason the cross-dataset flows pin the FS baseline. The 2026-06-16
10
- * feasibility doc blocked a cross-source retrain on "no non-circular anchor"; the anchor exists:
11
- * **CMS Open Payments joins NPPES by NPI** — the same practitioner in two INDEPENDENT registries,
12
- * each with independently human-entered name + address. Same-NPI cross-source pairs are
13
- * ground-truth positives labeled by a key the matcher's features never see.
14
- *
15
- * Pipeline (mirrors train-gbt.ts): assemble NPPES + Open Payments TX records for the same NPI
16
- * population → geocode both through the standard ingest → block over the UNION, keep only
17
- * CROSS-source candidate pairs → featurize with the SHARED `createMatchFeaturizer` (train ≡
18
- * inference) → label by NPI → held-out-NPI calibration (the #655 threshold rule: max recall
19
- * subject to a pairwise-precision bar, reported alongside F1-max) → train the shipped model on
20
- * all pairs → emit `registry/models/crosssource-gbt-en-us.ts`.
21
- *
22
- * Sources (both public domain, `.notes/data-sources.md`):
23
- *
24
- * - `nppes_npi-registry_*.tsv` — the practice-location + primary-name records.
25
- * - `openpayments_covered-recipient-profile_*.csv` — the OP profile supplement (NPI, profile
26
- * first/last, profile practice address).
27
- *
28
- * Run: `mailwoman registry train-scorer cross-gbt [--state TX] [--npis 2000]
29
- * [--precision-bar 0.95] [--wof <admin.db>] [--data-root <dir>]
30
- * [--out registry/models/crosssource-gbt-en-us.ts]`
31
- */
32
-
33
- import { mkdirSync, writeFileSync } from "node:fs"
34
- import { dirname } from "node:path"
35
-
36
- import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
37
- import { block, gbtScore, trainGBT } from "@mailwoman/match"
38
- import {
39
- addressFrequencyKey,
40
- buildDefaultModel,
41
- createMatchFeaturizer,
42
- defaultBlockingKeys,
43
- ingestRows,
44
- streamRows,
45
- type ColumnMapping,
46
- type SourceRecord,
47
- } from "@mailwoman/registry"
48
-
49
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
50
- import { addr, norm, NPPES_COLUMNS as N, uniqueQuantiles } from "./shared.ts"
51
-
52
- /**
53
- * Share of entities assigned to fit; the rest are held out.
54
- */
55
- const FIT_SPLIT_FRACTION = 0.8
56
-
57
- /**
58
- * Options for {@linkcode trainCrossSourceGBT}.
59
- */
60
- export interface TrainCrossSourceGBTOptions {
61
- /**
62
- * The injected geocoder factory (the command wires `mailwoman/geocode-core`; see `./eval-geocoder.ts`).
63
- */
64
- createGeocoder: EvalGeocoderFactory
65
- /**
66
- * Record-matcher sources directory. Default `$MAILWOMAN_DATA_ROOT/record-matcher/sources`.
67
- */
68
- sources?: string
69
- /**
70
- * State filter. Default TX.
71
- */
72
- state?: string
73
- /**
74
- * NPIs sampled. Default 2000.
75
- */
76
- npis?: number
77
- /**
78
- * Output TS module path. Default `registry/models/crosssource-gbt-en-us.ts`.
79
- */
80
- out?: string
81
- /**
82
- * Locale recorded in the model meta. Default en-US.
83
- */
84
- locale?: string
85
- /**
86
- * #655 threshold rule: max cross-source recall subject to this held-out pairwise precision. Default 0.95.
87
- */
88
- precisionBar?: number
89
- /**
90
- * Training date stamped into the meta. Default today.
91
- */
92
- date?: string
93
- }
94
-
95
- interface MessyRow {
96
- npi: string
97
- name: string
98
- org: string
99
- address: string
100
- source: string
101
- }
102
-
103
- /**
104
- * Train + emit the cross-source link GBT — see the module doc.
105
- */
106
- export async function trainCrossSourceGBT(
107
- options: TrainCrossSourceGBTOptions,
108
- report?: (line: string) => void
109
- ): Promise<{ out: string; pairs: number; recommendedThreshold: number }> {
110
- const SOURCES = options.sources || String(dataRootPath("record-matcher", "sources"))
111
- const STATE = (options.state || "TX").toUpperCase()
112
- const NPIS = options.npis ?? 2000
113
- const OUT = options.out || "registry/models/crosssource-gbt-en-us.ts"
114
- const LOCALE = options.locale || "en-US"
115
- // #655 threshold rule: max cross-source recall subject to this held-out pairwise precision.
116
- const PRECISION_BAR = options.precisionBar ?? 0.95
117
- const TRAIN_DATE = options.date || new Date().toISOString().slice(0, 10)
118
-
119
- const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
120
- const OP_PROFILE = `${SOURCES}/openpayments_covered-recipient-profile_20260603.csv`
121
-
122
- // --- Phase A: Open Payments TX practitioners (NPI + profile name + profile address). ---
123
- report?.(`[A] streaming the OP profile supplement (${STATE})…`)
124
- const opByNPI = new Map<string, MessyRow>()
125
-
126
- for await (const r of streamRows(OP_PROFILE)) {
127
- if (opByNPI.size >= NPIS) break
128
- const npi = norm(r["Covered_Recipient_NPI"])
129
- const st = norm(r["Covered_Recipient_Profile_State"]).toUpperCase()
130
-
131
- if (!npi || st !== STATE || opByNPI.has(npi)) continue
132
-
133
- const name =
134
- `${norm(r["Covered_Recipient_Profile_First_Name"])} ${norm(r["Covered_Recipient_Profile_Last_Name"])}`.trim()
135
-
136
- const address = addr(
137
- r["Covered_Recipient_Profile_Address_Line_1"]!,
138
- r["Covered_Recipient_Profile_City"]!,
139
- st,
140
- r["Covered_Recipient_Profile_Zipcode"]!
141
- )
142
-
143
- if (!name || !address) continue
144
- opByNPI.set(npi, { npi, name, org: "", address, source: "openpayments" })
145
- }
146
-
147
- report?.(` ${opByNPI.size} OP ${STATE} practitioners`)
148
-
149
- // --- Phase B: the SAME NPIs from NPPES (practice address + legal name) + the corpus-wide
150
- // address-frequency table (one full registry pass, identical to train-gbt). ---
151
- report?.("[B] full registry pass: address-frequency table + the NPI-joined NPPES rows…")
152
- const rows: MessyRow[] = []
153
- const joined = new Set<string>()
154
- const addrCounts = new Map<string, number>()
155
- let addrTotal = 0
156
- let scanned = 0
157
-
158
- for await (const r of streamRows(REGISTRY)) {
159
- if (++scanned % 1_000_000 === 0) {
160
- report?.(` scanned ${scanned / 1e6}M, joined ${joined.size}`)
161
- }
162
-
163
- const practice = addr(r[N.pAddr]!, r[N.pCity]!, r[N.pState]!, r[N.pZip]!)
164
-
165
- if (practice) {
166
- const k = addressFrequencyKey(practice)
167
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
168
-
169
- addrTotal++
170
- }
171
-
172
- const npi = norm(r[N.npi])
173
-
174
- if (!npi || !opByNPI.has(npi) || joined.has(npi) || !practice) continue
175
-
176
- // Practitioner-level matching: OP covered recipients are individuals (entity type 1).
177
- if (norm(r[N.entityType]) !== "1") continue
178
- const name = `${norm(r[N.first])} ${norm(r[N.last])}`.trim()
179
-
180
- if (!name) continue
181
- joined.add(npi)
182
- rows.push({ npi, name, org: "", address: practice, source: "nppes" })
183
- }
184
-
185
- // Keep only NPIs present in BOTH sources — every record has a cross-source counterpart.
186
- for (const npi of joined) {
187
- rows.push(opByNPI.get(npi)!)
188
- }
189
-
190
- const addressFrequency = {
191
- total: addrTotal,
192
- distinct: addrCounts.size,
193
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
194
- }
195
-
196
- report?.(` ${joined.size} NPI-joined pairs → ${rows.length} records`)
197
-
198
- // --- Phase C: geocode + ingest (record.id = the NPI label; `source` rides the record). The heavy
199
- // geocoder is injected (see ./eval-geocoder.ts). ---
200
- report?.("[C] geocoding…")
201
- const geocoder = await options.createGeocoder()
202
-
203
- // `ColumnMapping.source` is a LITERAL provenance label — ingest each source separately so every
204
- // record carries its registry of origin (the cross-source filter + the sweep harness key on it).
205
- const mappingFor = (source: string): ColumnMapping => ({
206
- id: "npi",
207
- name: "name",
208
- organization: "org",
209
- address: "address",
210
- source,
211
- })
212
-
213
- const nppesRows = rows.filter((r) => r.source === "nppes")
214
- const opRows = rows.filter((r) => r.source === "openpayments")
215
-
216
- const records: SourceRecord[] = [
217
- ...(await ingestRows(nppesRows as unknown as Record<string, string>[], mappingFor("nppes"), {
218
- geocodeAddress: geocoder.seam,
219
- })),
220
- ...(await ingestRows(opRows as unknown as Record<string, string>[], mappingFor("openpayments"), {
221
- geocodeAddress: geocoder.seam,
222
- })),
223
- ]
224
-
225
- geocoder.close()
226
- report?.(` ${records.length} records, ${records.filter((r) => r.address?.geocode).length} geocoded`)
227
-
228
- // --- Phase D: block over the UNION; keep only CROSS-source pairs; featurize; label by NPI. ---
229
- report?.("[D] blocking + featurizing (cross-source pairs only)…")
230
- const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
231
- const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
232
- const { pairs: allPairs } = block(records, defaultBlockingKeys())
233
- const pairs = allPairs.filter(([a, b]) => a.source !== b.source)
234
- const X = pairs.map(([a, b]) => featurize(a, b))
235
- const Y: number[] = pairs.map(([a, b]) => (a.id === b.id ? 1 : 0))
236
- const posRate = Y.reduce((s, y) => s + y, 0) / Math.max(1, Y.length)
237
- const W = Y.map((y) => (y === 1 ? 1 - posRate : posRate))
238
-
239
- report?.(
240
- ` ${allPairs.length} blocked pairs → ${pairs.length} cross-source (${(100 * posRate).toFixed(1)}% positive)`
241
- )
242
-
243
- // --- Phase E: held-out-NPI calibration — the #655 threshold rule. ---
244
- report?.("[E] held-out calibration…")
245
- const hyperparams = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
246
- const rnd = makeLcg(655)
247
- const split = new Map<string, "fit" | "holdout">()
248
-
249
- for (const npi of joined) {
250
- split.set(npi, rnd() < FIT_SPLIT_FRACTION ? "fit" : "holdout")
251
- }
252
-
253
- const fitIdx = pairs
254
- .map((_, i) => i)
255
- .filter((i) => split.get(pairs[i]![0].id) === "fit" && split.get(pairs[i]![1].id) === "fit")
256
-
257
- const holdIdx = pairs
258
- .map((_, i) => i)
259
- .filter((i) => split.get(pairs[i]![0].id) === "holdout" && split.get(pairs[i]![1].id) === "holdout")
260
-
261
- const calib = trainGBT(
262
- fitIdx.map((i) => X[i]!),
263
- fitIdx.map((i) => Y[i]!),
264
- fitIdx.map((i) => W[i]!),
265
- hyperparams
266
- )
267
-
268
- const holdScores = holdIdx.map((i) => ({ s: gbtScore(calib, X[i]!), y: Y[i]! }))
269
- const sorted = holdScores.map((h) => h.s).toSorted((a, b) => a - b)
270
- const totalPos = holdScores.reduce((s, h) => s + h.y, 0)
271
- let recommendedThreshold = Number.POSITIVE_INFINITY
272
- let barRecall = 0
273
- let f1MaxThreshold = 0
274
- let bestF1 = -1
275
-
276
- for (const t of uniqueQuantiles(sorted, 60)) {
277
- let tp = 0
278
- let fp = 0
279
-
280
- for (const h of holdScores) {
281
- if (h.s < t) continue
282
-
283
- if (h.y) {
284
- tp++
285
- } else {
286
- fp++
287
- }
288
- }
289
-
290
- const precision = tp + fp > 0 ? tp / (tp + fp) : 1
291
- const recall = totalPos > 0 ? tp / totalPos : 0
292
- const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
293
-
294
- // The #655 rule: the LOWEST threshold whose precision clears the bar (maximizes recall under it).
295
- if (precision >= PRECISION_BAR && recall > barRecall) {
296
- barRecall = recall
297
- recommendedThreshold = t
298
- }
299
-
300
- if (f1 > bestF1) {
301
- bestF1 = f1
302
- f1MaxThreshold = t
303
- }
304
- }
305
-
306
- if (!Number.isFinite(recommendedThreshold)) {
307
- recommendedThreshold = f1MaxThreshold
308
- }
309
-
310
- report?.(
311
- ` held-out (${holdIdx.length} pairs, ${totalPos} pos): precision-bar ${PRECISION_BAR} → threshold ${recommendedThreshold.toFixed(3)} (recall ${(100 * barRecall).toFixed(1)}%); F1-max ${(100 * bestF1).toFixed(1)}% @ ${f1MaxThreshold.toFixed(3)}`
312
- )
313
-
314
- // --- Phase F: train the SHIPPED model on ALL cross-source pairs; emit the committed module. ---
315
- report?.("[F] training the shipped model on all pairs…")
316
- const model = trainGBT(X, Y, W, hyperparams)
317
-
318
- const meta = {
319
- version: "1.0.0",
320
- objective: "cross-source-link" as const,
321
- locale: LOCALE,
322
- trainedOn: TRAIN_DATE,
323
- state: STATE,
324
- npis: joined.size,
325
- records: records.length,
326
- pairs: pairs.length,
327
- posRate: Number(posRate.toFixed(4)),
328
- precisionBar: PRECISION_BAR,
329
- holdoutBarRecall: Number(barRecall.toFixed(4)),
330
- holdoutF1Max: Number(bestF1.toFixed(4)),
331
- hyperparams,
332
- recommendedThreshold: Number(recommendedThreshold.toFixed(4)),
333
- features: X[0]?.length ?? 0,
334
- sources: ["nppes", "openpayments"],
335
- }
336
-
337
- const moduleSource =
338
- `/**\n` +
339
- ` * @copyright Sister Software\n` +
340
- ` * @license AGPL-3.0\n` +
341
- ` * @author Teffen Ellis, et al.\n` +
342
- ` *\n` +
343
- ` * The CROSS-SOURCE link scorer (#655 option 2) — trained on NPI-joined NPPES ↔ Open Payments\n` +
344
- ` * pairs (the non-circular cross-registry anchor; both public domain). Scores "same provider,\n` +
345
- ` * different registry text" links the dedup GBT rejects by construction. Generated by\n` +
346
- ` * scripts/eval/record-matcher/train-cross-gbt.ts — retrain + re-run rather than editing.\n` +
347
- ` */\n\n` +
348
- `import type { GBT } from "@mailwoman/match"\n\n` +
349
- `export const CROSS_SOURCE_GBT_META = ${JSON.stringify(meta)} as const\n\n` +
350
- `// prettier-ignore\n` +
351
- `export const CROSS_SOURCE_GBT_MODEL: GBT = ${JSON.stringify(model)}\n`
352
-
353
- mkdirSync(dirname(OUT), { recursive: true })
354
- writeFileSync(OUT, moduleSource)
355
- report?.(` ${model.trees.length} trees, ${meta.features} features -> ${OUT}`)
356
-
357
- return { out: OUT, pairs: pairs.length, recommendedThreshold }
358
- }