@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
@@ -1,330 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Train the ORG-LEVEL cross-source link scorer (#655 follow-on, 2026-07-06). The practitioner
7
- * cross-source GBT does not transfer to organization records (its person-name features go dark),
8
- * so the org-level cross-dataset flows pin the FS baseline. The org anchor: **CMS Provider of
9
- * Services joins Care Compare by CCN** — the same facility in two separately-maintained CMS
10
- * systems (certification vs quality reporting), each with independently-entered name + address.
11
- * Measured drift across the national join (n≈5.4k): 12.2% name, 4.9% address — the rename /
12
- * system-vs-facility / acquisition class the org objective exists for.
13
- *
14
- * Pipeline: national CCN join → one record per source per facility → geocode → block the UNION,
15
- * keep only CROSS-source pairs → the SHARED featurizer → label by CCN → held-out-CCN calibration
16
- * (max recall s.t. precision ≥ bar) → train on all pairs → emit
17
- * `registry/models/org-crosssource-gbt-en-us.ts`.
18
- *
19
- * Sources (both public domain, direct CSVs):
20
- *
21
- * - `cms-pos_hospital-other_*.csv` — Provider of Services (PRVDR_NUM, FAC_NAME, ST_ADR…).
22
- * - `cms-carecompare_hospital-general_*.csv` — Care Compare (Facility ID, Facility Name, Address…).
23
- *
24
- * Run: `mailwoman registry train-scorer org-cross-gbt [--cap 6000] [--precision-bar 0.95]
25
- * [--wof <admin.db>] [--data-root <dir>] [--out registry/models/org-crosssource-gbt-en-us.ts]`
26
- */
27
-
28
- import { mkdirSync, writeFileSync } from "node:fs"
29
- import { dirname } from "node:path"
30
-
31
- import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
32
- import { block, gbtScore, trainGBT } from "@mailwoman/match"
33
-
34
- import {
35
- addressFrequencyKey,
36
- buildDefaultModel,
37
- createMatchFeaturizer,
38
- defaultBlockingKeys,
39
- ingestRows,
40
- streamRows,
41
- type ColumnMapping,
42
- type SourceRecord,
43
- } from "#index"
44
-
45
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
46
- import { addr, norm, uniqueQuantiles } from "./shared.ts"
47
-
48
- /**
49
- * Share of entities assigned to fit; the rest are held out.
50
- */
51
- const FIT_SPLIT_FRACTION = 0.8
52
-
53
- /**
54
- * Options for {@linkcode trainOrgCrossSourceGBT}.
55
- */
56
- export interface TrainOrgCrossSourceGBTOptions {
57
- /**
58
- * The injected geocoder factory (the command wires `mailwoman/geocode-core`; see `./eval-geocoder.ts`).
59
- */
60
- createGeocoder: EvalGeocoderFactory
61
- /**
62
- * Record-matcher sources directory. Default `$MAILWOMAN_DATA_ROOT/record-matcher/sources`.
63
- */
64
- sources?: string
65
- /**
66
- * Care Compare facilities sampled. Default 6000.
67
- */
68
- cap?: number
69
- /**
70
- * Output TS module path. Default `registry/models/org-crosssource-gbt-en-us.ts`.
71
- */
72
- out?: string
73
- /**
74
- * Locale recorded in the model meta. Default en-US.
75
- */
76
- locale?: string
77
- /**
78
- * #655 threshold rule: max cross-source recall subject to this held-out pairwise precision. Default 0.95.
79
- */
80
- precisionBar?: number
81
- /**
82
- * Training date stamped into the meta. Default today.
83
- */
84
- date?: string
85
- }
86
-
87
- interface MessyRow extends Record<string, string> {
88
- /**
89
- * The CCN — the cross-system facility key; rides `record.id` as the held-out label.
90
- */
91
- npi: string
92
- name: string
93
- org: string
94
- address: string
95
- source: string
96
- }
97
-
98
- /**
99
- * Train + emit the org-level cross-source link GBT — see the module doc.
100
- */
101
- export async function trainOrgCrossSourceGBT(
102
- options: TrainOrgCrossSourceGBTOptions,
103
- report?: (line: string) => void
104
- ): Promise<{ out: string; pairs: number; recommendedThreshold: number }> {
105
- const SOURCES = options.sources || String(dataRootPath("record-matcher", "sources"))
106
- const CAP = options.cap ?? 6000
107
- const OUT = options.out || "packages/registry/models/org-crosssource-gbt-en-us.ts"
108
- const LOCALE = options.locale || "en-US"
109
- // #655 threshold rule: max cross-source recall subject to this held-out pairwise precision.
110
- const PRECISION_BAR = options.precisionBar ?? 0.95
111
- const TRAIN_DATE = options.date || new Date().toISOString().slice(0, 10)
112
-
113
- const POS = `${SOURCES}/cms-pos_hospital-other_2026q1.csv`
114
- const CARE_COMPARE = `${SOURCES}/cms-carecompare_hospital-general_20260706.csv`
115
-
116
- // --- Phase A: Care Compare (Facility ID + name + address). ---
117
- report?.("[A] streaming Care Compare…")
118
- const ccByID = new Map<string, MessyRow>()
119
-
120
- for await (const r of streamRows(CARE_COMPARE)) {
121
- if (ccByID.size >= CAP) break
122
- const ccn = norm(r["Facility ID"])
123
- const name = norm(r["Facility Name"])
124
- const address = addr(r["Address"]!, r["City/Town"]!, r["State"]!, r["ZIP Code"]!)
125
-
126
- if (!ccn || !name || !address) continue
127
- ccByID.set(ccn, { npi: ccn, name, org: name, address, source: "care-compare" })
128
- }
129
-
130
- report?.(` ${ccByID.size} Care Compare facilities`)
131
-
132
- // --- Phase B: the SAME CCNs from the POS file + the corpus-wide address-frequency table. ---
133
- report?.("[B] streaming POS + building the frequency table…")
134
- const rows: MessyRow[] = []
135
- const joined = new Set<string>()
136
- const addrCounts = new Map<string, number>()
137
- let addrTotal = 0
138
-
139
- for await (const r of streamRows(POS)) {
140
- const address = addr(r["ST_ADR"]!, r["CITY_NAME"]!, r["STATE_CD"]!, r["ZIP_CD"]!)
141
-
142
- if (address) {
143
- const k = addressFrequencyKey(address)
144
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
145
-
146
- addrTotal++
147
- }
148
-
149
- const ccn = norm(r["PRVDR_NUM"])
150
-
151
- if (!ccn || !ccByID.has(ccn) || joined.has(ccn) || !address) continue
152
- const name = norm(r["FAC_NAME"])
153
-
154
- if (!name) continue
155
- joined.add(ccn)
156
- rows.push({ npi: ccn, name, org: name, address, source: "cms-pos" })
157
- }
158
-
159
- for (const ccn of joined) {
160
- rows.push(ccByID.get(ccn)!)
161
- }
162
-
163
- const addressFrequency = {
164
- total: addrTotal,
165
- distinct: addrCounts.size,
166
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
167
- }
168
-
169
- report?.(` ${joined.size} CCN-joined facilities → ${rows.length} records`)
170
-
171
- // --- Phase C: geocode + ingest (record.id = the NPI label; `source` rides the record). The heavy
172
- // geocoder is injected (see ./eval-geocoder.ts). ---
173
- report?.("[C] geocoding…")
174
- const geocoder = await options.createGeocoder()
175
-
176
- // `ColumnMapping.source` is a LITERAL provenance label — ingest each source separately so every
177
- // record carries its registry of origin (the cross-source filter + the sweep harness key on it).
178
- const mappingFor = (source: string): ColumnMapping => ({
179
- id: "npi",
180
- name: "name",
181
- organization: "org",
182
- address: "address",
183
- source,
184
- })
185
-
186
- const posRows = rows.filter((r) => r.source === "cms-pos")
187
- const ccRows = rows.filter((r) => r.source === "care-compare")
188
-
189
- const records: SourceRecord[] = [
190
- ...(await ingestRows(posRows, mappingFor("cms-pos"), {
191
- geocodeAddress: geocoder.seam,
192
- })),
193
- ...(await ingestRows(ccRows, mappingFor("care-compare"), {
194
- geocodeAddress: geocoder.seam,
195
- })),
196
- ]
197
-
198
- geocoder.close()
199
- report?.(` ${records.length} records, ${records.filter((r) => r.address?.geocode).length} geocoded`)
200
-
201
- // --- Phase D: block over the UNION; keep only CROSS-source pairs; featurize; label by NPI. ---
202
- report?.("[D] blocking + featurizing (cross-source pairs only)…")
203
- const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
204
- const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
205
- const { pairs: allPairs } = block(records, defaultBlockingKeys())
206
- const pairs = allPairs.filter(([a, b]) => a.source !== b.source)
207
- const X = pairs.map(([a, b]) => featurize(a, b))
208
- const Y: number[] = pairs.map(([a, b]) => (a.id === b.id ? 1 : 0))
209
- const posRate = Y.reduce((s, y) => s + y, 0) / Math.max(1, Y.length)
210
- const W = Y.map((y) => (y === 1 ? 1 - posRate : posRate))
211
-
212
- report?.(
213
- ` ${allPairs.length} blocked pairs → ${pairs.length} cross-source (${(100 * posRate).toFixed(1)}% positive)`
214
- )
215
-
216
- // --- Phase E: held-out-NPI calibration — the #655 threshold rule. ---
217
- report?.("[E] held-out calibration…")
218
- const hyperparams = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
219
- const rnd = makeLcg(655)
220
- const split = new Map<string, "fit" | "holdout">()
221
-
222
- for (const ccn of joined) {
223
- split.set(ccn, rnd() < FIT_SPLIT_FRACTION ? "fit" : "holdout")
224
- }
225
-
226
- const fitIdx = pairs
227
- .map((_, i) => i)
228
- .filter((i) => split.get(pairs[i]![0].id) === "fit" && split.get(pairs[i]![1].id) === "fit")
229
-
230
- const holdIdx = pairs
231
- .map((_, i) => i)
232
- .filter((i) => split.get(pairs[i]![0].id) === "holdout" && split.get(pairs[i]![1].id) === "holdout")
233
-
234
- const calib = trainGBT(
235
- fitIdx.map((i) => X[i]!),
236
- fitIdx.map((i) => Y[i]!),
237
- fitIdx.map((i) => W[i]!),
238
- hyperparams
239
- )
240
-
241
- const holdScores = holdIdx.map((i) => ({ s: gbtScore(calib, X[i]!), y: Y[i]! }))
242
- const sorted = holdScores.map((h) => h.s).toSorted((a, b) => a - b)
243
- const totalPos = holdScores.reduce((s, h) => s + h.y, 0)
244
- let recommendedThreshold = Number.POSITIVE_INFINITY
245
- let barRecall = 0
246
- let f1MaxThreshold = 0
247
- let bestF1 = -1
248
-
249
- for (const t of uniqueQuantiles(sorted, 60)) {
250
- let tp = 0
251
- let fp = 0
252
-
253
- for (const h of holdScores) {
254
- if (h.s < t) continue
255
-
256
- if (h.y) {
257
- tp++
258
- } else {
259
- fp++
260
- }
261
- }
262
-
263
- const precision = tp + fp > 0 ? tp / (tp + fp) : 1
264
- const recall = totalPos > 0 ? tp / totalPos : 0
265
- const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
266
-
267
- // The #655 rule: the LOWEST threshold whose precision clears the bar (maximizes recall under it).
268
- if (precision >= PRECISION_BAR && recall > barRecall) {
269
- barRecall = recall
270
- recommendedThreshold = t
271
- }
272
-
273
- if (f1 > bestF1) {
274
- bestF1 = f1
275
- f1MaxThreshold = t
276
- }
277
- }
278
-
279
- if (!Number.isFinite(recommendedThreshold)) {
280
- recommendedThreshold = f1MaxThreshold
281
- }
282
-
283
- report?.(
284
- ` 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)}`
285
- )
286
-
287
- // --- Phase F: train the SHIPPED model on ALL cross-source pairs; emit the committed module. ---
288
- report?.("[F] training the shipped model on all pairs…")
289
- const model = trainGBT(X, Y, W, hyperparams)
290
-
291
- const meta = {
292
- version: "1.0.0",
293
- objective: "org-cross-source-link" as const,
294
- locale: LOCALE,
295
- trainedOn: TRAIN_DATE,
296
- facilities: joined.size,
297
- records: records.length,
298
- pairs: pairs.length,
299
- posRate: Number(posRate.toFixed(4)),
300
- precisionBar: PRECISION_BAR,
301
- holdoutBarRecall: Number(barRecall.toFixed(4)),
302
- holdoutF1Max: Number(bestF1.toFixed(4)),
303
- hyperparams,
304
- recommendedThreshold: Number(recommendedThreshold.toFixed(4)),
305
- features: X[0]?.length ?? 0,
306
- sources: ["cms-pos", "care-compare"],
307
- }
308
-
309
- const moduleSource =
310
- `/**\n` +
311
- ` * @copyright Sister Software\n` +
312
- ` * @license AGPL-3.0\n` +
313
- ` * @author Teffen Ellis, et al.\n` +
314
- ` *\n` +
315
- ` * The ORG-LEVEL cross-source link scorer (#655 follow-on) — trained on CCN-joined CMS POS ↔\n` +
316
- ` * Care Compare facility pairs (both public domain). Scores "same facility, different registry\n` +
317
- ` * text" links for org-level cross-dataset flows. Generated by\n` +
318
- ` * \`mailwoman registry train-scorer org-cross-gbt\` (registry/tools/train-org-cross-gbt.ts) — retrain rather than editing.\n` +
319
- ` */\n\n` +
320
- `import type { GBT } from "@mailwoman/match"\n\n` +
321
- `export const ORG_CROSS_SOURCE_GBT_META = ${JSON.stringify(meta)} as const\n\n` +
322
- `// prettier-ignore\n` +
323
- `export const ORG_CROSS_SOURCE_GBT_MODEL: GBT = ${JSON.stringify(model)}\n`
324
-
325
- mkdirSync(dirname(OUT), { recursive: true })
326
- writeFileSync(OUT, moduleSource)
327
- report?.(` ${model.trees.length} trees, ${meta.features} features -> ${OUT}`)
328
-
329
- return { out: OUT, pairs: pairs.length, recommendedThreshold }
330
- }
@@ -1,113 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Render a self-contained Plotly HTML to a PNG via headless Chromium — the shared renderer behind
7
- * the `registry viz` figures (an internal helper, not a command).
8
- *
9
- * Plotly 3D (`surface`/`scatter3d`) needs a real WebGL context; headless Chromium has none by
10
- * default, so we force ANGLE's SwiftShader software rasterizer (`--use-gl=angle
11
- * --use-angle=swiftshader --enable-unsafe-swiftshader`). 2D traces (`contour`/`heatmap`) render
12
- * on the 2D canvas regardless. We wait for Plotly's `plotly_afterplot` to fire on every graph div
13
- * rather than a fixed sleep, so the screenshot can't race the (async) WebGL paint.
14
- *
15
- * Playwright (headless Chromium) is a heavy dev-only dependency — lazy-imported inside the entry
16
- * fn (the corpus-tools lazy-import convention), so importing `@mailwoman/registry/tools` never
17
- * pays for it.
18
- */
19
-
20
- import { resolve } from "node:path"
21
- import { pathToFileURL } from "node:url"
22
-
23
- /**
24
- * Options for {@linkcode renderPlotlyHTMLToPNG}.
25
- */
26
- export interface RenderPlotlyOptions {
27
- /**
28
- * The self-contained Plotly HTML file.
29
- */
30
- inHTML: string
31
- /**
32
- * Output PNG path.
33
- */
34
- outPNG: string
35
- /**
36
- * Viewport width. Default 1160.
37
- */
38
- width?: number
39
- /**
40
- * Viewport height. Default 1000.
41
- */
42
- height?: number
43
- }
44
-
45
- /**
46
- * Screenshot a Plotly HTML page after every graph div's `plotly_afterplot` fires.
47
- */
48
- export async function renderPlotlyHTMLToPNG(
49
- options: RenderPlotlyOptions,
50
- report?: (line: string) => void
51
- ): Promise<{ outPNG: string; consoleErrors: string[] }> {
52
- // playwright + Chromium are heavy — lazy import (the pipeline convention).
53
- const { chromium } = await import("playwright")
54
-
55
- const browser = await chromium.launch({
56
- args: ["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"],
57
- })
58
-
59
- const page = await browser.newPage({
60
- viewport: { width: options.width ?? 1160, height: options.height ?? 1000 },
61
- deviceScaleFactor: 2,
62
- })
63
-
64
- const errors: string[] = []
65
- page.on("console", (m) => m.type() === "error" && errors.push(m.text()))
66
- page.on("pageerror", (e) => errors.push(String(e)))
67
-
68
- await page.goto(pathToFileURL(resolve(options.inHTML)).href, { waitUntil: "networkidle" })
69
-
70
- // Resolve once every Plotly graph div has fired plotly_afterplot (3D paints land async, after
71
- // newPlot's promise resolves), with a per-div fallback so an already-painted div can't hang us.
72
- await page.evaluate(async () => {
73
- // Runs in the BROWSER — reach DOM/Plotly globals via globalThis so the script needs no DOM lib.
74
- interface PlotlyDiv {
75
- _fullLayout?: unknown
76
- on?: (event: string, cb: () => void) => void
77
- }
78
-
79
- const doc = Reflect.get(globalThis, "document") as { querySelectorAll(s: string): Iterable<unknown> }
80
-
81
- const divs = [...doc.querySelectorAll("div")]
82
- .map((d) => d as PlotlyDiv)
83
- .filter((d) => d._fullLayout && typeof d.on === "function")
84
-
85
- await Promise.all(
86
- divs.map(
87
- (d) =>
88
- new Promise<void>((res) => {
89
- d.on!("plotly_afterplot", () => res())
90
- setTimeout(() => res(), 2000)
91
- })
92
- )
93
- )
94
- })
95
-
96
- // Final settle for the software WebGL rasterizer.
97
- await page.waitForTimeout(800)
98
-
99
- await page.screenshot({ path: resolve(options.outPNG), fullPage: true })
100
- await browser.close()
101
-
102
- if (errors.length) {
103
- report?.(`[render] ${errors.length} console error(s):`)
104
-
105
- for (const e of errors.slice(0, 8)) {
106
- report?.(" " + e)
107
- }
108
- }
109
-
110
- report?.(`[render] ${options.outPNG}`)
111
-
112
- return { outPNG: options.outPNG, consoleErrors: errors }
113
- }
File without changes
File without changes
File without changes
File without changes