@mailwoman/entity-resolution 0.0.0-stage → 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 (227) hide show
  1. package/README.md +114 -2
  2. package/lib/address-key.ts +46 -0
  3. package/lib/geocode-handler.ts +37 -0
  4. package/lib/geojson.ts +72 -0
  5. package/lib/index.ts +23 -0
  6. package/lib/ingest.ts +349 -0
  7. package/lib/learned-scorer.ts +134 -0
  8. package/lib/map-html.ts +287 -0
  9. package/lib/models/crosssource-gbt-en-us.ts +43 -0
  10. package/lib/models/dedup-gbt-en-us.ts +47 -0
  11. package/lib/models/org-crosssource-gbt-en-us.ts +43 -0
  12. package/lib/reconcile.ts +239 -0
  13. package/lib/resolve.ts +569 -0
  14. package/lib/types.ts +110 -0
  15. package/out/address-key.d.ts +34 -0
  16. package/out/address-key.d.ts.map +1 -0
  17. package/out/address-key.js +41 -0
  18. package/out/address-key.js.map +1 -0
  19. package/out/geocode-handler.d.ts +20 -0
  20. package/out/geocode-handler.d.ts.map +1 -0
  21. package/out/geocode-handler.js +29 -0
  22. package/out/geocode-handler.js.map +1 -0
  23. package/out/geojson.d.ts +28 -0
  24. package/out/geojson.d.ts.map +1 -0
  25. package/out/geojson.js +62 -0
  26. package/out/geojson.js.map +1 -0
  27. package/out/index.d.ts +23 -0
  28. package/out/index.d.ts.map +1 -0
  29. package/out/index.js +23 -0
  30. package/out/index.js.map +1 -0
  31. package/out/ingest.d.ts +173 -0
  32. package/out/ingest.d.ts.map +1 -0
  33. package/out/ingest.js +185 -0
  34. package/out/ingest.js.map +1 -0
  35. package/out/learned-scorer.d.ts +61 -0
  36. package/out/learned-scorer.d.ts.map +1 -0
  37. package/out/learned-scorer.js +91 -0
  38. package/out/learned-scorer.js.map +1 -0
  39. package/out/map-html.d.ts +39 -0
  40. package/out/map-html.d.ts.map +1 -0
  41. package/out/map-html.js +220 -0
  42. package/out/map-html.js.map +1 -0
  43. package/out/models/crosssource-gbt-en-us.d.ts +45 -0
  44. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -0
  45. package/out/models/crosssource-gbt-en-us.js +40 -0
  46. package/out/models/crosssource-gbt-en-us.js.map +1 -0
  47. package/out/models/dedup-gbt-en-us.d.ts +44 -0
  48. package/out/models/dedup-gbt-en-us.d.ts.map +1 -0
  49. package/out/models/dedup-gbt-en-us.js +44 -0
  50. package/out/models/dedup-gbt-en-us.js.map +1 -0
  51. package/out/models/org-crosssource-gbt-en-us.d.ts +45 -0
  52. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -0
  53. package/out/models/org-crosssource-gbt-en-us.js +40 -0
  54. package/out/models/org-crosssource-gbt-en-us.js.map +1 -0
  55. package/out/reconcile.d.ts +96 -0
  56. package/out/reconcile.d.ts.map +1 -0
  57. package/out/reconcile.js +127 -0
  58. package/out/reconcile.js.map +1 -0
  59. package/out/resolve.d.ts +264 -0
  60. package/out/resolve.d.ts.map +1 -0
  61. package/out/resolve.js +282 -0
  62. package/out/resolve.js.map +1 -0
  63. package/out/tools/coverage-reconciliation.d.ts +67 -0
  64. package/out/tools/coverage-reconciliation.d.ts.map +1 -0
  65. package/out/tools/coverage-reconciliation.js +113 -0
  66. package/out/tools/coverage-reconciliation.js.map +1 -0
  67. package/out/tools/cross/dataset-correlation.d.ts +61 -0
  68. package/out/tools/cross/dataset-correlation.d.ts.map +1 -0
  69. package/out/tools/cross/dataset-correlation.js +244 -0
  70. package/out/tools/cross/dataset-correlation.js.map +1 -0
  71. package/out/tools/cross/source-threshold-sweep.d.ts +60 -0
  72. package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -0
  73. package/out/tools/cross/source-threshold-sweep.js +264 -0
  74. package/out/tools/cross/source-threshold-sweep.js.map +1 -0
  75. package/out/tools/dedup-ceiling.d.ts +62 -0
  76. package/out/tools/dedup-ceiling.d.ts.map +1 -0
  77. package/out/tools/dedup-ceiling.js +171 -0
  78. package/out/tools/dedup-ceiling.js.map +1 -0
  79. package/out/tools/eval-geocoder.d.ts +68 -0
  80. package/out/tools/eval-geocoder.d.ts.map +1 -0
  81. package/out/tools/eval-geocoder.js +13 -0
  82. package/out/tools/eval-geocoder.js.map +1 -0
  83. package/out/tools/geocoder/namesake-probe.d.ts +33 -0
  84. package/out/tools/geocoder/namesake-probe.d.ts.map +1 -0
  85. package/out/tools/geocoder/namesake-probe.js +60 -0
  86. package/out/tools/geocoder/namesake-probe.js.map +1 -0
  87. package/out/tools/geocoder/vs-provided-coords.d.ts +53 -0
  88. package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -0
  89. package/out/tools/geocoder/vs-provided-coords.js +161 -0
  90. package/out/tools/geocoder/vs-provided-coords.js.map +1 -0
  91. package/out/tools/gold-set-sample.d.ts +67 -0
  92. package/out/tools/gold-set-sample.d.ts.map +1 -0
  93. package/out/tools/gold-set-sample.js +81 -0
  94. package/out/tools/gold-set-sample.js.map +1 -0
  95. package/out/tools/learned/scorer/clustering-eval.d.ts +77 -0
  96. package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -0
  97. package/out/tools/learned/scorer/clustering-eval.js +207 -0
  98. package/out/tools/learned/scorer/clustering-eval.js.map +1 -0
  99. package/out/tools/learned/scorer/crossstate-eval.d.ts +65 -0
  100. package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -0
  101. package/out/tools/learned/scorer/crossstate-eval.js +168 -0
  102. package/out/tools/learned/scorer/crossstate-eval.js.map +1 -0
  103. package/out/tools/learned/scorer/eval.d.ts +64 -0
  104. package/out/tools/learned/scorer/eval.d.ts.map +1 -0
  105. package/out/tools/learned/scorer/eval.js +275 -0
  106. package/out/tools/learned/scorer/eval.js.map +1 -0
  107. package/out/tools/matcher-scale.d.ts +40 -0
  108. package/out/tools/matcher-scale.d.ts.map +1 -0
  109. package/out/tools/matcher-scale.js +111 -0
  110. package/out/tools/matcher-scale.js.map +1 -0
  111. package/out/tools/nppes/dedup-benchmark.d.ts +82 -0
  112. package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -0
  113. package/out/tools/nppes/dedup-benchmark.js +226 -0
  114. package/out/tools/nppes/dedup-benchmark.js.map +1 -0
  115. package/out/tools/nppes/org-name.d.ts +15 -0
  116. package/out/tools/nppes/org-name.d.ts.map +1 -0
  117. package/out/tools/nppes/org-name.js +6 -0
  118. package/out/tools/nppes/org-name.js.map +1 -0
  119. package/out/tools/nppes/overmerge-packet.d.ts +43 -0
  120. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  121. package/out/tools/nppes/overmerge-packet.js +54 -0
  122. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  123. package/out/tools/nppes/report.d.ts +97 -0
  124. package/out/tools/nppes/report.d.ts.map +1 -0
  125. package/out/tools/nppes/report.js +178 -0
  126. package/out/tools/nppes/report.js.map +1 -0
  127. package/out/tools/nppes/sample.d.ts +101 -0
  128. package/out/tools/nppes/sample.d.ts.map +1 -0
  129. package/out/tools/nppes/sample.js +127 -0
  130. package/out/tools/nppes/sample.js.map +1 -0
  131. package/out/tools/nppes/scoring.d.ts +37 -0
  132. package/out/tools/nppes/scoring.d.ts.map +1 -0
  133. package/out/tools/nppes/scoring.js +81 -0
  134. package/out/tools/nppes/scoring.js.map +1 -0
  135. package/out/tools/nppes/settings.d.ts +41 -0
  136. package/out/tools/nppes/settings.d.ts.map +1 -0
  137. package/out/tools/nppes/settings.js +79 -0
  138. package/out/tools/nppes/settings.js.map +1 -0
  139. package/out/tools/nppes/truth-grains.d.ts +63 -0
  140. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  141. package/out/tools/nppes/truth-grains.js +142 -0
  142. package/out/tools/nppes/truth-grains.js.map +1 -0
  143. package/out/tools/shared.d.ts +325 -0
  144. package/out/tools/shared.d.ts.map +1 -0
  145. package/out/tools/shared.js +453 -0
  146. package/out/tools/shared.js.map +1 -0
  147. package/out/tools/train/cross-gbt.d.ts +89 -0
  148. package/out/tools/train/cross-gbt.d.ts.map +1 -0
  149. package/out/tools/train/cross-gbt.js +132 -0
  150. package/out/tools/train/cross-gbt.js.map +1 -0
  151. package/out/tools/train/gbt.d.ts +85 -0
  152. package/out/tools/train/gbt.d.ts.map +1 -0
  153. package/out/tools/train/gbt.js +155 -0
  154. package/out/tools/train/gbt.js.map +1 -0
  155. package/out/tools/train/org-cross-gbt.d.ts +85 -0
  156. package/out/tools/train/org-cross-gbt.d.ts.map +1 -0
  157. package/out/tools/train/org-cross-gbt.js +122 -0
  158. package/out/tools/train/org-cross-gbt.js.map +1 -0
  159. package/out/tools/txhhsc-to-oarow.d.ts +42 -0
  160. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -0
  161. package/out/tools/txhhsc-to-oarow.js +78 -0
  162. package/out/tools/txhhsc-to-oarow.js.map +1 -0
  163. package/out/tools/viz/browser.d.ts +31 -0
  164. package/out/tools/viz/browser.d.ts.map +1 -0
  165. package/out/tools/viz/browser.js +26 -0
  166. package/out/tools/viz/browser.js.map +1 -0
  167. package/out/tools/viz/cross-dataset-map.d.ts +39 -0
  168. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -0
  169. package/out/tools/viz/cross-dataset-map.js +84 -0
  170. package/out/tools/viz/cross-dataset-map.js.map +1 -0
  171. package/out/tools/viz/geocode-first-surface.d.ts +36 -0
  172. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -0
  173. package/out/tools/viz/geocode-first-surface.js +234 -0
  174. package/out/tools/viz/geocode-first-surface.js.map +1 -0
  175. package/out/tools/viz/render/map.d.ts +42 -0
  176. package/out/tools/viz/render/map.d.ts.map +1 -0
  177. package/out/tools/viz/render/map.js +40 -0
  178. package/out/tools/viz/render/map.js.map +1 -0
  179. package/out/tools/viz/render.d.ts +46 -0
  180. package/out/tools/viz/render.d.ts.map +1 -0
  181. package/out/tools/viz/render.js +49 -0
  182. package/out/tools/viz/render.js.map +1 -0
  183. package/out/tools/viz/source-provenance-map.d.ts +57 -0
  184. package/out/tools/viz/source-provenance-map.d.ts.map +1 -0
  185. package/out/tools/viz/source-provenance-map.js +82 -0
  186. package/out/tools/viz/source-provenance-map.js.map +1 -0
  187. package/out/tools/viz/yardstick-figure.d.ts +22 -0
  188. package/out/tools/viz/yardstick-figure.d.ts.map +1 -0
  189. package/out/tools/viz/yardstick-figure.js +106 -0
  190. package/out/tools/viz/yardstick-figure.js.map +1 -0
  191. package/out/types.d.ts +108 -0
  192. package/out/types.d.ts.map +1 -0
  193. package/out/types.js +11 -0
  194. package/out/types.js.map +1 -0
  195. package/package.json +113 -3
  196. package/tools/coverage-reconciliation.ts +192 -0
  197. package/tools/cross/dataset-correlation.ts +380 -0
  198. package/tools/cross/source-threshold-sweep.ts +416 -0
  199. package/tools/dedup-ceiling.ts +225 -0
  200. package/tools/eval-geocoder.ts +77 -0
  201. package/tools/geocoder/namesake-probe.ts +91 -0
  202. package/tools/geocoder/vs-provided-coords.ts +232 -0
  203. package/tools/gold-set-sample.ts +147 -0
  204. package/tools/learned/scorer/clustering-eval.ts +349 -0
  205. package/tools/learned/scorer/crossstate-eval.ts +280 -0
  206. package/tools/learned/scorer/eval.ts +429 -0
  207. package/tools/matcher-scale.ts +185 -0
  208. package/tools/nppes/dedup-benchmark.ts +364 -0
  209. package/tools/nppes/org-name.ts +15 -0
  210. package/tools/nppes/overmerge-packet.ts +98 -0
  211. package/tools/nppes/report.ts +380 -0
  212. package/tools/nppes/sample.ts +250 -0
  213. package/tools/nppes/scoring.ts +115 -0
  214. package/tools/nppes/settings.ts +102 -0
  215. package/tools/nppes/truth-grains.ts +185 -0
  216. package/tools/shared.ts +743 -0
  217. package/tools/train/cross-gbt.ts +214 -0
  218. package/tools/train/gbt.ts +261 -0
  219. package/tools/train/org-cross-gbt.ts +189 -0
  220. package/tools/txhhsc-to-oarow.ts +118 -0
  221. package/tools/viz/browser.ts +41 -0
  222. package/tools/viz/cross-dataset-map.ts +133 -0
  223. package/tools/viz/geocode-first-surface.ts +305 -0
  224. package/tools/viz/render/map.ts +61 -0
  225. package/tools/viz/render.ts +103 -0
  226. package/tools/viz/source-provenance-map.ts +154 -0
  227. package/tools/viz/yardstick-figure.ts +197 -0
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Convert the TX hhsc nursing-facilities source into the OaRow jsonl the resolver eval consumes.
7
+ * The source ships an authoritative `Geo Location` = `lat,lon` per facility, so the geocoder is
8
+ * graded against the provided coordinates on real facility addresses. `oa-resolver-eval
9
+ * --address-points` reports a great-circle delta and a tier breakdown.
10
+ *
11
+ * Neutral scope: this measures geocoder accuracy on real public addresses and makes no claim about
12
+ * the facilities themselves.
13
+ *
14
+ * Run: `mailwoman registry convert tx-hhsc [--src <tsv>] [--out /tmp/txhhsc-oarow.jsonl]`
15
+ */
16
+
17
+ import { dataRootPath, tempRootPath } from "@mailwoman/core/data-root"
18
+ import { readLocalTextFile } from "@mailwoman/core/fs/readers"
19
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers"
20
+ import { stringifyJSON } from "@mailwoman/core/json"
21
+ import type { PathBuilderLike } from "path-ts"
22
+ import { TSVSpliterator } from "spliterator"
23
+
24
+ import { inTXBBOX } from "#tools/shared"
25
+
26
+ /**
27
+ * Options for {@linkcode convertTXHHSC}.
28
+ */
29
+ export interface TXHHSCConvertOptions {
30
+ /**
31
+ * The TX hhsc nursing-facilities TSV.
32
+ *
33
+ * @defaultValue `$MAILWOMAN_DATA_ROOT/record-matcher/sources/…`
34
+ */
35
+ src?: PathBuilderLike
36
+ /**
37
+ * Output OaRow jsonl path.
38
+ *
39
+ * @defaultValue `/tmp/txhhsc-oarow.jsonl`
40
+ */
41
+ out?: string
42
+ }
43
+
44
+ const GEO = /^\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*$/
45
+
46
+ /**
47
+ * Convert the TX hhsc nursing-facilities TSV into OaRow jsonl for `oa-resolver-eval`.
48
+ */
49
+ export async function convertTXHHSC(
50
+ options: TXHHSCConvertOptions = {},
51
+ report?: (line: string) => void
52
+ ): Promise<{ written: number; skipped: number; out: string }> {
53
+ const src = options.src ?? dataRootPath("record-matcher", "sources", "txhhsc_nursing-facilities_20260611.tsv")
54
+ const out = options.out || tempRootPath("txhhsc-oarow.jsonl")
55
+
56
+ const records: string[] = []
57
+ let skipped = 0
58
+
59
+ // Column indices come from the first non-blank row.
60
+ // `header: false` keeps that row in the stream, so the blank-row guard below applies to it.
61
+ let cAddr = -1
62
+ let cCity = -1
63
+ let cZip = -1
64
+ let cGeo = -1
65
+ let sawHeader = false
66
+
67
+ for (const f of TSVSpliterator.from(await readLocalTextFile(src), { header: false })) {
68
+ if (f.every((value) => !value)) continue
69
+
70
+ if (!sawHeader) {
71
+ sawHeader = true
72
+ const col = (name: string) => f.indexOf(name)
73
+ cAddr = col("Physical Address")
74
+ cCity = col("Physical Address CITY")
75
+ cZip = col("Physical Address Zipcode")
76
+ cGeo = col("Geo Location")
77
+
78
+ continue
79
+ }
80
+
81
+ const addr = f[cAddr] ?? ""
82
+ const city = f[cCity] ?? ""
83
+ const zip = f[cZip] ?? ""
84
+ const m = GEO.exec(f[cGeo] ?? "")
85
+
86
+ if (!addr || !city || !m) {
87
+ skipped++
88
+
89
+ continue
90
+ }
91
+
92
+ const lat = Number(m[1])
93
+ const lon = Number(m[2])
94
+
95
+ // Sanity: TX bounding box (rejects swapped/garbage coords).
96
+ if (!inTXBBOX(lat, lon)) {
97
+ skipped++
98
+
99
+ continue
100
+ }
101
+
102
+ records.push(
103
+ stringifyJSON({
104
+ input: `${addr}, ${city}, TX ${zip}`,
105
+ lat,
106
+ lon,
107
+ expected: { locality: city, region: "TX", postcode: zip },
108
+ state: "TX",
109
+ source: "txhhsc:nursing-facilities",
110
+ })
111
+ )
112
+ }
113
+
114
+ await writeLocalTextFile(records, out)
115
+ report?.(`wrote ${records.length} rows (skipped ${skipped}) → ${out}`)
116
+
117
+ return { written: records.length, skipped, out }
118
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * This module configures the shared browser for Plotly and MapLibre rendering.
7
+ * SwiftShader supplies WebGL without a hardware GPU.
8
+ * Each caller owns navigation, readiness checks, and screenshots.
9
+ * The browser package loads Playwright and stealth plugins when a session starts.
10
+ */
11
+
12
+ import { withBrowserPage } from "@mailwoman/browser"
13
+ import type { Page } from "playwright"
14
+
15
+ /**
16
+ * Options for {@linkcode withChromiumPage}.
17
+ */
18
+ export interface ChromiumPageOptions {
19
+ viewport: { width: number; height: number }
20
+ }
21
+
22
+ /**
23
+ * Launch headless Chromium (SwiftShader WebGL), open one page at `deviceScaleFactor: 2`,
24
+ * collect console + page errors, run `fn`, and dispose the browser.
25
+ *
26
+ * The callback owns navigation, waits and the screenshot.
27
+ */
28
+ export async function withChromiumPage<T>(
29
+ options: ChromiumPageOptions,
30
+ fn: (page: Page) => Promise<T>
31
+ ): Promise<{ result: T; consoleErrors: string[] }> {
32
+ return withBrowserPage(
33
+ {
34
+ launchOptions: {
35
+ args: ["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"],
36
+ },
37
+ contextOptions: { viewport: options.viewport, deviceScaleFactor: 2 },
38
+ },
39
+ fn
40
+ )
41
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Render linked entities from a GeoJSON file in MapLibre, colored by source combination.
7
+ * `crossAgencyOnly` removes links whose sources belong to one agency.
8
+ */
9
+
10
+ import { dataRootPath, tempRootPath } from "@mailwoman/core/data-root"
11
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
12
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
13
+ import type { GeoFeature, GeoFeatureCollection, PointLiteral } from "@mailwoman/spatial"
14
+
15
+ import { type MapFeatureData, toMapHTML } from "#index"
16
+
17
+ /**
18
+ * Distinct agencies a combination needs before it is plotted as a cross-agency cluster.
19
+ */
20
+ const MIN_DISTINCT_AGENCIES = 3
21
+
22
+ /**
23
+ * Options for {@linkcode crossDatasetMap}.
24
+ */
25
+ export interface CrossDatasetMapOptions {
26
+ /**
27
+ * The `cross-dataset-links` GeoJSON.
28
+ *
29
+ * @defaultValue `$MAILWOMAN_DATA_ROOT/record-matcher/2026-06-16-cross-dataset-links.geojson`
30
+ */
31
+ in?: string
32
+ /**
33
+ * Output html path.
34
+ *
35
+ * @defaultValue `/tmp/cross-dataset-map.html`
36
+ */
37
+ outHTML?: string
38
+ /**
39
+ * Keep only entities whose sources span >1 agency (the two FCC datasets count as one).
40
+ */
41
+ crossAgencyOnly?: boolean
42
+ }
43
+
44
+ const SOURCE_LABELS: Record<string, string> = {
45
+ nppes: "NPPES",
46
+ "fcc-rhc": "FCC RHC",
47
+ "fcc-rhc-commitments": "FCC commitments",
48
+ "txhhsc-nursing": "TX HHSC",
49
+ }
50
+
51
+ const label = (s: string) => SOURCE_LABELS[s] ?? s
52
+
53
+ /**
54
+ * Which agency each source belongs to.
55
+ *
56
+ * The two FCC datasets (RHC posted-services + commitments) are one agency.
57
+ * So an NPPES↔FCC or FCC↔TX link is cross-agency, but an RHC↔commitments link is not.
58
+ *
59
+ * `--cross-agency-only` keeps only the entities whose sources span >1 agency: the harder,
60
+ * more striking "no shared key across agencies" subset (most of the raw links are FCC-internal).
61
+ */
62
+ const SOURCE_AGENCY: Record<string, string> = {
63
+ nppes: "CMS",
64
+ "fcc-rhc": "FCC",
65
+ "fcc-rhc-commitments": "FCC",
66
+ "txhhsc-nursing": "TX HHSC",
67
+ }
68
+
69
+ const agencyOf = (s: string) => SOURCE_AGENCY[s] ?? s
70
+
71
+ const sourcesOf = (f: GeoFeature<PointLiteral, MapFeatureData>): string[] =>
72
+ Array.isArray(f.properties?.sources) ? f.properties.sources : []
73
+
74
+ /**
75
+ * Render the cross-dataset-links GeoJSON to a bucket-colored MapLibre html page.
76
+ */
77
+ export async function crossDatasetMap(
78
+ options: CrossDatasetMapOptions = {},
79
+ report?: (line: string) => void
80
+ ): Promise<{ outHTML: string; kept: number; total: number; triple: number }> {
81
+ const IN = options.in || dataRootPath("record-matcher", "2026-06-16-cross-dataset-links.geojson")
82
+ const OUT = options.outHTML || tempRootPath("cross-dataset-map.html")
83
+ const CROSS_AGENCY_ONLY = options.crossAgencyOnly ?? false
84
+
85
+ const parsed = await readLocalJSONFile<GeoFeatureCollection<PointLiteral, MapFeatureData>>(IN)
86
+
87
+ const total = parsed.features.length
88
+
89
+ const geojson = CROSS_AGENCY_ONLY
90
+ ? { ...parsed, features: parsed.features.filter((f) => new Set(sourcesOf(f).map(agencyOf)).size > 1) }
91
+ : parsed
92
+
93
+ // Synthesize a `bucket` per entity = its sorted source-combination, so toMapHTML colors by the link
94
+ // type (two-source vs the rarer all-three-source spans) rather than the binary cross/single status.
95
+ let triple = 0
96
+ const comboCounts = new Map<string, number>()
97
+
98
+ for (const f of geojson.features) {
99
+ const combo = [...new Set(sourcesOf(f))].toSorted()
100
+ const bucket = combo.map(label).join(" + ") || "unlinked"
101
+
102
+ if (f.properties) {
103
+ f.properties.bucket = bucket
104
+ }
105
+
106
+ if (new Set(combo.map(agencyOf)).size >= MIN_DISTINCT_AGENCIES) {
107
+ triple++
108
+ }
109
+
110
+ comboCounts.set(bucket, (comboCounts.get(bucket) ?? 0) + 1)
111
+ }
112
+
113
+ const kept = geojson.features.length
114
+ const scope = CROSS_AGENCY_ONLY ? "across agencies" : "across sources"
115
+
116
+ const html = toMapHTML(geojson, {
117
+ title: `Cross-dataset entity links — ${kept} resolved ${scope} (no shared key)`,
118
+ flavor: "light",
119
+ colorBy: "bucket",
120
+ })
121
+
122
+ await writeLocalFile(html, OUT)
123
+ report?.(`[written] ${OUT} (${kept}${CROSS_AGENCY_ONLY ? ` of ${total} cross-AGENCY` : ""} entities)`)
124
+ report?.(` source combinations:`)
125
+
126
+ for (const [combo, n] of [...comboCounts.entries()].toSorted((a, b) => b[1] - a[1])) {
127
+ report?.(` ${n.toString().padStart(4)} ${combo}`)
128
+ }
129
+
130
+ report?.(` spanning all three agencies: ${triple}`)
131
+
132
+ return { outHTML: OUT, kept, total, triple }
133
+ }
@@ -0,0 +1,305 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Plot string-only and string-plus-distance match probabilities using the record matcher's
7
+ * Fellegi-Sunter weights. The supplied prior is illustrative and the output is self-contained html.
8
+ */
9
+
10
+ import { tempRootPath } from "@mailwoman/core/data-root"
11
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
12
+ import { stringifyJSON } from "@mailwoman/core/json"
13
+
14
+ /**
15
+ * Options for {@linkcode geocodeFirstSurface}.
16
+ */
17
+ export interface GeocodeFirstSurfaceOptions {
18
+ /**
19
+ * Illustrative prior λ.
20
+ *
21
+ * Production's record matcher uses λ=1e-4 (calibrated for the full multi-field model with phone
22
+ *
23
+ * - Spatial exact-key); here we want the boundary visible in a two-axis projection.
24
+ *
25
+ * @defaultValue `0.02`
26
+ */
27
+ lambda?: number
28
+ /**
29
+ * Output html path.
30
+ *
31
+ * @defaultValue `/tmp/geocode-first-surface.html`
32
+ */
33
+ outHTML?: string
34
+ }
35
+
36
+ // ── Real Bayes-factor weights, transcribed from source (values kept in sync by comment rather than import,
37
+ // so this generator is self-contained / independent of the match package's build state). ───────────
38
+
39
+ interface Level {
40
+ label: string
41
+ m: number
42
+ u: number
43
+ minSimilarity?: number
44
+ maxKm?: number
45
+ }
46
+
47
+ /**
48
+ * Registry/resolve.ts → NAME_LEVELS.
49
+ */
50
+ const NAME_LEVELS: Level[] = [
51
+ { label: "exact", minSimilarity: 1, m: 0.8, u: 0.01 },
52
+ { label: "high", minSimilarity: 0.88, m: 0.15, u: 0.03 },
53
+ { label: "different", minSimilarity: 0, m: 0.05, u: 0.96 },
54
+ ]
55
+
56
+ /**
57
+ * Match/distance.ts → DEFAULT_DISTANCE_LEVELS.
58
+ */
59
+ const DISTANCE_LEVELS: Level[] = [
60
+ { label: "same-building", maxKm: 0.05, m: 0.7, u: 0.001 },
61
+ { label: "same-block", maxKm: 0.5, m: 0.2, u: 0.02 },
62
+ { label: "same-area", maxKm: 5, m: 0.08, u: 0.2 },
63
+ { label: "far", m: 0.02, u: 0.779 },
64
+ ]
65
+
66
+ // match/fellegi-sunter.ts → levelWeight / priorWeight / probabilityFromWeight
67
+ const levelWeight = (lvl: Level) => (lvl.u <= 0 ? (lvl.m > 0 ? Infinity : 0) : Math.log2(lvl.m / lvl.u))
68
+ const priorWeight = (lambda: number) => Math.log2(lambda / (1 - lambda))
69
+ const probabilityFromWeight = (w: number) => 1 / (1 + 2 ** -w)
70
+
71
+ /**
72
+ * Assign a name-similarity score to its agreement-level weight (levels ordered high→low sim).
73
+ */
74
+ function nameWeight(sim: number): number {
75
+ for (const lvl of NAME_LEVELS) if (sim >= (lvl.minSimilarity ?? 0)) return levelWeight(lvl)
76
+
77
+ return levelWeight(NAME_LEVELS.at(-1)!)
78
+ }
79
+
80
+ /**
81
+ * Assign a distance (km) to its agreement-level weight (levels ordered near→far).
82
+ */
83
+ function distanceWeight(km: number): number {
84
+ for (const lvl of DISTANCE_LEVELS) if (km <= (lvl.maxKm ?? Infinity)) return levelWeight(lvl)
85
+
86
+ return levelWeight(DISTANCE_LEVELS.at(-1)!)
87
+ }
88
+
89
+ /**
90
+ * Emit the geocode-first decision-surface Plotly html — see the module doc.
91
+ */
92
+ export async function geocodeFirstSurface(
93
+ options: GeocodeFirstSurfaceOptions = {},
94
+ report?: (line: string) => void
95
+ ): Promise<{ outHTML: string }> {
96
+ const LAMBDA = options.lambda ?? 0.02
97
+ const OUT_HTML = options.outHTML || tempRootPath("geocode-first-surface.html")
98
+
99
+ const PRIOR = priorWeight(LAMBDA)
100
+
101
+ /**
102
+ * String-first model: name evidence only — distance is invisible to it.
103
+ */
104
+ const pStringFirst = (sim: number, _km: number) => probabilityFromWeight(PRIOR + nameWeight(sim))
105
+ /**
106
+ * Geocode-first model: name + distance evidence.
107
+ */
108
+ const pGeocodeFirst = (sim: number, km: number) => probabilityFromWeight(PRIOR + nameWeight(sim) + distanceWeight(km))
109
+
110
+ // ── Grid.
111
+ // X = string similarity 0→1.
112
+ // Y = geographic distance, sampled denser near 0 (log-ish) so the meaningful same-building
113
+ // / same-block transitions aren't a single pixel. ────────────────
114
+
115
+ const NX = 60
116
+ const NY = 60
117
+ const KM_MAX = 50 // 0 → 50 km, log-spaced
118
+
119
+ const simAxis = Array.from({ length: NX }, (_, i) => i / (NX - 1))
120
+
121
+ // log-spaced distance: 0.005 km (5 m) → 50 km, plus a literal 0 at the front
122
+ const kmAxis = Array.from({ length: NY }, (_, j) => {
123
+ const t = j / (NY - 1)
124
+
125
+ return 0.005 * Math.pow(KM_MAX / 0.005, t)
126
+ })
127
+
128
+ function surface(p: (sim: number, km: number) => number): number[][] {
129
+ // Plotly z is row-major over y (distance), each row across x (similarity).
130
+ return kmAxis.map((km) => simAxis.map((sim) => p(sim, km)))
131
+ }
132
+
133
+ const zString = surface(pStringFirst)
134
+ const zGeo = surface(pGeocodeFirst)
135
+
136
+ // ── The two trap points.
137
+ // (sim, km) chosen to sit in the off-diagonal quadrants. ─────────────────
138
+
139
+ interface Trap {
140
+ label: string
141
+ detail: string
142
+ sim: number
143
+ km: number
144
+ }
145
+
146
+ const TRAPS: Trap[] = [
147
+ {
148
+ label: "Springfield General — IL vs MA",
149
+ detail: "identical name, ~1500 km apart",
150
+ sim: 1,
151
+ km: 15, // plotted on the far plateau (real distance ~1500 km. clamped into view)
152
+ },
153
+ {
154
+ // "St" → "Street" canonicalizes to a high (not exact) name agreement.
155
+ // The trailing "Apt 2" keeps it off 1.0.
156
+ // Lands in the 0.88 "high" tier — same place, drifted-but-recognizable string.
157
+ label: "123 Main St vs 123 Main Street Apt 2",
158
+ detail: "same building, drifted string",
159
+ sim: 0.9,
160
+ km: 0.01,
161
+ },
162
+ ]
163
+
164
+ // Decision verdicts at each trap (for the annotation text).
165
+ const verdict = (p: number) => (p >= 0.5 ? "MATCH" : "no")
166
+
167
+ const trapRows = TRAPS.map((t) => ({
168
+ ...t,
169
+ stringP: pStringFirst(t.sim, t.km),
170
+ geoP: pGeocodeFirst(t.sim, t.km),
171
+ }))
172
+
173
+ // ── html. ───────────────────────────────────────────────────────────────────────────────────────
174
+
175
+ const data = {
176
+ simAxis,
177
+ kmAxis,
178
+ zString,
179
+ zGeo,
180
+ traps: trapRows,
181
+ lambda: LAMBDA,
182
+ prior: PRIOR,
183
+ }
184
+
185
+ // Every `<`, not only `</script>`: `<!--` also leaves script-data state in the html
186
+ // tokenizer, after which a later `</script>` no longer ends the element.
187
+ // `\u003c` is the same string to a JSON reader.
188
+ const safe = stringifyJSON(data).replaceAll("<", "\\u003c")
189
+
190
+ const html = `<!doctype html><html><head><meta charset="utf-8"/>
191
+ <script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>
192
+ <style>
193
+ body{margin:0;font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#111}
194
+ h1{font-size:18px;margin:14px 0 2px 20px}
195
+ h2{font-size:14px;margin:14px 0 0 20px;font-weight:600}
196
+ p.sub{margin:2px 20px 0;color:#555;font-size:12px;max-width:1100px;line-height:1.45}
197
+ #pair{width:1120px;height:440px}
198
+ #contour{width:1120px;height:520px}
199
+ .cap{margin:6px 20px 14px;color:#666;font-size:11px;max-width:1100px;line-height:1.4}
200
+ </style></head><body>
201
+ <h1>Two ways to draw the line — string-first vs geocode-first</h1>
202
+ <p class="sub">P(match) over the same record-pair space: string similarity (x) × geographic distance (y).
203
+ Same Fellegi-Sunter scorer, real per-level Bayes factors; the only difference is which evidence each
204
+ model may see. <b>String-first</b> sees the name only — its boundary is a vertical wall at high
205
+ similarity, blind to where the records are. <b>Geocode-first</b> also sees distance — the wall bends,
206
+ becoming a basin you can only climb out of <i>near a shared place</i>.</p>
207
+ <div id="pair"></div>
208
+ <h2>The decision boundary, read from above</h2>
209
+ <p class="sub">The geocode-first P(match) contour with the string-first boundary (dashed) drawn for
210
+ contrast, and the two traps string matching was built to fall into. Geocode-first puts the far-apart
211
+ namesakes in the reject basin and pulls the same-building pair across the line — string-first inverts
212
+ both.</p>
213
+ <div id="contour"></div>
214
+ <p class="cap" id="cap"></p>
215
+ <script>
216
+ const D = ${safe};
217
+ const COMMON_SCENE = (title) => ({
218
+ xaxis:{title:"string similarity", range:[0,1], backgroundcolor:"#fafafa", gridcolor:"#e5e5e5"},
219
+ yaxis:{title:"distance (km, log)", type:"log", backgroundcolor:"#fafafa", gridcolor:"#e5e5e5"},
220
+ zaxis:{title:"P(match)", range:[0,1], gridcolor:"#e5e5e5"},
221
+ camera:{eye:{x:-1.6,y:-1.5,z:0.9}},
222
+ aspectratio:{x:1,y:1,z:0.6}
223
+ });
224
+ const surfFor = (z, name, colorscale) => ({
225
+ type:"surface", z:z, x:D.simAxis, y:D.kmAxis, name:name,
226
+ colorscale:colorscale, cmin:0, cmax:1, showscale:false,
227
+ contours:{z:{show:true, usecolormap:true, project:{z:true}, start:0, end:1, size:0.1}},
228
+ lighting:{ambient:0.75, diffuse:0.6, roughness:0.9}, opacity:1
229
+ });
230
+ Plotly.newPlot("pair", [
231
+ Object.assign(surfFor(D.zString, "string-first", "YlOrRd"), {scene:"scene"}),
232
+ Object.assign(surfFor(D.zGeo, "geocode-first", "Viridis"), {scene:"scene2"})
233
+ ], {
234
+ margin:{l:0,r:0,t:24,b:0},
235
+ scene:Object.assign(COMMON_SCENE(), {domain:{x:[0,0.48]}}),
236
+ scene2:Object.assign(COMMON_SCENE(), {domain:{x:[0.52,1]}}),
237
+ annotations:[],
238
+ showlegend:false
239
+ }, {displayModeBar:false, responsive:false}).then(()=>{
240
+ // titles over each scene
241
+ Plotly.relayout("pair", {
242
+ "annotations":[
243
+ {text:"<b>STRING-FIRST</b> — name only (vertical wall)", x:0.22, y:1.04, xref:"paper", yref:"paper", showarrow:false, font:{size:13, color:"#b3402a"}},
244
+ {text:"<b>GEOCODE-FIRST</b> — name + distance (basin)", x:0.78, y:1.04, xref:"paper", yref:"paper", showarrow:false, font:{size:13, color:"#2a6b6b"}}
245
+ ]
246
+ });
247
+ });
248
+
249
+ // 2D contour of geocode-first, traps annotated.
250
+ const trapX = D.traps.map(t=>t.sim);
251
+ const trapY = D.traps.map(t=>Math.max(t.km, D.kmAxis[0]));
252
+ Plotly.newPlot("contour", [
253
+ {type:"contour", z:D.zGeo, x:D.simAxis, y:D.kmAxis, colorscale:"Viridis", zmin:0, zmax:1,
254
+ contours:{coloring:"heatmap", showlines:true, start:0, end:1, size:0.1,
255
+ // emphasize the P=0.5 decision isocline
256
+ }, colorbar:{title:"P(match)", thickness:12, len:0.8}},
257
+ // string-first boundary: vertical line where name alone crosses 0.5
258
+ {type:"scatter", mode:"lines", x:[0.985,0.985], y:[D.kmAxis[0], D.kmAxis[D.kmAxis.length-1]],
259
+ line:{color:"#b3402a", width:2, dash:"dash"}, name:"string-first boundary", hoverinfo:"name"},
260
+ {type:"scatter", mode:"markers+text", x:trapX, y:trapY,
261
+ marker:{size:13, color:"#fff", line:{color:"#111", width:2}, symbol:"x-thin", "line.width":3},
262
+ text:D.traps.map((t,i)=> (i===0?"①":"②")), textposition:"middle center",
263
+ textfont:{size:13,color:"#111"}, name:"traps", hoverinfo:"text",
264
+ hovertext:D.traps.map(t=>t.label)}
265
+ ], {
266
+ margin:{l:70,r:20,t:10,b:50},
267
+ yaxis:{title:"geographic distance (km, log)", type:"log", range:[Math.log10(D.kmAxis[0]), Math.log10(D.kmAxis[D.kmAxis.length-1])], autorange:false},
268
+ xaxis:{title:"string similarity", range:[0,1]},
269
+ showlegend:true, legend:{x:0.62, y:0.06, bgcolor:"rgba(255,255,255,0.85)", font:{size:11}},
270
+ shapes:[0.05,0.5,5].map((km)=>({type:"line", xref:"paper", x0:0, x1:1, yref:"y", y0:km, y1:km, line:{color:"rgba(255,255,255,0.45)", width:1, dash:"dot"}})),
271
+ annotations:[
272
+ {x:0.015, y:0.05, text:"same-building", showarrow:false, font:{size:9,color:"#eee"}, xanchor:"left", yanchor:"bottom"},
273
+ {x:0.015, y:0.5, text:"same-block", showarrow:false, font:{size:9,color:"#eee"}, xanchor:"left", yanchor:"bottom"},
274
+ {x:0.015, y:5, text:"same-area", showarrow:false, font:{size:9,color:"#ddd"}, xanchor:"left", yanchor:"bottom"},
275
+ // Paper-anchored callout boxes (stable placement), each tied to its ①/② marker, with a paper→data arrow.
276
+ {xref:"paper", yref:"paper", x:0.30, y:0.86, ax:trapX[0], ay:trapY[0], axref:"x", ayref:"y",
277
+ text:"① "+D.traps[0].label+"<br>"+D.traps[0].detail+"<br><b>string-first: MATCH ✗ · geocode-first: reject ✓</b>",
278
+ showarrow:true, arrowhead:2, arrowcolor:"#b3402a", align:"left", font:{size:10,color:"#111"}, bgcolor:"rgba(255,255,255,0.94)", bordercolor:"#b3402a", borderpad:3},
279
+ {xref:"paper", yref:"paper", x:0.30, y:0.30, ax:trapX[1], ay:trapY[1], axref:"x", ayref:"y",
280
+ text:"② "+D.traps[1].label+"<br>"+D.traps[1].detail+"<br><b>string-first: reject ✗ · geocode-first: MATCH ✓</b>",
281
+ showarrow:true, arrowhead:2, arrowcolor:"#2a6b6b", align:"left", font:{size:10,color:"#111"}, bgcolor:"rgba(255,255,255,0.94)", bordercolor:"#2a6b6b", borderpad:3}
282
+ ]
283
+ }, {displayModeBar:false, responsive:false});
284
+
285
+ const fmt = (p)=> (p*100).toFixed(p>=0.5?0:1)+"%";
286
+ document.getElementByID("cap").innerHTML =
287
+ "Real per-level Bayes factors (NAME_LEVELS, DEFAULT_DISTANCE_LEVELS); illustrative prior λ="+D.lambda+
288
+ " (production λ=1e-4 + phone/spatial-key corroboration, omitted here to isolate the two-axis boundary). "+
289
+ "Trap ① string-first="+fmt(D.traps[0].stringP)+" (MATCH ✗) · geocode-first="+fmt(D.traps[0].geoP)+" (reject ✓). "+
290
+ "Trap ② string-first="+fmt(D.traps[1].stringP)+" (reject ✗) · geocode-first="+fmt(D.traps[1].geoP)+" (MATCH ✓).";
291
+ </script>
292
+ </body></html>`
293
+
294
+ await writeLocalFile(html, OUT_HTML)
295
+ report?.(`[written] ${OUT_HTML}`)
296
+ report?.(`λ=${LAMBDA} prior=${PRIOR.toFixed(2)} bits`)
297
+
298
+ for (const t of trapRows) {
299
+ report?.(
300
+ ` ${t.label}: string-first ${(t.stringP * 100).toFixed(1)}% (${verdict(t.stringP)}) | geocode-first ${(t.geoP * 100).toFixed(1)}% (${verdict(t.geoP)})`
301
+ )
302
+ }
303
+
304
+ return { outHTML: OUT_HTML }
305
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Render a {@link toMapHTML} page (MapLibre GL + Protomaps basemap) to a PNG via headless Chromium
7
+ * — the shared map renderer behind the `registry viz` map figures (an internal helper rather than a
8
+ * command).
9
+ *
10
+ * Two house-stack constraints make this fiddlier than the Plotly/SVG renderers:
11
+ *
12
+ * - MapLibre needs a real WebGL context — the shared harness (`./browser.ts`) provides one through
13
+ * SwiftShader.
14
+ * - The basemap tiles come from `tiles.mailwoman.post`, which cors-restricts to localhost + the docs
15
+ * domains . Therefore, the page must be served over localhost rather than opened as a file (a file:// page
16
+ * renders accurate markers on a blank basemap). Serve the output dir first, e.g. `python3 -m
17
+ * http.server 8899 -d <dir>`, then point this at `http://localhost:8899/<page>.html`.
18
+ *
19
+ * The map paints asynchronously after the network settles. we wait for networkidle, then a fixed
20
+ * beat for the basemap tiles + marker layer to finish compositing.
21
+ */
22
+
23
+ import { withChromiumPage } from "#tools/viz/browser"
24
+
25
+ /**
26
+ * Options for {@linkcode renderServedMapToPNG}.
27
+ */
28
+ export interface RenderMapOptions {
29
+ /**
30
+ * The served localhost URL of the map page (not a file:// path — see the module doc).
31
+ */
32
+ url: string
33
+ /**
34
+ * Output PNG path.
35
+ */
36
+ outPNG: string
37
+ }
38
+
39
+ /**
40
+ * Screenshot a served MapLibre map page once the tiles + marker layer settle.
41
+ */
42
+ export async function renderServedMapToPNG(
43
+ options: RenderMapOptions,
44
+ report?: (line: string) => void
45
+ ): Promise<{ outPNG: string; consoleErrors: string[] }> {
46
+ const { consoleErrors: errors } = await withChromiumPage({ viewport: { width: 1100, height: 760 } }, async (page) => {
47
+ await page.goto(options.url, { waitUntil: "networkidle", timeout: 30_000 })
48
+ // MapLibre composites tiles + the marker layer async after the network settles.
49
+ // Give it a beat.
50
+ await page.waitForTimeout(4000)
51
+ await page.screenshot({ path: options.outPNG })
52
+ })
53
+
54
+ report?.(`[map-render] ${options.outPNG}; console errors=${errors.length}`)
55
+
56
+ for (const e of errors.slice(0, 6)) {
57
+ report?.(" " + e)
58
+ }
59
+
60
+ return { outPNG: options.outPNG, consoleErrors: errors }
61
+ }