@mailwoman/registry 9.1.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +2 -2
  2. package/{address-key.ts → lib/address-key.ts} +1 -1
  3. package/{geocode-handler.ts → lib/geocode-handler.ts} +7 -7
  4. package/{geojson.ts → lib/geojson.ts} +12 -6
  5. package/{index.ts → lib/index.ts} +10 -10
  6. package/{ingest.ts → lib/ingest.ts} +77 -69
  7. package/{learned-scorer.ts → lib/learned-scorer.ts} +1 -1
  8. package/{map-html.ts → lib/map-html.ts} +10 -16
  9. package/{reconcile.ts → lib/reconcile.ts} +9 -24
  10. package/{resolve.ts → lib/resolve.ts} +31 -13
  11. package/{tools → lib/tools}/coverage-reconciliation.ts +13 -15
  12. package/{tools → lib/tools}/cross-dataset-correlation.ts +64 -139
  13. package/{tools → lib/tools}/cross-source-threshold-sweep.ts +21 -32
  14. package/{tools → lib/tools}/dedup-ceiling.ts +33 -144
  15. package/{tools → lib/tools}/eval-geocoder.ts +10 -11
  16. package/{tools → lib/tools}/geocoder-namesake-probe.ts +5 -12
  17. package/{tools → lib/tools}/geocoder-vs-provided-coords.ts +12 -11
  18. package/lib/tools/gold-set-sample.ts +141 -0
  19. package/lib/tools/index.ts +31 -0
  20. package/{tools → lib/tools}/learned-scorer-clustering-eval.ts +71 -260
  21. package/{tools → lib/tools}/learned-scorer-crossstate-eval.ts +62 -245
  22. package/{tools → lib/tools}/learned-scorer-eval.ts +64 -263
  23. package/{tools → lib/tools}/matcher-scale.ts +5 -5
  24. package/lib/tools/nppes/org-name.ts +23 -0
  25. package/lib/tools/nppes/overmerge-packet.ts +94 -0
  26. package/lib/tools/nppes/report.ts +373 -0
  27. package/lib/tools/nppes/sample.ts +245 -0
  28. package/lib/tools/nppes/scoring.ts +114 -0
  29. package/lib/tools/nppes/settings.ts +102 -0
  30. package/lib/tools/nppes/truth-grains.ts +161 -0
  31. package/lib/tools/nppes-dedup-benchmark.ts +408 -0
  32. package/lib/tools/shared.ts +763 -0
  33. package/lib/tools/train-cross-gbt.ts +209 -0
  34. package/{tools → lib/tools}/train-gbt.ts +38 -156
  35. package/lib/tools/train-org-cross-gbt.ts +179 -0
  36. package/{tools → lib/tools}/txhhsc-to-oarow.ts +10 -28
  37. package/lib/tools/viz/browser.ts +50 -0
  38. package/{tools → lib/tools}/viz/cross-dataset-map.ts +16 -39
  39. package/{tools → lib/tools}/viz/geocode-first-surface.ts +13 -39
  40. package/{tools → lib/tools}/viz/render-map.ts +10 -23
  41. package/lib/tools/viz/render.ts +98 -0
  42. package/{tools → lib/tools}/viz/source-provenance-map.ts +20 -39
  43. package/{tools → lib/tools}/viz/yardstick-figure.ts +6 -5
  44. package/{types.ts → lib/types.ts} +10 -1
  45. package/out/address-key.d.ts +1 -1
  46. package/out/address-key.d.ts.map +1 -1
  47. package/out/address-key.js.map +1 -1
  48. package/out/geocode-handler.d.ts +6 -6
  49. package/out/geocode-handler.d.ts.map +1 -1
  50. package/out/geocode-handler.js +6 -6
  51. package/out/geocode-handler.js.map +1 -1
  52. package/out/geojson.d.ts +7 -2
  53. package/out/geojson.d.ts.map +1 -1
  54. package/out/geojson.js +8 -5
  55. package/out/geojson.js.map +1 -1
  56. package/out/index.d.ts +10 -10
  57. package/out/index.d.ts.map +1 -1
  58. package/out/index.js +10 -10
  59. package/out/index.js.map +1 -1
  60. package/out/ingest.d.ts +64 -46
  61. package/out/ingest.d.ts.map +1 -1
  62. package/out/ingest.js +33 -46
  63. package/out/ingest.js.map +1 -1
  64. package/out/learned-scorer.d.ts +1 -1
  65. package/out/learned-scorer.d.ts.map +1 -1
  66. package/out/learned-scorer.js.map +1 -1
  67. package/out/map-html.d.ts +4 -4
  68. package/out/map-html.d.ts.map +1 -1
  69. package/out/map-html.js +6 -11
  70. package/out/map-html.js.map +1 -1
  71. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -1
  72. package/out/models/crosssource-gbt-en-us.js.map +1 -1
  73. package/out/models/dedup-gbt-en-us.d.ts.map +1 -1
  74. package/out/models/dedup-gbt-en-us.js.map +1 -1
  75. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -1
  76. package/out/models/org-crosssource-gbt-en-us.js.map +1 -1
  77. package/out/reconcile.d.ts +6 -1
  78. package/out/reconcile.d.ts.map +1 -1
  79. package/out/reconcile.js +7 -21
  80. package/out/reconcile.js.map +1 -1
  81. package/out/resolve.d.ts +19 -7
  82. package/out/resolve.d.ts.map +1 -1
  83. package/out/resolve.js +20 -6
  84. package/out/resolve.js.map +1 -1
  85. package/out/tools/coverage-reconciliation.d.ts +1 -1
  86. package/out/tools/coverage-reconciliation.d.ts.map +1 -1
  87. package/out/tools/coverage-reconciliation.js +12 -12
  88. package/out/tools/coverage-reconciliation.js.map +1 -1
  89. package/out/tools/cross-dataset-correlation.d.ts +4 -4
  90. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  91. package/out/tools/cross-dataset-correlation.js +60 -111
  92. package/out/tools/cross-dataset-correlation.js.map +1 -1
  93. package/out/tools/cross-source-threshold-sweep.d.ts +2 -2
  94. package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -1
  95. package/out/tools/cross-source-threshold-sweep.js +19 -27
  96. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  97. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  98. package/out/tools/dedup-ceiling.js +36 -118
  99. package/out/tools/dedup-ceiling.js.map +1 -1
  100. package/out/tools/eval-geocoder.d.ts +9 -13
  101. package/out/tools/eval-geocoder.d.ts.map +1 -1
  102. package/out/tools/eval-geocoder.js +2 -2
  103. package/out/tools/eval-geocoder.js.map +1 -1
  104. package/out/tools/geocoder-namesake-probe.d.ts +2 -2
  105. package/out/tools/geocoder-namesake-probe.d.ts.map +1 -1
  106. package/out/tools/geocoder-namesake-probe.js +4 -8
  107. package/out/tools/geocoder-namesake-probe.js.map +1 -1
  108. package/out/tools/geocoder-vs-provided-coords.d.ts +1 -1
  109. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  110. package/out/tools/geocoder-vs-provided-coords.js +11 -9
  111. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  112. package/out/tools/gold-set-sample.d.ts +5 -5
  113. package/out/tools/gold-set-sample.d.ts.map +1 -1
  114. package/out/tools/gold-set-sample.js +37 -121
  115. package/out/tools/gold-set-sample.js.map +1 -1
  116. package/out/tools/index.d.ts +24 -29
  117. package/out/tools/index.d.ts.map +1 -1
  118. package/out/tools/index.js +24 -29
  119. package/out/tools/index.js.map +1 -1
  120. package/out/tools/learned-scorer-clustering-eval.d.ts +1 -1
  121. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  122. package/out/tools/learned-scorer-clustering-eval.js +35 -170
  123. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  124. package/out/tools/learned-scorer-crossstate-eval.d.ts +5 -5
  125. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  126. package/out/tools/learned-scorer-crossstate-eval.js +44 -166
  127. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  128. package/out/tools/learned-scorer-eval.d.ts +1 -1
  129. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  130. package/out/tools/learned-scorer-eval.js +37 -173
  131. package/out/tools/learned-scorer-eval.js.map +1 -1
  132. package/out/tools/matcher-scale.d.ts.map +1 -1
  133. package/out/tools/matcher-scale.js +5 -5
  134. package/out/tools/matcher-scale.js.map +1 -1
  135. package/out/tools/nppes/org-name.d.ts +21 -0
  136. package/out/tools/nppes/org-name.d.ts.map +1 -0
  137. package/out/tools/nppes/org-name.js +13 -0
  138. package/out/tools/nppes/org-name.js.map +1 -0
  139. package/out/tools/nppes/overmerge-packet.d.ts +39 -0
  140. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  141. package/out/tools/nppes/overmerge-packet.js +55 -0
  142. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  143. package/out/tools/nppes/report.d.ts +93 -0
  144. package/out/tools/nppes/report.d.ts.map +1 -0
  145. package/out/tools/nppes/report.js +186 -0
  146. package/out/tools/nppes/report.js.map +1 -0
  147. package/out/tools/nppes/sample.d.ts +90 -0
  148. package/out/tools/nppes/sample.d.ts.map +1 -0
  149. package/out/tools/nppes/sample.js +131 -0
  150. package/out/tools/nppes/sample.js.map +1 -0
  151. package/out/tools/nppes/scoring.d.ts +36 -0
  152. package/out/tools/nppes/scoring.d.ts.map +1 -0
  153. package/out/tools/nppes/scoring.js +80 -0
  154. package/out/tools/nppes/scoring.js.map +1 -0
  155. package/out/tools/nppes/settings.d.ts +38 -0
  156. package/out/tools/nppes/settings.d.ts.map +1 -0
  157. package/out/tools/nppes/settings.js +79 -0
  158. package/out/tools/nppes/settings.js.map +1 -0
  159. package/out/tools/nppes/truth-grains.d.ts +50 -0
  160. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  161. package/out/tools/nppes/truth-grains.js +123 -0
  162. package/out/tools/nppes/truth-grains.js.map +1 -0
  163. package/out/tools/nppes-dedup-benchmark.d.ts +7 -3
  164. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  165. package/out/tools/nppes-dedup-benchmark.js +106 -673
  166. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  167. package/out/tools/shared.d.ts +244 -7
  168. package/out/tools/shared.d.ts.map +1 -1
  169. package/out/tools/shared.js +353 -21
  170. package/out/tools/shared.js.map +1 -1
  171. package/out/tools/train-cross-gbt.d.ts +7 -7
  172. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  173. package/out/tools/train-cross-gbt.js +47 -145
  174. package/out/tools/train-cross-gbt.js.map +1 -1
  175. package/out/tools/train-gbt.d.ts +7 -7
  176. package/out/tools/train-gbt.d.ts.map +1 -1
  177. package/out/tools/train-gbt.js +31 -111
  178. package/out/tools/train-gbt.js.map +1 -1
  179. package/out/tools/train-org-cross-gbt.d.ts +7 -5
  180. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  181. package/out/tools/train-org-cross-gbt.js +45 -141
  182. package/out/tools/train-org-cross-gbt.js.map +1 -1
  183. package/out/tools/txhhsc-to-oarow.d.ts +2 -2
  184. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  185. package/out/tools/txhhsc-to-oarow.js +9 -23
  186. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  187. package/out/tools/viz/browser.d.ts +34 -0
  188. package/out/tools/viz/browser.d.ts.map +1 -0
  189. package/out/tools/viz/browser.js +33 -0
  190. package/out/tools/viz/browser.js.map +1 -0
  191. package/out/tools/viz/cross-dataset-map.d.ts +4 -25
  192. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  193. package/out/tools/viz/cross-dataset-map.js +12 -33
  194. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  195. package/out/tools/viz/geocode-first-surface.d.ts +6 -35
  196. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  197. package/out/tools/viz/geocode-first-surface.js +10 -37
  198. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  199. package/out/tools/viz/render-map.d.ts +3 -6
  200. package/out/tools/viz/render-map.d.ts.map +1 -1
  201. package/out/tools/viz/render-map.js +9 -19
  202. package/out/tools/viz/render-map.js.map +1 -1
  203. package/out/tools/viz/render.d.ts +4 -9
  204. package/out/tools/viz/render.d.ts.map +1 -1
  205. package/out/tools/viz/render.js +24 -39
  206. package/out/tools/viz/render.js.map +1 -1
  207. package/out/tools/viz/source-provenance-map.d.ts +4 -24
  208. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  209. package/out/tools/viz/source-provenance-map.js +12 -32
  210. package/out/tools/viz/source-provenance-map.js.map +1 -1
  211. package/out/tools/viz/yardstick-figure.d.ts +2 -2
  212. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  213. package/out/tools/viz/yardstick-figure.js +5 -4
  214. package/out/tools/viz/yardstick-figure.js.map +1 -1
  215. package/out/types.d.ts +11 -1
  216. package/out/types.d.ts.map +1 -1
  217. package/out/types.js.map +1 -1
  218. package/package.json +180 -11
  219. package/tools/gold-set-sample.ts +0 -252
  220. package/tools/index.ts +0 -36
  221. package/tools/nppes-dedup-benchmark.ts +0 -1180
  222. package/tools/shared.ts +0 -160
  223. package/tools/train-cross-gbt.ts +0 -358
  224. package/tools/train-org-cross-gbt.ts +0 -329
  225. package/tools/viz/render.ts +0 -113
  226. /package/{models → lib/models}/crosssource-gbt-en-us.ts +0 -0
  227. /package/{models → lib/models}/dedup-gbt-en-us.ts +0 -0
  228. /package/{models → lib/models}/org-crosssource-gbt-en-us.ts +0 -0
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file Pairwise cluster scoring for the NPPES benchmark — precision/recall/F1 and adjusted Rand of recovered clusters
6
+ * against a truth labelling, plus the over-merge / under-merge shape counts.
7
+ */
8
+
9
+ import type { ResolvedEntity, SourceRecord } from "#index"
10
+
11
+ /**
12
+ * Pairs within a group of `n`.
13
+ */
14
+ export const choose2 = (n: number): number => (n * (n - 1)) / 2
15
+
16
+ /**
17
+ * One clustering scored against one truth labelling.
18
+ */
19
+ export interface Score {
20
+ precision: number
21
+ recall: number
22
+ f1: number
23
+ ari: number
24
+ clusters: number
25
+ singletons: number
26
+ overMergedClusters: number
27
+ recordsInOverMerged: number
28
+ maxNpisFused: number
29
+ splitNpis: number
30
+ }
31
+
32
+ /**
33
+ * Score recovered clusters against a truth labelling.
34
+ *
35
+ * Pairwise, not set-matching: a true pair is two records carrying the same `labelOf`, a predicted pair is two records
36
+ * in the same entity. `totalRecords` is the labelled population and only feeds the adjusted-Rand expectation, so it
37
+ * must be the whole record set rather than the clustered subset — a smaller value inflates ARI.
38
+ */
39
+ export function scoreEntities(
40
+ entities: readonly ResolvedEntity[],
41
+ labelOf: (rec: SourceRecord) => string,
42
+ totalRecords: number
43
+ ): Score {
44
+ const npiTotals = new Map<string, number>()
45
+ const npiClusters = new Map<string, Set<number>>()
46
+ let sumCK = 0 // Σ C(n_ck, 2)
47
+ let sumCluster = 0 // Σ_c C(|c|, 2)
48
+ let singletons = 0
49
+ let overMergedClusters = 0
50
+ let recordsInOverMerged = 0
51
+ let maxNpisFused = 0
52
+
53
+ entities.forEach((e, ci) => {
54
+ const byNPI = new Map<string, number>()
55
+
56
+ for (const rec of e.records) {
57
+ const lbl = labelOf(rec)
58
+ byNPI.set(lbl, (byNPI.get(lbl) ?? 0) + 1)
59
+ }
60
+
61
+ sumCluster += choose2(e.records.length)
62
+
63
+ if (e.records.length === 1) {
64
+ singletons++
65
+ }
66
+
67
+ if (byNPI.size > 1) {
68
+ overMergedClusters++
69
+ recordsInOverMerged += e.records.length
70
+ maxNpisFused = Math.max(maxNpisFused, byNPI.size)
71
+ }
72
+
73
+ for (const [npi, n] of byNPI) {
74
+ sumCK += choose2(n)
75
+ npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + n)
76
+ }
77
+
78
+ for (const rec of e.records) {
79
+ const lbl = labelOf(rec)
80
+ const s = npiClusters.get(lbl) ?? new Set<number>()
81
+ s.add(ci)
82
+ npiClusters.set(lbl, s)
83
+ }
84
+ })
85
+
86
+ let sumClass = 0
87
+
88
+ // Σ_k C(|k|, 2)
89
+ for (const total of npiTotals.values()) {
90
+ sumClass += choose2(total)
91
+ }
92
+
93
+ const tp = sumCK
94
+ const precision = tp + (sumCluster - tp) > 0 ? tp / sumCluster : 0
95
+ const recall = sumClass > 0 ? tp / sumClass : 0
96
+ const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
97
+ const expected = (sumCluster * sumClass) / choose2(totalRecords)
98
+ const maxIndex = (sumCluster + sumClass) / 2
99
+ const ari = maxIndex - expected !== 0 ? (tp - expected) / (maxIndex - expected) : 1
100
+ const splitNpis = [...npiClusters.values()].filter((s) => s.size > 1).length
101
+
102
+ return {
103
+ precision,
104
+ recall,
105
+ f1,
106
+ ari,
107
+ clusters: entities.length,
108
+ singletons,
109
+ overMergedClusters,
110
+ recordsInOverMerged,
111
+ maxNpisFused,
112
+ splitNpis,
113
+ }
114
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file The comparison-model setting progression the NPPES benchmark walks — each row turns one setting on so its marginal
6
+ * effect is isolated.
7
+ */
8
+
9
+ import type { TermFrequencyTable } from "@mailwoman/match"
10
+
11
+ /**
12
+ * The subset of `ResolveConfig` this progression varies.
13
+ */
14
+ export interface SettingConfig {
15
+ addressFrequency?: TermFrequencyTable | false
16
+ collapseSpatial?: boolean
17
+ discriminators?: string[]
18
+ requireCorroboration?: boolean
19
+ usePhone?: boolean
20
+ linkage?: "single" | "average"
21
+ exactDiscriminators?: string[]
22
+ }
23
+
24
+ /**
25
+ * One row of the progression.
26
+ */
27
+ export interface Setting {
28
+ label: string
29
+ config: SettingConfig
30
+ }
31
+
32
+ /**
33
+ * Build the progression against a corpus-wide address-frequency table.
34
+ *
35
+ * Every row sets BOTH `collapseSpatial` and `addressFrequency` EXPLICITLY, because the proven settings are default-on
36
+ * in `resolveEntities`: leave either implicit and the flipped default silently rides the `+ inverse-address-frequency`
37
+ * row, making the A1 delta read as 0. Every row is fed the corpus-wide table — the realistic deployment, where the CLI
38
+ * builds it from the full source files — so the zero-config default, whose input-scoped table is intentionally sparse
39
+ * on a sub-sample, has to be measured separately.
40
+ */
41
+ export function buildSettings(addressFrequency: TermFrequencyTable): Setting[] {
42
+ return [
43
+ {
44
+ label: "baseline (legacy: address-key + distance, settings OFF)",
45
+ config: { collapseSpatial: false, addressFrequency: false },
46
+ },
47
+ { label: "+ inverse-address-frequency (#617, corpus-wide)", config: { collapseSpatial: false, addressFrequency } },
48
+ { label: "+ collapsed spatial signal (A1, #625)", config: { collapseSpatial: true, addressFrequency } },
49
+ {
50
+ label: "+ authorized-official discriminator (#625)",
51
+ config: { collapseSpatial: true, addressFrequency, discriminators: ["authorizedOfficial"] },
52
+ },
53
+ // A2–A4 (#625): the built-but-unmeasured over-merge settings. Each builds on the A1 + discriminator
54
+ // stack so the marginal effect is isolated. A2 (require name/org corroboration) is the direct
55
+ // over-merge precision setting; A3 (phone) is the recall-tail corroborator that should keep A2 from
56
+ // killing name-drift links; A4 (average-linkage) splits a component joined only by a weak bridge.
57
+ {
58
+ label: "+ require name/org corroboration (A2, #625)",
59
+ config: {
60
+ collapseSpatial: true,
61
+ addressFrequency,
62
+ discriminators: ["authorizedOfficial"],
63
+ requireCorroboration: true,
64
+ },
65
+ },
66
+ {
67
+ label: "+ phone comparison (A3, #625)",
68
+ config: {
69
+ collapseSpatial: true,
70
+ addressFrequency,
71
+ discriminators: ["authorizedOfficial"],
72
+ requireCorroboration: true,
73
+ usePhone: true,
74
+ },
75
+ },
76
+ {
77
+ label: "+ average-linkage clustering (A4, #625, full A1–A4 stack)",
78
+ config: {
79
+ collapseSpatial: true,
80
+ addressFrequency,
81
+ discriminators: ["authorizedOfficial"],
82
+ requireCorroboration: true,
83
+ usePhone: true,
84
+ linkage: "average",
85
+ },
86
+ },
87
+ // A5 (#625): the taxonomy code-set discriminator — set-overlap agreement over the NPI's 15 taxonomy
88
+ // slots. The named "still-more-distinctive identifier" from the 2026-06-16 report: co-located
89
+ // DISTINCT providers usually have disjoint sets (the over-merge separator) while an entity's own
90
+ // records always share theirs (never splits). Stacked on the BEST prior classical config (A1 +
91
+ // authorized-official; A3 phone + A4 avg-linkage were measured neutral-to-negative and are left off).
92
+ {
93
+ label: "+ taxonomy code-set discriminator (A5, #625)",
94
+ config: {
95
+ collapseSpatial: true,
96
+ addressFrequency,
97
+ discriminators: ["authorizedOfficial"],
98
+ exactDiscriminators: ["taxonomy"],
99
+ },
100
+ },
101
+ ]
102
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file The org-name entity-truth grains: union-find labellings that collapse co-located same-org NPIs, keyed three
6
+ * ways — the address string, a haversine co-location radius, and an H3 cell.
7
+ */
8
+
9
+ import { createUnionFind, type UnionFind } from "@mailwoman/core/utils"
10
+ import { haversineKm, jaccard, type LatLon } from "@mailwoman/match"
11
+ import { latLngToCell } from "h3-js"
12
+
13
+ import type { SourceRecord } from "#index"
14
+ import { ORG_TAU, type NPIPrimary } from "#tools/nppes/org-name"
15
+
16
+ /**
17
+ * Same-building distance for the coordinate grain — the `DEFAULT_DISTANCE_LEVELS` grain.
18
+ */
19
+ export const COLOCATION_KM = 0.05
20
+
21
+ /**
22
+ * A truth labelling: the entity class a record belongs to.
23
+ */
24
+ export type TruthLabel = (rec: SourceRecord) => string
25
+
26
+ /**
27
+ * Union every pair in each block whose org names agree.
28
+ *
29
+ * Quadratic within a block, which is what keeps the test honest: the Jaccard test is per PAIR, so a chain of
30
+ * near-matches cannot transitively fuse two genuinely distinct co-located orgs unless some pair actually agrees.
31
+ */
32
+ function unionAgreeingPairs(
33
+ blocks: Iterable<readonly string[]>,
34
+ npiPrimary: Map<string, NPIPrimary>,
35
+ uf: UnionFind
36
+ ): void {
37
+ for (const group of blocks) {
38
+ for (let i = 0; i < group.length; i++) {
39
+ for (let j = i + 1; j < group.length; j++) {
40
+ if (jaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
41
+ uf.union(group[i]!, group[j]!)
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ /**
49
+ * An NPI's primary practice coordinate — the FIRST geocoded record it owns, which is its primary row because the sample
50
+ * builder pushes that row before the alternate-name and mailing variants.
51
+ */
52
+ export function collectPrimaryCoordinates(records: readonly SourceRecord[]): Map<string, LatLon> {
53
+ const npiCoord = new Map<string, LatLon>()
54
+
55
+ for (const rec of records) {
56
+ const c = rec.address?.geocode?.coordinate
57
+
58
+ if (c && !npiCoord.has(rec.id)) {
59
+ npiCoord.set(rec.id, c)
60
+ }
61
+ }
62
+
63
+ return npiCoord
64
+ }
65
+
66
+ /**
67
+ * The string-keyed org-name truth: same NPI ⇒ same entity (so an NPI's records stay together and recall is preserved),
68
+ * PLUS union two NPIs at the same address KEY whose primary org names agree.
69
+ *
70
+ * Blocking on the address string is a conservative LOWER bound — `1504 Taub LOOP` and `1504 Taub LP STE 100` key apart
71
+ * even though they are one building, so a correct merge across them is still charged as an error. The coordinate grain
72
+ * below is the tighter reading. Neither relies on the NPPES subpart flag, which the gold set showed misses 37%.
73
+ */
74
+ export function buildOrgNameGrain(npiPrimary: Map<string, NPIPrimary>): TruthLabel {
75
+ const uf = createUnionFind()
76
+ const byAddr = new Map<string, string[]>()
77
+
78
+ for (const [npi, info] of npiPrimary) {
79
+ uf.find(npi)
80
+
81
+ // seed
82
+ if (!info.addrKey) continue
83
+
84
+ if (!byAddr.has(info.addrKey)) {
85
+ byAddr.set(info.addrKey, [])
86
+ }
87
+
88
+ byAddr.get(info.addrKey)!.push(npi)
89
+ }
90
+
91
+ unionAgreeingPairs(byAddr.values(), npiPrimary, uf)
92
+
93
+ return (rec) => (npiPrimary.has(rec.id) ? uf.find(rec.id) : rec.id)
94
+ }
95
+
96
+ /**
97
+ * The coordinate-keyed org-name truth: union same-org NPIs whose primary practice coordinates fall within
98
+ * {@linkcode COLOCATION_KM}. Blocking by the GEOCODED BUILDING catches the same-building pairs the address string keys
99
+ * apart, so this F1 is at or above the string grain's; the Jaccard test still blocks distinct co-located orgs.
100
+ *
101
+ * Brute-force pairwise over the sampled NPIs — trivial at this scale, and unlike a cell key it has no boundary
102
+ * artifact.
103
+ */
104
+ export function buildOrgNameCoordGrain(npiPrimary: Map<string, NPIPrimary>, npiCoord: Map<string, LatLon>): TruthLabel {
105
+ const uf = createUnionFind()
106
+ const coLocated = [...npiPrimary.keys()].filter((n) => npiCoord.has(n))
107
+
108
+ for (const n of npiPrimary.keys()) {
109
+ uf.find(n)
110
+ }
111
+
112
+ // seed every NPI (un-geocoded ones stay singletons)
113
+ for (let i = 0; i < coLocated.length; i++) {
114
+ for (let j = i + 1; j < coLocated.length; j++) {
115
+ const a = coLocated[i]!
116
+ const b = coLocated[j]!
117
+
118
+ if (haversineKm(npiCoord.get(a)!, npiCoord.get(b)!) > COLOCATION_KM) continue
119
+
120
+ if (jaccard(npiPrimary.get(a)!.tokens, npiPrimary.get(b)!.tokens) >= ORG_TAU) {
121
+ uf.union(a, b)
122
+ }
123
+ }
124
+ }
125
+
126
+ return (rec) => (npiPrimary.has(rec.id) ? uf.find(rec.id) : rec.id)
127
+ }
128
+
129
+ /**
130
+ * The H3-cell org-name truth — the same building grain keyed on a cell instead of a radius, so co-location blocking is
131
+ * O(n) rather than O(n²).
132
+ *
133
+ * A robustness check on the coordinate grain, not a replacement: a hard cell boundary can split a same-building pair
134
+ * into adjacent cells, so this slightly UNDER-counts relative to the radius. Coarser resolutions absorb more of that.
135
+ */
136
+ export function buildOrgNameH3Grain(
137
+ npiPrimary: Map<string, NPIPrimary>,
138
+ npiCoord: Map<string, LatLon>,
139
+ h3Res: number
140
+ ): TruthLabel {
141
+ const uf = createUnionFind()
142
+ const byCell = new Map<string, string[]>()
143
+
144
+ for (const n of npiPrimary.keys()) {
145
+ uf.find(n) // seed every NPI (un-geocoded ones stay singletons)
146
+ const c = npiCoord.get(n)
147
+
148
+ if (!c) continue
149
+ const cell = latLngToCell(c.latitude, c.longitude, h3Res)
150
+
151
+ if (!byCell.has(cell)) {
152
+ byCell.set(cell, [])
153
+ }
154
+
155
+ byCell.get(cell)!.push(n)
156
+ }
157
+
158
+ unionAgreeingPairs(byCell.values(), npiPrimary, uf)
159
+
160
+ return (rec) => (npiPrimary.has(rec.id) ? uf.find(rec.id) : rec.id)
161
+ }