@mailwoman/registry 8.6.0 → 9.1.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 (98) hide show
  1. package/README.md +62 -36
  2. package/ingest.ts +7 -2
  3. package/learned-scorer.ts +2 -2
  4. package/models/dedup-gbt-en-us.ts +1 -1
  5. package/out/ingest.d.ts +3 -0
  6. package/out/ingest.d.ts.map +1 -1
  7. package/out/ingest.js +4 -2
  8. package/out/ingest.js.map +1 -1
  9. package/out/learned-scorer.d.ts +2 -2
  10. package/out/learned-scorer.js +2 -2
  11. package/out/models/dedup-gbt-en-us.d.ts +1 -1
  12. package/out/models/dedup-gbt-en-us.js +1 -1
  13. package/out/resolve.js +2 -2
  14. package/out/tools/coverage-reconciliation.d.ts.map +1 -1
  15. package/out/tools/coverage-reconciliation.js +1 -47
  16. package/out/tools/coverage-reconciliation.js.map +1 -1
  17. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  18. package/out/tools/cross-dataset-correlation.js +1 -1
  19. package/out/tools/cross-dataset-correlation.js.map +1 -1
  20. package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -1
  21. package/out/tools/cross-source-threshold-sweep.js +4 -50
  22. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  23. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  24. package/out/tools/dedup-ceiling.js +2 -11
  25. package/out/tools/dedup-ceiling.js.map +1 -1
  26. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  27. package/out/tools/geocoder-vs-provided-coords.js +12 -1
  28. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  29. package/out/tools/gold-set-sample.d.ts +1 -1
  30. package/out/tools/gold-set-sample.d.ts.map +1 -1
  31. package/out/tools/gold-set-sample.js +3 -12
  32. package/out/tools/gold-set-sample.js.map +1 -1
  33. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  34. package/out/tools/learned-scorer-clustering-eval.js +3 -44
  35. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  36. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  37. package/out/tools/learned-scorer-crossstate-eval.js +3 -34
  38. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  39. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  40. package/out/tools/learned-scorer-eval.js +3 -38
  41. package/out/tools/learned-scorer-eval.js.map +1 -1
  42. package/out/tools/matcher-scale.d.ts.map +1 -1
  43. package/out/tools/matcher-scale.js +2 -11
  44. package/out/tools/matcher-scale.js.map +1 -1
  45. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  46. package/out/tools/nppes-dedup-benchmark.js +8 -46
  47. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  48. package/out/tools/shared.d.ts +92 -0
  49. package/out/tools/shared.d.ts.map +1 -0
  50. package/out/tools/shared.js +139 -0
  51. package/out/tools/shared.js.map +1 -0
  52. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  53. package/out/tools/train-cross-gbt.js +4 -99
  54. package/out/tools/train-cross-gbt.js.map +1 -1
  55. package/out/tools/train-gbt.d.ts.map +1 -1
  56. package/out/tools/train-gbt.js +4 -49
  57. package/out/tools/train-gbt.js.map +1 -1
  58. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  59. package/out/tools/train-org-cross-gbt.js +6 -92
  60. package/out/tools/train-org-cross-gbt.js.map +1 -1
  61. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  62. package/out/tools/txhhsc-to-oarow.js +20 -11
  63. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  64. package/out/tools/viz/cross-dataset-map.d.ts +2 -2
  65. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  66. package/out/tools/viz/cross-dataset-map.js +4 -3
  67. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  68. package/out/tools/viz/geocode-first-surface.d.ts +2 -2
  69. package/out/tools/viz/geocode-first-surface.js +2 -2
  70. package/out/tools/viz/source-provenance-map.d.ts +2 -2
  71. package/out/tools/viz/source-provenance-map.js +3 -3
  72. package/out/tools/viz/source-provenance-map.js.map +1 -1
  73. package/out/tools/viz/yardstick-figure.d.ts +6 -6
  74. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  75. package/out/tools/viz/yardstick-figure.js +6 -5
  76. package/out/tools/viz/yardstick-figure.js.map +1 -1
  77. package/package.json +9 -10
  78. package/resolve.ts +2 -2
  79. package/tools/coverage-reconciliation.ts +1 -57
  80. package/tools/cross-dataset-correlation.ts +1 -2
  81. package/tools/cross-source-threshold-sweep.ts +4 -60
  82. package/tools/dedup-ceiling.ts +3 -14
  83. package/tools/geocoder-vs-provided-coords.ts +12 -2
  84. package/tools/gold-set-sample.ts +5 -16
  85. package/tools/learned-scorer-clustering-eval.ts +11 -54
  86. package/tools/learned-scorer-crossstate-eval.ts +11 -41
  87. package/tools/learned-scorer-eval.ts +3 -47
  88. package/tools/matcher-scale.ts +2 -14
  89. package/tools/nppes-dedup-benchmark.ts +8 -53
  90. package/tools/shared.ts +160 -0
  91. package/tools/train-cross-gbt.ts +4 -114
  92. package/tools/train-gbt.ts +4 -59
  93. package/tools/train-org-cross-gbt.ts +6 -105
  94. package/tools/txhhsc-to-oarow.ts +23 -13
  95. package/tools/viz/cross-dataset-map.ts +7 -6
  96. package/tools/viz/geocode-first-surface.ts +4 -4
  97. package/tools/viz/source-provenance-map.ts +5 -5
  98. package/tools/viz/yardstick-figure.ts +9 -8
