@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,429 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { dataRootPath } from "@mailwoman/core/data-root"
8
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
9
+ import { makeLcg } from "@mailwoman/core/random"
10
+ import { mean } from "@mailwoman/core/utils"
11
+ import { agreementPattern, block, estimateParameters, gbtScore, scorePair, trainGBT } from "@mailwoman/match"
12
+
13
+ import { buildDefaultModel, createMatchFeaturizer, defaultBlockingKeys, ingestRows, type ColumnMapping } from "#index"
14
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
15
+ import { buildNPPESSample } from "#tools/nppes/sample"
16
+ import { pct, sgn, stateOption, std, trainLogisticRegression } from "#tools/shared"
17
+
18
+ const MIN_MEANINGFUL_DELTA = 0.005
19
+
20
+ const CLEAR_WIN_DELTA = 0.01
21
+
22
+ const CLEAR_WIN_F1_DELTA = 0.02
23
+
24
+ const STRONG_EVIDENCE_Z = 3
25
+
26
+ const TRAIN_SPLIT_FRACTION = 0.67
27
+
28
+ /**
29
+ * Options for {@linkcode scorerPairwiseEval}.
30
+ */
31
+ export interface ScorerPairwiseEvalOptions {
32
+ /**
33
+ * Creates the geocoder that places each sampled record's address.
34
+ */
35
+ createGeocoder: EvalGeocoderFactory
36
+
37
+ /**
38
+ * The record-matcher sources directory.
39
+ *
40
+ * @defaultValue `record-matcher/sources` under the data root.
41
+ */
42
+ sources?: string
43
+
44
+ /**
45
+ * The state to sample providers from.
46
+ *
47
+ * @defaultValue {@linkcode TX}
48
+ */
49
+ state?: string
50
+
51
+ /**
52
+ * The number of NPIs to sample.
53
+ *
54
+ * @defaultValue `1500`
55
+ */
56
+ npis?: number
57
+
58
+ /**
59
+ * The base PRNG seed.
60
+ *
61
+ * Each split adds its index to that value.
62
+ *
63
+ * @defaultValue `1`
64
+ */
65
+ seed?: number
66
+
67
+ /**
68
+ * The number of train/test splits to average over.
69
+ *
70
+ * @defaultValue `8`
71
+ */
72
+ seeds?: number
73
+
74
+ /**
75
+ * An optional path for the Markdown report.
76
+ */
77
+ outMd?: string
78
+ }
79
+
80
+ /**
81
+ * Compares Fellegi-Sunter, logistic-regression and gradient-boosted-tree pair scorers on an NPPES sample.
82
+ *
83
+ * A pair is a match when both records share an NPI.
84
+ * The function averages ROC-AUC and best F1 over several train/test splits.
85
+ *
86
+ * It prints and returns the Markdown report.
87
+ * It also writes the report to `outMd` when that option is set.
88
+ */
89
+ export async function scorerPairwiseEval(
90
+ options: ScorerPairwiseEvalOptions,
91
+ report?: (line: string) => void
92
+ ): Promise<{ markdown: string }> {
93
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
94
+ const STATE = stateOption(options)
95
+ const NPIS = options.npis ?? 1500
96
+ const SEED = options.seed ?? 1
97
+ const OUT_MD = options.outMd || ""
98
+
99
+ const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
100
+ const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
101
+
102
+ const { rows, keptNpis, addressFrequency } = await buildNPPESSample(
103
+ { registryPath: REGISTRY, otherNamesPath: OTHER_NAMES, state: STATE, maxNpis: NPIS },
104
+ report
105
+ )
106
+
107
+ report?.("[C] geocoding…")
108
+ const geocoder = await options.createGeocoder()
109
+
110
+ const mapping: ColumnMapping = {
111
+ id: "npi",
112
+ name: "name",
113
+ organization: "org",
114
+ address: "address",
115
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
116
+ source: "nppes",
117
+ }
118
+
119
+ const records = await ingestRows(rows, mapping, {
120
+ geocodeAddress: geocoder.geocodeAddress,
121
+ })
122
+
123
+ geocoder[Symbol.dispose]()
124
+
125
+ report?.("[D] blocking + features…")
126
+ const model = buildDefaultModel({ collapseSpatial: true, addressFrequency })
127
+ const { pairs } = block(records, defaultBlockingKeys())
128
+ const patterns = pairs.map(([a, b]) => agreementPattern(model.comparisons, a, b))
129
+ const fsModel = estimateParameters(model, patterns).model
130
+
131
+ const featurize = createMatchFeaturizer({ comparisons: model.comparisons, addressFrequency })
132
+
133
+ interface Sample {
134
+ x: number[]
135
+ y: number
136
+ fs: number
137
+ }
138
+
139
+ interface Scored {
140
+ s: number
141
+ y: number
142
+ }
143
+
144
+ interface SplitScored {
145
+ seed: number
146
+ trainN: number
147
+ testN: number
148
+ lrScored: Scored[]
149
+ fsScored: Scored[]
150
+ gbtScored: Scored[]
151
+ }
152
+
153
+ function runSplit(seed: number): SplitScored {
154
+ const rnd = makeLcg(seed || 1)
155
+ const npiSplit = new Map<string, "train" | "test">()
156
+
157
+ for (const npi of keptNpis) {
158
+ npiSplit.set(npi, rnd() < TRAIN_SPLIT_FRACTION ? "train" : "test")
159
+ }
160
+
161
+ const train: Sample[] = []
162
+ const test: Sample[] = []
163
+
164
+ pairs.forEach(([a, b]) => {
165
+ const sa = npiSplit.get(a.id)
166
+ const sb = npiSplit.get(b.id)
167
+
168
+ if (!sa || sa !== sb) return
169
+
170
+ const sample: Sample = {
171
+ x: featurize(a, b),
172
+ y: a.id === b.id ? 1 : 0,
173
+ fs: scorePair(fsModel, a, b).weight,
174
+ }
175
+ ;(sa === "train" ? train : test).push(sample)
176
+ })
177
+
178
+ const dim = train[0]?.x.length ?? 0
179
+ const posWeight = train.filter((s) => s.y === 1).length / Math.max(1, train.length)
180
+ const sampleWeights = train.map((s) => (s.y === 1 ? 1 - posWeight : posWeight))
181
+
182
+ const lrScore = trainLogisticRegression(
183
+ train.map((s) => s.x),
184
+ train.map((s) => s.y),
185
+ sampleWeights,
186
+ dim
187
+ )
188
+
189
+ const gbt = trainGBT(
190
+ train.map((s) => s.x),
191
+ train.map((s) => s.y),
192
+ sampleWeights,
193
+ { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
194
+ )
195
+
196
+ return {
197
+ seed,
198
+ trainN: train.length,
199
+ testN: test.length,
200
+ lrScored: test.map((s) => ({ s: lrScore(s.x), y: s.y })),
201
+ fsScored: test.map((s) => ({ s: s.fs, y: s.y })),
202
+ gbtScored: test.map((s) => ({ s: gbtScore(gbt, s.x), y: s.y })),
203
+ }
204
+ }
205
+
206
+ function auc(scored: Array<{ s: number; y: number }>): number {
207
+ const pos = scored.filter((d) => d.y === 1)
208
+ const neg = scored.filter((d) => d.y === 0)
209
+
210
+ if (!pos.length || !neg.length) return Number.NaN
211
+
212
+ const sorted = [...scored].toSorted((p, q) => p.s - q.s)
213
+ let rank = 1
214
+ let rankSum = 0
215
+
216
+ for (let i = 0; i < sorted.length;) {
217
+ let j = i
218
+
219
+ while (j < sorted.length && sorted[j]!.s === sorted[i]!.s) {
220
+ j++
221
+ }
222
+
223
+ const avg = (rank + (rank + (j - i) - 1)) / 2
224
+
225
+ for (let k = i; k < j; k++)
226
+ if (sorted[k]!.y === 1) {
227
+ rankSum += avg
228
+ }
229
+
230
+ rank += j - i
231
+ i = j
232
+ }
233
+
234
+ return (rankSum - (pos.length * (pos.length + 1)) / 2) / (pos.length * neg.length)
235
+ }
236
+
237
+ function bestF1(scored: Array<{ s: number; y: number }>): { f1: number; precision: number; recall: number } {
238
+ const thresholds = [...new Set(scored.map((d) => d.s))].toSorted((p, q) => p - q)
239
+ let best = { f1: 0, precision: 0, recall: 0 }
240
+ const P = scored.filter((d) => d.y === 1).length
241
+
242
+ for (const t of thresholds) {
243
+ let tp = 0
244
+ let fp = 0
245
+
246
+ for (const d of scored) {
247
+ if (d.s >= t) {
248
+ if (d.y === 1) {
249
+ tp++
250
+ } else {
251
+ fp++
252
+ }
253
+ }
254
+ }
255
+
256
+ const precision = tp + fp > 0 ? tp / (tp + fp) : 0
257
+ const recall = P > 0 ? tp / P : 0
258
+ const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
259
+
260
+ if (f1 > best.f1) {
261
+ best = { f1, precision, recall }
262
+ }
263
+ }
264
+
265
+ return best
266
+ }
267
+
268
+ report?.("[E] training across seeds…")
269
+ const SEEDS = options.seeds ?? 8
270
+ const splits = Array.from({ length: SEEDS }, (_, k) => runSplit(SEED + k))
271
+
272
+ const fsAucs = splits.map((r) => auc(r.fsScored))
273
+ const lrAucs = splits.map((r) => auc(r.lrScored))
274
+ const deltas = splits.map((_, i) => lrAucs[i]! - fsAucs[i]!)
275
+ const fsF1s = splits.map((r) => bestF1(r.fsScored).f1)
276
+ const lrF1s = splits.map((r) => bestF1(r.lrScored).f1)
277
+ const lrWins = deltas.filter((d) => d > 0).length
278
+ const meanDelta = mean(deltas)!
279
+ const avgTestN = mean(splits.map((r) => r.testN))!
280
+ const avgTestPos = mean(splits.map((r) => r.lrScored.filter((d) => d.y === 1).length))!
281
+ const seMean = std(deltas) / Math.sqrt(SEEDS)
282
+ const zScore = seMean > 0 ? meanDelta / seMean : 0
283
+ const f1Delta = mean(lrF1s)! - mean(fsF1s)!
284
+ const unanimous = lrWins === SEEDS
285
+
286
+ const gbtAucs = splits.map((r) => auc(r.gbtScored))
287
+ const gbtF1s = splits.map((r) => bestF1(r.gbtScored).f1)
288
+ const gbtVsFs = splits.map((_, i) => gbtAucs[i]! - fsAucs[i]!)
289
+ const gbtVsLr = splits.map((_, i) => gbtAucs[i]! - lrAucs[i]!)
290
+ const gbtBeatsLr = gbtVsLr.filter((d) => d > 0).length
291
+ const meanGbtVsFs = mean(gbtVsFs)!
292
+ const meanGbtVsLr = mean(gbtVsLr)!
293
+ const f1DeltaGbt = mean(gbtF1s)! - mean(fsF1s)!
294
+
295
+ for (const r of splits) {
296
+ const dl = auc(r.lrScored) - auc(r.fsScored)
297
+ const dg = auc(r.gbtScored) - auc(r.fsScored)
298
+
299
+ report?.(
300
+ ` seed ${r.seed}: ${r.trainN}tr/${r.testN}te FS ${auc(r.fsScored).toFixed(4)} ` +
301
+ `LR ${auc(r.lrScored).toFixed(4)} (Δ${dl >= 0 ? "+" : ""}${dl.toFixed(4)}) ` +
302
+ `GBT ${auc(r.gbtScored).toFixed(4)} (Δ${dg >= 0 ? "+" : ""}${dg.toFixed(4)})`
303
+ )
304
+ }
305
+
306
+ report?.(
307
+ ` mean/${SEEDS} — FS ${mean(fsAucs)!.toFixed(4)} LR ${mean(lrAucs)!.toFixed(4)} (Δ${meanDelta >= 0 ? "+" : ""}${meanDelta.toFixed(4)}) ` +
308
+ `GBT ${mean(gbtAucs)!.toFixed(4)} (Δ${meanGbtVsFs >= 0 ? "+" : ""}${meanGbtVsFs.toFixed(4)} vs FS, ` +
309
+ `${meanGbtVsLr >= 0 ? "+" : ""}${meanGbtVsLr.toFixed(4)} vs LR)`
310
+ )
311
+
312
+ const f4 = (x: number) => x.toFixed(4)
313
+
314
+ const lines: string[] = [
315
+ `# Learned-scorer probe (#603) — does a model beat Fellegi-Sunter on the FS feature vector?`,
316
+ "",
317
+ `_Generated by \`mailwoman registry scorer-eval pairwise\`. ${keptNpis.size} ${STATE} NPIs → ${records.length} ` +
318
+ `records, geocoded. Candidate pairs are split BY NPI into train/test (no NPI's records cross the split), repeated ` +
319
+ `over ${SEEDS} seeds to bound split variance. Two learned scorers over the FS agreement pattern + over-merge ` +
320
+ `interaction features (spatial-exact × name-disagree, spatial-exact × org-disagree, address crowdedness) — features ` +
321
+ `FS structurally cannot express — vs the EM-fitted FS scorer, on the held-out test pairs: an **L2 logistic ` +
322
+ `regression** (linear) and **gradient-boosted trees** (non-linear, the model #603 names). AUC is threshold-free ` +
323
+ `(does it RANK matches above non-matches?). The FS scorer is fit unsupervised on ALL pairs, so the comparison ` +
324
+ `slightly favors FS — it has already seen the test pairs (label-free), the learned scorers have not._`,
325
+ "",
326
+ `## Result — mean over ${SEEDS} NPI-splits (~${Math.round(avgTestN)} test pairs/split, ~${Math.round(avgTestPos)} matches)`,
327
+ "",
328
+ `| scorer | ROC-AUC (mean±std) | ΔAUC vs FS | best F1 (mean) |`,
329
+ `|---|---:|---:|---:|`,
330
+ `| Fellegi-Sunter (EM-fit) | ${f4(mean(fsAucs)!)} ± ${f4(std(fsAucs))} | — | ${pct(mean(fsF1s)!)}% |`,
331
+ `| logistic regression (linear) | ${f4(mean(lrAucs)!)} ± ${f4(std(lrAucs))} | ${sgn(meanDelta)}${f4(meanDelta)} | ${pct(mean(lrF1s)!)}% |`,
332
+ `| **gradient-boosted trees** | **${f4(mean(gbtAucs)!)} ± ${f4(std(gbtAucs))}** | **${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}** | **${pct(mean(gbtF1s)!)}%** |`,
333
+ "",
334
+ `**ΔAUC (LR − FS): ${sgn(meanDelta)}${f4(meanDelta)} ± ${f4(std(deltas))}, LR > FS in ${lrWins}/${SEEDS} seeds.**`,
335
+ "",
336
+ `Robustness: the ΔAUC is small but **consistent** — std ${f4(std(deltas))} across seeds, SE ±${f4(seMean)} → ` +
337
+ `≈${zScore.toFixed(1)}σ above zero, ${lrWins}/${SEEDS} seeds in LR's favor. At the operating point the gap is ` +
338
+ `larger: **ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp** (${pct(mean(fsF1s)!)}% → ${pct(mean(lrF1s)!)}%), ` +
339
+ `because the interaction features sharpen the hard co-located band near the decision boundary even where overall ` +
340
+ `ranking barely moves.`,
341
+ "",
342
+ ]
343
+
344
+ const treeVerdict =
345
+ meanGbtVsLr > MIN_MEANINGFUL_DELTA && gbtBeatsLr >= SEEDS - 1
346
+ ? `**The tree extends the linear gain** — GBT beats the LR by ΔAUC ${sgn(meanGbtVsLr)}${f4(meanGbtVsLr)} ` +
347
+ `(${gbtBeatsLr}/${SEEDS} seeds), ${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)} over FS, ΔF1 ${sgn(f1DeltaGbt * 100)}${(f1DeltaGbt * 100).toFixed(1)}pp. ` +
348
+ `Non-linear interactions the hand-crafted features miss carry additional signal — a real GBM (XGBoost/LightGBM, ` +
349
+ `more NPIs, more features) is worth building.`
350
+ : meanGbtVsLr < -MIN_MEANINGFUL_DELTA
351
+ ? `**The tree does NOT beat the linear model** (GBT − LR = ${sgn(meanGbtVsLr)}${f4(meanGbtVsLr)} AUC, ` +
352
+ `${gbtBeatsLr}/${SEEDS} seeds; GBT − FS = ${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}). With the over-merge interactions ` +
353
+ `already hand-engineered into the feature vector, a shallow tree finds little extra and slightly overfits the ` +
354
+ `small label set — the LR is the better-behaved scorer here.`
355
+ : `**The tree roughly TIES the linear model** (GBT − LR = ${sgn(meanGbtVsLr)}${f4(meanGbtVsLr)} AUC, ` +
356
+ `${gbtBeatsLr}/${SEEDS} seeds; GBT − FS = ${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}, ΔF1 ${sgn(f1DeltaGbt * 100)}${(f1DeltaGbt * 100).toFixed(1)}pp). ` +
357
+ `Because the key over-merge interactions are ALREADY hand-engineered into the feature vector, the tree's main ` +
358
+ `advantage — auto-discovering interactions — is largely pre-empted; it neither extends nor erases the linear ` +
359
+ `gain. The signal in this feature set is close to linearly saturated, so a production GBM should budget for the ` +
360
+ `SAME modest margin the LR shows, not a step change — its real value is generalizing the #625 changes, not ` +
361
+ `finding hidden non-linear structure here.`
362
+
363
+ lines.push(treeVerdict)
364
+ lines.push("")
365
+ lines.push(`### Per-seed`)
366
+ lines.push("")
367
+ lines.push(`| seed | test pairs | FS AUC | LR AUC | GBT AUC |`)
368
+ lines.push(`|---:|---:|---:|---:|---:|`)
369
+
370
+ for (const r of splits) {
371
+ lines.push(`| ${r.seed} | ${r.testN} | ${f4(auc(r.fsScored))} | ${f4(auc(r.lrScored))} | ${f4(auc(r.gbtScored))} |`)
372
+ }
373
+
374
+ lines.push("")
375
+
376
+ const verdict =
377
+ unanimous && (meanDelta > CLEAR_WIN_DELTA || f1Delta > CLEAR_WIN_F1_DELTA)
378
+ ? `The LR beats FS **consistently** — it wins ${lrWins}/${SEEDS} seeds and lifts the operating-point F1 by ` +
379
+ `${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp (${pct(mean(fsF1s)!)}% → ${pct(mean(lrF1s)!)}%). The ΔAUC is ` +
380
+ `small (+${f4(meanDelta)}) only because FS already ranks well (${f4(mean(fsAucs)!)}); the gain concentrates at the ` +
381
+ `decision boundary, exactly where the interaction features (which FS structurally can't express) bite. ` +
382
+ `**This greenlights the #603 learned scorer:** a GBM — non-linear over the same features — is the principled ` +
383
+ `generalization of the hand-tuned #625 changes and should extend this linear gain. Honest framing: the linear ` +
384
+ `headroom is modest, so the GBM's job is to *widen a real-but-small margin*, not to unlock a step change past the ` +
385
+ `64.7% dedup plateau on its own — the reliable secondary identifier (#625) is still the larger gain.`
386
+ : unanimous && zScore >= STRONG_EVIDENCE_Z
387
+ ? `The LR beats FS by a **small but statistically robust** margin (ΔAUC +${f4(meanDelta)}, ≈${zScore.toFixed(1)}σ, ` +
388
+ `${lrWins}/${SEEDS} seeds; ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp). The interaction features ` +
389
+ `carry real signal, but FS's calibrated weights already capture most of it. **Qualified greenlight for #603:** a ` +
390
+ `tree may extend the margin, but budget for a modest gain, not a plateau-breaker.`
391
+ : meanDelta < -MIN_MEANINGFUL_DELTA && lrWins < SEEDS / 2
392
+ ? `The LR is **worse** than FS (ΔAUC ${f4(meanDelta)}, ${lrWins}/${SEEDS} seeds) — the linear+interaction features ` +
393
+ `don't help on this sample. FS's calibrated weights are hard to beat here; a tree is the only remaining test ` +
394
+ `before committing to #603.`
395
+ : `The LR and FS are **statistically indistinguishable** (ΔAUC ${sgn(meanDelta)}${f4(meanDelta)}, ${lrWins}/${SEEDS} ` +
396
+ `seeds, within noise). On these features the over-merge resists a learned scorer — the discriminating signal a ` +
397
+ `reliable secondary identifier provides (#625) isn't recoverable from the FS feature vector alone. A richer ` +
398
+ `feature set or a tree is the next test before committing to #603.`
399
+
400
+ lines.push(verdict)
401
+ lines.push("")
402
+ lines.push(`## Honest caveats`)
403
+ lines.push("")
404
+
405
+ lines.push(
406
+ `In-domain (${STATE} only), ${keptNpis.size} NPIs, PAIRWISE ranking (not the assembled clustering metric the dedup ` +
407
+ `benchmark reports against the 64.7% baseline — a better pairwise scorer need not translate 1:1 to cluster F1). The GBT ` +
408
+ `is a compact pure-Node implementation (120 boosting rounds, depth 3), a faithful stand-in for an offline ` +
409
+ `XGBoost/LightGBM but not tuned. The split is by NPI so there's no record-level leakage, but the address-frequency ` +
410
+ `feature is a corpus statistic over all NPIs (a population prior, not per-pair leakage), and the FS scorer is EM-fit ` +
411
+ `on all pairs including the test subset (standard for label-free FS — it makes the learned scorers' win the harder ` +
412
+ `result). At ~${Math.round(avgTestN)} test pairs/split both AUC and F1 are stable across seeds (per-seed table). The ` +
413
+ `definitive test remains a GBM A/B on the **clustering** metric with a train-TX / eval-held-out-state split (#603 ` +
414
+ `Tier 2)._`
415
+ )
416
+
417
+ lines.push("")
418
+
419
+ const md = lines.join("\n")
420
+
421
+ console.log(md)
422
+
423
+ if (OUT_MD) {
424
+ await writeLocalFile(md, OUT_MD)
425
+ report?.(`[written] ${OUT_MD}`)
426
+ }
427
+
428
+ return { markdown: md }
429
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
8
+ import { makeLcg } from "@mailwoman/core/random"
9
+
10
+ import { resolveEntities, type SourceRecord } from "#index"
11
+
12
+ /**
13
+ * Options for {@linkcode matcherScale}.
14
+ */
15
+ export interface MatcherScaleOptions {
16
+ /**
17
+ * Lists the record counts to measure, defaulting to 10,000, 50,000, 100,000, 250,000 and 500,000.
18
+ */
19
+ sizes?: number[]
20
+
21
+ /**
22
+ * Sets the average number of records per distinct synthetic place, defaulting to 3.
23
+ */
24
+ dup?: number
25
+
26
+ /**
27
+ * Fits the Fellegi-Sunter m and u probabilities with EM at each size.
28
+ *
29
+ * This is slower.
30
+ * The option defaults to `false`.
31
+ */
32
+ em?: boolean
33
+
34
+ /**
35
+ * Gives a path where the Markdown report is also written.
36
+ */
37
+ outMd?: string
38
+ }
39
+
40
+ function generate(n: number, dup: number, seed = 1): SourceRecord[] {
41
+ const rnd = makeLcg(seed || 1)
42
+ const places = Math.max(1, Math.round(n / dup))
43
+ const records: SourceRecord[] = new Array(n)
44
+
45
+ for (let i = 0; i < n; i++) {
46
+ const place = i % places
47
+ const latitude = 25 + rnd() * 24
48
+ const longitude = -124 + rnd() * 57
49
+ const variant = i < places ? "" : rnd() < 0.5 ? " llc" : " inc"
50
+
51
+ records[i] = {
52
+ id: String(i),
53
+ organization: { canonical: `org ${place}${variant}`, raw: `Org ${place}` },
54
+ address: {
55
+ components: {},
56
+ canonicalKey: `key-${place}`,
57
+ raw: `${place} main st`,
58
+ geocode: {
59
+ coordinate: { latitude: latitude + (place % 7) * 1e-4, longitude: longitude + (place % 5) * 1e-4 },
60
+ tier: "address_point",
61
+ uncertaintyMeters: 5,
62
+ },
63
+ },
64
+ } as SourceRecord
65
+ }
66
+
67
+ return records
68
+ }
69
+
70
+ const mb = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(0)} MB`
71
+ const sec = (ms: number) => `${(ms / 1000).toFixed(2)} s`
72
+
73
+ /**
74
+ * Measures entity-resolution time, candidate pairs and memory on synthetic records
75
+ * of increasing size, all in one Node process.
76
+ *
77
+ * The function prints the Markdown report to stdout and returns it.
78
+ * It also writes to `outMd` when set.
79
+ */
80
+ export async function matcherScale(
81
+ options: MatcherScaleOptions = {},
82
+ report?: (line: string) => void
83
+ ): Promise<{ markdown: string }> {
84
+ const SIZES = options.sizes?.length ? options.sizes : [10_000, 50_000, 100_000, 250_000, 500_000]
85
+ const DUP = options.dup ?? 3
86
+ const EM = options.em ?? false
87
+ const OUT_MD = options.outMd || ""
88
+
89
+ interface Measurement {
90
+ n: number
91
+ records: number
92
+ entities: number
93
+ candidatePairs: number
94
+ wallMs: number
95
+ rssBytes: number
96
+ }
97
+
98
+ const rows: Measurement[] = []
99
+
100
+ for (const n of SIZES) {
101
+ const records = generate(n, DUP)
102
+ const t0 = performance.now()
103
+
104
+ const { entities, candidatePairs } = resolveEntities(records, {
105
+ collapseSpatial: true,
106
+ trainEM: EM,
107
+ learnedScorer: false,
108
+ })
109
+
110
+ const wallMs = performance.now() - t0
111
+ const rssBytes = process.memoryUsage().rss
112
+ rows.push({ n, records: records.length, entities: entities.length, candidatePairs, wallMs, rssBytes })
113
+ report?.(` N=${n}: ${sec(wallMs)}, ${candidatePairs} pairs → ${entities.length} entities, RSS ${mb(rssBytes)}`)
114
+
115
+ if (globalThis.gc) {
116
+ globalThis.gc()
117
+ }
118
+ }
119
+
120
+ const lines: string[] = [
121
+ `# Matcher scale — pure-Node block → score → cluster (#K)`,
122
+ "",
123
+ `_Generated by \`registry/tools/matcher-scale.ts\`. Synthetic geo-clustered records (~${DUP} per ` +
124
+ `distinct place), resolved with the geo-first baseline (collapsed spatial${EM ? " + EM" : ""}) in one Node ` +
125
+ `process without Elasticsearch or a server. Geocoding is out of scope (measured separately); this isolates the ` +
126
+ `matcher's block/score/cluster cost vs N._`,
127
+ "",
128
+ `| records | candidate pairs | entities | wall-clock | resolve rate | RSS (high-water) |`,
129
+ `|---:|---:|---:|---:|---:|---:|`,
130
+ ]
131
+
132
+ for (const r of rows) {
133
+ const rate = Math.round(r.records / (r.wallMs / 1000))
134
+
135
+ lines.push(
136
+ `| ${r.records.toLocaleString()} | ${r.candidatePairs.toLocaleString()} | ${r.entities.toLocaleString()} | ` +
137
+ `${sec(r.wallMs)} | ${rate.toLocaleString()}/s | ${mb(r.rssBytes)} |`
138
+ )
139
+ }
140
+
141
+ lines.push("")
142
+ lines.push(`## Reading`)
143
+ lines.push("")
144
+ const last = rows.at(-1)!
145
+
146
+ lines.push(
147
+ `The matcher resolves **${last.records.toLocaleString()} records in ${sec(last.wallMs)}** in a single Node ` +
148
+ `process (block → Fellegi-Sunter → union-find clustering) without an external service. Geo-cell + canonical-key ` +
149
+ `blocking keeps candidate generation near-linear (it never enumerates the O(n²) pair space), so the wall-clock ` +
150
+ `scales with the number of *blocked* pairs, not the square of N. That is the architectural claim made ` +
151
+ `concrete: a calibrated street-level geocoder feeding the blocking lets entity resolution run in-process at ` +
152
+ `hundreds of thousands of records, where a string-similarity matcher would need a search cluster to make the ` +
153
+ `candidate generation tractable.`
154
+ )
155
+
156
+ lines.push("")
157
+
158
+ lines.push(
159
+ `RSS is the shared-process high-water mark across the sweep (each size reuses the heap), so it is an upper ` +
160
+ `bound, not a per-N working set. The largest size that fits is bounded by the record objects + the link array; ` +
161
+ `beyond that, extract by geography (each cell is independent) — the same partition the blocking already implies.`
162
+ )
163
+
164
+ lines.push("")
165
+
166
+ lines.push(
167
+ `One honest caveat on the shape: these are uniform-random US coordinates, so as N rises the geo-cell collision ` +
168
+ `rate climbs and the candidate-pair count grows faster than N (visible in the table). Real address data clusters ` +
169
+ `into a roughly fixed set of places, so its pair/record ratio is flatter — the wall-clock here, which tracks the ` +
170
+ `number of PAIRS, is a conservative upper bound on a realistic workload of the same N.`
171
+ )
172
+
173
+ lines.push("")
174
+
175
+ const md = lines.join("\n")
176
+
177
+ console.log(md)
178
+
179
+ if (OUT_MD) {
180
+ await writeLocalFile(md, OUT_MD)
181
+ report?.(`[written] ${OUT_MD}`)
182
+ }
183
+
184
+ return { markdown: md }
185
+ }