@mailwoman/entity-resolution 0.0.0-stage → 10.8.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 +114 -2
  2. package/lib/address-key.ts +46 -0
  3. package/lib/geocode-handler.ts +37 -0
  4. package/lib/geojson.ts +72 -0
  5. package/lib/index.ts +23 -0
  6. package/lib/ingest.ts +349 -0
  7. package/lib/learned-scorer.ts +134 -0
  8. package/lib/map-html.ts +287 -0
  9. package/lib/models/crosssource-gbt-en-us.ts +43 -0
  10. package/lib/models/dedup-gbt-en-us.ts +47 -0
  11. package/lib/models/org-crosssource-gbt-en-us.ts +43 -0
  12. package/lib/reconcile.ts +239 -0
  13. package/lib/resolve.ts +569 -0
  14. package/lib/types.ts +110 -0
  15. package/out/address-key.d.ts +34 -0
  16. package/out/address-key.d.ts.map +1 -0
  17. package/out/address-key.js +41 -0
  18. package/out/address-key.js.map +1 -0
  19. package/out/geocode-handler.d.ts +20 -0
  20. package/out/geocode-handler.d.ts.map +1 -0
  21. package/out/geocode-handler.js +29 -0
  22. package/out/geocode-handler.js.map +1 -0
  23. package/out/geojson.d.ts +28 -0
  24. package/out/geojson.d.ts.map +1 -0
  25. package/out/geojson.js +62 -0
  26. package/out/geojson.js.map +1 -0
  27. package/out/index.d.ts +23 -0
  28. package/out/index.d.ts.map +1 -0
  29. package/out/index.js +23 -0
  30. package/out/index.js.map +1 -0
  31. package/out/ingest.d.ts +173 -0
  32. package/out/ingest.d.ts.map +1 -0
  33. package/out/ingest.js +185 -0
  34. package/out/ingest.js.map +1 -0
  35. package/out/learned-scorer.d.ts +61 -0
  36. package/out/learned-scorer.d.ts.map +1 -0
  37. package/out/learned-scorer.js +91 -0
  38. package/out/learned-scorer.js.map +1 -0
  39. package/out/map-html.d.ts +39 -0
  40. package/out/map-html.d.ts.map +1 -0
  41. package/out/map-html.js +220 -0
  42. package/out/map-html.js.map +1 -0
  43. package/out/models/crosssource-gbt-en-us.d.ts +45 -0
  44. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -0
  45. package/out/models/crosssource-gbt-en-us.js +40 -0
  46. package/out/models/crosssource-gbt-en-us.js.map +1 -0
  47. package/out/models/dedup-gbt-en-us.d.ts +44 -0
  48. package/out/models/dedup-gbt-en-us.d.ts.map +1 -0
  49. package/out/models/dedup-gbt-en-us.js +44 -0
  50. package/out/models/dedup-gbt-en-us.js.map +1 -0
  51. package/out/models/org-crosssource-gbt-en-us.d.ts +45 -0
  52. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -0
  53. package/out/models/org-crosssource-gbt-en-us.js +40 -0
  54. package/out/models/org-crosssource-gbt-en-us.js.map +1 -0
  55. package/out/reconcile.d.ts +96 -0
  56. package/out/reconcile.d.ts.map +1 -0
  57. package/out/reconcile.js +127 -0
  58. package/out/reconcile.js.map +1 -0
  59. package/out/resolve.d.ts +264 -0
  60. package/out/resolve.d.ts.map +1 -0
  61. package/out/resolve.js +282 -0
  62. package/out/resolve.js.map +1 -0
  63. package/out/tools/coverage-reconciliation.d.ts +67 -0
  64. package/out/tools/coverage-reconciliation.d.ts.map +1 -0
  65. package/out/tools/coverage-reconciliation.js +113 -0
  66. package/out/tools/coverage-reconciliation.js.map +1 -0
  67. package/out/tools/cross/dataset-correlation.d.ts +61 -0
  68. package/out/tools/cross/dataset-correlation.d.ts.map +1 -0
  69. package/out/tools/cross/dataset-correlation.js +244 -0
  70. package/out/tools/cross/dataset-correlation.js.map +1 -0
  71. package/out/tools/cross/source-threshold-sweep.d.ts +60 -0
  72. package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -0
  73. package/out/tools/cross/source-threshold-sweep.js +264 -0
  74. package/out/tools/cross/source-threshold-sweep.js.map +1 -0
  75. package/out/tools/dedup-ceiling.d.ts +62 -0
  76. package/out/tools/dedup-ceiling.d.ts.map +1 -0
  77. package/out/tools/dedup-ceiling.js +171 -0
  78. package/out/tools/dedup-ceiling.js.map +1 -0
  79. package/out/tools/eval-geocoder.d.ts +68 -0
  80. package/out/tools/eval-geocoder.d.ts.map +1 -0
  81. package/out/tools/eval-geocoder.js +13 -0
  82. package/out/tools/eval-geocoder.js.map +1 -0
  83. package/out/tools/geocoder/namesake-probe.d.ts +33 -0
  84. package/out/tools/geocoder/namesake-probe.d.ts.map +1 -0
  85. package/out/tools/geocoder/namesake-probe.js +60 -0
  86. package/out/tools/geocoder/namesake-probe.js.map +1 -0
  87. package/out/tools/geocoder/vs-provided-coords.d.ts +53 -0
  88. package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -0
  89. package/out/tools/geocoder/vs-provided-coords.js +161 -0
  90. package/out/tools/geocoder/vs-provided-coords.js.map +1 -0
  91. package/out/tools/gold-set-sample.d.ts +67 -0
  92. package/out/tools/gold-set-sample.d.ts.map +1 -0
  93. package/out/tools/gold-set-sample.js +81 -0
  94. package/out/tools/gold-set-sample.js.map +1 -0
  95. package/out/tools/learned/scorer/clustering-eval.d.ts +77 -0
  96. package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -0
  97. package/out/tools/learned/scorer/clustering-eval.js +207 -0
  98. package/out/tools/learned/scorer/clustering-eval.js.map +1 -0
  99. package/out/tools/learned/scorer/crossstate-eval.d.ts +65 -0
  100. package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -0
  101. package/out/tools/learned/scorer/crossstate-eval.js +168 -0
  102. package/out/tools/learned/scorer/crossstate-eval.js.map +1 -0
  103. package/out/tools/learned/scorer/eval.d.ts +64 -0
  104. package/out/tools/learned/scorer/eval.d.ts.map +1 -0
  105. package/out/tools/learned/scorer/eval.js +275 -0
  106. package/out/tools/learned/scorer/eval.js.map +1 -0
  107. package/out/tools/matcher-scale.d.ts +40 -0
  108. package/out/tools/matcher-scale.d.ts.map +1 -0
  109. package/out/tools/matcher-scale.js +111 -0
  110. package/out/tools/matcher-scale.js.map +1 -0
  111. package/out/tools/nppes/dedup-benchmark.d.ts +82 -0
  112. package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -0
  113. package/out/tools/nppes/dedup-benchmark.js +226 -0
  114. package/out/tools/nppes/dedup-benchmark.js.map +1 -0
  115. package/out/tools/nppes/org-name.d.ts +15 -0
  116. package/out/tools/nppes/org-name.d.ts.map +1 -0
  117. package/out/tools/nppes/org-name.js +6 -0
  118. package/out/tools/nppes/org-name.js.map +1 -0
  119. package/out/tools/nppes/overmerge-packet.d.ts +43 -0
  120. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  121. package/out/tools/nppes/overmerge-packet.js +54 -0
  122. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  123. package/out/tools/nppes/report.d.ts +97 -0
  124. package/out/tools/nppes/report.d.ts.map +1 -0
  125. package/out/tools/nppes/report.js +178 -0
  126. package/out/tools/nppes/report.js.map +1 -0
  127. package/out/tools/nppes/sample.d.ts +101 -0
  128. package/out/tools/nppes/sample.d.ts.map +1 -0
  129. package/out/tools/nppes/sample.js +127 -0
  130. package/out/tools/nppes/sample.js.map +1 -0
  131. package/out/tools/nppes/scoring.d.ts +37 -0
  132. package/out/tools/nppes/scoring.d.ts.map +1 -0
  133. package/out/tools/nppes/scoring.js +81 -0
  134. package/out/tools/nppes/scoring.js.map +1 -0
  135. package/out/tools/nppes/settings.d.ts +41 -0
  136. package/out/tools/nppes/settings.d.ts.map +1 -0
  137. package/out/tools/nppes/settings.js +79 -0
  138. package/out/tools/nppes/settings.js.map +1 -0
  139. package/out/tools/nppes/truth-grains.d.ts +63 -0
  140. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  141. package/out/tools/nppes/truth-grains.js +142 -0
  142. package/out/tools/nppes/truth-grains.js.map +1 -0
  143. package/out/tools/shared.d.ts +325 -0
  144. package/out/tools/shared.d.ts.map +1 -0
  145. package/out/tools/shared.js +453 -0
  146. package/out/tools/shared.js.map +1 -0
  147. package/out/tools/train/cross-gbt.d.ts +89 -0
  148. package/out/tools/train/cross-gbt.d.ts.map +1 -0
  149. package/out/tools/train/cross-gbt.js +132 -0
  150. package/out/tools/train/cross-gbt.js.map +1 -0
  151. package/out/tools/train/gbt.d.ts +85 -0
  152. package/out/tools/train/gbt.d.ts.map +1 -0
  153. package/out/tools/train/gbt.js +155 -0
  154. package/out/tools/train/gbt.js.map +1 -0
  155. package/out/tools/train/org-cross-gbt.d.ts +85 -0
  156. package/out/tools/train/org-cross-gbt.d.ts.map +1 -0
  157. package/out/tools/train/org-cross-gbt.js +122 -0
  158. package/out/tools/train/org-cross-gbt.js.map +1 -0
  159. package/out/tools/txhhsc-to-oarow.d.ts +42 -0
  160. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -0
  161. package/out/tools/txhhsc-to-oarow.js +78 -0
  162. package/out/tools/txhhsc-to-oarow.js.map +1 -0
  163. package/out/tools/viz/browser.d.ts +31 -0
  164. package/out/tools/viz/browser.d.ts.map +1 -0
  165. package/out/tools/viz/browser.js +26 -0
  166. package/out/tools/viz/browser.js.map +1 -0
  167. package/out/tools/viz/cross-dataset-map.d.ts +39 -0
  168. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -0
  169. package/out/tools/viz/cross-dataset-map.js +84 -0
  170. package/out/tools/viz/cross-dataset-map.js.map +1 -0
  171. package/out/tools/viz/geocode-first-surface.d.ts +36 -0
  172. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -0
  173. package/out/tools/viz/geocode-first-surface.js +234 -0
  174. package/out/tools/viz/geocode-first-surface.js.map +1 -0
  175. package/out/tools/viz/render/map.d.ts +42 -0
  176. package/out/tools/viz/render/map.d.ts.map +1 -0
  177. package/out/tools/viz/render/map.js +40 -0
  178. package/out/tools/viz/render/map.js.map +1 -0
  179. package/out/tools/viz/render.d.ts +46 -0
  180. package/out/tools/viz/render.d.ts.map +1 -0
  181. package/out/tools/viz/render.js +49 -0
  182. package/out/tools/viz/render.js.map +1 -0
  183. package/out/tools/viz/source-provenance-map.d.ts +57 -0
  184. package/out/tools/viz/source-provenance-map.d.ts.map +1 -0
  185. package/out/tools/viz/source-provenance-map.js +82 -0
  186. package/out/tools/viz/source-provenance-map.js.map +1 -0
  187. package/out/tools/viz/yardstick-figure.d.ts +22 -0
  188. package/out/tools/viz/yardstick-figure.d.ts.map +1 -0
  189. package/out/tools/viz/yardstick-figure.js +106 -0
  190. package/out/tools/viz/yardstick-figure.js.map +1 -0
  191. package/out/types.d.ts +108 -0
  192. package/out/types.d.ts.map +1 -0
  193. package/out/types.js +11 -0
  194. package/out/types.js.map +1 -0
  195. package/package.json +113 -3
  196. package/tools/coverage-reconciliation.ts +192 -0
  197. package/tools/cross/dataset-correlation.ts +380 -0
  198. package/tools/cross/source-threshold-sweep.ts +416 -0
  199. package/tools/dedup-ceiling.ts +225 -0
  200. package/tools/eval-geocoder.ts +77 -0
  201. package/tools/geocoder/namesake-probe.ts +91 -0
  202. package/tools/geocoder/vs-provided-coords.ts +232 -0
  203. package/tools/gold-set-sample.ts +147 -0
  204. package/tools/learned/scorer/clustering-eval.ts +349 -0
  205. package/tools/learned/scorer/crossstate-eval.ts +280 -0
  206. package/tools/learned/scorer/eval.ts +429 -0
  207. package/tools/matcher-scale.ts +185 -0
  208. package/tools/nppes/dedup-benchmark.ts +364 -0
  209. package/tools/nppes/org-name.ts +15 -0
  210. package/tools/nppes/overmerge-packet.ts +98 -0
  211. package/tools/nppes/report.ts +380 -0
  212. package/tools/nppes/sample.ts +250 -0
  213. package/tools/nppes/scoring.ts +115 -0
  214. package/tools/nppes/settings.ts +102 -0
  215. package/tools/nppes/truth-grains.ts +185 -0
  216. package/tools/shared.ts +743 -0
  217. package/tools/train/cross-gbt.ts +214 -0
  218. package/tools/train/gbt.ts +261 -0
  219. package/tools/train/org-cross-gbt.ts +189 -0
  220. package/tools/txhhsc-to-oarow.ts +118 -0
  221. package/tools/viz/browser.ts +41 -0
  222. package/tools/viz/cross-dataset-map.ts +133 -0
  223. package/tools/viz/geocode-first-surface.ts +305 -0
  224. package/tools/viz/render/map.ts +61 -0
  225. package/tools/viz/render.ts +103 -0
  226. package/tools/viz/source-provenance-map.ts +154 -0
  227. package/tools/viz/yardstick-figure.ts +197 -0