@@ -37,7 +37,7 @@
37
37
 
38
38
  import { writeFileSync } from "node:fs"
39
39
 
40
- import { dataRootPath } from "@mailwoman/core/utils"
40
+ import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
41
41
  import { agreementPattern, block, estimateParameters, gbtScore, scorePair, trainGBT } from "@mailwoman/match"
42
42
  import {
43
43
  addressFrequencyKey,
@@ -50,6 +50,7 @@ import {
50
50
  } from "@mailwoman/registry"
51
51
 
52
52
  import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
53
+ import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C, TRAINING_EPOCHS } from "./shared.ts"
53
54
 
54
55
  /**
55
56
  * Smallest mean gap counted as a real difference rather than seed noise.
@@ -76,16 +77,6 @@ const STRONG_EVIDENCE_Z = 3
76
77
  */
77
78
  const TRAIN_SPLIT_FRACTION = 0.67
78
79
 
79
- /**
80
- * Groups below this size are too small for a held-out split to mean anything.
81
- */
82
- const MIN_GROUP_SIZE = 5
83
-
84
- /**
85
- * Gradient-boosting rounds. Fixed rather than early-stopped so seeds stay comparable.
86
- */
87
- const TRAINING_EPOCHS = 400
88
-
89
80
  /**
90
81
  * Highest k swept when scanning cluster counts.
91
82
  */
@@ -125,41 +116,6 @@ export interface ScorerPairwiseEvalOptions {
125
116
  outMd?: string
126
117
  }
127
118
 
