@mailwoman/registry 9.2.0 → 9.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/{address-key.ts → lib/address-key.ts} +1 -1
- package/{geocode-handler.ts → lib/geocode-handler.ts} +7 -7
- package/{geojson.ts → lib/geojson.ts} +9 -4
- package/{index.ts → lib/index.ts} +10 -10
- package/{ingest.ts → lib/ingest.ts} +75 -68
- package/{learned-scorer.ts → lib/learned-scorer.ts} +1 -1
- package/{map-html.ts → lib/map-html.ts} +7 -13
- package/{reconcile.ts → lib/reconcile.ts} +7 -23
- package/{resolve.ts → lib/resolve.ts} +25 -12
- package/{tools → lib/tools}/coverage-reconciliation.ts +12 -14
- package/{tools → lib/tools}/cross-dataset-correlation.ts +60 -137
- package/{tools → lib/tools}/cross-source-threshold-sweep.ts +20 -31
- package/{tools → lib/tools}/dedup-ceiling.ts +33 -144
- package/{tools → lib/tools}/eval-geocoder.ts +9 -10
- package/{tools → lib/tools}/geocoder-namesake-probe.ts +5 -12
- package/{tools → lib/tools}/geocoder-vs-provided-coords.ts +9 -10
- package/lib/tools/gold-set-sample.ts +141 -0
- package/lib/tools/index.ts +31 -0
- package/{tools → lib/tools}/learned-scorer-clustering-eval.ts +68 -257
- package/{tools → lib/tools}/learned-scorer-crossstate-eval.ts +60 -243
- package/{tools → lib/tools}/learned-scorer-eval.ts +63 -257
- package/{tools → lib/tools}/matcher-scale.ts +4 -5
- package/lib/tools/nppes/org-name.ts +23 -0
- package/{tools → lib/tools}/nppes/overmerge-packet.ts +5 -7
- package/{tools → lib/tools}/nppes/report.ts +22 -25
- package/{tools → lib/tools}/nppes/sample.ts +80 -32
- package/{tools/nppes/levers.ts → lib/tools/nppes/settings.ts} +10 -10
- package/{tools → lib/tools}/nppes/truth-grains.ts +4 -44
- package/{tools → lib/tools}/nppes-dedup-benchmark.ts +42 -38
- package/lib/tools/shared.ts +761 -0
- package/lib/tools/train-cross-gbt.ts +209 -0
- package/{tools → lib/tools}/train-gbt.ts +35 -154
- package/lib/tools/train-org-cross-gbt.ts +179 -0
- package/{tools → lib/tools}/txhhsc-to-oarow.ts +9 -27
- package/lib/tools/viz/browser.ts +50 -0
- package/{tools → lib/tools}/viz/cross-dataset-map.ts +7 -8
- package/{tools → lib/tools}/viz/geocode-first-surface.ts +10 -8
- package/{tools → lib/tools}/viz/render-map.ts +10 -23
- package/lib/tools/viz/render.ts +98 -0
- package/{tools → lib/tools}/viz/source-provenance-map.ts +8 -10
- package/{tools → lib/tools}/viz/yardstick-figure.ts +6 -5
- package/out/address-key.d.ts +1 -1
- package/out/address-key.d.ts.map +1 -1
- package/out/address-key.js.map +1 -1
- package/out/geocode-handler.d.ts +6 -6
- package/out/geocode-handler.d.ts.map +1 -1
- package/out/geocode-handler.js +6 -6
- package/out/geocode-handler.js.map +1 -1
- package/out/geojson.d.ts +7 -2
- package/out/geojson.d.ts.map +1 -1
- package/out/geojson.js +5 -3
- package/out/geojson.js.map +1 -1
- package/out/index.d.ts +10 -10
- package/out/index.d.ts.map +1 -1
- package/out/index.js +10 -10
- package/out/index.js.map +1 -1
- package/out/ingest.d.ts +64 -46
- package/out/ingest.d.ts.map +1 -1
- package/out/ingest.js +31 -45
- package/out/ingest.js.map +1 -1
- package/out/learned-scorer.d.ts +1 -1
- package/out/learned-scorer.d.ts.map +1 -1
- package/out/learned-scorer.js.map +1 -1
- package/out/map-html.d.ts +3 -3
- package/out/map-html.d.ts.map +1 -1
- package/out/map-html.js +6 -11
- package/out/map-html.js.map +1 -1
- package/out/models/crosssource-gbt-en-us.d.ts.map +1 -1
- package/out/models/crosssource-gbt-en-us.js.map +1 -1
- package/out/models/dedup-gbt-en-us.d.ts.map +1 -1
- package/out/models/dedup-gbt-en-us.js.map +1 -1
- package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -1
- package/out/models/org-crosssource-gbt-en-us.js.map +1 -1
- package/out/reconcile.d.ts +6 -1
- package/out/reconcile.d.ts.map +1 -1
- package/out/reconcile.js +5 -20
- package/out/reconcile.js.map +1 -1
- package/out/resolve.d.ts +19 -7
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +16 -5
- package/out/resolve.js.map +1 -1
- package/out/tools/coverage-reconciliation.d.ts +1 -1
- package/out/tools/coverage-reconciliation.d.ts.map +1 -1
- package/out/tools/coverage-reconciliation.js +11 -11
- package/out/tools/coverage-reconciliation.js.map +1 -1
- package/out/tools/cross-dataset-correlation.d.ts +4 -4
- package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
- package/out/tools/cross-dataset-correlation.js +57 -109
- package/out/tools/cross-dataset-correlation.js.map +1 -1
- package/out/tools/cross-source-threshold-sweep.d.ts +2 -2
- package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -1
- package/out/tools/cross-source-threshold-sweep.js +19 -27
- package/out/tools/cross-source-threshold-sweep.js.map +1 -1
- package/out/tools/dedup-ceiling.d.ts.map +1 -1
- package/out/tools/dedup-ceiling.js +36 -117
- package/out/tools/dedup-ceiling.js.map +1 -1
- package/out/tools/eval-geocoder.d.ts +8 -12
- package/out/tools/eval-geocoder.d.ts.map +1 -1
- package/out/tools/eval-geocoder.js +2 -2
- package/out/tools/eval-geocoder.js.map +1 -1
- package/out/tools/geocoder-namesake-probe.d.ts +2 -2
- package/out/tools/geocoder-namesake-probe.d.ts.map +1 -1
- package/out/tools/geocoder-namesake-probe.js +4 -8
- package/out/tools/geocoder-namesake-probe.js.map +1 -1
- package/out/tools/geocoder-vs-provided-coords.d.ts +1 -1
- package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
- package/out/tools/geocoder-vs-provided-coords.js +8 -7
- package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
- package/out/tools/gold-set-sample.d.ts +5 -5
- package/out/tools/gold-set-sample.d.ts.map +1 -1
- package/out/tools/gold-set-sample.js +37 -122
- package/out/tools/gold-set-sample.js.map +1 -1
- package/out/tools/index.d.ts +23 -23
- package/out/tools/index.d.ts.map +1 -1
- package/out/tools/index.js +23 -23
- package/out/tools/index.js.map +1 -1
- package/out/tools/learned-scorer-clustering-eval.d.ts +1 -1
- package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
- package/out/tools/learned-scorer-clustering-eval.js +36 -169
- package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
- package/out/tools/learned-scorer-crossstate-eval.d.ts +5 -5
- package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
- package/out/tools/learned-scorer-crossstate-eval.js +44 -166
- package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
- package/out/tools/learned-scorer-eval.d.ts +1 -1
- package/out/tools/learned-scorer-eval.d.ts.map +1 -1
- package/out/tools/learned-scorer-eval.js +38 -168
- package/out/tools/learned-scorer-eval.js.map +1 -1
- package/out/tools/matcher-scale.d.ts.map +1 -1
- package/out/tools/matcher-scale.js +4 -4
- package/out/tools/matcher-scale.js.map +1 -1
- package/out/tools/nppes/org-name.d.ts +2 -5
- package/out/tools/nppes/org-name.d.ts.map +1 -1
- package/out/tools/nppes/org-name.js +1 -30
- package/out/tools/nppes/org-name.js.map +1 -1
- package/out/tools/nppes/overmerge-packet.d.ts +3 -3
- package/out/tools/nppes/overmerge-packet.d.ts.map +1 -1
- package/out/tools/nppes/overmerge-packet.js +3 -3
- package/out/tools/nppes/overmerge-packet.js.map +1 -1
- package/out/tools/nppes/report.d.ts +5 -5
- package/out/tools/nppes/report.d.ts.map +1 -1
- package/out/tools/nppes/report.js +17 -19
- package/out/tools/nppes/report.js.map +1 -1
- package/out/tools/nppes/sample.d.ts +32 -6
- package/out/tools/nppes/sample.d.ts.map +1 -1
- package/out/tools/nppes/sample.js +44 -26
- package/out/tools/nppes/sample.js.map +1 -1
- package/out/tools/nppes/scoring.d.ts.map +1 -1
- package/out/tools/nppes/scoring.js.map +1 -1
- package/out/tools/nppes/{levers.d.ts → settings.d.ts} +8 -8
- package/out/tools/nppes/settings.d.ts.map +1 -0
- package/out/tools/nppes/{levers.js → settings.js} +8 -8
- package/out/tools/nppes/settings.js.map +1 -0
- package/out/tools/nppes/truth-grains.d.ts +2 -2
- package/out/tools/nppes/truth-grains.d.ts.map +1 -1
- package/out/tools/nppes/truth-grains.js +4 -29
- package/out/tools/nppes/truth-grains.js.map +1 -1
- package/out/tools/nppes-dedup-benchmark.d.ts +4 -4
- package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
- package/out/tools/nppes-dedup-benchmark.js +40 -34
- package/out/tools/nppes-dedup-benchmark.js.map +1 -1
- package/out/tools/shared.d.ts +243 -7
- package/out/tools/shared.d.ts.map +1 -1
- package/out/tools/shared.js +348 -18
- package/out/tools/shared.js.map +1 -1
- package/out/tools/train-cross-gbt.d.ts +7 -7
- package/out/tools/train-cross-gbt.d.ts.map +1 -1
- package/out/tools/train-cross-gbt.js +47 -145
- package/out/tools/train-cross-gbt.js.map +1 -1
- package/out/tools/train-gbt.d.ts +7 -7
- package/out/tools/train-gbt.d.ts.map +1 -1
- package/out/tools/train-gbt.js +31 -111
- package/out/tools/train-gbt.js.map +1 -1
- package/out/tools/train-org-cross-gbt.d.ts +7 -5
- package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
- package/out/tools/train-org-cross-gbt.js +45 -141
- package/out/tools/train-org-cross-gbt.js.map +1 -1
- package/out/tools/txhhsc-to-oarow.d.ts +2 -2
- package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
- package/out/tools/txhhsc-to-oarow.js +8 -22
- package/out/tools/txhhsc-to-oarow.js.map +1 -1
- package/out/tools/viz/browser.d.ts +34 -0
- package/out/tools/viz/browser.d.ts.map +1 -0
- package/out/tools/viz/browser.js +33 -0
- package/out/tools/viz/browser.js.map +1 -0
- package/out/tools/viz/cross-dataset-map.d.ts +2 -2
- package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
- package/out/tools/viz/cross-dataset-map.js +6 -6
- package/out/tools/viz/cross-dataset-map.js.map +1 -1
- package/out/tools/viz/geocode-first-surface.d.ts +4 -3
- package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
- package/out/tools/viz/geocode-first-surface.js +7 -5
- package/out/tools/viz/geocode-first-surface.js.map +1 -1
- package/out/tools/viz/render-map.d.ts +3 -6
- package/out/tools/viz/render-map.d.ts.map +1 -1
- package/out/tools/viz/render-map.js +9 -19
- package/out/tools/viz/render-map.js.map +1 -1
- package/out/tools/viz/render.d.ts +4 -9
- package/out/tools/viz/render.d.ts.map +1 -1
- package/out/tools/viz/render.js +24 -39
- package/out/tools/viz/render.js.map +1 -1
- package/out/tools/viz/source-provenance-map.d.ts +2 -2
- package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
- package/out/tools/viz/source-provenance-map.js +6 -7
- package/out/tools/viz/source-provenance-map.js.map +1 -1
- package/out/tools/viz/yardstick-figure.d.ts +2 -2
- package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
- package/out/tools/viz/yardstick-figure.js +5 -4
- package/out/tools/viz/yardstick-figure.js.map +1 -1
- package/out/types.d.ts.map +1 -1
- package/out/types.js.map +1 -1
- package/package.json +115 -15
- package/out/tools/nppes/levers.d.ts.map +0 -1
- package/out/tools/nppes/levers.js.map +0 -1
- package/tools/gold-set-sample.ts +0 -254
- package/tools/index.ts +0 -31
- package/tools/nppes/org-name.ts +0 -56
- package/tools/shared.ts +0 -162
- package/tools/train-cross-gbt.ts +0 -359
- package/tools/train-org-cross-gbt.ts +0 -330
- package/tools/viz/render.ts +0 -113
- /package/{models → lib/models}/crosssource-gbt-en-us.ts +0 -0
- /package/{models → lib/models}/dedup-gbt-en-us.ts +0 -0
- /package/{models → lib/models}/org-crosssource-gbt-en-us.ts +0 -0
- /package/{tools → lib/tools}/nppes/scoring.ts +0 -0
- /package/{types.ts → lib/types.ts} +0 -0
|
@@ -0,0 +1,761 @@
|
|
|
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 { makeDirectories, writeLocalFile } from "@mailwoman/core/fs/writers"
|
|
13
|
+
import { isPresent } from "@mailwoman/core/objects"
|
|
14
|
+
import { makeLcg } from "@mailwoman/core/random"
|
|
15
|
+
import { block, gbtScore, trainGBT, type TermFrequencyTable } from "@mailwoman/match"
|
|
16
|
+
import { dirname } from "path-ts"
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
addressFrequencyKey,
|
|
20
|
+
buildDefaultModel,
|
|
21
|
+
createMatchFeaturizer,
|
|
22
|
+
defaultBlockingKeys,
|
|
23
|
+
ingestRows,
|
|
24
|
+
normalizePhoneStrict,
|
|
25
|
+
streamRows,
|
|
26
|
+
type ColumnMapping,
|
|
27
|
+
type SourceRecord,
|
|
28
|
+
} from "#index"
|
|
29
|
+
import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
|
|
30
|
+
import type { Score } from "#tools/nppes/scoring"
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* One source a cross-source probe ingests: where it lives, the column mapping, and an in-state filter.
|
|
34
|
+
*/
|
|
35
|
+
export interface SourceSpec {
|
|
36
|
+
source: string
|
|
37
|
+
path: string
|
|
38
|
+
mapping: ColumnMapping
|
|
39
|
+
/**
|
|
40
|
+
* Keep only rows in-state (reads the row's state column).
|
|
41
|
+
*/
|
|
42
|
+
inState: (row: Record<string, string>) => boolean
|
|
43
|
+
/**
|
|
44
|
+
* Optional: a row carries ≥1 addressable entity — yield each as its own row. Default identity.
|
|
45
|
+
*/
|
|
46
|
+
explode?: (row: Record<string, string>) => Record<string, string>[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Trim, treating `undefined` as empty — the shape every probe's raw CSV columns arrive in.
|
|
51
|
+
*/
|
|
52
|
+
export const norm = (s: string | undefined): string => (s ?? "").trim()
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Corporate-form suffixes and function words that carry no identity — dropped from an organization name before its
|
|
56
|
+
* tokens are compared, so the domain words carry the distinguishing signal.
|
|
57
|
+
*/
|
|
58
|
+
const ORGANIZATION_STOP_WORDS = new Set([
|
|
59
|
+
"llc",
|
|
60
|
+
"inc",
|
|
61
|
+
"incorporated",
|
|
62
|
+
"corp",
|
|
63
|
+
"corporation",
|
|
64
|
+
"co",
|
|
65
|
+
"ltd",
|
|
66
|
+
"pllc",
|
|
67
|
+
"pc",
|
|
68
|
+
"pa",
|
|
69
|
+
"lp",
|
|
70
|
+
"llp",
|
|
71
|
+
"the",
|
|
72
|
+
"of",
|
|
73
|
+
"and",
|
|
74
|
+
])
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The token set of an organization name: lower-cased, non-alphanumerics folded to spaces, stop words removed.
|
|
78
|
+
*
|
|
79
|
+
* NOT a canonical form — `@mailwoman/record`'s `canonicalizeOrganizationName` is the stronger canonical key
|
|
80
|
+
* (jurisdiction-aware designation stripping, a DBA split). This set serves the probes' cheap Jaccard overlap over raw
|
|
81
|
+
* registry names, never blocking or display.
|
|
82
|
+
*/
|
|
83
|
+
export function orgTokens(s: string): Set<string> {
|
|
84
|
+
return new Set(
|
|
85
|
+
s
|
|
86
|
+
.toLowerCase()
|
|
87
|
+
.replaceAll(/[^a-z0-9 ]/g, " ")
|
|
88
|
+
.split(/\s+/)
|
|
89
|
+
.filter((t) => t && !ORGANIZATION_STOP_WORDS.has(t))
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Join the four US address columns into one line, dropping blanks.
|
|
95
|
+
*/
|
|
96
|
+
export const addr = (line: string, city: string, st: string, zip: string): string =>
|
|
97
|
+
[norm(line), norm(city), norm(st), norm(zip)].filter(isPresent).join(", ")
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Population standard deviation; `0` on an empty sample, because these feed report tables that print a number per row.
|
|
101
|
+
*/
|
|
102
|
+
export const std = (xs: readonly number[]): number => {
|
|
103
|
+
const m = xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
|
|
104
|
+
|
|
105
|
+
return Math.sqrt(xs.map((x) => (x - m) ** 2).reduce((a, b) => a + b, 0) / Math.max(1, xs.length))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// NOTE(phase4): pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
|
|
109
|
+
// numerator/denominator contract (call sites append their own "%").
|
|
110
|
+
export const pct = (x: number): string => (100 * x).toFixed(1)
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Sign prefix for a signed delta — `"+"` for a non-negative value (a negative one carries its own sign).
|
|
114
|
+
*/
|
|
115
|
+
export const sgn = (x: number): string => (x >= 0 ? "+" : "")
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Logistic function with the input clamped to +/-30 — past that `Math.exp` underflows to 0 and the gradient step
|
|
119
|
+
* silently becomes a no-op.
|
|
120
|
+
*/
|
|
121
|
+
export const sigmoid = (z: number): number => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The probes' shared `--state` option: upper-cased, defaulting to TX (the benchmark corpus state).
|
|
125
|
+
*/
|
|
126
|
+
export const stateOption = (options: { state?: string }): string => (options.state || "TX").toUpperCase()
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Texas bounding box (generous) — the shared wrong-region test.
|
|
130
|
+
*/
|
|
131
|
+
export const TX_BBOX = { latMin: 25.8, latMax: 36.6, lonMin: -106.7, lonMax: -93.4 }
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Whether a coordinate falls inside {@link TX_BBOX}.
|
|
135
|
+
*/
|
|
136
|
+
export const inTXBBOX = (lat: number, lon: number): boolean =>
|
|
137
|
+
lat >= TX_BBOX.latMin && lat <= TX_BBOX.latMax && lon >= TX_BBOX.lonMin && lon <= TX_BBOX.lonMax
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* NPPES registry column headers, by the short name the probes read them under.
|
|
141
|
+
*
|
|
142
|
+
* The NPI registry export is a ~330-column TSV with headers this long, so every probe that touches it needs this map,
|
|
143
|
+
* and five of them had grown their own copy. The copies were a NESTED SUPERSET chain, not a disagreement -- each new
|
|
144
|
+
* probe took the previous one's map and appended what it additionally read -- so this is the widest of the five, and no
|
|
145
|
+
* consumer loses a column. Reading extra keys costs nothing: they are inert strings, and nothing enumerates this object
|
|
146
|
+
* (checked: no `Object.keys`/`values`/`entries`/spread over it anywhere in `tools/`), so adding a column can never
|
|
147
|
+
* change a probe's behavior.
|
|
148
|
+
*/
|
|
149
|
+
export const NPPES_COLUMNS = {
|
|
150
|
+
npi: "NPI",
|
|
151
|
+
entityType: "Entity Type Code",
|
|
152
|
+
orgLegal: "Provider Organization Name (Legal Business Name)",
|
|
153
|
+
last: "Provider Last Name (Legal Name)",
|
|
154
|
+
first: "Provider First Name",
|
|
155
|
+
pAddr: "Provider First Line Business Practice Location Address",
|
|
156
|
+
pCity: "Provider Business Practice Location Address City Name",
|
|
157
|
+
pState: "Provider Business Practice Location Address State Name",
|
|
158
|
+
pZip: "Provider Business Practice Location Address Postcode",
|
|
159
|
+
pPhone: "Provider Business Practice Location Address Telephone Number",
|
|
160
|
+
mAddr: "Provider First Line Business Mailing Address",
|
|
161
|
+
mCity: "Provider Business Mailing Address City Name",
|
|
162
|
+
mState: "Provider Business Mailing Address State Name",
|
|
163
|
+
mZip: "Provider Business Mailing Address Postcode",
|
|
164
|
+
otherOrg: "Provider Other Organization Name",
|
|
165
|
+
authLast: "Authorized Official Last Name",
|
|
166
|
+
authFirst: "Authorized Official First Name",
|
|
167
|
+
isSubpart: "Is Organization Subpart",
|
|
168
|
+
parentLBN: "Parent Organization LBN",
|
|
169
|
+
parentTIN: "Parent Organization TIN",
|
|
170
|
+
// #625 taxonomy discriminator: the 15 taxonomy slots; collected as a set (any shared code = agreement).
|
|
171
|
+
taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Groups below this size are too small for a held-out split to mean anything.
|
|
176
|
+
*/
|
|
177
|
+
export const MIN_GROUP_SIZE = 5
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Gradient-descent epochs for {@link trainLogisticRegression}. Fixed rather than early-stopped so seeds stay comparable.
|
|
181
|
+
*/
|
|
182
|
+
export const TRAINING_EPOCHS = 400
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Smallest mean F1 gap counted as a real difference between models rather than seed noise. Verdicts inside ±this are
|
|
186
|
+
* reported as a tie.
|
|
187
|
+
*/
|
|
188
|
+
export const MIN_MEANINGFUL_F1_DELTA = 0.02
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Batch-gradient-descent learning rate for {@link trainLogisticRegression}.
|
|
192
|
+
*/
|
|
193
|
+
export const LR_LEARNING_RATE = 0.1
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* L2 regularization strength for {@link trainLogisticRegression}.
|
|
197
|
+
*/
|
|
198
|
+
export const LR_L2 = 1e-3
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* L2-regularized logistic regression by batch gradient descent ({@link TRAINING_EPOCHS} epochs) — the probes' linear
|
|
202
|
+
* arm. `w` carries the per-sample class weights (the caller up-weights the rare class). Returns the linear scorer: the
|
|
203
|
+
* logit, not the probability, threshold-comparable across a fixed feature layout.
|
|
204
|
+
*/
|
|
205
|
+
export function trainLogisticRegression(
|
|
206
|
+
X: readonly (readonly number[])[],
|
|
207
|
+
y: readonly number[],
|
|
208
|
+
w: readonly number[],
|
|
209
|
+
dim: number
|
|
210
|
+
): (x: readonly number[]) => number {
|
|
211
|
+
const weights = new Array<number>(dim).fill(0)
|
|
212
|
+
let bias = 0
|
|
213
|
+
|
|
214
|
+
for (let epoch = 0; epoch < TRAINING_EPOCHS; epoch++) {
|
|
215
|
+
const gw = new Array<number>(dim).fill(0)
|
|
216
|
+
let gb = 0
|
|
217
|
+
|
|
218
|
+
for (let i = 0; i < X.length; i++) {
|
|
219
|
+
let z = bias
|
|
220
|
+
|
|
221
|
+
for (let j = 0; j < dim; j++) {
|
|
222
|
+
z += weights[j]! * X[i]![j]!
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const err = (sigmoid(z) - y[i]!) * w[i]!
|
|
226
|
+
|
|
227
|
+
for (let j = 0; j < dim; j++) {
|
|
228
|
+
gw[j]! += err * X[i]![j]!
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
gb += err
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
for (let j = 0; j < dim; j++) {
|
|
235
|
+
weights[j]! -= LR_LEARNING_RATE * (gw[j]! / X.length + LR_L2 * weights[j]!)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
bias -= LR_LEARNING_RATE * (gb / X.length)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return (x) => {
|
|
242
|
+
let z = bias
|
|
243
|
+
|
|
244
|
+
for (let j = 0; j < x.length; j++) {
|
|
245
|
+
z += weights[j]! * x[j]!
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return z
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* `n + 1` evenly-spaced order statistics of an already-sorted sample, de-duplicated — the candidate split thresholds a
|
|
254
|
+
* GBT node considers. `[0]` for an empty sample so a degenerate feature still yields one (useless but well-formed)
|
|
255
|
+
* threshold rather than an empty split set.
|
|
256
|
+
*/
|
|
257
|
+
export function uniqueQuantiles(sorted: readonly number[], n: number): number[] {
|
|
258
|
+
if (!sorted.length) return [0]
|
|
259
|
+
const ts = new Set<number>()
|
|
260
|
+
|
|
261
|
+
for (let k = 0; k <= n; k++) {
|
|
262
|
+
ts.add(sorted[Math.floor((k / n) * (sorted.length - 1))]!)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return [...ts]
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Quantile points swept per learned-scorer arm.
|
|
270
|
+
*/
|
|
271
|
+
const THRESHOLD_QUANTILE_POINTS = 32
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Link-threshold candidates for a learned scorer: de-duplicated quantiles of the scorer's own eval-pair score
|
|
275
|
+
* distribution across the 0.2–0.999 quantile band — fine enough that a coarse grid can't understate an arm.
|
|
276
|
+
*/
|
|
277
|
+
export const quantileThresholds = (scores: readonly number[]): number[] => {
|
|
278
|
+
const sorted = [...scores].toSorted((p, q) => p - q)
|
|
279
|
+
const ts = new Set<number>()
|
|
280
|
+
|
|
281
|
+
for (let k = 0; k <= THRESHOLD_QUANTILE_POINTS; k++) {
|
|
282
|
+
ts.add(sorted[Math.floor((0.2 + (0.999 - 0.2) * (k / THRESHOLD_QUANTILE_POINTS)) * (sorted.length - 1))]!)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return [...ts]
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* One clustering arm's operating point, as the eval tables print it.
|
|
290
|
+
*/
|
|
291
|
+
export interface ArmScore {
|
|
292
|
+
precision: number
|
|
293
|
+
recall: number
|
|
294
|
+
f1: number
|
|
295
|
+
overMerged: number
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Project a full {@link Score} onto the arm shape the eval tables print.
|
|
300
|
+
*/
|
|
301
|
+
export const toArmScore = (s: Score): ArmScore => ({
|
|
302
|
+
precision: s.precision,
|
|
303
|
+
recall: s.recall,
|
|
304
|
+
f1: s.f1,
|
|
305
|
+
overMerged: s.overMergedClusters,
|
|
306
|
+
})
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The best-F1 operating point over a threshold sweep.
|
|
310
|
+
*/
|
|
311
|
+
export function bestOver(thresholds: readonly number[], scoreAt: (threshold: number) => ArmScore): ArmScore {
|
|
312
|
+
let best: ArmScore = { precision: 0, recall: 0, f1: -1, overMerged: 0 }
|
|
313
|
+
|
|
314
|
+
for (const t of thresholds) {
|
|
315
|
+
const s = scoreAt(t)
|
|
316
|
+
|
|
317
|
+
if (s.f1 > best.f1) {
|
|
318
|
+
best = s
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
return best
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* One organization provider at its practice address, as the geocode-free co-location probes read it — the union of what
|
|
327
|
+
* `dedup-ceiling` and `gold-set-sample` each collect.
|
|
328
|
+
*/
|
|
329
|
+
export interface ColocatedProvider {
|
|
330
|
+
npi: string
|
|
331
|
+
org: string
|
|
332
|
+
tokens: Set<string>
|
|
333
|
+
/**
|
|
334
|
+
* The composed practice address ({@link addr}), the string the adjudication packets carry.
|
|
335
|
+
*/
|
|
336
|
+
address: string
|
|
337
|
+
/**
|
|
338
|
+
* Strict last-10-digit phone key; `""` when the column carries fewer than 10 digits.
|
|
339
|
+
*/
|
|
340
|
+
phone: string
|
|
341
|
+
/**
|
|
342
|
+
* Authorized official, `"last first"`, lowercased.
|
|
343
|
+
*/
|
|
344
|
+
auth: string
|
|
345
|
+
/**
|
|
346
|
+
* Primary taxonomy (specialty) code.
|
|
347
|
+
*/
|
|
348
|
+
taxonomy: string
|
|
349
|
+
subpart: boolean
|
|
350
|
+
/**
|
|
351
|
+
* `parentLBN|parentTIN`, lowercased — `"|"` when both are blank.
|
|
352
|
+
*/
|
|
353
|
+
parent: string
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* What {@link scanColocatedProviders} collects.
|
|
358
|
+
*/
|
|
359
|
+
export interface ColocatedScan {
|
|
360
|
+
/**
|
|
361
|
+
* Providers grouped by their normalized practice-address key.
|
|
362
|
+
*/
|
|
363
|
+
byAddr: Map<string, ColocatedProvider[]>
|
|
364
|
+
kept: number
|
|
365
|
+
scanned: number
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Stream in-state type-2 (organization) providers from the registry — one record per row at its practice address,
|
|
370
|
+
* grouped by `addressFrequencyKey`. Geocode-free on purpose, so it runs at large caps in seconds.
|
|
371
|
+
*/
|
|
372
|
+
export async function scanColocatedProviders(options: {
|
|
373
|
+
registryPath: string
|
|
374
|
+
state: string
|
|
375
|
+
cap: number
|
|
376
|
+
}): Promise<ColocatedScan> {
|
|
377
|
+
const { registryPath, state, cap } = options
|
|
378
|
+
const C = NPPES_COLUMNS
|
|
379
|
+
const byAddr = new Map<string, ColocatedProvider[]>()
|
|
380
|
+
let kept = 0
|
|
381
|
+
let scanned = 0
|
|
382
|
+
|
|
383
|
+
for await (const r of streamRows(registryPath)) {
|
|
384
|
+
scanned++
|
|
385
|
+
|
|
386
|
+
if (norm(r[C.entityType]) !== "2") continue
|
|
387
|
+
|
|
388
|
+
if (norm(r[C.pState]).toUpperCase() !== state) continue
|
|
389
|
+
const org = norm(r[C.orgLegal])
|
|
390
|
+
const line1 = norm(r[C.pAddr])
|
|
391
|
+
|
|
392
|
+
if (!org || !line1) continue
|
|
393
|
+
const address = addr(line1, r[C.pCity]!, state, r[C.pZip]!)
|
|
394
|
+
const addrKey = addressFrequencyKey(address)
|
|
395
|
+
|
|
396
|
+
if (!addrKey) continue
|
|
397
|
+
|
|
398
|
+
const provider: ColocatedProvider = {
|
|
399
|
+
npi: norm(r[C.npi]),
|
|
400
|
+
org,
|
|
401
|
+
tokens: orgTokens(org),
|
|
402
|
+
address,
|
|
403
|
+
phone: normalizePhoneStrict(r[C.pPhone]),
|
|
404
|
+
auth: `${norm(r[C.authLast])} ${norm(r[C.authFirst])}`.toLowerCase().trim(),
|
|
405
|
+
taxonomy: norm(r[C.taxonomy[0]!]),
|
|
406
|
+
subpart: norm(r[C.isSubpart]).toUpperCase() === "Y",
|
|
407
|
+
parent: `${norm(r[C.parentLBN])}|${norm(r[C.parentTIN])}`.toLowerCase(),
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (!byAddr.has(addrKey)) {
|
|
411
|
+
byAddr.set(addrKey, [])
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
byAddr.get(addrKey)!.push(provider)
|
|
415
|
+
|
|
416
|
+
kept++
|
|
417
|
+
|
|
418
|
+
if (kept >= cap) break
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
return { byAddr, kept, scanned }
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* One co-located distinct-NPI pair, with the address group it came from.
|
|
426
|
+
*/
|
|
427
|
+
export interface ColocatedPair {
|
|
428
|
+
a: ColocatedProvider
|
|
429
|
+
b: ColocatedProvider
|
|
430
|
+
/**
|
|
431
|
+
* The distinct-NPI providers at the shared address, length ≥ 2. One array reference per group, so a consumer tracking
|
|
432
|
+
* group-level tallies can detect the group boundary by identity.
|
|
433
|
+
*/
|
|
434
|
+
group: readonly ColocatedProvider[]
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Every unordered pair of DISTINCT NPIs sharing a practice-address key — the over-merge population. Providers are
|
|
439
|
+
* de-duplicated per address by NPI (first record wins); single-NPI addresses yield nothing.
|
|
440
|
+
*/
|
|
441
|
+
export function* colocatedDistinctPairs(
|
|
442
|
+
byAddr: ReadonlyMap<string, readonly ColocatedProvider[]>
|
|
443
|
+
): Generator<ColocatedPair> {
|
|
444
|
+
for (const providers of byAddr.values()) {
|
|
445
|
+
const distinct = new Map<string, ColocatedProvider>()
|
|
446
|
+
|
|
447
|
+
for (const p of providers)
|
|
448
|
+
if (!distinct.has(p.npi)) {
|
|
449
|
+
distinct.set(p.npi, p)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const group = [...distinct.values()]
|
|
453
|
+
|
|
454
|
+
if (group.length < 2) continue
|
|
455
|
+
|
|
456
|
+
for (let i = 0; i < group.length; i++) {
|
|
457
|
+
for (let j = i + 1; j < group.length; j++) {
|
|
458
|
+
yield { a: group[i]!, b: group[j]!, group }
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* The TX facility source specs the cross-source probes share. `cross-dataset-correlation` composes these with its own
|
|
466
|
+
* commitments spec (the exploded two-entity-per-row source).
|
|
467
|
+
*/
|
|
468
|
+
export const buildSpecs = (S: string, STATE: string): SourceSpec[] => [
|
|
469
|
+
{
|
|
470
|
+
source: "txhhsc-nursing",
|
|
471
|
+
path: `${S}/txhhsc_nursing-facilities_20260611.tsv`,
|
|
472
|
+
mapping: {
|
|
473
|
+
id: "Facility ID",
|
|
474
|
+
organization: "Facility Name",
|
|
475
|
+
address: ["Physical Address", "Physical Address CITY", "Physical Address State", "Physical Address Zipcode"],
|
|
476
|
+
phone: "Facility Phone Number",
|
|
477
|
+
source: "txhhsc-nursing",
|
|
478
|
+
},
|
|
479
|
+
inState: (r) => norm(r["Physical Address State"]).toUpperCase() === STATE,
|
|
480
|
+
},
|
|
481
|
+
{
|
|
482
|
+
source: "fcc-rhc",
|
|
483
|
+
path: `${S}/fcc-rhc_posted-services_form461-465_20260615.tsv`,
|
|
484
|
+
mapping: {
|
|
485
|
+
id: "HCP Number",
|
|
486
|
+
organization: "HCP Name",
|
|
487
|
+
address: ["Site Address Line 1", "Site City", "Site State", "Site ZIP Code"],
|
|
488
|
+
phone: "Contact Phone",
|
|
489
|
+
email: "Contact E-mail",
|
|
490
|
+
source: "fcc-rhc",
|
|
491
|
+
},
|
|
492
|
+
inState: (r) => norm(r["Site State"]).toUpperCase() === STATE,
|
|
493
|
+
},
|
|
494
|
+
{
|
|
495
|
+
source: "nppes",
|
|
496
|
+
path: `${S}/nppes_npi-registry_20260607.tsv`,
|
|
497
|
+
mapping: {
|
|
498
|
+
id: NPPES_COLUMNS.npi,
|
|
499
|
+
organization: NPPES_COLUMNS.orgLegal,
|
|
500
|
+
address: [NPPES_COLUMNS.pAddr, NPPES_COLUMNS.pCity, NPPES_COLUMNS.pState, NPPES_COLUMNS.pZip],
|
|
501
|
+
phone: NPPES_COLUMNS.pPhone,
|
|
502
|
+
source: "nppes",
|
|
503
|
+
},
|
|
504
|
+
inState: (r) =>
|
|
505
|
+
norm(r[NPPES_COLUMNS.pState]).toUpperCase() === STATE &&
|
|
506
|
+
norm(r[NPPES_COLUMNS.entityType]) === "2" &&
|
|
507
|
+
!!norm(r[NPPES_COLUMNS.orgLegal]),
|
|
508
|
+
},
|
|
509
|
+
]
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* The GBT hyperparameter shape the trainers stamp into their model meta.
|
|
513
|
+
*/
|
|
514
|
+
export interface GBTHyperparameters {
|
|
515
|
+
rounds: number
|
|
516
|
+
depth: number
|
|
517
|
+
lr: number
|
|
518
|
+
minLeaf: number
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* The compact pure-Node GBT configuration the cross-source trainers fit with.
|
|
523
|
+
*/
|
|
524
|
+
const CROSS_SOURCE_HYPERPARAMS: GBTHyperparameters = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Share of join keys assigned to fit during calibration; the rest are held out.
|
|
528
|
+
*/
|
|
529
|
+
const FIT_SPLIT_FRACTION = 0.8
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* One assembled input row for a cross-source trainer. `npi` carries the cross-system join key (an NPI or a CCN) — it
|
|
533
|
+
* rides `record.id` as the held-out label.
|
|
534
|
+
*/
|
|
535
|
+
export interface CrossSourceRow extends Record<string, string> {
|
|
536
|
+
npi: string
|
|
537
|
+
name: string
|
|
538
|
+
org: string
|
|
539
|
+
address: string
|
|
540
|
+
source: string
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Every figure Phases D–F compute — what {@link TrainCrossSourceModelOptions.meta} receives.
|
|
545
|
+
*/
|
|
546
|
+
export interface CrossSourceTrainingFigures {
|
|
547
|
+
records: number
|
|
548
|
+
pairs: number
|
|
549
|
+
posRate: number
|
|
550
|
+
barRecall: number
|
|
551
|
+
f1Max: number
|
|
552
|
+
recommendedThreshold: number
|
|
553
|
+
features: number
|
|
554
|
+
hyperparams: GBTHyperparameters
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Options for {@linkcode trainCrossSourceModel}.
|
|
559
|
+
*/
|
|
560
|
+
export interface TrainCrossSourceModelOptions {
|
|
561
|
+
/**
|
|
562
|
+
* The injected geocoder factory (the command wires `mailwoman/geocode-core`; see `./eval-geocoder.ts`).
|
|
563
|
+
*/
|
|
564
|
+
createGeocoder: EvalGeocoderFactory
|
|
565
|
+
/**
|
|
566
|
+
* The assembled two-source rows — the caller's source-loading phases stay with the caller.
|
|
567
|
+
*/
|
|
568
|
+
rows: readonly CrossSourceRow[]
|
|
569
|
+
/**
|
|
570
|
+
* The join keys present in BOTH sources.
|
|
571
|
+
*/
|
|
572
|
+
joined: ReadonlySet<string>
|
|
573
|
+
addressFrequency: TermFrequencyTable
|
|
574
|
+
/**
|
|
575
|
+
* The two provenance labels, in ingest order.
|
|
576
|
+
*/
|
|
577
|
+
sources: readonly [string, string]
|
|
578
|
+
/**
|
|
579
|
+
* #655 threshold rule: max cross-source recall subject to this held-out pairwise precision.
|
|
580
|
+
*/
|
|
581
|
+
precisionBar: number
|
|
582
|
+
/**
|
|
583
|
+
* Output TS module path.
|
|
584
|
+
*/
|
|
585
|
+
out: string
|
|
586
|
+
/**
|
|
587
|
+
* The emitted module's docstring prose — the ` * `-prefixed lines between the author block and the closer.
|
|
588
|
+
*/
|
|
589
|
+
moduleDoc: string
|
|
590
|
+
/**
|
|
591
|
+
* Emitted export prefix — the module exports `<prefix>_META` + `<prefix>_MODEL`.
|
|
592
|
+
*/
|
|
593
|
+
exportPrefix: string
|
|
594
|
+
/**
|
|
595
|
+
* Assemble the emitted `<prefix>_META` object. The caller owns field names and order so a retrain diffs cleanly
|
|
596
|
+
* against its committed module.
|
|
597
|
+
*/
|
|
598
|
+
meta: (figures: CrossSourceTrainingFigures) => Record<string, unknown>
|
|
599
|
+
report?: (line: string) => void
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Phases C–F shared by the cross-source trainers: geocode + ingest each source under its own provenance label, block
|
|
604
|
+
* the union and keep only CROSS-source candidate pairs, featurize with the SHARED `createMatchFeaturizer` (train ≡
|
|
605
|
+
* inference), calibrate the #655 threshold on a held-out split of the join keys, train the shipped model on ALL pairs,
|
|
606
|
+
* and emit it as a committed TS module.
|
|
607
|
+
*/
|
|
608
|
+
export async function trainCrossSourceModel(
|
|
609
|
+
options: TrainCrossSourceModelOptions
|
|
610
|
+
): Promise<{ out: string; pairs: number; recommendedThreshold: number }> {
|
|
611
|
+
const { rows, joined, addressFrequency, sources, precisionBar, out, report } = options
|
|
612
|
+
|
|
613
|
+
// --- Phase C: geocode + ingest (record.id = the join-key label; `source` rides the record). The
|
|
614
|
+
// heavy geocoder is injected (see ./eval-geocoder.ts). ---
|
|
615
|
+
report?.("[C] geocoding…")
|
|
616
|
+
const geocoder = await options.createGeocoder()
|
|
617
|
+
|
|
618
|
+
// `ColumnMapping.source` is a LITERAL provenance label — ingest each source separately so every
|
|
619
|
+
// record carries its registry of origin (the cross-source filter + the sweep harness key on it).
|
|
620
|
+
const mappingFor = (source: string): ColumnMapping => ({
|
|
621
|
+
id: "npi",
|
|
622
|
+
name: "name",
|
|
623
|
+
organization: "org",
|
|
624
|
+
address: "address",
|
|
625
|
+
source,
|
|
626
|
+
})
|
|
627
|
+
|
|
628
|
+
const records: SourceRecord[] = []
|
|
629
|
+
|
|
630
|
+
for (const source of sources) {
|
|
631
|
+
records.push(
|
|
632
|
+
...(await ingestRows(
|
|
633
|
+
rows.filter((r) => r.source === source),
|
|
634
|
+
mappingFor(source),
|
|
635
|
+
{ geocodeAddress: geocoder.geocodeAddress }
|
|
636
|
+
))
|
|
637
|
+
)
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
geocoder[Symbol.dispose]()
|
|
641
|
+
report?.(` ${records.length} records, ${records.filter((r) => r.address?.geocode).length} geocoded`)
|
|
642
|
+
|
|
643
|
+
// --- Phase D: block over the UNION; keep only CROSS-source pairs; featurize; label by join key. ---
|
|
644
|
+
report?.("[D] blocking + featurizing (cross-source pairs only)…")
|
|
645
|
+
const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
|
|
646
|
+
const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
|
|
647
|
+
const { pairs: allPairs } = block(records, defaultBlockingKeys())
|
|
648
|
+
const pairs = allPairs.filter(([a, b]) => a.source !== b.source)
|
|
649
|
+
const X = pairs.map(([a, b]) => featurize(a, b))
|
|
650
|
+
const Y: number[] = pairs.map(([a, b]) => (a.id === b.id ? 1 : 0))
|
|
651
|
+
const posRate = Y.reduce((s, y) => s + y, 0) / Math.max(1, Y.length)
|
|
652
|
+
const W = Y.map((y) => (y === 1 ? 1 - posRate : posRate))
|
|
653
|
+
|
|
654
|
+
report?.(
|
|
655
|
+
` ${allPairs.length} blocked pairs → ${pairs.length} cross-source (${(100 * posRate).toFixed(1)}% positive)`
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
// --- Phase E: held-out calibration — the #655 threshold rule. ---
|
|
659
|
+
report?.("[E] held-out calibration…")
|
|
660
|
+
const rnd = makeLcg(655)
|
|
661
|
+
const split = new Map<string, "fit" | "holdout">()
|
|
662
|
+
|
|
663
|
+
for (const key of joined) {
|
|
664
|
+
split.set(key, rnd() < FIT_SPLIT_FRACTION ? "fit" : "holdout")
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const fitIdx = pairs
|
|
668
|
+
.map((_, i) => i)
|
|
669
|
+
.filter((i) => split.get(pairs[i]![0].id) === "fit" && split.get(pairs[i]![1].id) === "fit")
|
|
670
|
+
|
|
671
|
+
const holdIdx = pairs
|
|
672
|
+
.map((_, i) => i)
|
|
673
|
+
.filter((i) => split.get(pairs[i]![0].id) === "holdout" && split.get(pairs[i]![1].id) === "holdout")
|
|
674
|
+
|
|
675
|
+
const calib = trainGBT(
|
|
676
|
+
fitIdx.map((i) => X[i]!),
|
|
677
|
+
fitIdx.map((i) => Y[i]!),
|
|
678
|
+
fitIdx.map((i) => W[i]!),
|
|
679
|
+
CROSS_SOURCE_HYPERPARAMS
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
const holdScores = holdIdx.map((i) => ({ s: gbtScore(calib, X[i]!), y: Y[i]! }))
|
|
683
|
+
const sorted = holdScores.map((h) => h.s).toSorted((a, b) => a - b)
|
|
684
|
+
const totalPos = holdScores.reduce((s, h) => s + h.y, 0)
|
|
685
|
+
let recommendedThreshold = Number.POSITIVE_INFINITY
|
|
686
|
+
let barRecall = 0
|
|
687
|
+
let f1MaxThreshold = 0
|
|
688
|
+
let bestF1 = -1
|
|
689
|
+
|
|
690
|
+
for (const t of uniqueQuantiles(sorted, 60)) {
|
|
691
|
+
let tp = 0
|
|
692
|
+
let fp = 0
|
|
693
|
+
|
|
694
|
+
for (const h of holdScores) {
|
|
695
|
+
if (h.s < t) continue
|
|
696
|
+
|
|
697
|
+
if (h.y) {
|
|
698
|
+
tp++
|
|
699
|
+
} else {
|
|
700
|
+
fp++
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const precision = tp + fp > 0 ? tp / (tp + fp) : 1
|
|
705
|
+
const recall = totalPos > 0 ? tp / totalPos : 0
|
|
706
|
+
const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
|
|
707
|
+
|
|
708
|
+
// The #655 rule: the LOWEST threshold whose precision clears the bar (maximizes recall under it).
|
|
709
|
+
if (precision >= precisionBar && recall > barRecall) {
|
|
710
|
+
barRecall = recall
|
|
711
|
+
recommendedThreshold = t
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
if (f1 > bestF1) {
|
|
715
|
+
bestF1 = f1
|
|
716
|
+
f1MaxThreshold = t
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (!Number.isFinite(recommendedThreshold)) {
|
|
721
|
+
recommendedThreshold = f1MaxThreshold
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
report?.(
|
|
725
|
+
` held-out (${holdIdx.length} pairs, ${totalPos} pos): precision-bar ${precisionBar} → threshold ${recommendedThreshold.toFixed(3)} (recall ${(100 * barRecall).toFixed(1)}%); F1-max ${(100 * bestF1).toFixed(1)}% @ ${f1MaxThreshold.toFixed(3)}`
|
|
726
|
+
)
|
|
727
|
+
|
|
728
|
+
// --- Phase F: train the SHIPPED model on ALL cross-source pairs; emit the committed module. ---
|
|
729
|
+
report?.("[F] training the shipped model on all pairs…")
|
|
730
|
+
const model = trainGBT(X, Y, W, CROSS_SOURCE_HYPERPARAMS)
|
|
731
|
+
|
|
732
|
+
const meta = options.meta({
|
|
733
|
+
records: records.length,
|
|
734
|
+
pairs: pairs.length,
|
|
735
|
+
posRate: Number(posRate.toFixed(4)),
|
|
736
|
+
barRecall: Number(barRecall.toFixed(4)),
|
|
737
|
+
f1Max: Number(bestF1.toFixed(4)),
|
|
738
|
+
recommendedThreshold: Number(recommendedThreshold.toFixed(4)),
|
|
739
|
+
features: X[0]?.length ?? 0,
|
|
740
|
+
hyperparams: CROSS_SOURCE_HYPERPARAMS,
|
|
741
|
+
})
|
|
742
|
+
|
|
743
|
+
const moduleSource =
|
|
744
|
+
`/**\n` +
|
|
745
|
+
` * @copyright Sister Software\n` +
|
|
746
|
+
` * @license AGPL-3.0\n` +
|
|
747
|
+
` * @author Teffen Ellis, et al.\n` +
|
|
748
|
+
` *\n` +
|
|
749
|
+
options.moduleDoc +
|
|
750
|
+
` */\n\n` +
|
|
751
|
+
`import type { GBT } from "@mailwoman/match"\n\n` +
|
|
752
|
+
`export const ${options.exportPrefix}_META = ${JSON.stringify(meta)} as const\n\n` +
|
|
753
|
+
`// prettier-ignore\n` +
|
|
754
|
+
`export const ${options.exportPrefix}_MODEL: GBT = ${JSON.stringify(model)}\n`
|
|
755
|
+
|
|
756
|
+
await makeDirectories(dirname(out))
|
|
757
|
+
await writeLocalFile(moduleSource, out)
|
|
758
|
+
report?.(` ${model.trees.length} trees, ${X[0]?.length ?? 0} features -> ${out}`)
|
|
759
|
+
|
|
760
|
+
return { out, pairs: pairs.length, recommendedThreshold }
|
|
761
|
+
}
|