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