128
- const C = {
129
- npi: "NPI",
130
- entityType: "Entity Type Code",
131
- orgLegal: "Provider Organization Name (Legal Business Name)",
132
- last: "Provider Last Name (Legal Name)",
133
- first: "Provider First Name",
134
- pAddr: "Provider First Line Business Practice Location Address",
135
- pCity: "Provider Business Practice Location Address City Name",
136
- pState: "Provider Business Practice Location Address State Name",
137
- pZip: "Provider Business Practice Location Address Postal Code",
138
- mAddr: "Provider First Line Business Mailing Address",
139
- mCity: "Provider Business Mailing Address City Name",
140
- mState: "Provider Business Mailing Address State Name",
141
- mZip: "Provider Business Mailing Address Postal Code",
142
- otherOrg: "Provider Other Organization Name",
143
- }
144
-
145
- const norm = (s: string | undefined) => (s ?? "").trim()
146
-
147
- const addr = (line: string, city: string, st: string, zip: string) =>
148
- [norm(line), norm(city), norm(st), norm(zip)].filter(Boolean).join(", ")
149
-
150
- /**
151
- * Deterministic LCG (no Math.random — reproducible split).
152
- */
153
- function lcg(seed: number): () => number {
154
- let s = seed >>> 0 || 1
155
-
156
- return () => {
157
- s = (Math.imul(s, 1_664_525) + 1_013_904_223) >>> 0
158
-
159
- return s / 0x1_00_00_00_00
160
- }
161
- }
162
-
163
119
  interface MessyRow {
164
120
  npi: string
165
121
  name: string
@@ -379,7 +335,7 @@ export async function scorerPairwiseEval(
379
335
  * pairs); only the LR weights and the test subset move with the seed, so repeating over seeds bounds split variance.
380
336
  */
381
337
  function runSplit(seed: number): SplitScored {
382
- const rnd = lcg(seed)
338
+ const rnd = makeLcg(seed || 1)
383
339
  const npiSplit = new Map<string, "train" | "test">()
384
340
 
385
341
  for (const npi of keptNPIs) {
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { writeFileSync } from "node:fs"
20
20
 
21
+ import { makeLcg } from "@mailwoman/core/utils"
21
22
  import { resolveEntities, type SourceRecord } from "@mailwoman/registry"
22
23
 
23
24
  /**
@@ -42,19 +43,6 @@ export interface MatcherScaleOptions {
42
43
  outMd?: string
43
44
  }
44
45
 
45
- /**
46
- * Deterministic LCG so the eval is reproducible run to run (no Math.random).
47
- */
48
- function lcg(seed: number): () => number {
49
- let s = seed >>> 0
50
-
51
- return () => {
52
- s = (Math.imul(s, 1_664_525) + 1_013_904_223) >>> 0
53
-
54
- return s / 0x1_00_00_00_00
55
- }
56
- }
57
-
58
46
  /**
59
47
  * Generate N synthetic records clustered into ~N/DUP distinct "places". Each place gets a coordinate in the
60
48
  * continental-US box, a canonical key, and an org name; its DUP duplicates carry a lightly-varied name and a jittered
@@ -62,7 +50,7 @@ function lcg(seed: number): () => number {
62
50
  * workload.
63
51
  */
64
52
  function generate(n: number, dup: number, seed = 1): SourceRecord[] {
65
- const rnd = lcg(seed)
53
+ const rnd = makeLcg(seed || 1)
66
54
  const places = Math.max(1, Math.round(n / dup))
67
55
  const records: SourceRecord[] = new Array(n)
68
56
 
@@ -31,7 +31,7 @@ import { resolve as resolvePath } from "node:path"
31
31
  import { pathToFileURL } from "node:url"
32
32
 
33
33
  import { dataRootPath } from "@mailwoman/core/utils"
34
- import { haversineKm, type GBT } from "@mailwoman/match"
34
+ import { haversineKm, jaccard, type GBT } from "@mailwoman/match"
35
35
  import {
36
36
  addressFrequencyKey,
37
37
  ingestRows,
@@ -45,11 +45,7 @@ import {
45
45
  import { latLngToCell } from "h3-js"
46
46
 
47
47
  import type { EvalGeocodeStream, EvalGeocoderFactory } from "./eval-geocoder.ts"
48
-
49
- /**
50
- * Groups below this size are too small for a held-out split to mean anything.
51
- */
52
- const MIN_GROUP_SIZE = 5
48
+ import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C } from "./shared.ts"
53
49
 
54
50
  /**
55
51
  * F1 gap within which two blocking strategies are treated as equivalent.
@@ -122,35 +118,6 @@ export interface NPPESDedupBenchmarkOptions {
122
118
  /**
123
119
  * NPPES column names (verbatim from the file headers).
124
120
  */
125
- const C = {
126
- npi: "NPI",
127
- entityType: "Entity Type Code",
128
- orgLegal: "Provider Organization Name (Legal Business Name)",
129
- last: "Provider Last Name (Legal Name)",
130
- first: "Provider First Name",
131
- pAddr: "Provider First Line Business Practice Location Address",
132
- pCity: "Provider Business Practice Location Address City Name",
133
- pState: "Provider Business Practice Location Address State Name",
134
- pZip: "Provider Business Practice Location Address Postal Code",
135
- mAddr: "Provider First Line Business Mailing Address",
136
- mCity: "Provider Business Mailing Address City Name",
137
- mState: "Provider Business Mailing Address State Name",
138
- mZip: "Provider Business Mailing Address Postal Code",
139
- otherOrg: "Provider Other Organization Name",
140
- authLast: "Authorized Official Last Name",
141
- authFirst: "Authorized Official First Name",
142
- isSubpart: "Is Organization Subpart",
143
- parentLBN: "Parent Organization LBN",
144
- parentTIN: "Parent Organization TIN",
145
- // #625 taxonomy discriminator: the 15 taxonomy slots; collected as a set (any shared code = agreement).
146
- taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
147
- }
148
-
149
- const norm = (s: string | undefined) => (s ?? "").trim()
150
-
151
- const addr = (line: string, city: string, st: string, zip: string) =>
152
- [norm(line), norm(city), norm(st), norm(zip)].filter(Boolean).join(", ")
153
-
154
121
  /**
155
122
  * Org-name similarity for the org-name entity-truth (the gold-set rule: same address + same org name ⇒ same entity,
156
123
  * even when NPPES doesn't flag the subpart). Strip corporate-form + articles, keep domain words (the distinguishing
@@ -183,18 +150,6 @@ const orgTokens = (s: string): Set<string> =>
183
150
  .filter((t) => t && !ORG_STOP.has(t))
184
151
  )
185
152
 
186
- function orgJaccard(a: Set<string>, b: Set<string>): number {
187
- if (!a.size || !b.size) return 0
188
- let inter = 0
189
-
190
- for (const t of a)
191
- if (b.has(t)) {
192
- inter++
193
- }
194
-
195
- return inter / (a.size + b.size - inter)
196
- }
197
-
198
153
  /**
199
154
  * Gold-set threshold.
200
155
  */
@@ -575,7 +530,7 @@ export async function nppesDedupBenchmark(
575
530
  for (const group of byAddr.values()) {
576
531
  for (let i = 0; i < group.length; i++) {
577
532
  for (let j = i + 1; j < group.length; j++) {
578
- if (orgJaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
533
+ if (jaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
579
534
  union(group[i]!, group[j]!)
580
535
  }
581
536
  }
@@ -650,7 +605,7 @@ export async function nppesDedupBenchmark(
650
605
 
651
606
  if (haversineKm(npiCoord.get(a)!, npiCoord.get(b)!) > COLOCATION_KM) continue
652
607
 
653
- if (orgJaccard(npiPrimary.get(a)!.tokens, npiPrimary.get(b)!.tokens) >= ORG_TAU) {
608
+ if (jaccard(npiPrimary.get(a)!.tokens, npiPrimary.get(b)!.tokens) >= ORG_TAU) {
654
609
  unionC(a, b)
655
610
  }
656
611
  }
@@ -659,7 +614,7 @@ export async function nppesDedupBenchmark(
659
614
  const geocodedNpis = [...npiPrimary.keys()].filter((n) => npiCoord.has(n)).length
660
615
  const orgNameCoordLabel = (rec: SourceRecord) => (npiPrimary.has(rec.id) ? findC(rec.id) : rec.id)
661
616
 
662
- // --- ORG-NAME-H3 entity-truth (Task 4, #109). The same building-grain co-location, but keyed on an
617
+ // --- ORG-NAME-H3 entity-truth (#109). The same building-grain co-location, but keyed on an
663
618
  // H3 CELL (the geocode-first "cell" the issue suggested) instead of a pairwise 50 m haversine: assign
664
619
  // each NPI's coordinate to an H3 cell at building-block resolution, then union same-org (Jaccard ≥
665
620
  // ORG_TAU) NPIs that share a cell. A robustness check on the haversine coord-grain — if the F1
@@ -718,7 +673,7 @@ export async function nppesDedupBenchmark(
718
673
  for (const group of byCell.values()) {
719
674
  for (let i = 0; i < group.length; i++) {
720
675
  for (let j = i + 1; j < group.length; j++) {
721
- if (orgJaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
676
+ if (jaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
722
677
  unionH(group[i]!, group[j]!)
723
678
  }
724
679
  }
@@ -877,7 +832,7 @@ export async function nppesDedupBenchmark(
877
832
  const orgCoordCount = new Set(records.map((r) => orgNameCoordLabel(r))).size
878
833
  const fsOrgCoord = scoreEntities(bestLever.res.entities, orgNameCoordLabel)
879
834
  const gbtOrgCoord = scoreEntities(gbtRes.entities, orgNameCoordLabel)
880
- // Task 4 (#109): the H3-cell co-location truth — a robustness check on the haversine coord-grain.
835
+ // #109: the H3-cell co-location truth — a robustness check on the haversine coord-grain.
881
836
  const orgH3Count = new Set(records.map((r) => orgNameH3Label(r))).size
882
837
  const gbtOrgH3 = scoreEntities(gbtRes.entities, orgNameH3Label)
883
838
 
@@ -1147,7 +1102,7 @@ export async function nppesDedupBenchmark(
1147
1102
  lines.push("")
1148
1103
 
1149
1104
  lines.push(
1150
- `**Task 4 (#109) — H3-cell robustness check.** Re-keying the same building-grain co-location on an H3 cell ` +
1105
+ `**H3-cell robustness check (#109).** Re-keying the same building-grain co-location on an H3 cell ` +
1151
1106
  `(res ${H3_RES}) instead of the 50 m haversine radius — the deterministic, O(n) "geocode-first cell" the issue ` +
1152
1107
  `suggested — gives GBT **org-name-h3 ${pct(gbtOrgH3.f1)}%** (${orgH3Count} classes), vs the haversine ` +
1153
1108
  `${pct(gbtOrgCoord.f1)}% (${orgCoordCount}). ${
@@ -0,0 +1,160 @@
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
+ ]
@@ -33,7 +33,7 @@
33
33
  import { mkdirSync, writeFileSync } from "node:fs"
34
34
  import { dirname } from "node:path"
35
35
 
36
- import { dataRootPath } from "@mailwoman/core/utils"
36
+ import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
37
37
  import { block, gbtScore, trainGBT } from "@mailwoman/match"
38
38
  import {
39
39
  addressFrequencyKey,
@@ -45,9 +45,9 @@ import {
45
45
  type ColumnMapping,
46
46
  type SourceRecord,
47
47
  } from "@mailwoman/registry"
48
- import { TextSpliterator } from "spliterator"
49
48
 
50
49
  import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
50
+ import { addr, norm, NPPES_COLUMNS as N, uniqueQuantiles } from "./shared.ts"
51
51
 
52
52
  /**
53
53
  * Share of entities assigned to fit; the rest are held out.
@@ -92,22 +92,6 @@ export interface TrainCrossSourceGBTOptions {
92
92
  date?: string
93
93
  }
94
94
 
95
- const N = {
96
- npi: "NPI",
97
- entityType: "Entity Type Code",
98
- last: "Provider Last Name (Legal Name)",
99
- first: "Provider First Name",
100
- pAddr: "Provider First Line Business Practice Location Address",
101
- pCity: "Provider Business Practice Location Address City Name",
102
- pState: "Provider Business Practice Location Address State Name",
103
- pZip: "Provider Business Practice Location Address Postal Code",
104
- }
105
-
106
- const norm = (s: string | undefined) => (s ?? "").trim()
107
-
108
- const addr = (line: string, city: string, st: string, zip: string) =>
109
- [norm(line), norm(city), norm(st), norm(zip)].filter(Boolean).join(", ")
110
-
111
95
  interface MessyRow {
112
96
  npi: string
113
97
  name: string
@@ -116,100 +100,6 @@ interface MessyRow {
116
100
  source: string
117
101
  }
118
102
 
119
- /**
120
- * Deterministic LCG (no Math.random — reproducible split + commit).
121
- */
122
- function lcg(seed: number): () => number {
123
- let s = seed >>> 0 || 1
124
-
125
- return () => {
126
- s = (Math.imul(s, 1_664_525) + 1_013_904_223) >>> 0
127
-
128
- return s / 0x1_00_00_00_00
129
- }
130
- }
131
-
132
- /**
133
- * Up to `n` unique sorted-quantile values from a sorted score array — link-threshold candidates.
134
- */
135
- function uniqueQuantiles(sorted: number[], n: number): number[] {
136
- if (!sorted.length) return [0]
137
- const ts = new Set<number>()
138
-
139
- for (let k = 0; k <= n; k++) {
140
- ts.add(sorted[Math.floor((k / n) * (sorted.length - 1))]!)
141
- }
142
-
143
- return [...ts]
144
- }
145
-
146
- /**
147
- * Stream a comma CSV with quoted fields (the OP profile format) as header-keyed rows.
148
- */
149
- async function* streamCSV(path: string): AsyncGenerator<Record<string, string>> {
150
- // spliterator owns the line layer (crlf keeps header keys + the last column clean on CRLF sources);
151
- // the manual quote/pending re-join + tokenizer below stays deliberately — spliterator ≥ 3.2.0 CAN
152
- // do quote handling end-to-end, but this parse feeds model training, so its byte-for-byte behavior
153
- // is pinned until a re-validation run signs off a swap. Default skipEmpty drops truly-empty lines,
154
- // so a trailing newline can't inject a spurious empty row.
155
- let header: string[] | null = null
156
- let pending = ""
157
-
158
- for await (const rawLine of TextSpliterator.fromAsync(path, { crlf: true })) {
159
- // Re-join physical lines until quotes balance (quoted fields may contain newlines).
160
- pending = pending ? `${pending}\n${rawLine}` : rawLine
161
- const quotes = (pending.match(/"/g) ?? []).length
162
-
163
- if (quotes % 2 === 1) continue
164
- const line = pending
165
- pending = ""
166
- const cells: string[] = []
167
- let cur = ""
168
- let inQ = false
169
-
170
- for (let i = 0; i < line.length; i++) {
171
- const ch = line[i]!
172
-
173
- if (inQ) {
174
- if (ch === '"') {
175
- if (line[i + 1] === '"') {
176
- cur += '"'
177
-
178
- i++
179
- } else {
180
- inQ = false
181
- }
182
- } else {
183
- cur += ch
184
- }
185
- } else if (ch === '"') {
186
- inQ = true
187
- } else if (ch === ",") {
188
- cells.push(cur)
189
- cur = ""
190
- } else {
191
- cur += ch
192
- }
193
- }
194
-
195
- cells.push(cur)
196
-
197
- if (!header) {
198
- header = cells
199
-
200
- continue
201
- }
202
-
203
- const row: Record<string, string> = {}
204
-
205
- for (let i = 0; i < header.length; i++) {
206
- row[header[i]!] = cells[i] ?? ""
207
- }
208
-
209
- yield row
210
- }
211
- }
212
-
213
103
  /**
214
104
  * Train + emit the cross-source link GBT — see the module doc.
215
105
  */
@@ -233,7 +123,7 @@ export async function trainCrossSourceGBT(
233
123
  report?.(`[A] streaming the OP profile supplement (${STATE})…`)
234
124
  const opByNPI = new Map<string, MessyRow>()
235
125
 
236
- for await (const r of streamCSV(OP_PROFILE)) {
126
+ for await (const r of streamRows(OP_PROFILE)) {
237
127
  if (opByNPI.size >= NPIS) break
238
128
  const npi = norm(r["Covered_Recipient_NPI"])
239
129
  const st = norm(r["Covered_Recipient_Profile_State"]).toUpperCase()
@@ -353,7 +243,7 @@ export async function trainCrossSourceGBT(
353
243
  // --- Phase E: held-out-NPI calibration — the #655 threshold rule. ---
354
244
  report?.("[E] held-out calibration…")
355
245
  const hyperparams = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
356
- const rnd = lcg(655)
246
+ const rnd = makeLcg(655)
357
247
  const split = new Map<string, "fit" | "holdout">()
358
248
 
359
249
  for (const npi of joined) {
@@ -21,7 +21,7 @@
21
21
  import { mkdirSync, writeFileSync } from "node:fs"
22
22
  import { dirname } from "node:path"
23
23
 
24
- import { dataRootPath } from "@mailwoman/core/utils"
24
+ import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
25
25
  import { block, gbtScore, trainGBT } from "@mailwoman/match"
26
26
  import {
27
27
  addressFrequencyKey,
@@ -36,17 +36,13 @@ import {
36
36
  } from "@mailwoman/registry"
37
37
 
38
38
  import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
39
+ import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C, uniqueQuantiles } from "./shared.ts"
39
40
 
40
41
  /**
41
42
  * Share of entities assigned to fit; the rest are held out.
42
43
  */
43
44
  const FIT_SPLIT_FRACTION = 0.8
44
45
 
45
- /**
46
- * Groups below this size are too small for a held-out split to mean anything.
47
- */
48
- const MIN_GROUP_SIZE = 5
49
-
50
46
  /**
51
47
  * Options for {@linkcode trainDedupGBT}.
52
48
  */
@@ -87,30 +83,6 @@ export interface TrainDedupGBTOptions {
87
83
  date?: string
88
84
  }
89
85
 
90
- const C = {
91
- npi: "NPI",
92
- entityType: "Entity Type Code",
93
- orgLegal: "Provider Organization Name (Legal Business Name)",
94
- last: "Provider Last Name (Legal Name)",
95
- first: "Provider First Name",
96
- pAddr: "Provider First Line Business Practice Location Address",
97
- pCity: "Provider Business Practice Location Address City Name",
98
- pState: "Provider Business Practice Location Address State Name",
99
- pZip: "Provider Business Practice Location Address Postal Code",
100
- mAddr: "Provider First Line Business Mailing Address",
101
- mCity: "Provider Business Mailing Address City Name",
102
- mState: "Provider Business Mailing Address State Name",
103
- mZip: "Provider Business Mailing Address Postal Code",
104
- otherOrg: "Provider Other Organization Name",
105
- authLast: "Authorized Official Last Name",
106
- authFirst: "Authorized Official First Name",
107
- }
108
-
109
- const norm = (s: string | undefined) => (s ?? "").trim()
110
-
111
- const addr = (line: string, city: string, st: string, zip: string) =>
112
- [norm(line), norm(city), norm(st), norm(zip)].filter(Boolean).join(", ")
113
-
114
86
  interface MessyRow {
115
87
  npi: string
116
88
  name: string
@@ -122,33 +94,6 @@ interface MessyRow {
122
94
  auth: string
123
95
  }
124
96
 
125
- /**
126
- * Deterministic LCG (no Math.random — reproducible split + commit).
127
- */
128
- function lcg(seed: number): () => number {
129
- let s = seed >>> 0 || 1
130
-
131
- return () => {
132
- s = (Math.imul(s, 1_664_525) + 1_013_904_223) >>> 0
133
-
134
- return s / 0x1_00_00_00_00
135
- }
136
- }
137
-
138
- /**
139
- * Up to `n` unique sorted-quantile values from a sorted score array — link-threshold candidates.
140
- */
141
- function uniqueQuantiles(sorted: number[], n: number): number[] {
142
- if (!sorted.length) return [0]
143
- const ts = new Set<number>()
144
-
145
- for (let k = 0; k <= n; k++) {
146
- ts.add(sorted[Math.floor((k / n) * (sorted.length - 1))]!)
147
- }
148
-
149
- return [...ts]
150
- }
151
-
152
97
  /**
153
98
  * Pairwise clustering F1 of resolved entities vs the NPI grouping (record.id = the NPI).
154
99
  */
@@ -326,7 +271,7 @@ export async function trainDedupGBT(
326
271
  // CLUSTERING threshold on the held-out 20% (the metric resolveEntities actually optimizes) for F1-max.
327
272
  // The shipped full-data model has near-identical logit calibration, so the threshold transfers. ---
328
273
  report?.("[E] calibrating the default link threshold on a held-out NPI split…")
329
- const rnd = lcg(20_260_615)
274
+ const rnd = makeLcg(20_260_615)
330
275
  const split = new Map<string, "fit" | "holdout">()
331
276
 
332
277
  for (const npi of kept) {
@@ -404,7 +349,7 @@ export async function trainDedupGBT(
404
349
  ` * The default learned-scorer model (#603): a gradient-boosted-tree dedup scorer trained on the\n` +
405
350
  ` * NPPES NPI-truth set (${STATE}, ${kept.size} NPIs → ${pairs.length} candidate pairs). Validated to\n` +
406
351
  ` * generalize across states by learned-scorer-crossstate-eval.ts. Used by resolveEntities'\n` +
407
- ` * opt-in learnedScorer hook via createGbtScorer. The trained {@link GBT} is plain data.\n` +
352
+ ` * opt-in learnedScorer hook via createGBTScorer. The trained {@link GBT} is plain data.\n` +
408
353
  ` */\n\n` +
409
354
  `import type { GBT } from "@mailwoman/match"\n\n` +
410
355
  `/** Provenance for the bundled model — what it was trained on. */\n` +