@mailwoman/registry 9.4.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/README.md +10 -10
  2. package/lib/address-key.ts +14 -10
  3. package/lib/geocode-handler.ts +6 -4
  4. package/lib/geojson.ts +13 -17
  5. package/lib/ingest.ts +57 -83
  6. package/lib/learned-scorer.ts +38 -44
  7. package/lib/map-html.ts +24 -70
  8. package/lib/models/crosssource-gbt-en-us.ts +9 -7
  9. package/lib/models/dedup-gbt-en-us.ts +9 -8
  10. package/lib/models/org-crosssource-gbt-en-us.ts +10 -8
  11. package/lib/reconcile.ts +45 -55
  12. package/lib/resolve.ts +180 -124
  13. package/lib/types.ts +18 -12
  14. package/out/address-key.d.ts +14 -10
  15. package/out/address-key.d.ts.map +1 -1
  16. package/out/address-key.js +14 -10
  17. package/out/address-key.js.map +1 -1
  18. package/out/geocode-handler.d.ts +6 -4
  19. package/out/geocode-handler.d.ts.map +1 -1
  20. package/out/geocode-handler.js +6 -4
  21. package/out/geocode-handler.js.map +1 -1
  22. package/out/geojson.d.ts +9 -5
  23. package/out/geojson.d.ts.map +1 -1
  24. package/out/geojson.js +13 -15
  25. package/out/geojson.js.map +1 -1
  26. package/out/ingest.d.ts +46 -75
  27. package/out/ingest.d.ts.map +1 -1
  28. package/out/ingest.js +27 -54
  29. package/out/ingest.js.map +1 -1
  30. package/out/learned-scorer.d.ts +29 -26
  31. package/out/learned-scorer.d.ts.map +1 -1
  32. package/out/learned-scorer.js +31 -39
  33. package/out/learned-scorer.js.map +1 -1
  34. package/out/map-html.d.ts +13 -32
  35. package/out/map-html.d.ts.map +1 -1
  36. package/out/map-html.js +9 -62
  37. package/out/map-html.js.map +1 -1
  38. package/out/models/crosssource-gbt-en-us.d.ts +9 -7
  39. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -1
  40. package/out/models/crosssource-gbt-en-us.js +9 -7
  41. package/out/models/crosssource-gbt-en-us.js.map +1 -1
  42. package/out/models/dedup-gbt-en-us.d.ts +9 -8
  43. package/out/models/dedup-gbt-en-us.d.ts.map +1 -1
  44. package/out/models/dedup-gbt-en-us.js +9 -8
  45. package/out/models/dedup-gbt-en-us.js.map +1 -1
  46. package/out/models/org-crosssource-gbt-en-us.d.ts +10 -8
  47. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -1
  48. package/out/models/org-crosssource-gbt-en-us.js +10 -8
  49. package/out/models/org-crosssource-gbt-en-us.js.map +1 -1
  50. package/out/reconcile.d.ts +35 -50
  51. package/out/reconcile.d.ts.map +1 -1
  52. package/out/reconcile.js +19 -43
  53. package/out/reconcile.js.map +1 -1
  54. package/out/resolve.d.ts +150 -90
  55. package/out/resolve.d.ts.map +1 -1
  56. package/out/resolve.js +62 -63
  57. package/out/resolve.js.map +1 -1
  58. package/out/tools/coverage-reconciliation.d.ts +23 -23
  59. package/out/tools/coverage-reconciliation.d.ts.map +1 -1
  60. package/out/tools/coverage-reconciliation.js +15 -26
  61. package/out/tools/coverage-reconciliation.js.map +1 -1
  62. package/out/tools/cross/dataset-correlation.d.ts +58 -0
  63. package/out/tools/cross/dataset-correlation.d.ts.map +1 -0
  64. package/out/tools/{cross-dataset-correlation.js → cross/dataset-correlation.js} +10 -62
  65. package/out/tools/cross/dataset-correlation.js.map +1 -0
  66. package/out/tools/cross/source-threshold-sweep.d.ts +60 -0
  67. package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -0
  68. package/out/tools/{cross-source-threshold-sweep.js → cross/source-threshold-sweep.js} +15 -41
  69. package/out/tools/cross/source-threshold-sweep.js.map +1 -0
  70. package/out/tools/dedup-ceiling.d.ts +23 -26
  71. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  72. package/out/tools/dedup-ceiling.js +22 -41
  73. package/out/tools/dedup-ceiling.js.map +1 -1
  74. package/out/tools/eval-geocoder.d.ts +22 -15
  75. package/out/tools/eval-geocoder.d.ts.map +1 -1
  76. package/out/tools/eval-geocoder.js +5 -6
  77. package/out/tools/eval-geocoder.js.map +1 -1
  78. package/out/tools/geocoder/namesake-probe.d.ts +33 -0
  79. package/out/tools/geocoder/namesake-probe.d.ts.map +1 -0
  80. package/out/tools/{geocoder-namesake-probe.js → geocoder/namesake-probe.js} +7 -8
  81. package/out/tools/geocoder/namesake-probe.js.map +1 -0
  82. package/out/tools/geocoder/vs-provided-coords.d.ts +53 -0
  83. package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -0
  84. package/out/tools/{geocoder-vs-provided-coords.js → geocoder/vs-provided-coords.js} +31 -28
  85. package/out/tools/geocoder/vs-provided-coords.js.map +1 -0
  86. package/out/tools/gold-set-sample.d.ts +27 -18
  87. package/out/tools/gold-set-sample.d.ts.map +1 -1
  88. package/out/tools/gold-set-sample.js +18 -22
  89. package/out/tools/gold-set-sample.js.map +1 -1
  90. package/out/tools/learned/scorer/clustering-eval.d.ts +77 -0
  91. package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -0
  92. package/out/tools/{learned-scorer-clustering-eval.js → learned/scorer/clustering-eval.js} +29 -39
  93. package/out/tools/learned/scorer/clustering-eval.js.map +1 -0
  94. package/out/tools/learned/scorer/crossstate-eval.d.ts +65 -0
  95. package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -0
  96. package/out/tools/{learned-scorer-crossstate-eval.js → learned/scorer/crossstate-eval.js} +20 -26
  97. package/out/tools/learned/scorer/crossstate-eval.js.map +1 -0
  98. package/out/tools/learned/scorer/eval.d.ts +60 -0
  99. package/out/tools/learned/scorer/eval.d.ts.map +1 -0
  100. package/out/tools/{learned-scorer-eval.js → learned/scorer/eval.js} +12 -72
  101. package/out/tools/learned/scorer/eval.js.map +1 -0
  102. package/out/tools/matcher-scale.d.ts +12 -17
  103. package/out/tools/matcher-scale.d.ts.map +1 -1
  104. package/out/tools/matcher-scale.js +11 -29
  105. package/out/tools/matcher-scale.js.map +1 -1
  106. package/out/tools/nppes/dedup-benchmark.d.ts +81 -0
  107. package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -0
  108. package/out/tools/{nppes-dedup-benchmark.js → nppes/dedup-benchmark.js} +21 -67
  109. package/out/tools/nppes/dedup-benchmark.js.map +1 -0
  110. package/out/tools/nppes/org-name.d.ts +5 -4
  111. package/out/tools/nppes/org-name.d.ts.map +1 -1
  112. package/out/tools/nppes/org-name.js +2 -2
  113. package/out/tools/nppes/org-name.js.map +1 -1
  114. package/out/tools/nppes/overmerge-packet.d.ts +15 -11
  115. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -1
  116. package/out/tools/nppes/overmerge-packet.js +7 -8
  117. package/out/tools/nppes/overmerge-packet.js.map +1 -1
  118. package/out/tools/nppes/report.d.ts +17 -13
  119. package/out/tools/nppes/report.d.ts.map +1 -1
  120. package/out/tools/nppes/report.js +6 -14
  121. package/out/tools/nppes/report.js.map +1 -1
  122. package/out/tools/nppes/sample.d.ts +28 -17
  123. package/out/tools/nppes/sample.d.ts.map +1 -1
  124. package/out/tools/nppes/sample.js +23 -26
  125. package/out/tools/nppes/sample.js.map +1 -1
  126. package/out/tools/nppes/scoring.d.ts +7 -6
  127. package/out/tools/nppes/scoring.d.ts.map +1 -1
  128. package/out/tools/nppes/scoring.js +6 -5
  129. package/out/tools/nppes/scoring.js.map +1 -1
  130. package/out/tools/nppes/settings.d.ts +10 -7
  131. package/out/tools/nppes/settings.d.ts.map +1 -1
  132. package/out/tools/nppes/settings.js +16 -16
  133. package/out/tools/nppes/settings.js.map +1 -1
  134. package/out/tools/nppes/truth-grains.d.ts +36 -23
  135. package/out/tools/nppes/truth-grains.d.ts.map +1 -1
  136. package/out/tools/nppes/truth-grains.js +36 -20
  137. package/out/tools/nppes/truth-grains.js.map +1 -1
  138. package/out/tools/shared.d.ts +63 -59
  139. package/out/tools/shared.d.ts.map +1 -1
  140. package/out/tools/shared.js +49 -66
  141. package/out/tools/shared.js.map +1 -1
  142. package/out/tools/train/cross-gbt.d.ts +88 -0
  143. package/out/tools/train/cross-gbt.d.ts.map +1 -0
  144. package/out/tools/{train-cross-gbt.js → train/cross-gbt.js} +15 -26
  145. package/out/tools/train/cross-gbt.js.map +1 -0
  146. package/out/tools/train/gbt.d.ts +85 -0
  147. package/out/tools/train/gbt.d.ts.map +1 -0
  148. package/out/tools/{train-gbt.js → train/gbt.js} +28 -32
  149. package/out/tools/train/gbt.js.map +1 -0
  150. package/out/tools/train/org-cross-gbt.d.ts +84 -0
  151. package/out/tools/train/org-cross-gbt.d.ts.map +1 -0
  152. package/out/tools/{train-org-cross-gbt.js → train/org-cross-gbt.js} +19 -23
  153. package/out/tools/train/org-cross-gbt.js.map +1 -0
  154. package/out/tools/txhhsc-to-oarow.d.ts +14 -9
  155. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  156. package/out/tools/txhhsc-to-oarow.js +16 -15
  157. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  158. package/out/tools/viz/browser.d.ts +6 -5
  159. package/out/tools/viz/browser.d.ts.map +1 -1
  160. package/out/tools/viz/browser.js +6 -5
  161. package/out/tools/viz/browser.js.map +1 -1
  162. package/out/tools/viz/cross-dataset-map.d.ts +7 -4
  163. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  164. package/out/tools/viz/cross-dataset-map.js +9 -6
  165. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  166. package/out/tools/viz/geocode-first-surface.d.ts +10 -5
  167. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  168. package/out/tools/viz/geocode-first-surface.js +16 -11
  169. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  170. package/out/tools/viz/{render-map.d.ts → render/map.d.ts} +6 -6
  171. package/out/tools/viz/render/map.d.ts.map +1 -0
  172. package/out/tools/viz/{render-map.js → render/map.js} +7 -6
  173. package/out/tools/viz/render/map.js.map +1 -0
  174. package/out/tools/viz/render.d.ts +12 -8
  175. package/out/tools/viz/render.d.ts.map +1 -1
  176. package/out/tools/viz/render.js +8 -7
  177. package/out/tools/viz/render.js.map +1 -1
  178. package/out/tools/viz/source-provenance-map.d.ts +19 -7
  179. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  180. package/out/tools/viz/source-provenance-map.js +11 -8
  181. package/out/tools/viz/source-provenance-map.js.map +1 -1
  182. package/out/tools/viz/yardstick-figure.d.ts +2 -21
  183. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  184. package/out/tools/viz/yardstick-figure.js +3 -39
  185. package/out/tools/viz/yardstick-figure.js.map +1 -1
  186. package/out/types.d.ts +17 -11
  187. package/out/types.d.ts.map +1 -1
  188. package/out/types.js +2 -2
  189. package/out/types.js.map +1 -1
  190. package/package.json +41 -184
  191. package/{lib/tools → tools}/coverage-reconciliation.ts +27 -30
  192. package/{lib/tools/cross-dataset-correlation.ts → tools/cross/dataset-correlation.ts} +31 -72
  193. package/{lib/tools/cross-source-threshold-sweep.ts → tools/cross/source-threshold-sweep.ts} +29 -46
  194. package/{lib/tools → tools}/dedup-ceiling.ts +34 -45
  195. package/tools/eval-geocoder.ts +74 -0
  196. package/{lib/tools/geocoder-namesake-probe.ts → tools/geocoder/namesake-probe.ts} +9 -8
  197. package/{lib/tools/geocoder-vs-provided-coords.ts → tools/geocoder/vs-provided-coords.ts} +39 -30
  198. package/{lib/tools → tools}/gold-set-sample.ts +35 -29
  199. package/{lib/tools/learned-scorer-clustering-eval.ts → tools/learned/scorer/clustering-eval.ts} +49 -45
  200. package/{lib/tools/learned-scorer-crossstate-eval.ts → tools/learned/scorer/crossstate-eval.ts} +34 -30
  201. package/{lib/tools/learned-scorer-eval.ts → tools/learned/scorer/eval.ts} +35 -78
  202. package/{lib/tools → tools}/matcher-scale.ts +21 -33
  203. package/{lib/tools/nppes-dedup-benchmark.ts → tools/nppes/dedup-benchmark.ts} +37 -82
  204. package/{lib/tools → tools}/nppes/org-name.ts +5 -4
  205. package/{lib/tools → tools}/nppes/overmerge-packet.ts +17 -13
  206. package/{lib/tools → tools}/nppes/report.ts +32 -25
  207. package/{lib/tools → tools}/nppes/sample.ts +41 -36
  208. package/{lib/tools → tools}/nppes/scoring.ts +7 -6
  209. package/{lib/tools → tools}/nppes/settings.ts +16 -16
  210. package/{lib/tools → tools}/nppes/truth-grains.ts +46 -26
  211. package/{lib/tools → tools}/shared.ts +73 -83
  212. package/{lib/tools/train-cross-gbt.ts → tools/train/cross-gbt.ts} +38 -34
  213. package/{lib/tools/train-gbt.ts → tools/train/gbt.ts} +55 -41
  214. package/{lib/tools/train-org-cross-gbt.ts → tools/train/org-cross-gbt.ts} +39 -30
  215. package/{lib/tools → tools}/txhhsc-to-oarow.ts +24 -18
  216. package/{lib/tools → tools}/viz/browser.ts +6 -5
  217. package/{lib/tools → tools}/viz/cross-dataset-map.ts +15 -9
  218. package/{lib/tools → tools}/viz/geocode-first-surface.ts +28 -17
  219. package/{lib/tools/viz/render-map.ts → tools/viz/render/map.ts} +7 -6
  220. package/{lib/tools → tools}/viz/render.ts +16 -11
  221. package/{lib/tools → tools}/viz/source-provenance-map.ts +30 -15
  222. package/{lib/tools → tools}/viz/yardstick-figure.ts +6 -43
  223. package/lib/tools/eval-geocoder.ts +0 -67
  224. package/lib/tools/index.ts +0 -31
  225. package/out/tools/cross-dataset-correlation.d.ts +0 -65
  226. package/out/tools/cross-dataset-correlation.d.ts.map +0 -1
  227. package/out/tools/cross-dataset-correlation.js.map +0 -1
  228. package/out/tools/cross-source-threshold-sweep.d.ts +0 -66
  229. package/out/tools/cross-source-threshold-sweep.d.ts.map +0 -1
  230. package/out/tools/cross-source-threshold-sweep.js.map +0 -1
  231. package/out/tools/geocoder-namesake-probe.d.ts +0 -32
  232. package/out/tools/geocoder-namesake-probe.d.ts.map +0 -1
  233. package/out/tools/geocoder-namesake-probe.js.map +0 -1
  234. package/out/tools/geocoder-vs-provided-coords.d.ts +0 -50
  235. package/out/tools/geocoder-vs-provided-coords.d.ts.map +0 -1
  236. package/out/tools/geocoder-vs-provided-coords.js.map +0 -1
  237. package/out/tools/index.d.ts +0 -31
  238. package/out/tools/index.d.ts.map +0 -1
  239. package/out/tools/index.js +0 -31
  240. package/out/tools/index.js.map +0 -1
  241. package/out/tools/learned-scorer-clustering-eval.d.ts +0 -74
  242. package/out/tools/learned-scorer-clustering-eval.d.ts.map +0 -1
  243. package/out/tools/learned-scorer-clustering-eval.js.map +0 -1
  244. package/out/tools/learned-scorer-crossstate-eval.d.ts +0 -59
  245. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +0 -1
  246. package/out/tools/learned-scorer-crossstate-eval.js.map +0 -1
  247. package/out/tools/learned-scorer-eval.d.ts +0 -77
  248. package/out/tools/learned-scorer-eval.d.ts.map +0 -1
  249. package/out/tools/learned-scorer-eval.js.map +0 -1
  250. package/out/tools/nppes-dedup-benchmark.d.ts +0 -101
  251. package/out/tools/nppes-dedup-benchmark.d.ts.map +0 -1
  252. package/out/tools/nppes-dedup-benchmark.js.map +0 -1
  253. package/out/tools/train-cross-gbt.d.ts +0 -78
  254. package/out/tools/train-cross-gbt.d.ts.map +0 -1
  255. package/out/tools/train-cross-gbt.js.map +0 -1
  256. package/out/tools/train-gbt.d.ts +0 -69
  257. package/out/tools/train-gbt.d.ts.map +0 -1
  258. package/out/tools/train-gbt.js.map +0 -1
  259. package/out/tools/train-org-cross-gbt.d.ts +0 -71
  260. package/out/tools/train-org-cross-gbt.d.ts.map +0 -1
  261. package/out/tools/train-org-cross-gbt.js.map +0 -1
  262. package/out/tools/viz/render-map.d.ts.map +0 -1
  263. package/out/tools/viz/render-map.js.map +0 -1
