@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
package/lib/resolve.ts ADDED
@@ -0,0 +1,569 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The resolve pipeline wires the matching modules over concrete contact and organization records.
7
+ *
8
+ * The upstream pipeline geocodes each `address` and supplies its coordinate and canonical key.
9
+ */
10
+
11
+ import {
12
+ type ComparisonLevel,
13
+ type BlockingKey,
14
+ type FellegiSunterModel,
15
+ type GBT,
16
+ type ScoredLink,
17
+ type TermFrequencyTable,
18
+ DEFAULT_DISTANCE_LEVELS,
19
+ DEFAULT_SPATIAL_LEVELS,
20
+ agreementPattern,
21
+ block,
22
+ buildTermFrequencyTable,
23
+ cluster,
24
+ distanceComparison,
25
+ estimateParameters,
26
+ exactKey,
27
+ geoCellKey,
28
+ representative,
29
+ scorePair,
30
+ similarityComparison,
31
+ spatialComparison,
32
+ withTermFrequency,
33
+ } from "@mailwoman/match"
34
+
35
+ import { createGBTScorer } from "#learned-scorer"
36
+ import { DEDUP_GBT_META, DEDUP_GBT_MODEL } from "#models/dedup-gbt-en-us"
37
+ import type { ResolvedEntity, SourceRecord } from "#types"
38
+
39
+ /**
40
+ * Cheap, parse-free normalization for the address-frequency key: uppercase,
41
+ * collapse whitespace, drop punctuation.
42
+ *
43
+ * The count covers distinct entities that share an address.
44
+ * It is computable over millions of rows without geocoding.
45
+ *
46
+ * A crowded clinic or billing address is weak identity evidence.
47
+ * A lonely address is strong.
48
+ */
49
+ export function addressFrequencyKey(raw: string): string {
50
+ return raw
51
+ .toUpperCase()
52
+ .replaceAll(/[^A-Z0-9]+/g, " ")
53
+ .trim()
54
+ .replaceAll(/\s+/g, " ")
55
+ }
56
+
57
+ /**
58
+ * Default tiered levels for a name-like text field.
59
+ *
60
+ * `m`/`u` are EM-estimable seeds.
61
+ */
62
+ const NAME_LEVELS: ComparisonLevel[] = [
63
+ { label: "exact", minSimilarity: 1, m: 0.8, u: 0.01 },
64
+ { label: "high", minSimilarity: 0.88, m: 0.15, u: 0.03 },
65
+ { label: "different", minSimilarity: 0, m: 0.05, u: 0.96 },
66
+ ]
67
+
68
+ /**
69
+ * Exact-vs-different levels for a normalized phone.
70
+ *
71
+ * A shared line is strong, rarely-coincidental evidence.
72
+ */
73
+ const PHONE_LEVELS: ComparisonLevel[] = [
74
+ { label: "exact", minSimilarity: 1, m: 0.6, u: 0.002 },
75
+ { label: "different", minSimilarity: 0, m: 0.4, u: 0.998 },
76
+ ]
77
+
78
+ /**
79
+ * Exact-vs-different levels for a closed-vocabulary code set
80
+ * ({@link DefaultModelOptions.exactDiscriminators}), such as NPPES taxonomy codes or license numbers.
81
+ *
82
+ * These are seeds only, since EM refits.
83
+ * `u` starts well above phone's 0.002, because two random providers share a
84
+ * specialty at a far higher rate than a phone line.
85
+ */
86
+ const CODE_SET_LEVELS: ComparisonLevel[] = [
87
+ { label: "exact", minSimilarity: 1, m: 0.75, u: 0.08 },
88
+ { label: "different", minSimilarity: 0, m: 0.25, u: 0.92 },
89
+ ]
90
+
91
+ function codeSetOverlap(a: string, b: string): number {
92
+ const sa = new Set(
93
+ a
94
+ .toUpperCase()
95
+ .split(/\s+/)
96
+ .filter((value) => value.length)
97
+ )
98
+
99
+ for (const t of b.toUpperCase().split(/\s+/)) if (t && sa.has(t)) return 1
100
+
101
+ return 0
102
+ }
103
+
104
+ /**
105
+ * Last-10-digit normalization for phone agreement, dropping country code, punctuation and extensions.
106
+ *
107
+ * A shorter digit string is kept as-is, since partial agreement still contributes
108
+ * weight in the comparison model.
109
+ * `null` means no digits at all.
110
+ */
111
+ export function normalizePhone(raw: string | null | undefined): string | null {
112
+ if (!raw) return null
113
+ const digits = raw.replaceAll(/\D+/g, "")
114
+
115
+ return digits.length >= 10 ? digits.slice(-10) : digits || null
116
+ }
117
+
118
+ /**
119
+ * {@link normalizePhone} under the probes' stricter interface, where only a full line counts.
120
+ *
121
+ * Returns the last 10 digits when the input contains at least 10.
122
+ * Returns `""` for shorter input, so callers never receive a partial digit string.
123
+ *
124
+ * Callers guard on truthiness, so `""` reads as no comparable phone rather than a weaker key.
125
+ */
126
+ export function normalizePhoneStrict(raw: string | null | undefined): string {
127
+ const digits = normalizePhone(raw)
128
+
129
+ return digits && digits.length === 10 ? digits : ""
130
+ }
131
+
132
+ /**
133
+ * The identity-corroborating comparisons: person name, organization and phone.
134
+ *
135
+ * At least one must positively agree before a pair may link, since a shared
136
+ * address provides no identity evidence by itself.
137
+ * Phone is the secondary identifier that rescues a true same-entity link across name drift.
138
+ */
139
+ const CORROBORATING_FIELDS = new Set(["given", "family", "organization", "phone"])
140
+
141
+ /**
142
+ * Options for {@link buildDefaultModel}.
143
+ *
144
+ * Each change is default-off, so the base model is byte-stable.
145
+ */
146
+ export interface DefaultModelOptions {
147
+ /**
148
+ * Corpus-wide address-frequency table over {@link addressFrequencyKey}, which makes
149
+ * the address agreement weight inverse to how shared the address is.
150
+ *
151
+ * A building with 50 providers makes a same-address match near-worthless evidence.
152
+ *
153
+ * The table's `value` is the record's raw address string.
154
+ */
155
+ addressFrequency?: TermFrequencyTable
156
+ /**
157
+ * Collapse the redundant address-key and great-circle-distance comparisons into one
158
+ * {@link spatialComparison spatial-agreement} signal, an exact-key tier over distance buckets.
159
+ *
160
+ * Removes the double-count that over-merges co-located providers, since an
161
+ * exact key match already implies distance ≈ 0.
162
+ */
163
+ collapseSpatial?: boolean
164
+ /**
165
+ * Add a normalized-phone exact-match comparison.
166
+ *
167
+ * A shared line is strong evidence and the secondary corroborator that lets a
168
+ * true same-entity link survive name drift.
169
+ */
170
+ usePhone?: boolean
171
+ /**
172
+ * Extra secondary-identifier comparisons drawn from {@link SourceRecord.attributes},
173
+ * such as `["authorizedOfficial"]`.
174
+ *
175
+ * Each becomes an `attr:<key>` comparison and counts toward corroboration.
176
+ * It is a more reliable discriminator than phone where the data has one.
177
+ */
178
+ discriminators?: string[]
179
+ /**
180
+ * Closed-vocabulary code-set discriminators drawn from {@link SourceRecord.attributes},
181
+ * such as NPPES taxonomy codes or license numbers.
182
+ *
183
+ * The attribute value is a whitespace-joined set of codes.
184
+ * Any shared code counts as agreement.
185
+ *
186
+ * This is set overlap rather than string similarity, since `207R00000X`
187
+ * and `207Q00000X` are different specialties despite near-identical text.
188
+ *
189
+ * Similarity scores mis-rank that case because the codes identify different specialties.
190
+ * The over-merge separator: two co-located records of one entity nearly always share
191
+ * a code, while two distinct co-located providers mostly do not.
192
+ */
193
+ exactDiscriminators?: string[]
194
+ }
195
+
196
+ /**
197
+ * The default geocode-first scoring model: name, organization and a spatial signal.
198
+ *
199
+ * The spatial signal is either two comparisons (address-key similarity and great-circle distance)
200
+ * or, with {@link DefaultModelOptions.collapseSpatial}, one collapsed {@link spatialComparison}.
201
+ * `addressFrequency` down-weights agreement on a crowded address either way.
202
+ */
203
+ export function buildDefaultModel(opts: DefaultModelOptions = {}): FellegiSunterModel<SourceRecord> {
204
+ const identity = [
205
+ similarityComparison<SourceRecord>({ name: "given", extract: (r) => r.name?.given, levels: NAME_LEVELS }),
206
+ similarityComparison<SourceRecord>({ name: "family", extract: (r) => r.name?.family, levels: NAME_LEVELS }),
207
+ similarityComparison<SourceRecord>({
208
+ name: "organization",
209
+ extract: (r) => r.organization?.canonical,
210
+ levels: NAME_LEVELS,
211
+ }),
212
+ ]
213
+
214
+ if (opts.usePhone) {
215
+ identity.push(
216
+ similarityComparison<SourceRecord>({
217
+ name: "phone",
218
+ extract: (r) => normalizePhone(r.phone),
219
+ similarity: (a, b) => (a === b ? 1 : 0),
220
+ levels: PHONE_LEVELS,
221
+ })
222
+ )
223
+ }
224
+
225
+ for (const key of opts.discriminators ?? []) {
226
+ identity.push(
227
+ similarityComparison<SourceRecord>({
228
+ name: `attr:${key}`,
229
+ extract: (r) => r.attributes?.[key],
230
+ levels: NAME_LEVELS,
231
+ })
232
+ )
233
+ }
234
+
235
+ for (const key of opts.exactDiscriminators ?? []) {
236
+ identity.push(
237
+ similarityComparison<SourceRecord>({
238
+ name: `attr:${key}`,
239
+ extract: (r) => r.attributes?.[key],
240
+ similarity: codeSetOverlap,
241
+ levels: CODE_SET_LEVELS,
242
+ })
243
+ )
244
+ }
245
+
246
+ if (opts.collapseSpatial) {
247
+ let spatial = spatialComparison<SourceRecord>({
248
+ name: "spatial",
249
+ key: (r) => r.address?.canonicalKey,
250
+ coordinate: (r) => r.address?.geocode?.coordinate,
251
+ levels: DEFAULT_SPATIAL_LEVELS,
252
+ })
253
+
254
+ if (opts.addressFrequency) {
255
+ spatial = withTermFrequency(spatial, {
256
+ table: opts.addressFrequency,
257
+ value: (a) => a.address?.raw ?? null,
258
+ levels: [0],
259
+ })
260
+ }
261
+
262
+ return { lambda: 0.0001, comparisons: [...identity, spatial] }
263
+ }
264
+
265
+ let address = similarityComparison<SourceRecord>({
266
+ name: "address",
267
+ extract: (r) => r.address?.canonicalKey,
268
+ levels: NAME_LEVELS,
269
+ })
270
+
271
+ if (opts.addressFrequency) {
272
+ address = withTermFrequency(address, { table: opts.addressFrequency, value: (a) => a.address?.raw ?? null })
273
+ }
274
+
275
+ return {
276
+ lambda: 0.0001,
277
+ comparisons: [
278
+ ...identity,
279
+ address,
280
+ distanceComparison({
281
+ name: "distance",
282
+ extract: (r) => r.address?.geocode?.coordinate,
283
+ levels: DEFAULT_DISTANCE_LEVELS,
284
+ }),
285
+ ],
286
+ }
287
+ }
288
+
289
+ /**
290
+ * The default blocking keys include location and canonical address.
291
+ * They also include phone and email.
292
+ */
293
+ export function defaultBlockingKeys(): BlockingKey<SourceRecord>[] {
294
+ return [
295
+ geoCellKey((r) => r.address?.geocode?.coordinate ?? null),
296
+ exactKey((r) => r.address?.canonicalKey ?? null),
297
+ exactKey((r) => r.phone ?? null),
298
+ exactKey((r) => r.email ?? null),
299
+ ]
300
+ }
301
+
302
+ /**
303
+ * Options for {@link resolveEntities}.
304
+ */
305
+ export interface ResolveConfig {
306
+ /**
307
+ * The model used to score candidate pairs.
308
+ *
309
+ * @defaultValue {@link buildDefaultModel}
310
+ */
311
+ model?: FellegiSunterModel<SourceRecord>
312
+ /**
313
+ * The blocking keys whose union forms the candidate set.
314
+ *
315
+ * @defaultValue {@link defaultBlockingKeys}
316
+ */
317
+ blockingKeys?: BlockingKey<SourceRecord>[]
318
+ /**
319
+ * Link two records into the same entity at or above this match weight (bits).
320
+ *
321
+ * @defaultValue `0`
322
+ */
323
+ threshold?: number
324
+ /**
325
+ * Skip and report blocks larger than this rather than scanning them.
326
+ */
327
+ maxBlockSize?: number
328
+ /**
329
+ * Fit the model's `m`/`u` to the candidate pairs with EM before scoring (label-free).
330
+ *
331
+ * @defaultValue `false`
332
+ */
333
+ trainEM?: boolean
334
+ /**
335
+ * Address-frequency table over {@link addressFrequencyKey}, which down-weights address
336
+ * agreement by how shared the address is. **Default-on:** when omitted, `resolveEntities`
337
+ * computes the table over the input records' addresses, the right scope for a single dataset.
338
+ *
339
+ * Pass your own {@link TermFrequencyTable} (for example a corpus-wide one) to override,
340
+ * or `false` to disable (the legacy bare baseline).
341
+ * Ignored if `model` is supplied.
342
+ */
343
+ addressFrequency?: TermFrequencyTable | false
344
+ /**
345
+ * Collapse the redundant address-key and distance pair into one {@link spatialComparison}.
346
+ * **Default-on (true)** is the cleaner, less-over-merging spatial model.
347
+ *
348
+ * Set `false` for the legacy two-signal baseline.
349
+ * Ignored if `model` is supplied.
350
+ */
351
+ collapseSpatial?: boolean
352
+ /**
353
+ * Require positive name or organization corroboration ({@link CORROBORATING_FIELDS}) for
354
+ * a link, so a shared address cannot merge two records without that corroboration.
355
+ *
356
+ * Suppresses the spatial-only links that fuse distinct co-located providers.
357
+ *
358
+ * @defaultValue `false`
359
+ */
360
+ requireCorroboration?: boolean
361
+ /**
362
+ * Add a normalized-phone comparison to the default model.
363
+ *
364
+ * Phone agreement provides strong secondary evidence when entity names have drifted.
365
+ *
366
+ * Ignored if `model` is supplied.
367
+ */
368
+ usePhone?: boolean
369
+ /**
370
+ * The clustering step uses this linkage method.
371
+ *
372
+ * `"single"` (default) is connected components, while `"average"` is an average-linkage
373
+ * refinement that splits a component whose sub-clusters are joined only by a weak bridge.
374
+ */
375
+ linkage?: "single" | "average"
376
+ /**
377
+ * Extra secondary-identifier keys from {@link SourceRecord.attributes} to add as
378
+ * comparisons and corroborators, for example `["authorizedOfficial"]`.
379
+ *
380
+ * Ignored if `model` is supplied.
381
+ */
382
+ discriminators?: string[]
383
+ /**
384
+ * Closed-vocabulary code-set discriminator keys ({@link DefaultModelOptions.exactDiscriminators}),
385
+ * which use set-overlap agreement.
386
+ * An example is `["taxonomy"]`.
387
+ *
388
+ * Also corroborators.
389
+ * Ignored if `model` is supplied.
390
+ */
391
+ exactDiscriminators?: string[]
392
+ /**
393
+ * Override the Fellegi-Sunter link weight with a learned score.
394
+ *
395
+ * When set, a candidate pair's match weight is this function's return value instead of
396
+ * {@link scorePair}'s, in the same threshold-comparable units as the FS weight.
397
+ * Default is undefined (pure FS).
398
+ *
399
+ * The blocking and clustering are unchanged, so a trained scorer can be A/B tested
400
+ * against the FS baseline on the identical pipeline.
401
+ * The function is responsible for its own feature computation, such as the
402
+ * agreement pattern plus any corpus statistics it captured.
403
+ *
404
+ * The corroboration check is independent of the learned score and is still evaluated on
405
+ * the Fellegi-Sunter `contributions`, so a learned-high pair with no positive FS name,
406
+ * organization or phone agreement is still held out.
407
+ *
408
+ * A learned scorer is normally trained to subsume corroboration, so use one or the other.
409
+ * The independent FS check can veto the learned score when both checks run.
410
+ */
411
+ scorer?: (a: SourceRecord, b: SourceRecord) => number
412
+ /**
413
+ * The learned gradient-boosted-tree scorer, default-on.
414
+ *
415
+ * Omitted or `true` uses the bundled {@link DEDUP_GBT_MODEL}, which was trained on
416
+ * the NPPES NPI-truth set and beats the Fellegi-Sunter baseline by roughly +5pp dedup
417
+ * F1 held-out within a state and +22pp on states it never trained on.
418
+ *
419
+ * `false` opts out to the pure FS baseline.
420
+ * Pass your own {@link GBT} for a custom model.
421
+ *
422
+ * The scorer is built over the same collapsed-spatial and address-frequency feature
423
+ * model as training, independent of this call's comparison config.
424
+ * An explicit {@link scorer} takes precedence.
425
+ *
426
+ * When the bundled model is active and no {@link threshold} is set,
427
+ * its calibrated link threshold ({@link DEDUP_GBT_META}.recommendedThreshold) is used,
428
+ * because the GBT logit is not in FS-weight units and 0 would over-merge.
429
+ *
430
+ * The model is NPPES/US-trained.
431
+ * For a very different domain, A/B it or pass `false`.
432
+ */
433
+ learnedScorer?: boolean | GBT
434
+ }
435
+
436
+ /**
437
+ * The result of a resolve pass.
438
+ */
439
+ export interface ResolveResult {
440
+ entities: ResolvedEntity[]
441
+ /**
442
+ * Number of candidate pairs blocking produced.
443
+ */
444
+ candidatePairs: number
445
+ /**
446
+ * Blocks too large to scan, surfaced so coverage limits are visible.
447
+ */
448
+ droppedBlocks: Array<{ key: string; size: number }>
449
+ }
450
+
451
+ /**
452
+ * Resolve source records into canonical entities: block, score, cluster.
453
+ *
454
+ * Every record belongs to exactly one entity.
455
+ * A record without a confident link forms a singleton entity.
456
+ */
457
+ export function resolveEntities(records: readonly SourceRecord[], config: ResolveConfig = {}): ResolveResult {
458
+ const addressFrequency =
459
+ config.addressFrequency === false
460
+ ? undefined
461
+ : (config.addressFrequency ??
462
+ buildTermFrequencyTable(
463
+ records.map((r) => r.address?.raw),
464
+ { normalize: addressFrequencyKey }
465
+ ))
466
+
467
+ const collapseSpatial = config.collapseSpatial ?? true
468
+
469
+ const model =
470
+ config.model ??
471
+ buildDefaultModel({
472
+ addressFrequency,
473
+ collapseSpatial,
474
+ usePhone: config.usePhone,
475
+ discriminators: config.discriminators,
476
+ exactDiscriminators: config.exactDiscriminators,
477
+ })
478
+
479
+ const blockingKeys = config.blockingKeys ?? defaultBlockingKeys()
480
+
481
+ let scorer = config.scorer
482
+ let usingBundledModel = false
483
+
484
+ if (!scorer && config.learnedScorer !== false) {
485
+ const gbt = config.learnedScorer == null || config.learnedScorer === true ? DEDUP_GBT_MODEL : config.learnedScorer
486
+
487
+ usingBundledModel = gbt === DEDUP_GBT_MODEL
488
+
489
+ scorer = createGBTScorer({
490
+ model: gbt,
491
+ comparisons: buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons,
492
+ addressFrequency: addressFrequency ?? buildTermFrequencyTable([], { normalize: addressFrequencyKey }),
493
+ })
494
+ }
495
+
496
+ // An explicit threshold wins.
497
+ // Otherwise the bundled model uses its calibrated threshold, because its logit
498
+ // is not in FS-weight units and 0 would over-merge.
499
+ // The FS baseline or a custom model uses 0.
500
+ const threshold = config.threshold ?? (usingBundledModel ? DEDUP_GBT_META.recommendedThreshold : 0)
501
+
502
+ const { pairs, droppedBlocks } = block(records, blockingKeys, { maxBlockSize: config.maxBlockSize })
503
+
504
+ let scoringModel = model
505
+
506
+ if (config.trainEM && pairs.length) {
507
+ const patterns = pairs.map(([a, b]) => agreementPattern(model.comparisons, a, b))
508
+ scoringModel = estimateParameters(model, patterns).model
509
+ }
510
+
511
+ const links: ScoredLink<SourceRecord>[] = pairs.map(([a, b]) => {
512
+ const score = scorePair(scoringModel, a, b)
513
+ let weight = scorer ? scorer(a, b) : score.weight
514
+
515
+ // A link requires positive name or organization corroboration, since a shared
516
+ // address provides no identity evidence by itself.
517
+ if (config.requireCorroboration) {
518
+ const corroborated = score.contributions.some(
519
+ (c) => (CORROBORATING_FIELDS.has(c.name) || c.name.startsWith("attr:")) && c.weight > 0
520
+ )
521
+
522
+ if (!corroborated) {
523
+ weight = Number.NEGATIVE_INFINITY
524
+ }
525
+ }
526
+
527
+ return { a, b, weight }
528
+ })
529
+
530
+ const clusters = cluster(records, links, { threshold, linkage: config.linkage })
531
+
532
+ // Cohesion is the weakest within-cluster link weight.
533
+ // Compute it in one pass over links with a record-to-cluster index, because filtering
534
+ // every link for every cluster is O(clusters x links) and dominates the resolve at scale.
535
+ const clusterOf = new Map<SourceRecord, number>()
536
+
537
+ clusters.forEach((group, i) => {
538
+ for (const record of group) {
539
+ clusterOf.set(record, i)
540
+ }
541
+ })
542
+
543
+ const minIntraWeight = new Array<number>(clusters.length).fill(Infinity)
544
+
545
+ for (const link of links) {
546
+ if (link.weight < threshold) continue
547
+ const ci = clusterOf.get(link.a)
548
+
549
+ if (typeof ci !== "number" || ci !== clusterOf.get(link.b)) continue
550
+
551
+ if (link.weight < minIntraWeight[ci]!) {
552
+ minIntraWeight[ci] = link.weight
553
+ }
554
+ }
555
+
556
+ const entities: ResolvedEntity[] = clusters.map((group, i) => {
557
+ const rep = representative(group) ?? group[0]!
558
+
559
+ return {
560
+ id: `entity-${i}`,
561
+ records: group,
562
+ representative: rep,
563
+ coordinate: rep.address?.geocode?.coordinate ?? null,
564
+ cohesion: group.length > 1 && minIntraWeight[i]! !== Infinity ? minIntraWeight[i]! : null,
565
+ }
566
+ })
567
+
568
+ return { entities, candidatePairs: pairs.length, droppedBlocks }
569
+ }
package/lib/types.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The application's data shapes — the messy record that goes in and the canonical entity that
7
+ * comes out. Plain interfaces over the `@mailwoman/record` types.
8
+ */
9
+
10
+ import type { ResolutionTier } from "@mailwoman/annotations/geo"
11
+ import type { OrganizationName, PersonName, PostalAddress } from "@mailwoman/record"
12
+
13
+ /**
14
+ * A single source record: one row of a messy contact/organization dataset, after normalization.
15
+ */
16
+ export interface SourceRecord {
17
+ /**
18
+ * Stable identifier within the input (row id, primary key…).
19
+ */
20
+ id: string
21
+ /**
22
+ * Provenance: which file / dataset this came from.
23
+ */
24
+ source: string | null
25
+ /**
26
+ * Parsed person name, when the record is a contact.
27
+ */
28
+ name: PersonName | null
29
+ /**
30
+ * Canonicalized organization name, when the record is an org.
31
+ */
32
+ organization: OrganizationName | null
33
+ /**
34
+ * The address, normalized + (ideally) geocoded.
35
+ */
36
+ address: PostalAddress | null
37
+ phone: string | null
38
+ email: string | null
39
+ /**
40
+ * Additional secondary-identifier fields, normalized.
41
+ *
42
+ * Anything that helps tell two records apart or confirm they're the same beyond
43
+ * name/org/address/phone (an authorized-official name, a provider taxonomy, a license number…).
44
+ *
45
+ * Used as extra comparisons + corroborators when the model is built with matching `discriminators`.
46
+ * Keyed by a stable field name the model references.
47
+ */
48
+ attributes: Record<string, string> | null
49
+ /**
50
+ * The original row, verbatim, for audit.
51
+ */
52
+ raw: Record<string, string> | null
53
+ }
54
+
55
+ /**
56
+ * A resolved canonical entity: a cluster of source records judged to be the same real-world thing.
57
+ */
58
+ export interface ResolvedEntity {
59
+ /**
60
+ * Identifier assigned to the entity.
61
+ */
62
+ id: string
63
+ /**
64
+ * The source records that resolved to this entity.
65
+ */
66
+ records: SourceRecord[]
67
+ /**
68
+ * The most complete record, used as the entity's canonical face.
69
+ */
70
+ representative: SourceRecord
71
+ /**
72
+ * The entity's location, from the representative's geocode.
73
+ */
74
+ coordinate: { latitude: number; longitude: number } | null
75
+ /**
76
+ * Weakest within-cluster link weight in bits (how tightly it holds together); `null` for a singleton.
77
+ */
78
+ cohesion: number | null
79
+ }
80
+
81
+ /**
82
+ * The three reconciliation buckets an entity can fall into.
83
+ */
84
+ export type ReconciliationBucket = "enrolled" | "eligible-not-enrolled" | "funded-not-eligible"
85
+
86
+ export interface EntityGeoData {
87
+ entityID: string
88
+ sourceIDs: string[]
89
+ recordCount: number
90
+ cohesion: number | null
91
+ sources: string[]
92
+ name: string | null
93
+ organization: string | null
94
+ address: string | null
95
+ geocodeTier: ResolutionTier | null
96
+ bucket: ReconciliationBucket | null
97
+ }
98
+
99
+ /**
100
+ * Feature properties the map renderer consumes — {@link EntityGeoData} with every
101
+ * field optional, plus an unconstrained `bucket`.
102
+ *
103
+ * The renderer assigns a color per distinct bucket value in first-seen order and builds
104
+ * its legend from that set, so a bucket is any categorical label rather than only a
105
+ * {@link ReconciliationBucket}; and a collection assembled from something other than resolved
106
+ * entities (raw address points, links read back from a file) have no entity id or display name.
107
+ */
108
+ export type MapFeatureData = Partial<Omit<EntityGeoData, "bucket">> & { bucket?: string | null }
109
+
110
+ // #endregion
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The address-id consumer for the matcher. Derives a stable {@link PostalAddressID} from a
7
+ * resolved {@link SourceRecord} and exposes it as a blocking key, the deterministic
8
+ * exact-canonical-address complement to the fuzzy Fellegi-Sunter / GBT scoring. Two uses:
9
+ *
10
+ * - **As a pre-dedup / join key:** `group BY postalAddressID(record)` collapses records that resolve
11
+ * to the same place and share a canonical address with no scoring at all. That is the cheap,
12
+ * certain part of dedup before the matcher does the fuzzy rest.
13
+ * - **As a blocking key:** {@link addressIDBlockingKey} adds the address-id to the blocking union, so
14
+ * records sharing one are guaranteed to be compared.
15
+ */
16
+ import { type PostalAddressID } from "@mailwoman/address-id";
17
+ import { type BlockingKey } from "@mailwoman/match";
18
+ import type { SourceRecord } from "#types";
19
+ /**
20
+ * The stable address primary key for a record, or null when it is not geocoded
21
+ * (no coordinate means no locality cell) or includes no raw address to hash.
22
+ *
23
+ * The state prefix is plucked from the address when present.
24
+ */
25
+ export declare function postalAddressID(record: SourceRecord): PostalAddressID | null;
26
+ /**
27
+ * A blocking key on the {@link postalAddressID}.
28
+ *
29
+ * Records that resolve to the same place with the same canonical address block together.
30
+ *
31
+ * Add it to {@link defaultBlockingKeys}'s union when an exact address join should never be missed.
32
+ */
33
+ export declare function addressIDBlockingKey(): BlockingKey<SourceRecord>;
34
+ //# sourceMappingURL=address-key.d.ts.map