@@ -0,0 +1,364 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Builds a varied multi-record set per NPI from real data.
7
+ * Runs the matcher without NPI values, then scores recovered clusters against the NPI grouping.
8
+ *
9
+ * Run: `mailwoman registry scorer-eval nppes-benchmark [--state TX] [--max-npis 300] [--wof <admin.db>] [--data-root <dir>] [--no-train-em] [--out-md docs/articles/evals/matcher-dedup/<date>-nppes-dedup-benchmark.md]`
10
+ */
11
+
12
+ import { dataRootPath } from "@mailwoman/core/data-root"
13
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
14
+ import { pathToFileURL } from "@mailwoman/core/module/file-url"
15
+ import type { GBT } from "@mailwoman/match"
16
+ import { resolvePath } from "path-ts"
17
+
18
+ import {
19
+ ingestRows,
20
+ resolveEntities,
21
+ type ColumnMapping,
22
+ type GeocodeAddress,
23
+ type ResolvedEntity,
24
+ type SourceRecord,
25
+ } from "#index"
26
+ import type { EvalGeocodeStream, EvalGeocoderFactory } from "#tools/eval-geocoder"
27
+ import { writeOvermergePacket } from "#tools/nppes/overmerge-packet"
28
+ import { renderNPPESDedupReport, type SweepArm } from "#tools/nppes/report"
29
+ import { buildNPPESSample } from "#tools/nppes/sample"
30
+ import { scoreEntities, type Score } from "#tools/nppes/scoring"
31
+ import { buildSettings } from "#tools/nppes/settings"
32
+ import {
33
+ buildOrgNameCoordGrain,
34
+ buildOrgNameGrain,
35
+ buildOrgNameH3Grain,
36
+ collectPrimaryCoordinates,
37
+ type TruthLabel,
38
+ } from "#tools/nppes/truth-grains"
39
+ import { stateOption } from "#tools/shared"
40
+
41
+ /**
42
+ * Options for {@linkcode nppesDedupBenchmark}.
43
+ */
44
+ export interface NPPESDedupBenchmarkOptions {
45
+ /**
46
+ * The injected geocoder factory, wired by the command to `mailwoman/geocode-core`; model-swap
47
+ * overrides (`--model`/`--tokenizer`/`--model-card`) are its factory config rather than tool options.
48
+ */
49
+ createGeocoder: EvalGeocoderFactory
50
+ /**
51
+ * The threaded geocode surface — required when {@linkcode parallelGeocode} is set.
52
+ */
53
+ geocodeStream?: EvalGeocodeStream
54
+ /**
55
+ * Record-matcher sources directory, defaulting to `$MAILWOMAN_DATA_ROOT/record-matcher/sources`.
56
+ */
57
+ sources?: string
58
+ /**
59
+ * State filter, default TX.
60
+ */
61
+ state?: string
62
+ /**
63
+ * NPIs sampled, default 300.
64
+ */
65
+ maxNpis?: number
66
+ /**
67
+ * EM-train the FS arms (label-free), default true; `--no-train-em` uses the seeds.
68
+ */
69
+ trainEm?: boolean
70
+ /**
71
+ * Reproduce the pre-flip ingest (space-joined address columns with case normalization off),
72
+ * so that with the same data and GBT only the flip is toggled.
73
+ *
74
+ * @defaultValue `false`
75
+ */
76
+ legacyJoin?: boolean
77
+ /**
78
+ * Optional A/B: a path to a trained dedup-gbt TS module exporting DEDUP_GBT_MODEL +
79
+ * DEDUP_GBT_META, scored alongside the shipped GBT at both truth levels.
80
+ */
81
+ candidate?: string
82
+ /**
83
+ * Write the gold-set adjudication packet of org-name-grain over-merged clusters here.
84
+ */
85
+ dumpOvermerges?: string
86
+ /**
87
+ * H3 resolution for the org-name-h3 truth grain, default 11 (≈25 m edge).
88
+ */
89
+ h3Res?: number
90
+ /**
91
+ * Geocode the sample through a worker pool with {@linkcode geocodeStream}.
92
+ *
93
+ * The worker pool parallelizes the per-row ONNX parse and WOF SQLite work while preserving coordinates.
94
+ */
95
+ parallelGeocode?: boolean
96
+ /**
97
+ * Worker-pool concurrency for {@linkcode parallelGeocode}, default 2 (geocode is I/O-bound).
98
+ */
99
+ geoConcurrency?: number
100
+ /**
101
+ * Also write the markdown report here.
102
+ */
103
+ outMd?: string
104
+ }
105
+
106
+ /**
107
+ * The NPPES dedup benchmark (see the module doc), emitting the markdown report to stdout.
108
+ */
109
+ export async function nppesDedupBenchmark(
110
+ options: NPPESDedupBenchmarkOptions,
111
+ report?: (line: string) => void
112
+ ): Promise<{ markdown: string }> {
113
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
114
+ const STATE = stateOption(options)
115
+ const MAX_NPIS = options.maxNpis ?? 300
116
+ const OUT_MD = options.outMd || ""
117
+ const TRAIN_EM = options.trainEm ?? true
118
+ const LEGACY = options.legacyJoin ?? false
119
+ const CANDIDATE = options.candidate || ""
120
+ const PARALLEL_GEOCODE = options.parallelGeocode ?? false
121
+ const GEO_CONC = options.geoConcurrency ?? 2
122
+
123
+ const { rows, keptNpis, npiPrimary, addressFrequency } = await buildNPPESSample(
124
+ {
125
+ registryPath: `${SOURCES}/nppes_npi-registry_20260607.tsv`,
126
+ otherNamesPath: `${SOURCES}/nppes_other-names_20260607.tsv`,
127
+ state: STATE,
128
+ maxNpis: MAX_NPIS,
129
+ },
130
+ report
131
+ )
132
+
133
+ // Without `modelCardPath`, a STAGE3 model silently mis-decodes into empty parses when `modelPath` is set.
134
+ report?.("[C] building the geocoder + geocoding records…")
135
+
136
+ const mapping: ColumnMapping = {
137
+ id: "npi",
138
+ name: "name",
139
+ organization: "org",
140
+ address: "address",
141
+ // `entityTruth` appears as an attribute purely for scoring, never as a discriminator
142
+ // in matching, carrying the site-level label alongside the NPI.
143
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy", entityTruth: "entityID" },
144
+ source: "nppes",
145
+ }
146
+
147
+ let geo = 0
148
+ let records: SourceRecord[]
149
+
150
+ if (PARALLEL_GEOCODE) {
151
+ // `address` is a single pre-joined column on this path, so `--legacy-join` is a no-op
152
+ // and case normalization follows the worker default (`"title-case"`).
153
+ if (!options.geocodeStream) {
154
+ throw new Error("parallelGeocode requires the injected geocodeStream (see ./eval-geocoder.ts)")
155
+ }
156
+
157
+ const normalized = await ingestRows(rows, mapping)
158
+ const order = new Map(normalized.map((r, i) => [r.id, i]))
159
+ const geocoded: SourceRecord[] = []
160
+
161
+ for await (const rec of options.geocodeStream(normalized, { mapping, concurrency: GEO_CONC })) {
162
+ geocoded.push(rec)
163
+
164
+ if (rec.address?.geocode) {
165
+ geo++
166
+ }
167
+ }
168
+
169
+ // Restore input order because `geocodeStream` yields in completion order
170
+ // and downstream cluster tie-breaks must be byte-stable.
171
+ geocoded.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))
172
+ records = geocoded
173
+ } else {
174
+ const geocoder = await options.createGeocoder({ caseNormalization: LEGACY ? "preserve" : "title-case" })
175
+
176
+ const countedGeocodeForIngest: GeocodeAddress = async (raw) => {
177
+ const g = await geocoder.geocodeAddress(raw)
178
+
179
+ if (g?.geocode) {
180
+ geo++
181
+ }
182
+
183
+ return g
184
+ }
185
+
186
+ records = await ingestRows(rows, mapping, {
187
+ geocodeAddress: countedGeocodeForIngest,
188
+ addressSeparator: LEGACY ? " " : ", ",
189
+ })
190
+
191
+ geocoder[Symbol.dispose]()
192
+ }
193
+
194
+ report?.(` geocoded ${geo}/${rows.length} (${((100 * geo) / rows.length).toFixed(1)}%)`)
195
+
196
+ const N = records.length
197
+
198
+ // Every grain scores against the same record population, so the ARI expectation is fixed for the run.
199
+ const score = (entities: readonly ResolvedEntity[], labelOf: TruthLabel): Score => scoreEntities(entities, labelOf, N)
200
+
201
+ // A score for the same clusters at NPI and entity level isolates how much of the
202
+ // apparent over-merge is NPI over-segmentation rather than model error.
203
+ const npiLabel = (rec: SourceRecord) => rec.id
204
+ const entityLabel = (rec: SourceRecord) => rec.attributes?.["entityTruth"] ?? rec.id
205
+ const orgNameLabel = buildOrgNameGrain(npiPrimary)
206
+
207
+ const npiCoord = collectPrimaryCoordinates(records)
208
+ const orgNameCoordLabel = buildOrgNameCoordGrain(npiPrimary, npiCoord)
209
+ const geocodedNpis = [...npiPrimary.keys()].filter((n) => npiCoord.has(n)).length
210
+
211
+ const H3_RES = options.h3Res ?? 11 // res 11 ≈ 25 m edge. res 10 ≈ 65 m (block scale)
212
+ const orgNameH3Label = buildOrgNameH3Grain(npiPrimary, npiCoord, H3_RES)
213
+
214
+ report?.(`[D] resolving the setting progression${TRAIN_EM ? " (EM-trained)" : ""}…`)
215
+
216
+ // The learned scorer is default-on, so it is pinned off here.
217
+ // Otherwise every row would silently be the GBT.
218
+ const progression = buildSettings(addressFrequency).map((l) => {
219
+ const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0, ...l.config })
220
+
221
+ return { ...l, res, score: score(res.entities, npiLabel) }
222
+ })
223
+
224
+ const bestSetting = progression.at(-1)! // the full setting stack
225
+
226
+ // The shipped out-of-box default auto-computes an input-scoped address-frequency table.
227
+ // on this sub-sampled corpus it is sparse and F1 collapses to ≈baseline, because IDF is a
228
+ // corpus statistic, so the CLI passes a corpus-wide table built from the full source files.
229
+ const defaultRes = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0 })
230
+ const defaultOutOfBox = score(defaultRes.entities, npiLabel)
231
+
232
+ const THRESHOLDS = [0, 4, 8, 12, 16, 20]
233
+
234
+ const sweep: SweepArm[] = THRESHOLDS.map((t) => {
235
+ const res = resolveEntities(records, {
236
+ learnedScorer: false,
237
+ trainEM: TRAIN_EM,
238
+ threshold: t,
239
+ ...bestSetting.config,
240
+ })
241
+
242
+ return { t, res, score: score(res.entities, npiLabel) }
243
+ })
244
+
245
+ const base = sweep[0]! // threshold 0, full setting stack
246
+ let best = sweep[0]!
247
+
248
+ for (const arm of sweep) {
249
+ if (arm.score.f1 > best.score.f1) {
250
+ best = arm
251
+ }
252
+ }
253
+
254
+ report?.(
255
+ ` progression @ threshold 0: ${progression.map((p) => `${(100 * p.score.f1).toFixed(1)}%`).join(" → ")} F1`
256
+ )
257
+
258
+ report?.(
259
+ ` default F1 ${(100 * base.score.f1).toFixed(1)}% → best F1 ${(100 * best.score.f1).toFixed(1)}% @ threshold ${best.t}`
260
+ )
261
+
262
+ const entityCount = new Set(records.map((r) => entityLabel(r))).size
263
+ const orgCount = new Set(records.map((r) => orgNameLabel(r))).size
264
+ const fsNPI = bestSetting.score
265
+ const fsEntity = score(bestSetting.res.entities, entityLabel)
266
+ const fsOrg = score(bestSetting.res.entities, orgNameLabel)
267
+ const gbtRes = resolveEntities(records, { addressFrequency, trainEM: TRAIN_EM }) // GBT default-on (production)
268
+ const gbtNPI = score(gbtRes.entities, npiLabel)
269
+ const gbtEntity = score(gbtRes.entities, entityLabel)
270
+ const gbtOrg = score(gbtRes.entities, orgNameLabel)
271
+ const orgCoordCount = new Set(records.map((r) => orgNameCoordLabel(r))).size
272
+ const fsOrgCoord = score(bestSetting.res.entities, orgNameCoordLabel)
273
+ const gbtOrgCoord = score(gbtRes.entities, orgNameCoordLabel)
274
+ const orgH3Count = new Set(records.map((r) => orgNameH3Label(r))).size
275
+ const gbtOrgH3 = score(gbtRes.entities, orgNameH3Label)
276
+
277
+ const DUMP_OVERMERGES = options.dumpOvermerges || ""
278
+
279
+ if (DUMP_OVERMERGES) {
280
+ const clusters = await writeOvermergePacket(DUMP_OVERMERGES, {
281
+ state: STATE,
282
+ entities: gbtRes.entities,
283
+ rows,
284
+ recordCount: records.length,
285
+ maxNpis: MAX_NPIS,
286
+ orgNameLabel,
287
+ })
288
+
289
+ report?.(` adjudication packet: ${clusters} over-merged clusters -> ${DUMP_OVERMERGES}`)
290
+ }
291
+
292
+ let cand: { label: string; npi: Score; entity: Score } | null = null
293
+
294
+ if (CANDIDATE) {
295
+ const mod = (await import(pathToFileURL(resolvePath(CANDIDATE)).href)) as {
296
+ DEDUP_GBT_MODEL: GBT
297
+ DEDUP_GBT_META?: { recommendedThreshold?: number; features?: number; costNegative?: number }
298
+ }
299
+
300
+ const t = mod.DEDUP_GBT_META?.recommendedThreshold ?? 0
301
+
302
+ const res = resolveEntities(records, {
303
+ addressFrequency,
304
+ trainEM: TRAIN_EM,
305
+ learnedScorer: mod.DEDUP_GBT_MODEL,
306
+ threshold: t,
307
+ })
308
+
309
+ const cost = mod.DEDUP_GBT_META?.costNegative ?? 1
310
+
311
+ cand = {
312
+ label: `GBT candidate (${mod.DEDUP_GBT_META?.features ?? "?"}-feat${cost !== 1 ? `, cost ×${cost}` : ""})`,
313
+ npi: score(res.entities, npiLabel),
314
+ entity: score(res.entities, entityLabel),
315
+ }
316
+
317
+ report?.(
318
+ ` candidate ${CANDIDATE}: NPI ${(100 * cand.npi.f1).toFixed(1)}% / entity ${(100 * cand.entity.f1).toFixed(1)}%`
319
+ )
320
+ }
321
+
322
+ report?.(
323
+ ` truth-grains — GBT NPI ${(100 * gbtNPI.f1).toFixed(1)}% → site ${(100 * gbtEntity.f1).toFixed(1)}% → org-name ${(100 * gbtOrg.f1).toFixed(1)}% → org-name-coord ${(100 * gbtOrgCoord.f1).toFixed(1)}% → org-name-h3 ${(100 * gbtOrgH3.f1).toFixed(1)}% (res ${H3_RES}); ` +
324
+ `FS: NPI ${(100 * fsNPI.f1).toFixed(1)}% / entity ${(100 * fsEntity.f1).toFixed(1)}% / org-coord ${(100 * fsOrgCoord.f1).toFixed(1)}%`
325
+ )
326
+
327
+ const md = renderNPPESDedupReport({
328
+ state: STATE,
329
+ keptNpis: keptNpis.size,
330
+ recordCount: N,
331
+ geocoded: geo,
332
+ trainEM: TRAIN_EM,
333
+ addressFrequency,
334
+ progression,
335
+ defaultOutOfBox,
336
+ sweep,
337
+ best,
338
+ entityCount,
339
+ orgCount,
340
+ orgCoordCount,
341
+ orgH3Count,
342
+ fsNPI,
343
+ fsEntity,
344
+ fsOrg,
345
+ fsOrgCoord,
346
+ gbtNPI,
347
+ gbtEntity,
348
+ gbtOrg,
349
+ gbtOrgCoord,
350
+ gbtOrgH3,
351
+ candidate: cand,
352
+ h3Res: H3_RES,
353
+ geocodedNpis,
354
+ })
355
+
356
+ console.log(md)
357
+
358
+ if (OUT_MD) {
359
+ await writeLocalFile(md, OUT_MD)
360
+ report?.(`\n[written] ${OUT_MD}`)
361
+ }
362
+
363
+ return { markdown: md }
364
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Jaccard floor at or above which two {@linkcode orgTokens} sets count as the
3
+ * same organization — the gold-set threshold.
4
+ */
5
+ export const ORG_TAU = 0.7
6
+
7
+ /**
8
+ * An NPI's primary registry identity: the org-name token set plus the address key of its practice location.
9
+ *
10
+ * Every grain of the org-name truth blocks on a location and filters on the tokens.
11
+ */
12
+ export interface NPIPrimary {
13
+ tokens: Set<string>
14
+ addrKey: string
15
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file Writes the over-merged NPPES clusters with every matcher-visible field for human adjudication.
6
+ */
7
+
8
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers"
9
+ import { formatPersonName } from "@mailwoman/record/name"
10
+ import type { PathBuilderLike } from "path-ts"
11
+
12
+ import type { ResolvedEntity, SourceRecord } from "#index"
13
+ import type { MessyRow } from "#tools/nppes/sample"
14
+ import type { TruthLabel } from "#tools/nppes/truth-grains"
15
+
16
+ /**
17
+ * The inputs to {@link writeOvermergePacket}.
18
+ */
19
+ export interface OvermergePacketInput {
20
+ /**
21
+ * The clusters to inspect.
22
+ * Callers pass the clusters from the shipped matcher config.
23
+ */
24
+ entities: readonly ResolvedEntity[]
25
+ /**
26
+ * The source rows.
27
+ *
28
+ * The packet reads the authorized official and taxonomy from them.
29
+ */
30
+ rows: readonly MessyRow[]
31
+ recordCount: number
32
+ maxNpis: number
33
+ /**
34
+ * The state that the sample was drawn from.
35
+ * The packet header prints it.
36
+ */
37
+ state: string
38
+ orgNameLabel: TruthLabel
39
+ }
40
+
41
+ /**
42
+ * Writes the adjudication packet and returns the number of over-merged clusters in it.
43
+ *
44
+ * A cluster is over-merged when its members have more than one org-name truth label.
45
+ * A reviewer marks each cluster as one real entity or as distinct providers.
46
+ * which separates model error from truth-label error.
47
+ */
48
+ export async function writeOvermergePacket(path: PathBuilderLike, input: OvermergePacketInput): Promise<number> {
49
+ const { entities, rows, recordCount, maxNpis, state, orgNameLabel } = input
50
+ const rowByID = new Map(rows.map((r) => [r.npi, r]))
51
+
52
+ const out: string[] = [
53
+ "# #625 gold-set adjudication packet — org-name-grain over-merged clusters (GBT, shipped config)",
54
+ "",
55
+ `${state} --max-npis ${maxNpis} · ${recordCount} records · generated by \`registry scorer-eval nppes-benchmark --dump-overmerges\``,
56
+ "",
57
+ "For each cluster: the matcher fused records that the org-name truth says belong to DIFFERENT entities.",
58
+ "Adjudicate each: **[same]** one real-world entity (yardstick error — the truth under-collapsed) or",
59
+ "**[distinct]** genuinely different co-located providers (model over-merge). Mark inline and return.",
60
+ "",
61
+ ]
62
+
63
+ let n = 0
64
+
65
+ entities.forEach((e) => {
66
+ const byLabel = new Map<string, SourceRecord[]>()
67
+
68
+ for (const rec of e.records) {
69
+ const lbl = orgNameLabel(rec)
70
+ const list = byLabel.get(lbl) ?? []
71
+ list.push(rec)
72
+ byLabel.set(lbl, list)
73
+ }
74
+
75
+ if (byLabel.size <= 1) return
76
+
77
+ n++
78
+ out.push(`## Cluster ${n} — ${e.records.length} records, ${byLabel.size} org-name entities → verdict: [ ]`)
79
+
80
+ for (const [lbl, members] of byLabel) {
81
+ out.push(`- **entity ${lbl}**`)
82
+
83
+ for (const rec of members) {
84
+ const src = rowByID.get(rec.id)
85
+
86
+ out.push(
87
+ ` - npi=${rec.id} · name="${formatPersonName(rec.name ?? null, "short")}" · org="${rec.organization?.canonical ?? ""}" · addr="${rec.address?.raw ?? ""}" · auth="${src?.auth ?? ""}" · taxonomy="${src?.taxonomy ?? ""}"`
88
+ )
89
+ }
90
+ }
91
+
92
+ out.push("")
93
+ })
94
+
95
+ await writeLocalTextFile(out.join("\n"), path)
96
+
97
+ return n
98
+ }