-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
3208 lines (2869 loc) · 131 KB
/
Copy pathsearch.js
File metadata and controls
3208 lines (2869 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// search.js
// ---------------------------------------------------------------------------
// Search — tree-driven, on-demand retrieval of primary-source mentions that may
// refer to a person in the researcher's tree. Implements Search.md.
//
// search.scan(curTree, personId) -> coverage across all sources
// search.find(curTree, personId, { source }) -> ranked candidates in one source
// search.findBatch(curTree, personIds, {source})-> jointly resolve several
// tree persons against one
// source (cross-support +
// collision detection)
//
// Nothing here writes isSameAs to the tree/assertion store - that's still the
// caller's job. accept()/reject() emit assertion rows for the caller to
// persist, but they DO feed this Search instance's own in-session state right
// away: addAssertion() re-wires the surname bridge, and _recordOutcome() banks
// a labeled feature vector so this.match's calibration (Match.fitCalibration/
// probability) sharpens as researchers confirm or reject candidates.
//
// DEPENDS ON match.js (class Match). Scoring is delegated to Match.MatchPerson;
// this file supplies the person profile, the kin set, the constraints, and the
// retrieval. Two boosts that Match does not model (enslaver holding fit and
// nameless age-sex cohort fit) are applied here as residual-gap boosts on the
// returned score, so match.js needs no modification.
//
// WHY STAGE 1 IS NOT OPTIONAL
// curTree stores attributes as "value:mention_id" ("Crawford:AUG-CN-1870-4795").
// Match._birthYear/_gender/_race/_birthPlace/_normOccupation already split on
// ':' and are safe. The NAME fields are not:
// Match.normUpper("Crawford:AUG-CN-1870-4795") -> "CRAWFORDAUGCN"
// range("1835:AUG-CN-1870-4795") -> [1835, 4795]
// Every object handed to Match must be dereferenced first.
//
// No external dependencies beyond match.js.
// ---------------------------------------------------------------------------
(function (global) {
'use strict';
// -----------------------------------------------------------------------
// SOURCE TYPES
// Reliability drives Lever B sigma (Search.md Stage 1). Add rows as new
// source types are ingested; unknown types fall back to MEDIUM.
// -----------------------------------------------------------------------
var SOURCE_TYPES = {
CN: { label: 'Census', reliability: 'SOFT', schedule: false, roster: true },
SS: { label: 'Slave Schedule', reliability: 'SOFTEST', schedule: true, roster: true },
VR: { label: 'Vital Records', reliability: 'HARD', schedule: false, roster: false },
DR: { label: 'Death Records', reliability: 'HARD', schedule: false, roster: false },
DE: { label: 'Death Records', reliability: 'HARD', schedule: false, roster: false },
FG: { label: 'Find A Grave', reliability: 'HARD', schedule: false, roster: false },
FBR: { label: 'Free Black Register', reliability: 'MEDIUM', schedule: false, roster: false },
FL: { label: "Freedmen's List", reliability: 'MEDIUM', schedule: false, roster: false },
CH: { label: 'Church', reliability: 'MEDIUM', schedule: false, roster: false },
CF: { label: 'Cohabitation Family', reliability: 'MEDIUM', schedule: false, roster: true },
CC: { label: 'Cohabitation Child', reliability: 'MEDIUM', schedule: false, roster: true },
MN: { label: 'Mentions / Narrative', reliability: 'SOFTEST', schedule: false, roster: false }
};
// Birth profiles by the softest reliability present in the pair.
var BIRTH_PROFILES = {
HARD: { sigma: 1.5, knockout: 8 },
MEDIUM: { sigma: 2.5, knockout: 10 },
SOFT: { sigma: 3.0, knockout: 12 },
SOFTEST: { sigma: 3.5, knockout: 12 }
};
var RELIABILITY_RANK = { HARD: 0, MEDIUM: 1, SOFT: 2, SOFTEST: 3 };
// Sources that constrain rather than corroborate. Fetched automatically
// before every FIND (Search.md Stage 4) instead of being searched.
var CONSTRAINT_TYPES = ['VR', 'DR', 'FG'];
// Source types whose isSpouseOf start_year is an actual marriage DATE, and
// so may exclude a spouse from earlier years (see _marriageYear). A census
// or cohabitation-register date is an upper bound on the marriage, not the
// marriage itself, so neither belongs here. Vital records do.
var MARRIAGE_DATE_TYPES = ['VR'];
// Kin imputation weights (Search.md Stage 2).
var KIN_WEIGHTS = {
isSpouseOf: { hops: 1, weight: 1.0 },
isParentOf: { hops: 1, weight: 1.0 },
isChildOf: { hops: 1, weight: 1.0 },
wasEnslavedBy: { hops: 1, weight: 1.0 },
isEnslaverOf: { hops: 1, weight: 1.0 },
isSiblingOf: { hops: 2, weight: 0.8 },
isGrandParentOf: { hops: 2, weight: 0.5 },
isGrandChildOf: { hops: 2, weight: 0.5 }
};
// curTree stores the predicate from the OTHER person's point of view.
// "isChildOf:P002" on Jinnie means Jinnie isChildOf P002, so from P002 the
// relation is isParentOf. Explicit map; never string-manipulate.
var INVERSE = {
isChildOf: 'isParentOf',
isParentOf: 'isChildOf',
isSpouseOf: 'isSpouseOf',
isSiblingOf: 'isSiblingOf',
isEnslaverOf: 'wasEnslavedBy',
wasEnslavedBy: 'isEnslaverOf',
isGrandParentOf: 'isGrandChildOf',
isGrandChildOf: 'isGrandParentOf',
isHousemateOf: 'isHousemateOf',
isNeighborOf: 'isNeighborOf'
};
var DEFAULTS = {
maxCandidates: 800,
floor: 0.35,
ceiling: 0.80,
limit: 50,
maxHops: 2,
birthBucket: 5,
birthTolerance: 10, // buckets scanned either side of the window
verityMax: 4,
ungroundedWeight: 0.3, // kin with no mention in the target source-year
householdBoost: 0.6,
enslaverBoost: 0.45, // residual-gap boost when holding profile fits
proximityBoost: 0.35, // residual-gap boost for enumeration nearness
proximityWindow: 40, // enumeration lines within which nearness counts
cohortBoost: 0.40, // residual-gap boost for nameless age-sex fit
minMotherAge: 13,
maxMotherAge: 50,
minFatherAge: 14,
maxFatherAge: 70,
provisional: true, // run the constraint-source pre-pass
provisionalFloor: 0.80, // score a constraint hit must clear
provisionalMargin: 0.10, // and how far it must beat the runner-up
provisionalSpread: 2, // disagreement (years) that voids the ceiling
// Calibration feedback loop (see accept()/reject()/_maybeRefitCalibration).
calibMinSamples: 20, // total labeled pairs required before first fit
calibMinPerClass: 5, // accepts AND rejects required before first fit
calibRefitEvery: 5 // refit after this many new labels accrue
};
var MENTION_ID_RE = /^[A-Za-z]{2,5}[-_][A-Za-z0-9]{2,5}[-_]\d{3,4}[-_][\w.]+$/;
// =======================================================================
// SMALL HELPERS
// =======================================================================
function isPresent(v) {
if (v === null || v === undefined) return false;
var s = String(v).trim();
return s !== '' && s.toLowerCase() !== 'null' && s.toLowerCase() !== 'undefined';
}
function upper(s) {
return isPresent(s) ? String(s).trim().toUpperCase().replace(/[^A-Z]/g, '') : '';
}
function clamp(x, lo, hi) { return Math.max(lo, Math.min(hi, x)); }
function toInt(v) {
var n = parseInt(String(v == null ? '' : v).trim(), 10);
return Number.isFinite(n) ? n : null;
}
// Residual-gap boost. Raises a score toward 1 without ever dragging it,
// same shape as Match's household boost.
function boost(score, beta, strength) {
if (!(strength > 0)) return score;
return score + beta * strength * (1 - score);
}
// -----------------------------------------------------------------------
// STAGE 1 helper: split "value:mention_id" into value + provenance.
// Splits at the FIRST ':' only when the tail looks like a mention id, so a
// value that legitimately contains a colon is left intact.
// -----------------------------------------------------------------------
function deref(raw) {
if (!isPresent(raw)) return { value: '', source: null };
var s = String(raw).trim();
var i = s.indexOf(':');
if (i < 0) return { value: s, source: null };
var head = s.slice(0, i).trim();
var tail = s.slice(i + 1).trim();
if (MENTION_ID_RE.test(tail)) return { value: head, source: tail };
return { value: s, source: null };
}
// Parse a mention_id or source string into its parts.
// "AUG-CN-1870-4795" -> { county:'AUG', type:'CN', year:1870, seq:'4795' }
function parseId(id) {
if (!isPresent(id)) return null;
var parts = String(id).trim().split(/[-_]/);
if (parts.length < 3) return null;
var year = toInt(parts[2]);
if (year == null) return null;
return {
county: parts[0].toUpperCase(),
type: parts[1].toUpperCase(),
year: year,
seq: parts.slice(3).join('-'),
source: parts[0].toUpperCase() + '-' + parts[1].toUpperCase() + '-' + year
};
}
function sourceInfo(type) {
return SOURCE_TYPES[type] || { label: type || 'Unknown', reliability: 'MEDIUM', schedule: false, roster: false };
}
// The FB blocking key must use the same given-name token match.js compares
// on (_classifyGiven takes the first token). normUpper strips whitespace, so
// keying the whole value turns "MARTHA J" into MARTHAJ and it never collides
// with MARTHA - the record is unreachable through FB no matter how it is
// scored. 1,378 AUG mentions carry a multi-token norm_first_name and 1,343
// of those have a first token that already exists as a simple form, so this
// is the retrieval half of the same defect. Index and query both use this.
function givenKey(v) {
if (!isPresent(v)) return '';
var parts = String(v).trim().split(/[\s.]+/).filter(Boolean);
return parts.length ? upper(parts[0]) : '';
}
function bucketOf(year, size) {
if (year == null) return null;
return Math.floor(year / size) * size;
}
var GroupMatcherClass = (typeof globalThis !== 'undefined' && globalThis.GroupMatcher)
? globalThis.GroupMatcher
: (typeof require !== 'undefined' ? (require('./groupMatcher').GroupMatcher || require('./groupMatcher')) : null);
var DEFAULT_CRITERIA_CONFIG = {
jwFuzzyPassThreshold: 0.85,
birthYearWindows: {
Exact: 0,
"±1": 1,
"±2": 2,
"±3": 3,
"±5": 5,
"±10": 10
},
softmaxTemperature: 1.0,
debug: false
};
// =======================================================================
// SEARCH
// =======================================================================
function Search(config) {
config = config || {};
var MatchCls = config.MatchClass ||
(typeof global !== 'undefined' && global.Match) ||
(typeof Match !== 'undefined' ? Match : null);
if (!MatchCls && !config.match) {
throw new Error('search.js requires match.js (class Match) to be loaded first');
}
if (typeof app !== 'undefined') {
app.search = this;
}
this.opts = Object.assign({}, DEFAULTS, config.opts || {});
this.mentions = config.mentions || [];
this.assertions = config.assertions || [];
this.bridges = config.bridges || null; // optional precomputed household bridges
this.match = config.match || new MatchCls(config.matchConfig || {});
this.MatchClass = MatchCls || this.match.constructor;
// Calibration feedback loop (Stage 6a below). Rows are either produced
// by accept()/reject() during this session or supplied up front via
// config.calibrationSeed (e.g. a prior human-reviewed sample), in the
// same {features|res, label} shape Match.fitCalibration accepts.
this._calibLog = (config.calibrationSeed || []).slice();
this._calibLogAtLastFit = 0;
this._index();
this._wireRarity();
this._wireSurnameBridge();
this._maybeRefitCalibration();
}
// -----------------------------------------------------------------------
// INDEXING
// -----------------------------------------------------------------------
Search.prototype._index = function () {
var i, m, id, key, parsed;
this.byId = new Map(); // mention_id -> mention
this.bySource = new Map(); // "AUG-CN-1870" -> [mentions]
this.byHh = new Map(); // "AUG-CN-1870|FC1870-829" -> [mentions]
this.sources = new Map(); // "AUG-CN-1870" -> { source, county, type, year, count }
this.block = { L: new Map(), N: new Map(), F: new Map(), M: new Map(), FB: new Map() };
for (i = 0; i < this.mentions.length; i++) {
m = this.mentions[i];
if (!m) continue;
id = m.mention_id;
if (!isPresent(id)) continue;
this.byId.set(id, m);
parsed = parseId(id);
var src = isPresent(m.source) ? String(m.source).trim() : (parsed ? parsed.source : '');
if (!src) continue;
m._type = parsed ? parsed.type : '';
m._year = toInt(m.source_year) != null ? toInt(m.source_year) : (parsed ? parsed.year : null);
m._hh = this.hhKey(m);
push(this.bySource, src, m);
if (m._hh) push(this.byHh, src + '|' + m._hh, m);
if (!this.sources.has(src)) {
this.sources.set(src, {
source: src,
county: parsed ? parsed.county : '',
type: m._type,
year: m._year,
label: sourceInfo(m._type).label,
count: 0
});
}
this.sources.get(src).count++;
this._addBlockKeys(m);
}
function push(map, k, v) {
var a = map.get(k);
if (!a) { a = []; map.set(k, a); }
a.push(v);
}
};
// hhKey per Census2Census: 1850/1860 populate household_id, 1870/1880
// populate only family_id. Without the fallback Lever C scores zero for
// every 1870/1880 pass.
Search.prototype.hhKey = function (m) {
var h = isPresent(m.household_id) ? String(m.household_id).trim() : '';
if (h) return h;
return isPresent(m.family_id) ? String(m.family_id).trim() : '';
};
Search.prototype._addBlockKeys = function (m) {
var B = this.block, self = this;
var last = upper(m.last_name);
if (last) add(B.L, last, m);
var ny = upper(m.nysiis_last_name);
if (ny) add(B.N, ny, m);
var full = isPresent(m.full_name)
? String(m.full_name).toUpperCase().replace(/[^A-Z0-9]+/g, ' ').replace(/\s+/g, ' ').trim()
: '';
if (full) add(B.F, full, m);
if (isPresent(m.metaphone_last_name)) {
String(m.metaphone_last_name).toUpperCase().split(':').forEach(function (code) {
var c = code.replace(/[^A-Z]/g, '');
if (c) add(B.M, c, m);
});
}
var first = givenKey(isPresent(m.norm_first_name) ? m.norm_first_name : m.first_name);
var by = toInt(m.birth_year);
if (first && by != null) {
add(B.FB, first + '|' + bucketOf(by, self.opts.birthBucket), m);
}
function add(map, k, v) {
var a = map.get(k);
if (!a) { a = []; map.set(k, a); }
a.push(v);
}
};
// Rarity is judged against the pool (score.md), so frequencies come from the
// full corpus. Pass config.frequencyScope = 'source' to scope per source.
Search.prototype._wireRarity = function () {
this.match.usePool(this.mentions);
};
// Surname bridge: two surnames count as bridged when an assertion connects
// them (hasNameVariant, or a marriage/spouse link across the two names).
Search.prototype._computeSurnameVariants = function () {
var self = this;
var variants = new Map(); // UPPER surname -> Set of UPPER surnames
function link(a, b) {
if (!a || !b || a === b) return;
if (!variants.has(a)) variants.set(a, new Set());
if (!variants.has(b)) variants.set(b, new Set());
variants.get(a).add(b);
variants.get(b).add(a);
}
(this.assertions || []).forEach(function (a) {
if (!a) return;
// hasNameVariant ONLY. Building the class from isSpouseOf as well
// links Crawford<->Scott because some Crawford married some Scott,
// which collapses most of the county into one surname class and
// floods retrieval. Spouse-surname bridging is a per-pair question,
// handled in the scorer, not a global equivalence.
var p = String(a.predicate || '').trim();
if (p !== 'hasNameVariant') return;
var s = self.byId.get(a.subject_id), o = self.byId.get(a.object_id);
if (!s || !o) return;
link(upper(s.last_name), upper(o.last_name));
});
return variants;
};
Search.prototype._wireSurnameBridge = function () {
var self = this;
this._surnameVariants = this._computeSurnameVariants();
// Reads self._surnameVariants at call time (not a captured local), so
// refreshSurnameBridge() below can swap the Map in place and every
// retrieval from then on sees the update without re-wiring the closure.
this.match.setSurnameBridge(function (x, y) {
var lx = upper(x && x.last_name), ly = upper(y && y.last_name);
if (!lx || !ly) return false;
var set = self._surnameVariants.get(lx);
return !!(set && set.has(ly));
});
};
// Recompute the surname-variant map from the current this.assertions.
// personEditor.js keeps one Search instance alive for a whole session
// (window.app.search), so a hasNameVariant assertion added mid-session -
// via addAssertion() below, including the ones accept()/reject() record -
// would otherwise never reach retrieval until the page reloaded.
Search.prototype.refreshSurnameBridge = function () {
this._surnameVariants = this._computeSurnameVariants();
};
// =======================================================================
// STAGE 1 — DEREFERENCE, VALIDATE, BUILD PROFILE
// =======================================================================
Search.prototype.buildProfile = function (curTree, personId) {
var self = this;
var person = (curTree.persons || []).filter(function (p) { return p.person_id === personId; })[0];
if (!person) throw new Error('buildProfile: no person ' + personId + ' in tree');
var issues = [];
var fields = ['first_name', 'middle_name', 'last_name', 'suffix', 'birth_year',
'death_year', 'gender', 'race', 'occupation', 'birth_place'];
// 1a. Dereference the stored values and validate each against its source.
var attested = {}; // field -> [{ value, source, type, reliability, verified }]
fields.forEach(function (f) { attested[f] = []; });
fields.forEach(function (f) {
var d = deref(person[f]);
if (!isPresent(d.value)) return;
var rec = { value: d.value, source: d.source, type: null, reliability: 'MEDIUM', verified: null };
if (d.source) {
var m = self.byId.get(d.source);
if (!m) {
issues.push({ field: f, source: d.source, problem: 'MENTION_NOT_FOUND' });
return; // do not search on a value no source backs
}
rec.type = m._type;
rec.reliability = sourceInfo(m._type).reliability;
rec.verified = self._fieldAgrees(f, d.value, m);
if (rec.verified === false) {
issues.push({
field: f, source: d.source, problem: 'VALUE_NOT_IN_SOURCE',
stored: d.value, actual: self._fieldOf(f, m)
});
return;
}
}
attested[f].push(rec);
});
// 1b. Rebuild every field from ALL linked mentions, not the one stored
// value. Attributes are multi-valued across sources and curTree keeps one.
var linked = (person.mentions || []).filter(function (id) { return self.byId.has(id); });
linked.forEach(function (id) {
var m = self.byId.get(id);
fields.forEach(function (f) {
var v = self._fieldOf(f, m);
if (!isPresent(v)) return;
// Dedupe on source AND value, not source alone. When a tree
// field cites a mention ("Arch:AUG-CN-1880-24520") the 1a pass
// already registered that source, so a source-only check
// discards what the mention actually says ("Archy") and the
// second spelling never becomes an attestation. That is the
// input _nameVariants needs, and it is also what makes the
// CONFLICTING_ATTESTATIONS report below able to see the
// disagreement at all.
var already = attested[f].some(function (r) {
return r.source === id && upper(r.value) === upper(v);
});
if (already) return;
attested[f].push({
value: String(v).trim(), source: id, type: m._type,
reliability: sourceInfo(m._type).reliability, verified: true
});
});
});
// 1c. Birth window across all attestations, plus death ceiling.
var birthYears = attested.birth_year
.map(function (r) { return toInt(r.value); })
.filter(function (y) { return y != null; });
var birthWindow = birthYears.length
? [Math.min.apply(null, birthYears), Math.max.apply(null, birthYears)]
: null;
var deathYears = attested.death_year
.map(function (r) { return toInt(r.value); })
.filter(function (y) { return y != null; });
var deathCeiling = deathYears.length ? Math.min.apply(null, deathYears) : null;
// Conflicting attestations are reported, not silently resolved.
Object.keys(attested).forEach(function (f) {
var vals = {};
attested[f].forEach(function (r) { vals[String(r.value).trim().toUpperCase()] = true; });
var distinct = Object.keys(vals);
if (distinct.length > 1 && f !== 'birth_year' && f !== 'death_year') {
issues.push({
field: f, problem: 'CONFLICTING_ATTESTATIONS',
values: attested[f].map(function (r) { return r.value + '@' + (r.source || 'tree'); })
});
}
});
// Softest reliability present drives Lever B sigma.
var rel = 'HARD';
attested.birth_year.forEach(function (r) {
if (RELIABILITY_RANK[r.reliability] > RELIABILITY_RANK[rel]) rel = r.reliability;
});
if (!attested.birth_year.length) rel = 'SOFT';
return {
person_id: personId,
tree_person: person,
attested: attested,
mentions: linked,
birthWindow: birthWindow,
birthReliability: rel,
deathCeiling: deathCeiling,
verity: toInt(person.verity),
isEnslaver: person.isEnslaver === true,
issues: issues,
// A Match-ready object: plain values only, birth as a range string
// so Match's range() reads it as a window.
asMatchObject: this._matchObject(attested, birthWindow, deathCeiling)
};
};
Search.prototype._fieldOf = function (f, m) {
if (f === 'birth_place') return m.birth_place != null ? m.birth_place : m.norm_birth_place;
return m[f];
};
Search.prototype._fieldAgrees = function (f, value, m) {
var actual = this._fieldOf(f, m);
if (!isPresent(actual)) return null; // source silent, cannot verify
var a = String(actual).trim().toUpperCase();
var b = String(value).trim().toUpperCase();
if (a === b) return true;
if (f === 'birth_year' || f === 'death_year') return toInt(a) === toInt(b);
// Names: tolerate the source carrying a fuller form.
if (a.indexOf(b) === 0 || b.indexOf(a) === 0) return true;
return false;
};
// Pick the modal attested value rather than the first. When sources
// disagree (the tree says Cyrus, the cited mention says Thomas Farr) the
// most-attested value wins and the disagreement is reported, instead of one
// arbitrary source silently renaming the person.
Search.prototype._modal = function (list) {
if (!list || !list.length) return '';
var counts = new Map(), order = [];
list.forEach(function (r) {
var k = String(r.value).trim();
if (!counts.has(k)) { counts.set(k, { n: 0, rel: r.reliability }); order.push(k); }
counts.get(k).n++;
if (RELIABILITY_RANK[r.reliability] < RELIABILITY_RANK[counts.get(k).rel]) {
counts.get(k).rel = r.reliability;
}
});
order.sort(function (a, b) {
var ca = counts.get(a), cb = counts.get(b);
if (ca.n !== cb.n) return cb.n - ca.n;
return RELIABILITY_RANK[ca.rel] - RELIABILITY_RANK[cb.rel];
});
return order[0];
};
Search.prototype._matchObject = function (attested, birthWindow, deathCeiling) {
var self = this;
function best(list) { return self._modal(list); }
var first = best(attested.first_name);
var last = best(attested.last_name);
var mid = best(attested.middle_name);
var obj = {
first_name: first,
middle_name: mid,
last_name: last,
full_name: [first, mid, last].filter(Boolean).join(' '),
gender: best(attested.gender),
race: best(attested.race),
occupation: best(attested.occupation),
birth_place: best(attested.birth_place),
// Range string. Match.range() pulls all 3-4 digit runs and takes
// min/max, so "1835-1840" becomes the window [1835, 1840].
birth_year: birthWindow ? (birthWindow[0] === birthWindow[1]
? String(birthWindow[0])
: birthWindow[0] + '-' + birthWindow[1]) : '',
death_year: deathCeiling != null ? String(deathCeiling) : ''
};
// Phonetic keys for Match's surname cascade. Reuse a linked mention's
// precomputed codes, but only from a mention that agrees on the field
// being copied. The surname-gated block below must not also carry
// norm_first_name: _modal() may pick "Arch" as the given name while the
// mention it copies from says "Archy", and the two normalize
// differently (ARCHIBALD vs ARCHY), so the normalized given name ends
// up describing a spelling the object does not have.
var lastRec = attested.last_name[0];
if (lastRec && lastRec.source) {
var m = this.byId.get(lastRec.source);
if (m && upper(m.last_name) === upper(last)) {
obj.nysiis_last_name = m.nysiis_last_name;
obj.metaphone_last_name = m.metaphone_last_name;
obj.norm_race = m.norm_race;
obj.norm_occupation = m.norm_occupation;
}
}
// norm_first_name comes only from a mention carrying the chosen given name.
var firstRec = null;
attested.first_name.forEach(function (r) {
if (!firstRec && r.source && upper(r.value) === upper(first)) firstRec = r;
});
if (firstRec) {
var fm = this.byId.get(firstRec.source);
if (fm && upper(fm.first_name) === upper(first)) obj.norm_first_name = fm.norm_first_name;
}
return obj;
};
// Every distinct name spelling attested for this person. A person
// accumulates spellings across sources ("Arch" in the 1870 census, "Archy"
// in 1880) and Normalize.md's nickname table does not always collapse them:
// in AUG, Archibald/Arch/Archie all map to ARCHIBALD (166 mentions) but
// Archy -> ARCHY, Archd -> ARCHD, Archabald -> ARCHABALD are each left
// alone. Two spellings of one man then never compare equal on the given
// name, the rung falls to SURNAME_ONLY, and an EXACT_FULLNAME pair scores
// as though only the surname matched. Scoring every attested variant and
// keeping the best makes the result independent of which spelling happens
// to be modal, and of gaps in the nickname table. Fixing the table is still
// worth doing; this stops the search depending on it.
Search.prototype._nameVariants = function (profile) {
var self = this, seen = new Set(), out = [];
var base = profile.asMatchObject;
var firsts = profile.attested.first_name.map(function (r) { return r.value; });
var lasts = profile.attested.last_name.map(function (r) { return r.value; });
if (!firsts.length) firsts = [base.first_name];
if (!lasts.length) lasts = [base.last_name];
firsts.forEach(function (f) {
lasts.forEach(function (l) {
var key = upper(f) + '|' + upper(l);
if (seen.has(key)) return;
seen.add(key);
var v = Object.assign({}, base, {
first_name: f, last_name: l,
full_name: [f, base.middle_name, l].filter(Boolean).join(' ')
});
// Re-derive normalized/phonetic keys from a mention that
// actually carries this spelling, rather than inheriting the
// modal object's keys.
delete v.norm_first_name; delete v.nysiis_last_name; delete v.metaphone_last_name;
profile.mentions.forEach(function (id) {
var m = self.byId.get(id);
if (!m) return;
if (!v.norm_first_name && upper(m.first_name) === upper(f)) {
v.norm_first_name = m.norm_first_name;
}
if (!v.nysiis_last_name && upper(m.last_name) === upper(l)) {
v.nysiis_last_name = m.nysiis_last_name;
v.metaphone_last_name = m.metaphone_last_name;
}
});
out.push(v);
});
});
return out;
};
// Cached per profile object; profiles are rebuilt per find()/round anyway.
Search.prototype._variantsFor = function (profile) {
if (!profile._variants) profile._variants = this._nameVariants(profile);
return profile._variants;
};
// =======================================================================
// STAGE 2 — EGO-CENTRIC NORMALIZATION
// =======================================================================
Search.prototype.buildKin = function (curTree, personId) {
var self = this;
var persons = curTree.persons || [];
var byPid = new Map();
persons.forEach(function (p) { byPid.set(p.person_id, p); });
// 2a. Read the stored single-anchor edges into a bidirectional graph.
// curTree.relationships[] is currently unused; read it too if populated.
var edges = new Map(); // pid -> [{ to, predicate }]
function edge(from, to, predicate) {
if (!from || !to || !predicate) return;
if (!edges.has(from)) edges.set(from, []);
edges.get(from).push({ to: to, predicate: predicate });
}
persons.forEach(function (p) {
if (!isPresent(p.anchor)) return;
var bits = String(p.anchor).split(':');
var pred = bits[0].trim();
var target = bits.slice(1).join(':').trim();
if (!byPid.has(target)) return;
edge(p.person_id, target, pred); // p --pred--> target
var inv = INVERSE[pred];
if (inv) edge(target, p.person_id, inv); // target --inv--> p
});
(curTree.relationships || []).forEach(function (r) {
if (!r) return;
var pred, target;
if (typeof r === 'string') {
var bits = r.split(':');
pred = bits[0].trim(); target = bits.slice(1).join(':').trim();
} else {
pred = r.predicate; target = r.object_id || r.object;
}
if (!r.subject_id && typeof r === 'string') return;
var subj = (typeof r === 'object') ? (r.subject_id || r.subject) : null;
if (!subj || !byPid.has(subj) || !byPid.has(target)) return;
edge(subj, target, pred);
if (INVERSE[pred]) edge(target, subj, INVERSE[pred]);
});
// 2b. Impute. Capped at maxHops.
var out = new Map(); // pid -> kin record
function record(pid, predicate, hops, weightScale) {
if (pid === personId) return;
var spec = KIN_WEIGHTS[predicate] || { hops: hops, weight: 0.4 };
var w = spec.weight * (weightScale == null ? 1 : weightScale);
var prev = out.get(pid);
if (prev && prev.baseWeight >= w) return;
out.set(pid, {
person_id: pid,
predicate: predicate,
hops: hops,
baseWeight: w,
imputed: hops > 1
});
}
(edges.get(personId) || []).forEach(function (e) { record(e.to, e.predicate, 1); });
// Siblings: anyone sharing an anchor parent with the target.
var myParents = (edges.get(personId) || [])
.filter(function (e) { return e.predicate === 'isChildOf'; })
.map(function (e) { return e.to; });
myParents.forEach(function (par) {
(edges.get(par) || []).forEach(function (e) {
if (e.predicate === 'isParentOf') record(e.to, 'isSiblingOf', 2);
});
});
// Step-parents: my parent's spouse is my parent too (Search.md Stage 2,
// "spouse of parent -> isParentOf"). Single-anchor storage links Jinnie
// only to P002, never to P002's spouse Martha, so this has to be
// imputed from the child's side as well as the parent's side (the
// mirror case, spouse's children becoming the parent's, is below).
var myStepParents = [];
myParents.forEach(function (par) {
(edges.get(par) || []).forEach(function (e) {
if (e.predicate !== 'isSpouseOf') return;
if (!self._plausibleParent(byPid.get(e.to), byPid.get(personId))) return;
record(e.to, 'isChildOf', 2, 0.6);
myStepParents.push(e.to);
});
});
// Step-siblings: a step-parent's other children (Search.md Stage 2,
// "spouse's other children -> isSiblingOf, weight 0.5"). isSiblingOf's
// base weight is 0.8, so scale to 0.5 rather than adding a new entry
// to KIN_WEIGHTS just for this path.
myStepParents.forEach(function (sp) {
(edges.get(sp) || []).forEach(function (e) {
if (e.predicate === 'isParentOf' && e.to !== personId) {
record(e.to, 'isSiblingOf', 2, 0.625); // 0.8 * 0.625 = 0.5
}
});
});
// Spouse's children become the target's children, and the target's
// children become the spouse's, subject to the plausibility gate.
var mySpouses = (edges.get(personId) || [])
.filter(function (e) { return e.predicate === 'isSpouseOf'; })
.map(function (e) { return e.to; });
mySpouses.forEach(function (sp) {
(edges.get(sp) || []).forEach(function (e) {
if (e.predicate !== 'isParentOf') return;
if (!self._plausibleParent(byPid.get(personId), byPid.get(e.to))) return;
record(e.to, 'isParentOf', 2, 0.6);
});
});
// Grandparents.
myParents.forEach(function (par) {
(edges.get(par) || []).forEach(function (e) {
if (e.predicate === 'isChildOf') record(e.to, 'isGrandChildOf', 2);
});
});
// 2c. Attach profiles and weights.
var kin = [];
out.forEach(function (rec) {
var p = byPid.get(rec.person_id);
if (!p) return;
if (rec.hops > self.opts.maxHops) return;
var prof;
try { prof = self.buildProfile(curTree, rec.person_id); }
catch (err) { return; }
var verity = toInt(p.verity);
rec.verityScale = verity != null ? clamp(verity / self.opts.verityMax, 0.25, 1) : 0.5;
rec.profile = prof;
rec.isEnslaver = p.isEnslaver === true || rec.predicate === 'wasEnslavedBy';
kin.push(rec);
});
return kin;
};
// Plausibility gate on imputed parenthood (Search.md Stage 2). Outside the
// window the link is a hypothesis for the researcher, not a search input.
Search.prototype._plausibleParent = function (parentPerson, childPerson) {
if (!parentPerson || !childPerson) return false;
var py = toInt(deref(parentPerson.birth_year).value);
var cy = toInt(deref(childPerson.birth_year).value);
if (py == null || cy == null) return true; // cannot judge, allow
var age = cy - py;
var g = upper(deref(parentPerson.gender).value);
var lo = (g === 'F') ? this.opts.minMotherAge : this.opts.minFatherAge;
var hi = (g === 'F') ? this.opts.maxMotherAge : this.opts.maxFatherAge;
return age >= lo && age <= hi;
};
// =======================================================================
// STAGE 3 — TIME SLICE
// =======================================================================
// tentative (optional): Map<person_id, mention> of NOT-YET-ACCEPTED grounding
// hypotheses, supplied by findBatch() when it jointly resolves several tree
// persons against the same source-year. A kin member with no confirmed
// mention yet but a strong provisional pick from an earlier batch round can
// still ground household/proximity/cohort support for the rest of the
// batch. Single-person scan()/find() calls omit it and behave as before.
Search.prototype.timeSlice = function (kin, year, targetSource, egoMentions, tentative) {
var self = this;
if (year == null) return kin.slice();
return kin.filter(function (k) {
var w = k.profile.birthWindow;
if (w && w[0] > year) return false; // not yet born
if (k.profile.deathCeiling != null && k.profile.deathCeiling < year) return false;
if (k.predicate === 'isSpouseOf') {
var married = self._marriageYear(egoMentions, k.profile.mentions);
if (married != null && married > year) return false; // marriage postdates the year
}
return true;
}).map(function (k) {
var c = Object.assign({}, k);
// Grounded: does this relative hold a confirmed mention in the
// target source-year? Ungrounded kin are hints, not evidence.
c.groundedMention = null;
for (var i = 0; i < k.profile.mentions.length; i++) {
var m = self.byId.get(k.profile.mentions[i]);
if (m && m.source === targetSource) { c.groundedMention = m; break; }
}
if (!c.groundedMention && tentative && tentative.has(k.person_id)) {
var tm = tentative.get(k.person_id);
if (tm && tm.source === targetSource) c.groundedMention = tm;
}
c.grounded = !!c.groundedMention;
// Co-residence expectation. Only 'expected' kin count against a
// candidate when absent.
c.coresidence = self._coresidence(k, year);
c.weight = c.baseWeight * c.verityScale * (c.grounded ? 1.0 : self.opts.ungroundedWeight);
return c;
});
};
// Marriage year for an isSpouseOf pair, read from mention-level assertions
// (assertion subject_id/object_id are mention_ids, not person_ids - see
// _wireSurnameBridge above and ExpandAssertions.md). Earliest start_year
// found on any assertion linking either side's mentions wins. Returns null
// when no such assertion exists, in which case the spouse is never dropped
// on marriage-year grounds (curTree carries no marriage date otherwise).
//
// ONLY assertions from sources that RECORD a marriage date count. A census
// isSpouseOf carries start_year = the enumeration year, because that is
// when the couple was observed living as married - not when they married.
// Of the 4,646 isSpouseOf rows in AUG, every one comes from a census (3,773)
// or a cohabitation register (873), so reading start_year as the marriage
// date makes every couple look newly wed in whichever year they were first
// enumerated. Arch and Martha Crawford are enumerated together in 1880, so
// a literal reading drops Martha's spouse from every pre-1880 search - and
// with him the household, proximity and Lever C support that finding her in
// 1870 depends on. Her true 1870 record fell from rank 1 to rank 2 behind
// an unrelated Martha Crawford purely from this.
//
// An enumeration year is an UPPER bound on the marriage ("married by then"),
// so it must not exclude the spouse from earlier years. Cohabitation
// registers are worse than neutral here: they record couples formalizing
// unions that predate emancipation, so their date is the registration, not
// the marriage.
Search.prototype._marriageYear = function (egoMentions, spouseMentions) {
if (!egoMentions || !spouseMentions || !egoMentions.length || !spouseMentions.length) return null;
var a = new Set(egoMentions), b = new Set(spouseMentions);
var best = null;
(this.assertions || []).forEach(function (r) {
if (!r || String(r.predicate).trim() !== 'isSpouseOf') return;
var hit = (a.has(r.subject_id) && b.has(r.object_id)) || (a.has(r.object_id) && b.has(r.subject_id));
if (!hit) return;
if (!MARRIAGE_DATE_TYPES.length) return;
var src = parseId(r.subject_id) || parseId(r.object_id);
if (!src || MARRIAGE_DATE_TYPES.indexOf(src.type) < 0) return;
var y = toInt(r.start_year);
if (y != null && (best == null || y < best)) best = y;
});
return best;
};
Search.prototype._coresidence = function (k, year) {
var w = k.profile.birthWindow;
var age = w ? year - w[1] : null;
if (k.predicate === 'isSpouseOf') return 'EXPECTED';
if (k.predicate === 'isParentOf') {
if (age == null) return 'UNKNOWN';
return age < 18 ? 'EXPECTED' : 'NOT_EXPECTED';
}
if (k.predicate === 'isChildOf') return 'UNKNOWN'; // target may have left home
if (k.predicate === 'wasEnslavedBy') return 'NOT_EXPECTED';
return 'UNKNOWN';
};
// =======================================================================
// STAGE 4 — CONSTRAINTS
// =======================================================================
Search.prototype.buildConstraints = function (curTree, profile, kin, target) {
var self = this;
// Automatic constraint fetch: death year from VR/DR/FG, whether or not
// the tree carries one. curTree has no death years at all in practice.
var fetched = this._fetchConstraints(profile);
var deathCeiling = profile.deathCeiling;
if (fetched.deathYear != null && (deathCeiling == null || fetched.deathYear < deathCeiling)) {
deathCeiling = fetched.deathYear;
}
// Exclusions.
var excluded = new Set();
var reasons = new Map();
function exclude(id, why) {
if (!isPresent(id)) return;
excluded.add(id);
if (!reasons.has(id)) reasons.set(id, why);
}
// Already linked to this person, or to ANY person in the tree.
(curTree.persons || []).forEach(function (p) {
(p.mentions || []).forEach(function (id) {
exclude(id, p.person_id === profile.person_id ? 'ALREADY_LINKED' : 'CLAIMED_BY_' + p.person_id);
});
});
// Rejections previously recorded on the person.
(profile.tree_person.rejected || []).forEach(function (id) { exclude(id, 'REJECTED'); });
// isNotSameAs assertions against any of this person's mentions.
var mine = new Set(profile.mentions);
(this.assertions || []).forEach(function (a) {
if (!a || String(a.predicate).trim() !== 'isNotSameAs') return;
if (mine.has(a.subject_id)) exclude(a.object_id, 'IS_NOT_SAME_AS');
if (mine.has(a.object_id)) exclude(a.subject_id, 'IS_NOT_SAME_AS');
});