@@ -2,12 +2,13 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
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.
5
+ * @file Defines union-find truth labels that group co-located NPIs for one organization.
6
+ * One label uses address strings. Another uses a haversine radius. The third uses H3 cells.
7
7
  */
8
8
 
9
9
  import { createUnionFind, type UnionFind } from "@mailwoman/core/utils"
10
- import { haversineKm, jaccard, type LatLon } from "@mailwoman/match"
10
+ import { haversineKm, jaccard } from "@mailwoman/match"
11
+ import type { GeoCoordinate } from "@mailwoman/spatial"
11
12
  import { latLngToCell } from "h3-js"
12
13
 
13
14
  import type { SourceRecord } from "#index"
@@ -19,15 +20,18 @@ import { ORG_TAU, type NPIPrimary } from "#tools/nppes/org-name"
19
20
  export const COLOCATION_KM = 0.05
20
21
 
21
22
  /**
22
- * A truth labelling: the entity class a record belongs to.
23
+ * A truth labeling: the entity class a record belongs to.
23
24
  */
24
25
  export type TruthLabel = (rec: SourceRecord) => string
25
26
 
26
27
  /**
27
28
  * Union every pair in each block whose org names agree.
28
29
  *
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.
30
+ * Checks every pair within a block.
31
+ * This preserves the per-pair Jaccard test.
32
+ *
33
+ * Therefore, a chain of near-matches cannot transitively fuse two genuinely distinct
34
+ * co-located orgs unless some pair actually agrees.
31
35
  */
