@mailwoman/registry 10.0.0 → 10.2.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 (231) hide show
  1. package/README.md +11 -14
  2. package/lib/address-key.ts +14 -10
  3. package/lib/geocode-handler.ts +7 -5
  4. package/lib/geojson.ts +13 -7
  5. package/lib/ingest.ts +70 -92
  6. package/lib/learned-scorer.ts +38 -44
  7. package/lib/map-html.ts +26 -72
  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 -54
  12. package/lib/resolve.ts +187 -130
  13. package/lib/types.ts +35 -29
  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 +7 -5
  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 -7
  25. package/out/geojson.js.map +1 -1
  26. package/out/ingest.d.ts +49 -76
  27. package/out/ingest.d.ts.map +1 -1
  28. package/out/ingest.js +37 -62
  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 +11 -64
  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 +36 -50
  51. package/out/reconcile.d.ts.map +1 -1
  52. package/out/reconcile.js +18 -42
  53. package/out/reconcile.js.map +1 -1
  54. package/out/resolve.d.ts +152 -91
  55. package/out/resolve.d.ts.map +1 -1
  56. package/out/resolve.js +67 -68
  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 +23 -27
  63. package/out/tools/cross/dataset-correlation.d.ts.map +1 -1
  64. package/out/tools/cross/dataset-correlation.js +9 -61
  65. package/out/tools/cross/dataset-correlation.js.map +1 -1
  66. package/out/tools/cross/source-threshold-sweep.d.ts +20 -26
  67. package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -1
  68. package/out/tools/cross/source-threshold-sweep.js +14 -40
  69. package/out/tools/cross/source-threshold-sweep.js.map +1 -1
  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 +25 -16
  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 +9 -8
  79. package/out/tools/geocoder/namesake-probe.d.ts.map +1 -1
  80. package/out/tools/geocoder/namesake-probe.js +6 -7
  81. package/out/tools/geocoder/namesake-probe.js.map +1 -1
  82. package/out/tools/geocoder/vs-provided-coords.d.ts +18 -15
  83. package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -1
  84. package/out/tools/geocoder/vs-provided-coords.js +30 -27
  85. package/out/tools/geocoder/vs-provided-coords.js.map +1 -1
  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 +30 -27
  91. package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -1
  92. package/out/tools/learned/scorer/clustering-eval.js +28 -38
  93. package/out/tools/learned/scorer/clustering-eval.js.map +1 -1
  94. package/out/tools/learned/scorer/crossstate-eval.d.ts +24 -18
  95. package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -1
  96. package/out/tools/learned/scorer/crossstate-eval.js +19 -25
  97. package/out/tools/learned/scorer/crossstate-eval.js.map +1 -1
  98. package/out/tools/learned/scorer/eval.d.ts +26 -39
  99. package/out/tools/learned/scorer/eval.d.ts.map +1 -1
  100. package/out/tools/learned/scorer/eval.js +11 -71
  101. package/out/tools/learned/scorer/eval.js.map +1 -1
  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 +22 -41
  107. package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -1
  108. package/out/tools/nppes/dedup-benchmark.js +21 -67
  109. package/out/tools/nppes/dedup-benchmark.js.map +1 -1
  110. package/out/tools/nppes/org-name.d.ts +5 -11
  111. package/out/tools/nppes/org-name.d.ts.map +1 -1
  112. package/out/tools/nppes/org-name.js +2 -9
  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 +6 -7
  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 +29 -18
  123. package/out/tools/nppes/sample.d.ts.map +1 -1
  124. package/out/tools/nppes/sample.js +24 -28
  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 +68 -72
  139. package/out/tools/shared.d.ts.map +1 -1
  140. package/out/tools/shared.js +50 -67
  141. package/out/tools/shared.js.map +1 -1
  142. package/out/tools/train/cross-gbt.d.ts +37 -26
  143. package/out/tools/train/cross-gbt.d.ts.map +1 -1
  144. package/out/tools/train/cross-gbt.js +14 -25
  145. package/out/tools/train/cross-gbt.js.map +1 -1
  146. package/out/tools/train/gbt.d.ts +36 -20
  147. package/out/tools/train/gbt.d.ts.map +1 -1
  148. package/out/tools/train/gbt.js +27 -31
  149. package/out/tools/train/gbt.js.map +1 -1
  150. package/out/tools/train/org-cross-gbt.d.ts +38 -24
  151. package/out/tools/train/org-cross-gbt.d.ts.map +1 -1
  152. package/out/tools/train/org-cross-gbt.js +18 -22
  153. package/out/tools/train/org-cross-gbt.js.map +1 -1
  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 +11 -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 +5 -5
  171. package/out/tools/viz/render/map.d.ts.map +1 -1
  172. package/out/tools/viz/render/map.js +6 -5
  173. package/out/tools/viz/render/map.js.map +1 -1
  174. package/out/tools/viz/{render/index.d.ts → render.d.ts} +13 -9
  175. package/out/tools/viz/render.d.ts.map +1 -0
  176. package/out/tools/viz/{render/index.js → render.js} +9 -8
  177. package/out/tools/viz/render.js.map +1 -0
  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 +35 -29
  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 +42 -185
  191. package/{lib/tools → tools}/coverage-reconciliation.ts +27 -30
  192. package/{lib/tools → tools}/cross/dataset-correlation.ts +35 -73
  193. package/{lib/tools → tools}/cross/source-threshold-sweep.ts +29 -46
  194. package/{lib/tools → tools}/dedup-ceiling.ts +34 -45
  195. package/tools/eval-geocoder.ts +77 -0
  196. package/{lib/tools → tools}/geocoder/namesake-probe.ts +9 -8
  197. package/{lib/tools → tools}/geocoder/vs-provided-coords.ts +40 -31
  198. package/{lib/tools → tools}/gold-set-sample.ts +35 -29
  199. package/{lib/tools → tools}/learned/scorer/clustering-eval.ts +49 -45
  200. package/{lib/tools → tools}/learned/scorer/crossstate-eval.ts +34 -30
  201. package/{lib/tools → tools}/learned/scorer/eval.ts +39 -78
  202. package/{lib/tools → tools}/matcher-scale.ts +21 -33
  203. package/{lib/tools → tools}/nppes/dedup-benchmark.ts +39 -83
  204. package/tools/nppes/org-name.ts +15 -0
  205. package/{lib/tools → tools}/nppes/overmerge-packet.ts +16 -12
  206. package/{lib/tools → tools}/nppes/report.ts +32 -25
  207. package/{lib/tools → tools}/nppes/sample.ts +43 -38
  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 +79 -98
  212. package/{lib/tools → tools}/train/cross-gbt.ts +39 -34
  213. package/{lib/tools → tools}/train/gbt.ts +55 -41
  214. package/{lib/tools → tools}/train/org-cross-gbt.ts +40 -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 +29 -17
  219. package/{lib/tools → tools}/viz/render/map.ts +7 -6
  220. package/{lib/tools/viz/render/index.ts → 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/lib/tools/nppes/org-name.ts +0 -23
  226. package/out/tools/index.d.ts +0 -31
  227. package/out/tools/index.d.ts.map +0 -1
  228. package/out/tools/index.js +0 -31
  229. package/out/tools/index.js.map +0 -1
  230. package/out/tools/viz/render/index.d.ts.map +0 -1
  231. package/out/tools/viz/render/index.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,16 +3,14 @@
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
- import { block, gbtScore, trainGBT, type TermFrequencyTable } from "@mailwoman/match"
13
+ import { block, gbtScore, trainGBT, type GBTOpts, type TermFrequencyTable } from "@mailwoman/match"
16
14
  import { dirname } from "path-ts"
17
15
 
18
16
  import {
@@ -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,19 +42,21 @@ 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
+ *
47
+ * @defaultValue identity.
45
48
  */
46
49
  explode?: (row: Record<string, string>) => Record<string, string>[]
47
50
  }
48
51
 
49
52
  /**
50
- * Trim, treating `undefined` as empty — the shape every probe's raw CSV columns arrive in.
53
+ * Trim, treating `null` or `undefined` as empty — the shape every probe's raw CSV columns arrive in.
51
54
  */
52
- export const norm = (s: string | undefined): string => (s ?? "").trim()
55
+ export const norm = (s: string | null | undefined): string => (s ?? "").trim()
53
56
 
54
57
  /**
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.
58
+ * Corporate-form suffixes and function words that add no identity — dropped from an organization name
59
+ * before its tokens are compared, so the domain words include the distinguishing signal.
57
60
  */
58
61
  const ORGANIZATION_STOP_WORDS = new Set([
59
62
  "llc",
@@ -74,11 +77,8 @@ const ORGANIZATION_STOP_WORDS = new Set([
74
77
  ])
75
78
 
76
79
  /**
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.
80
+ * The token set of an organization name for the probes' cheap Jaccard overlap,
81
+ * never blocking or display — not a canonical form.
82
82
  */
83
83
  export function orgTokens(s: string): Set<string> {
84
84
  return new Set(
@@ -97,7 +97,8 @@ export const addr = (line: string, city: string, st: string, zip: string): strin
97
97
  [norm(line), norm(city), norm(st), norm(zip)].filter(isPresent).join(", ")
98
98
 
99
99
  /**
100
- * Population standard deviation; `0` on an empty sample, because these feed report tables that print a number per row.
100
+ * Population standard deviation; `0` on an empty sample, because these feed
101
+ * report tables that print a number per row.
101
102
  */
102
103
  export const std = (xs: readonly number[]): number => {
103
104
  const m = xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
@@ -105,18 +106,21 @@ export const std = (xs: readonly number[]): number => {
105
106
  return Math.sqrt(xs.map((x) => (x - m) ** 2).reduce((a, b) => a + b, 0) / Math.max(1, xs.length))
106
107
  }
107
108
 
108
- // NOTE(phase4): pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
109
- // numerator/denominator contract (call sites append their own "%").
109
+ /**
110
+ * Takes a fraction and omits the percent sign, unlike core `formatPercent`'s
111
+ * numerator/denominator interface.
112
+ * Call sites append their own `%`.
113
+ */
110
114
  export const pct = (x: number): string => (100 * x).toFixed(1)
111
115
 
112
116
  /**
113
- * Sign prefix for a signed delta — `"+"` for a non-negative value (a negative one carries its own sign).
117
+ * Sign prefix for a signed delta: `"+"` for a non-negative value, since a negative one includes its sign.
114
118
  */
115
119
  export const sgn = (x: number): string => (x >= 0 ? "+" : "")
116
120
 
117
121
  /**
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.
122
+ * Logistic function with the input clamped to ±30, past which `Math.exp` underflows to 0
123
+ * and the gradient step silently becomes a no-op.
120
124
  */
121
125
  export const sigmoid = (z: number): number => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
122
126
 
@@ -137,14 +141,8 @@ export const inTXBBOX = (lat: number, lon: number): boolean =>
137
141
  lat >= TX_BBOX.latMin && lat <= TX_BBOX.latMax && lon >= TX_BBOX.lonMin && lon <= TX_BBOX.lonMax
138
142
 
139
143
  /**
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.
144
+ * NPPES registry column headers, by the short name the probes read them under. no code
145
+ * enumerates this object, so adding a column cannot change a probe's behavior.
148
146
  */
149
147
  export const NPPES_COLUMNS = {
150
148
  npi: "NPI",
@@ -167,7 +165,8 @@ export const NPPES_COLUMNS = {
167
165
  isSubpart: "Is Organization Subpart",
168
166
  parentLBN: "Parent Organization LBN",
169
167
  parentTIN: "Parent Organization TIN",
170
- // #625 taxonomy discriminator: the 15 taxonomy slots; collected as a set (any shared code = agreement).
168
+ // The 15 taxonomy slots.
169
+ // Any shared code counts as agreement.
171
170
  taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
172
171
  }
173
172
 
@@ -177,13 +176,14 @@ export const NPPES_COLUMNS = {
177
176
  export const MIN_GROUP_SIZE = 5
178
177
 
179
178
  /**
180
- * Gradient-descent epochs for {@link trainLogisticRegression}. Fixed rather than early-stopped so seeds stay comparable.
179
+ * Gradient-descent epochs for {@link trainLogisticRegression}, fixed
180
+ * rather than early-stopped so seeds stay comparable.
181
181
  */
182
182
  export const TRAINING_EPOCHS = 400
183
183
 
184
184
  /**
185
- * Smallest mean F1 gap counted as a real difference between models rather than seed noise. Verdicts inside ±this are
186
- * reported as a tie.
185
+ * Smallest mean F1 gap counted as a real difference between models rather than seed
186
+ * noise. verdicts inside ±this are reported as a tie.
187
187
  */
188
188
  export const MIN_MEANINGFUL_F1_DELTA = 0.02
189
189
 
@@ -198,9 +198,9 @@ export const LR_LEARNING_RATE = 0.1
198
198
  export const LR_L2 = 1e-3
199
199
 
200
200
  /**
201
- * L2-regularized logistic regression by batch gradient descent ({@link TRAINING_EPOCHS} epochs) — the probes' linear
202
- * arm. `w` carries the per-sample class weights (the caller up-weights the rare class). Returns the linear scorer: the
203
- * logit, not the probability, threshold-comparable across a fixed feature layout.
201
+ * L2-regularized logistic regression by batch gradient descent over {@link TRAINING_EPOCHS}
202
+ * epochs, where `w` stores per-sample class weights, returning the logit rather than
203
+ * the probability so it is threshold-comparable across a fixed feature layout.
204
204
  */
205
205
  export function trainLogisticRegression(
206
206
  X: readonly (readonly number[])[],
@@ -250,9 +250,11 @@ export function trainLogisticRegression(
250
250
  }
251
251
 
252
252
  /**
253
- * `n + 1` evenly-spaced order statistics of an already-sorted sample, de-duplicated — the candidate split thresholds a
254
- * GBT node considers. `[0]` for an empty sample so a degenerate feature still yields one (useless but well-formed)
255
- * threshold rather than an empty split set.
253
+ * `n + 1` evenly-spaced order statistics of an already-sorted sample, de-duplicated,
254
+ * that a GBT node considers as candidate splits.
255
+ *
256
+ * An empty sample yields `[0]` so a degenerate feature still yields one threshold
257
+ * rather than an empty split set.
256
258
  */
257
259
  export function uniqueQuantiles(sorted: readonly number[], n: number): number[] {
258
260
  if (!sorted.length) return [0]
@@ -265,14 +267,11 @@ export function uniqueQuantiles(sorted: readonly number[], n: number): number[]
265
267
  return [...ts]
266
268
  }
267
269
 
268
- /**
269
- * Quantile points swept per learned-scorer arm.
270
- */
271
270
  const THRESHOLD_QUANTILE_POINTS = 32
272
271
 
273
272
  /**
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.
273
+ * Link-threshold candidates for a learned scorer: de-duplicated quantiles of the
274
+ * scorer's own eval-pair score distribution across the 0.2–0.999 band.
276
275
  */
277
276
  export const quantileThresholds = (scores: readonly number[]): number[] => {
278
277
  const sorted = [...scores].toSorted((p, q) => p - q)
@@ -323,19 +322,18 @@ export function bestOver(thresholds: readonly number[], scoreAt: (threshold: num
323
322
  }
324
323
 
325
324
  /**
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.
325
+ * One organization provider at its practice address, as the geocode-free co-location probes read it.
328
326
  */
329
327
  export interface ColocatedProvider {
330
328
  npi: string
331
329
  org: string
332
330
  tokens: Set<string>
333
331
  /**
334
- * The composed practice address ({@link addr}), the string the adjudication packets carry.
332
+ * The composed practice address ({@link addr}).
335
333
  */
336
334
  address: string
337
335
  /**
338
- * Strict last-10-digit phone key; `""` when the column carries fewer than 10 digits.
336
+ * Strict last-10-digit phone key; `""` when the column contains fewer than 10 digits.
339
337
  */
340
338
  phone: string
341
339
  /**
@@ -348,7 +346,7 @@ export interface ColocatedProvider {
348
346
  taxonomy: string
349
347
  subpart: boolean
350
348
  /**
351
- * `parentLBN|parentTIN`, lowercased — `"|"` when both are blank.
349
+ * `parentLBN|parentTIN`, lowercased; `"|"` when both are blank.
352
350
  */
353
351
  parent: string
354
352
  }
@@ -366,8 +364,9 @@ export interface ColocatedScan {
366
364
  }
367
365
 
368
366
  /**
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.
367
+ * Stream in-state type-2 (organization) providers from the registry,
368
+ * one record per row at its practice address, grouped by `addressFrequencyKey`;
369
+ * geocode-free on purpose so it runs at large caps in seconds.
371
370
  */
372
371
  export async function scanColocatedProviders(options: {
373
372
  registryPath: string
@@ -428,15 +427,15 @@ export interface ColocatedPair {
428
427
  a: ColocatedProvider
429
428
  b: ColocatedProvider
430
429
  /**
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.
430
+ * The distinct-NPI providers at the shared address, length ≥ 2, one array reference
431
+ * per group so a consumer can detect the group boundary by identity.
433
432
  */
434
433
  group: readonly ColocatedProvider[]
435
434
  }
436
435
 
437
436
  /**
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.
437
+ * Every unordered pair of distinct NPIs sharing a practice-address key, de-duplicated
438
+ * per address by NPI (first record wins) so single-NPI addresses yield no pair.
440
439
  */
441
440
  export function* colocatedDistinctPairs(
442
441
  byAddr: ReadonlyMap<string, readonly ColocatedProvider[]>
@@ -462,8 +461,7 @@ export function* colocatedDistinctPairs(
462
461
  }
463
462
 
464
463
  /**
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).
464
+ * The TX facility source specs the cross-source probes share.
467
465
  */
468
466
  export const buildSpecs = (S: string, STATE: string): SourceSpec[] => [
469
467
  {
@@ -508,29 +506,15 @@ export const buildSpecs = (S: string, STATE: string): SourceSpec[] => [
508
506
  },
509
507
  ]
510
508
 
511
- /**
512
- * The GBT hyperparameter shape the trainers stamp into their model meta.
513
- */
514
- export interface GBTHyperparameters {
515
- rounds: number
516
- depth: number
517
- lr: number
518
- minLeaf: number
519
- }
509
+ const CROSS_SOURCE_HYPERPARAMS: GBTOpts = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
520
510
 
521
- /**
522
- * The compact pure-Node GBT configuration the cross-source trainers fit with.
523
- */
524
- const CROSS_SOURCE_HYPERPARAMS: GBTHyperparameters = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
525
-
526
- /**
527
- * Share of join keys assigned to fit during calibration; the rest are held out.
528
- */
529
511
  const FIT_SPLIT_FRACTION = 0.8
530
512
 
531
513
  /**
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.
514
+ * One assembled input row for a cross-source trainer.
515
+ *
516
+ * Its `npi` field contains the cross-system join key (an NPI or a CCN).
517
+ * The trainer copies that key into `record.id` as the held-out label.
534
518
  */
535
519
  export interface CrossSourceRow extends Record<string, string> {
536
520
  npi: string
@@ -541,7 +525,7 @@ export interface CrossSourceRow extends Record<string, string> {
541
525
  }
542
526
 
543
527
  /**
544
- * Every figure Phases D–F compute — what {@link TrainCrossSourceModelOptions.meta} receives.
528
+ * Every figure passed to {@link TrainCrossSourceModelOptions.meta}.
545
529
  */
546
530
  export interface CrossSourceTrainingFigures {
547
531
  records: number
@@ -551,7 +535,7 @@ export interface CrossSourceTrainingFigures {
551
535
  f1Max: number
552
536
  recommendedThreshold: number
553
537
  features: number
554
- hyperparams: GBTHyperparameters
538
+ hyperparams: GBTOpts
555
539
  }
556
540
 
557
541
  /**
@@ -563,11 +547,12 @@ export interface TrainCrossSourceModelOptions {
563
547
  */
564
548
  createGeocoder: EvalGeocoderFactory
565
549
  /**
566
- * The assembled two-source rows — the caller's source-loading phases stay with the caller.
550
+ * The assembled two-source rows.
551
+ * The caller owns source loading.
567
552
  */
568
553
  rows: readonly CrossSourceRow[]
569
554
  /**
570
- * The join keys present in BOTH sources.
555
+ * The join keys present in both sources.
571
556
  */
572
557
  joined: ReadonlySet<string>
573
558
  addressFrequency: TermFrequencyTable
@@ -576,7 +561,7 @@ export interface TrainCrossSourceModelOptions {
576
561
  */
577
562
  sources: readonly [string, string]
578
563
  /**
579
- * #655 threshold rule: max cross-source recall subject to this held-out pairwise precision.
564
+ * Max cross-source recall subject to this held-out pairwise precision.
580
565
  */
581
566
  precisionBar: number
582
567
  /**
@@ -592,31 +577,30 @@ export interface TrainCrossSourceModelOptions {
592
577
  */
593
578
  exportPrefix: string
594
579
  /**
595
- * Assemble the emitted `<prefix>_META` object. The caller owns field names and order so a retrain diffs cleanly
596
- * against its committed module.
580
+ * Assemble the emitted `<prefix>_META` object.
581
+ *
582
+ * The caller owns field names and order so a retrain diffs cleanly against its committed module.
597
583
  */
598
584
  meta: (figures: CrossSourceTrainingFigures) => Record<string, unknown>
599
585
  report?: (line: string) => void
600
586
  }
601
587
 
602
588
  /**
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.
589
+ * Geocode and ingest each source under its own provenance label, block the union,
590
+ * keep only cross-source candidate pairs, featurize with `createMatchFeaturizer` so train
591
+ * and inference agree, calibrate the threshold on a held-out split of the join keys,
592
+ * then train and emit the shipped model as a committed TS module.
607
593
  */
608
594
  export async function trainCrossSourceModel(
609
595
  options: TrainCrossSourceModelOptions
610
596
  ): Promise<{ out: string; pairs: number; recommendedThreshold: number }> {
611
597
  const { rows, joined, addressFrequency, sources, precisionBar, out, report } = options
612
598
 
613
- // Geocode and ingest records, carrying the join-key label in record.id and source on the record.
614
- // heavy geocoder is injected (see ./eval-geocoder.ts). ---
615
599
  report?.("[C] geocoding…")
616
600
  const geocoder = await options.createGeocoder()
617
601
 
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).
602
+ // Ingest each source separately to retain its literal provenance label on every record.
603
+ // The cross-source filter uses that label.
620
604
  const mappingFor = (source: string): ColumnMapping => ({
621
605
  id: "npi",
622
606
  name: "name",
@@ -640,7 +624,6 @@ export async function trainCrossSourceModel(
640
624
  geocoder[Symbol.dispose]()
641
625
  report?.(` ${records.length} records, ${records.filter((r) => r.address?.geocode).length} geocoded`)
642
626
 
643
- // Block the union, retain cross-source pairs, generate features, and label by join key.
644
627
  report?.("[D] blocking + featurizing (cross-source pairs only)…")
645
628
  const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
646
629
  const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
@@ -655,7 +638,6 @@ export async function trainCrossSourceModel(
655
638
  ` ${allPairs.length} blocked pairs → ${pairs.length} cross-source (${(100 * posRate).toFixed(1)}% positive)`
656
639
  )
657
640
 
658
- // Calibrate the threshold against held-out pairs.
659
641
  report?.("[E] held-out calibration…")
660
642
  const rnd = makeLcg(655)
661
643
  const split = new Map<string, "fit" | "holdout">()
@@ -705,7 +687,7 @@ export async function trainCrossSourceModel(
705
687
  const recall = totalPos > 0 ? tp / totalPos : 0
706
688
  const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
707
689
 
708
- // The #655 rule: the LOWEST threshold whose precision clears the bar (maximizes recall under it).
690
+ // The lowest threshold whose precision clears the bar, maximizing recall under it.
709
691
  if (precision >= precisionBar && recall > barRecall) {
710
692
  barRecall = recall
711
693
  recommendedThreshold = t
@@ -725,7 +707,6 @@ export async function trainCrossSourceModel(
725
707
  ` 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
708
  )
727
709
 
728
- // Train the shipped model on all cross-source pairs and emit its committed module.
729
710
  report?.("[F] training the shipped model on all pairs…")
730
711
  const model = trainGBT(X, Y, W, CROSS_SOURCE_HYPERPARAMS)
731
712
 
@@ -749,9 +730,9 @@ export async function trainCrossSourceModel(
749
730
  options.moduleDoc +
750
731
  ` */\n\n` +
751
732
  `import type { GBT } from "@mailwoman/match"\n\n` +
752
- `export const ${options.exportPrefix}_META = ${JSON.stringify(meta)} as const\n\n` +
733
+ `export const ${options.exportPrefix}_META = ${stringifyJSON(meta)} as const\n\n` +
753
734
  `// prettier-ignore\n` +
754
- `export const ${options.exportPrefix}_MODEL: GBT = ${JSON.stringify(model)}\n`
735
+ `export const ${options.exportPrefix}_MODEL: GBT = ${stringifyJSON(model)}\n`
755
736
 
756
737
  await makeDirectories(dirname(out))
757
738
  await writeLocalFile(moduleSource, out)