32
36
  function unionAgreeingPairs(
33
37
  blocks: Iterable<readonly string[]>,
@@ -46,11 +50,13 @@ function unionAgreeingPairs(
46
50
  }
47
51
 
48
52
  /**
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.
53
+ * An NPI's primary practice coordinate.
54
+ *
55
+ * Returns the first geocoded record for the NPI.
56
+ * The sample builder adds this primary row before alternate-name and mailing variants.
51
57
  */
52
- export function collectPrimaryCoordinates(records: readonly SourceRecord[]): Map<string, LatLon> {
53
- const npiCoord = new Map<string, LatLon>()
58
+ export function collectPrimaryCoordinates(records: readonly SourceRecord[]): Map<string, GeoCoordinate> {
59
+ const npiCoord = new Map<string, GeoCoordinate>()
54
60
 
55
61
  for (const rec of records) {
56
62
  const c = rec.address?.geocode?.coordinate
@@ -64,12 +70,17 @@ export function collectPrimaryCoordinates(records: readonly SourceRecord[]): Map
64
70
  }
65
71
 
66
72
  /**
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.
73
+ * The string-keyed org-name truth: same NPI ⇒ same entity
74
+ * (so an NPI's records stay together and recall is preserved), plus union two NPIs
75
+ * at the same address KEY whose primary org names agree.
69
76
  *
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%.
77
+ * The address-string block provides a conservative lower bound.
78
+ * `1504 Taub loop` and `1504 Taub LP STE 100` key apart even though they are one building,
79
+ * so a correct merge across them is still charged as an error.
80
+ * The coordinate grain below is the tighter reading.
81
+ *
82
+ * Neither method uses the NPPES subpart flag.
83
+ * The gold set misses 37% of cases when grouped by that flag.
73
84
  */
74
85
  export function buildOrgNameGrain(npiPrimary: Map<string, NPIPrimary>): TruthLabel {
75
86
  const uf = createUnionFind()
@@ -94,14 +105,20 @@ export function buildOrgNameGrain(npiPrimary: Map<string, NPIPrimary>): TruthLab
94
105
  }
95
106
 
96
107
  /**
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.
108
+ * The coordinate-keyed org-name truth: union same-org NPIs whose primary practice
109
+ * coordinates fall within {@linkcode COLOCATION_KM}.
110
+ *
111
+ * A geocoded-building block catches same-building pairs that the address string keys apart,
112
+ * so this F1 is at or above the string grain's.
113
+ * The Jaccard test still blocks distinct co-located orgs.
100
114
  *
101
- * Brute-force pairwise over the sampled NPIs — trivial at this scale, and unlike a cell key it has no boundary
102
- * artifact.
115
+ * Compares every sampled NPI pair.
116
+ * This is small enough for the sample and has no cell-boundary artifact.
103
117
  */
104
- export function buildOrgNameCoordGrain(npiPrimary: Map<string, NPIPrimary>, npiCoord: Map<string, LatLon>): TruthLabel {
118
+ export function buildOrgNameCoordGrain(
119
+ npiPrimary: Map<string, NPIPrimary>,
120
+ npiCoord: Map<string, GeoCoordinate>
121
+ ): TruthLabel {
105
122
  const uf = createUnionFind()
106
123
  const coLocated = [...npiPrimary.keys()].filter((n) => npiCoord.has(n))
107
124
 
@@ -127,15 +144,18 @@ export function buildOrgNameCoordGrain(npiPrimary: Map<string, NPIPrimary>, npiC
127
144
  }
128
145
 
129
146
  /**
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²).
147
+ * The H3-cell org-name truth.
148
+ *
149
+ * The same building grain keyed on a cell instead of a radius, so co-location
150
+ * blocking is O(n) rather than O(n²).
132
151
  *
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.
152
+ * A robustness check on the coordinate grain rather than a replacement: a hard cell boundary can split
153
+ * a same-building pair into adjacent cells, so this slightly under-counts relative to the radius.
154
+ * Coarser resolutions absorb more of that.
135
155
  */
136
156
  export function buildOrgNameH3Grain(
137
157
  npiPrimary: Map<string, NPIPrimary>,
138
- npiCoord: Map<string, LatLon>,
158
+ npiCoord: Map<string, GeoCoordinate>,
139
159
  h3Res: number
140
160
  ): TruthLabel {
141
161
  const uf = createUnionFind()
@@ -3,13 +3,11 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
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.
6
+ * Shared helpers used by two or more probes in the `registry/tools` probe battery.
10
7
  */
11
8
 
12
9
  import { makeDirectories, writeLocalFile } from "@mailwoman/core/fs/writers"
10
+ import { stringifyJSON } from "@mailwoman/core/json"
13
11
  import { isPresent } from "@mailwoman/core/objects"
14
12
  import { makeLcg } from "@mailwoman/core/random"
15
13
  import { block, gbtScore, trainGBT, type TermFrequencyTable } from "@mailwoman/match"
@@ -30,7 +28,10 @@ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
30
28
  import type { Score } from "#tools/nppes/scoring"
31
29
 
32
30
  /**
33
- * One source a cross-source probe ingests: where it lives, the column mapping, and an in-state filter.
31
+ * One source a cross-source probe ingests.
32
+ *
33
+ * Its spec gives the path and column mapping.
34
+ * The spec also provides an in-state filter.
34
35
  */
35
36
  export interface SourceSpec {
36
37
  source: string
@@ -41,7 +42,8 @@ export interface SourceSpec {
41
42
  */
42
43
  inState: (row: Record<string, string>) => boolean
43
44
  /**
44
- * Optional: a row carries ≥1 addressable entity — yield each as its own row. Default identity.
45
+ * Optional: a row carrying ≥1 addressable entity yields each as its own row.
46
+ * Default identity.
45
47
  */
46
48
  explode?: (row: Record<string, string>) => Record<string, string>[]
47
49
  }
@@ -52,8 +54,8 @@ export interface SourceSpec {
52
54
  export const norm = (s: string | undefined): string => (s ?? "").trim()
53
55
 
54
56
  /**
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
+ * Corporate-form suffixes and function words that add no identity — dropped from an organization name
58
+ * before its tokens are compared, so the domain words include the distinguishing signal.
57
59
  */
58
60
  const ORGANIZATION_STOP_WORDS = new Set([
59
61
  "llc",
@@ -74,11 +76,8 @@ const ORGANIZATION_STOP_WORDS = new Set([
74
76
  ])
75
77
 
76
78
  /**
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.
79
+ * The token set of an organization name for the probes' cheap Jaccard overlap,
80
+ * never blocking or display — not a canonical form.
82
81
  */
83
82
  export function orgTokens(s: string): Set<string> {
84
83
  return new Set(
@@ -97,7 +96,8 @@ export const addr = (line: string, city: string, st: string, zip: string): strin
97
96
  [norm(line), norm(city), norm(st), norm(zip)].filter(isPresent).join(", ")
98
97
 
99
98
  /**
100
- * Population standard deviation; `0` on an empty sample, because these feed report tables that print a number per row.
99
+ * Population standard deviation; `0` on an empty sample, because these feed
100
+ * report tables that print a number per row.
101
101
  */
102
102
  export const std = (xs: readonly number[]): number => {
103
103
  const m = xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
@@ -105,18 +105,21 @@ export const std = (xs: readonly number[]): number => {
105
105
  return Math.sqrt(xs.map((x) => (x - m) ** 2).reduce((a, b) => a + b, 0) / Math.max(1, xs.length))
106
106
  }
107
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 "%").
108
+ /**
109
+ * Takes a fraction and omits the percent sign, unlike core `formatPercent`'s
110
+ * numerator/denominator interface.
111
+ * Call sites append their own `%`.
112
+ */
110
113
  export const pct = (x: number): string => (100 * x).toFixed(1)
111
114
 
112
115
  /**
113
- * Sign prefix for a signed delta — `"+"` for a non-negative value (a negative one carries its own sign).
116
+ * Sign prefix for a signed delta: `"+"` for a non-negative value, since a negative one includes its sign.
114
117
  */
115
118
  export const sgn = (x: number): string => (x >= 0 ? "+" : "")
116
119
 
117
120
  /**
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.
121
+ * Logistic function with the input clamped to ±30, past which `Math.exp` underflows to 0
122
+ * and the gradient step silently becomes a no-op.
120
123
  */
121
124
  export const sigmoid = (z: number): number => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
122
125
 
@@ -137,14 +140,8 @@ export const inTXBBOX = (lat: number, lon: number): boolean =>
137
140
  lat >= TX_BBOX.latMin && lat <= TX_BBOX.latMax && lon >= TX_BBOX.lonMin && lon <= TX_BBOX.lonMax
138
141
 
139
142
  /**
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.
143
+ * NPPES registry column headers, by the short name the probes read them under. no code
144
+ * enumerates this object, so adding a column cannot change a probe's behavior.
148
145
  */
149
146
  export const NPPES_COLUMNS = {
150
147
  npi: "NPI",
@@ -167,7 +164,8 @@ export const NPPES_COLUMNS = {
167
164
  isSubpart: "Is Organization Subpart",
168
165
  parentLBN: "Parent Organization LBN",
169
166
  parentTIN: "Parent Organization TIN",
170
- // #625 taxonomy discriminator: the 15 taxonomy slots; collected as a set (any shared code = agreement).
167
+ // The 15 taxonomy slots.
168
+ // Any shared code counts as agreement.
171
169
  taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
172
170
  }
173
171
 
@@ -177,13 +175,14 @@ export const NPPES_COLUMNS = {
177
175
  export const MIN_GROUP_SIZE = 5
178
176
 
179
177
  /**
180
- * Gradient-descent epochs for {@link trainLogisticRegression}. Fixed rather than early-stopped so seeds stay comparable.
178
+ * Gradient-descent epochs for {@link trainLogisticRegression}, fixed
179
+ * rather than early-stopped so seeds stay comparable.
181
180
  */
182
181
  export const TRAINING_EPOCHS = 400
183
182
 
184
183
  /**
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.
184
+ * Smallest mean F1 gap counted as a real difference between models rather than seed
185
+ * noise. verdicts inside ±this are reported as a tie.
187
186
  */
188
187
  export const MIN_MEANINGFUL_F1_DELTA = 0.02
189
188
 
@@ -198,9 +197,9 @@ export const LR_LEARNING_RATE = 0.1
198
197
  export const LR_L2 = 1e-3
199
198
 
200
199
  /**
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.
200
+ * L2-regularized logistic regression by batch gradient descent over {@link TRAINING_EPOCHS}
201
+ * epochs, where `w` stores per-sample class weights, returning the logit rather than
202
+ * the probability so it is threshold-comparable across a fixed feature layout.
204
203
  */
205
204
  export function trainLogisticRegression(
206
205
  X: readonly (readonly number[])[],
@@ -250,9 +249,11 @@ export function trainLogisticRegression(
250
249
  }
251
250
 
252
251
  /**
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.
252
+ * `n + 1` evenly-spaced order statistics of an already-sorted sample, de-duplicated,
253
+ * that a GBT node considers as candidate splits.
254
+ *
255
+ * An empty sample yields `[0]` so a degenerate feature still yields one threshold
256
+ * rather than an empty split set.
256
257
  */
257
258
  export function uniqueQuantiles(sorted: readonly number[], n: number): number[] {
258
259
  if (!sorted.length) return [0]
@@ -265,14 +266,11 @@ export function uniqueQuantiles(sorted: readonly number[], n: number): number[]
265
266
  return [...ts]
266
267
  }
267
268
 
268
- /**
269
- * Quantile points swept per learned-scorer arm.
270
- */
271
269
  const THRESHOLD_QUANTILE_POINTS = 32
272
270
 
273
271
  /**
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.
272
+ * Link-threshold candidates for a learned scorer: de-duplicated quantiles of the
273
+ * scorer's own eval-pair score distribution across the 0.2–0.999 band.
276
274
  */
277
275
  export const quantileThresholds = (scores: readonly number[]): number[] => {
278
276
  const sorted = [...scores].toSorted((p, q) => p - q)
@@ -323,19 +321,18 @@ export function bestOver(thresholds: readonly number[], scoreAt: (threshold: num
323
321
  }
324
322
 
325
323
  /**
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.
324
+ * One organization provider at its practice address, as the geocode-free co-location probes read it.
328
325
  */
329
326
  export interface ColocatedProvider {
330
327
  npi: string
331
328
  org: string
332
329
  tokens: Set<string>
333
330
  /**
334
- * The composed practice address ({@link addr}), the string the adjudication packets carry.
331
+ * The composed practice address ({@link addr}).
335
332
  */
336
333
  address: string
337
334
  /**
338
- * Strict last-10-digit phone key; `""` when the column carries fewer than 10 digits.
335
+ * Strict last-10-digit phone key; `""` when the column contains fewer than 10 digits.
339
336
  */
340
337
  phone: string
341
338
  /**
@@ -348,7 +345,7 @@ export interface ColocatedProvider {
348
345
  taxonomy: string
349
346
  subpart: boolean
350
347
  /**
351
- * `parentLBN|parentTIN`, lowercased — `"|"` when both are blank.
348
+ * `parentLBN|parentTIN`, lowercased; `"|"` when both are blank.
352
349
  */
353
350
  parent: string
354
351
  }
@@ -366,8 +363,9 @@ export interface ColocatedScan {
366
363
  }
367
364
 
368
365
  /**
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.
366
+ * Stream in-state type-2 (organization) providers from the registry,
367
+ * one record per row at its practice address, grouped by `addressFrequencyKey`;
368
+ * geocode-free on purpose so it runs at large caps in seconds.
371
369
  */
372
370
  export async function scanColocatedProviders(options: {
373
371
  registryPath: string
@@ -428,15 +426,15 @@ export interface ColocatedPair {
428
426
  a: ColocatedProvider
429
427
  b: ColocatedProvider
430
428
  /**
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.
429
+ * The distinct-NPI providers at the shared address, length ≥ 2, one array reference
430
+ * per group so a consumer can detect the group boundary by identity.
433
431
  */
434
432
  group: readonly ColocatedProvider[]
435
433
  }
436
434
 
437
435
  /**
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.
436
+ * Every unordered pair of distinct NPIs sharing a practice-address key, de-duplicated
437
+ * per address by NPI (first record wins) so single-NPI addresses yield no pair.
440
438
  */
441
439
  export function* colocatedDistinctPairs(
442
440
  byAddr: ReadonlyMap<string, readonly ColocatedProvider[]>
@@ -462,8 +460,7 @@ export function* colocatedDistinctPairs(
462
460
  }
463
461
 
464
462
  /**
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).
463
+ * The TX facility source specs the cross-source probes share.
467
464
  */
468
465
  export const buildSpecs = (S: string, STATE: string): SourceSpec[] => [
469
466
  {
@@ -518,19 +515,15 @@ export interface GBTHyperparameters {
518
515
  minLeaf: number
519
516
  }
520
517
 
521
- /**
522
- * The compact pure-Node GBT configuration the cross-source trainers fit with.
523
- */
524
518
  const CROSS_SOURCE_HYPERPARAMS: GBTHyperparameters = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
525
519
 
526
- /**
527
- * Share of join keys assigned to fit during calibration; the rest are held out.
528
- */
529
520
  const FIT_SPLIT_FRACTION = 0.8
530
521
 
531
522
  /**
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.
523
+ * One assembled input row for a cross-source trainer.
524
+ *
525
+ * Its `npi` field contains the cross-system join key (an NPI or a CCN).
526
+ * The trainer copies that key into `record.id` as the held-out label.
534
527
  */
535
528
  export interface CrossSourceRow extends Record<string, string> {
536
529
  npi: string
@@ -541,7 +534,7 @@ export interface CrossSourceRow extends Record<string, string> {
541
534
  }
542
535
 
543
536
  /**
544
- * Every figure Phases D–F compute — what {@link TrainCrossSourceModelOptions.meta} receives.
537
+ * Every figure passed to {@link TrainCrossSourceModelOptions.meta}.
545
538
  */
546
539
  export interface CrossSourceTrainingFigures {
547
540
  records: number
@@ -563,11 +556,12 @@ export interface TrainCrossSourceModelOptions {
563
556
  */
564
557
  createGeocoder: EvalGeocoderFactory
565
558
  /**
566
- * The assembled two-source rows — the caller's source-loading phases stay with the caller.
559
+ * The assembled two-source rows.
560
+ * The caller owns source loading.
567
561
  */
568
562
  rows: readonly CrossSourceRow[]
569
563
  /**
570
- * The join keys present in BOTH sources.
564
+ * The join keys present in both sources.
571
565
  */
572
566
  joined: ReadonlySet<string>
573
567
  addressFrequency: TermFrequencyTable
@@ -576,7 +570,7 @@ export interface TrainCrossSourceModelOptions {
576
570
  */
577
571
  sources: readonly [string, string]
578
572
  /**
579
- * #655 threshold rule: max cross-source recall subject to this held-out pairwise precision.
573
+ * Max cross-source recall subject to this held-out pairwise precision.
580
574
  */
581
575
  precisionBar: number
582
576
  /**
@@ -592,31 +586,30 @@ export interface TrainCrossSourceModelOptions {
592
586
  */
593
587
  exportPrefix: string
594
588
  /**
595
- * Assemble the emitted `<prefix>_META` object. The caller owns field names and order so a retrain diffs cleanly
596
- * against its committed module.
589
+ * Assemble the emitted `<prefix>_META` object.
590
+ *
591
+ * The caller owns field names and order so a retrain diffs cleanly against its committed module.
597
592
  */
598
593
  meta: (figures: CrossSourceTrainingFigures) => Record<string, unknown>
599
594
  report?: (line: string) => void
600
595
  }
601
596
 
602
597
  /**
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.
598
+ * Geocode and ingest each source under its own provenance label, block the union,
599
+ * keep only cross-source candidate pairs, featurize with `createMatchFeaturizer` so train
600
+ * and inference agree, calibrate the threshold on a held-out split of the join keys,
601
+ * then train and emit the shipped model as a committed TS module.
607
602
  */
608
603
  export async function trainCrossSourceModel(
609
604
  options: TrainCrossSourceModelOptions
610
605
  ): Promise<{ out: string; pairs: number; recommendedThreshold: number }> {
611
606
  const { rows, joined, addressFrequency, sources, precisionBar, out, report } = options
612
607
 
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
608
  report?.("[C] geocoding…")
616
609
  const geocoder = await options.createGeocoder()
617
610
 
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).
611
+ // Ingest each source separately to retain its literal provenance label on every record.
612
+ // The cross-source filter uses that label.
620
613
  const mappingFor = (source: string): ColumnMapping => ({
621
614
  id: "npi",
622
615
  name: "name",
@@ -640,7 +633,6 @@ export async function trainCrossSourceModel(
640
633
  geocoder[Symbol.dispose]()
641
634
  report?.(` ${records.length} records, ${records.filter((r) => r.address?.geocode).length} geocoded`)
642
635
 
643
- // --- Phase D: block over the UNION; keep only CROSS-source pairs; featurize; label by join key. ---
644
636
  report?.("[D] blocking + featurizing (cross-source pairs only)…")
645
637
  const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
646
638
  const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
@@ -655,7 +647,6 @@ export async function trainCrossSourceModel(
655
647
  ` ${allPairs.length} blocked pairs → ${pairs.length} cross-source (${(100 * posRate).toFixed(1)}% positive)`
656
648
  )
657
649
 
658
- // --- Phase E: held-out calibration — the #655 threshold rule. ---
659
650
  report?.("[E] held-out calibration…")
660
651
  const rnd = makeLcg(655)
661
652
  const split = new Map<string, "fit" | "holdout">()
@@ -705,7 +696,7 @@ export async function trainCrossSourceModel(
705
696
  const recall = totalPos > 0 ? tp / totalPos : 0
706
697
  const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
707
698
 
708
- // The #655 rule: the LOWEST threshold whose precision clears the bar (maximizes recall under it).
699
+ // The lowest threshold whose precision clears the bar, maximizing recall under it.
709
700
  if (precision >= precisionBar && recall > barRecall) {
710
701
  barRecall = recall
711
702
  recommendedThreshold = t
@@ -725,7 +716,6 @@ export async function trainCrossSourceModel(
725
716
  ` 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
717
  )
727
718
 
728
- // --- Phase F: train the SHIPPED model on ALL cross-source pairs; emit the committed module. ---
729
719
  report?.("[F] training the shipped model on all pairs…")
730
720
  const model = trainGBT(X, Y, W, CROSS_SOURCE_HYPERPARAMS)
731
721
 
@@ -749,9 +739,9 @@ export async function trainCrossSourceModel(
749
739
  options.moduleDoc +
750
740
  ` */\n\n` +
751
741
  `import type { GBT } from "@mailwoman/match"\n\n` +
752
- `export const ${options.exportPrefix}_META = ${JSON.stringify(meta)} as const\n\n` +
742
+ `export const ${options.exportPrefix}_META = ${stringifyJSON(meta)} as const\n\n` +
753
743
  `// prettier-ignore\n` +
754
- `export const ${options.exportPrefix}_MODEL: GBT = ${JSON.stringify(model)}\n`
744
+ `export const ${options.exportPrefix}_MODEL: GBT = ${stringifyJSON(model)}\n`
755
745
 
756
746
  await makeDirectories(dirname(out))
757
747
  await writeLocalFile(moduleSource, out)