-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathdata.py
More file actions
1833 lines (1632 loc) · 78.6 KB
/
data.py
File metadata and controls
1833 lines (1632 loc) · 78.6 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
from typing import Optional, Union, Dict, List, Any, Tuple, Set, NamedTuple
import os
import re
import json
import platform
import numpy as np
import pandas as pd
import logging
import pickle
from tqdm import tqdm
from functools import reduce
from collections import defaultdict, Counter
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
from s2and.mp import UniversalPool
from s2and.sampling import sampling, random_sampling
from s2and.consts import (
NUMPY_NAN,
NAME_COUNTS_PATH,
PROJECT_ROOT_PATH,
LARGE_DISTANCE,
CLUSTER_SEEDS_LOOKUP,
)
from s2and.file_cache import cached_path
from s2and.text import (
normalize_text,
get_text_ngrams,
compute_block,
get_text_ngrams_words,
detect_language,
same_prefix_tokens,
AFFILIATIONS_STOP_WORDS,
VENUE_STOP_WORDS,
NAME_PREFIXES,
DROPPED_AFFIXES,
ORCID_PATTERN,
)
logger = logging.getLogger("s2and")
# Global variable for multiprocessing
global_preprocess: bool
# Lazy-initialized global for Sinonym detector within worker processes
_SINONYM_DETECTOR = None # type: ignore
CHUNK_SIZE = 1000 # for multiprocessing imap chunks
class NameCounts(NamedTuple):
first: Optional[int]
last: Optional[int]
first_last: Optional[int]
last_first_initial: Optional[int]
class Signature(NamedTuple):
author_info_first: Optional[str]
author_info_first_normalized_without_apostrophe: Optional[str]
author_info_middle: Optional[str]
author_info_middle_normalized_without_apostrophe: Optional[str]
author_info_last_normalized: Optional[str]
author_info_last: str
author_info_suffix_normalized: Optional[str]
author_info_suffix: Optional[str]
author_info_first_normalized: Optional[str]
author_info_coauthors: Optional[List[str]]
author_info_coauthor_blocks: Optional[List[str]]
author_info_full_name: Optional[str]
author_info_affiliations: List[str]
author_info_affiliations_n_grams: Optional[Counter]
author_info_coauthor_n_grams: Optional[Counter]
author_info_email: Optional[str]
author_info_orcid: Optional[str]
author_info_name_counts: Optional[NameCounts]
author_info_position: int
author_info_block: str
author_info_given_block: Optional[str]
author_info_estimated_gender: Optional[str]
author_info_estimated_ethnicity: Optional[str]
paper_id: int
sourced_author_source: Optional[str]
sourced_author_ids: List[str]
author_id: Optional[int]
signature_id: str
class Author(NamedTuple):
author_name: str
position: int
class Paper(NamedTuple):
title: str
has_abstract: Optional[bool]
in_signatures: Optional[bool]
is_english: Optional[bool]
is_reliable: Optional[bool]
predicted_language: Optional[str]
title_ngrams_words: Optional[Counter]
authors: List[Author]
venue: Optional[str]
journal_name: Optional[str]
title_ngrams_chars: Optional[Counter]
venue_ngrams: Optional[Counter]
journal_ngrams: Optional[Counter]
reference_details: Optional[Tuple[Counter, Counter, Counter, Counter]]
year: Optional[int]
references: Optional[List[int]]
paper_id: int
class MiniPaper(NamedTuple):
title: str
venue: Optional[str]
journal_name: Optional[str]
authors: List[str]
class ANDData:
"""
The main class for holding our representation of an author disambiguation dataset
Input:
signatures: path to the signatures json file (or the json object)
papers: path to the papers information json file (or the json object)
name: name of the dataset, used for caching computed features
mode: 'train' or 'inference'; if 'inference', everything related to splitting will be ignored
clusters: path to the clusters json file (or the json object)
specter_embeddings: path to the specter embeddings pickle (or the dictionary object)
cluster_seeds: path to the cluster seed json file (or the json object)
altered_cluster_signatures: path to the signature ids \n-separated txt file (or a list or set object)
Clusters that these signatures appear in will be marked as "altered"
train_pairs: path to predefined train pairs csv (or the dataframe object)
val_pairs: path to predefined val pairs csv (or the dataframe object)
test_pairs: path to predefined test pairs csv (or the dataframe object)
train_blocks: path to predefined train blocks (or the json object)
val_blocks: path to predefined val blocks (or the json object)
test_blocks: path to predefined test blocks (or the json object)
train_signatures: path to predefined train signatures (or the json object)
val_signatures: path to predefined val signatures (or the json object)
test_signatures: path to predefined test signatures (or the json object)
block_type: can be either "s2" or "original"
unit_of_data_split: options are ("signatures", "blocks", "time")
num_clusters_for_block_size: probably leave as default,
controls train/val/test splits based on block size
train_ratio: training ratio of instances for clustering
val_ratio: validation ratio of instances for clustering
test_ratio: test ratio of instances for clustering
train_pairs_size: number of training pairs for learning the linkage function
val_pairs_size: number of validation pairs for fine-tuning the linkage function parameters
test_pairs_size: number of test pairs for evaluating the linkage function
pair_sampling_block: sample pairs from only within blocks?,
pair_sampling_balanced_classes: sample a balanced number of positive and negative pairs?,
pair_sampling_balanced_homonym_synonym: sample a balanced number of homonymous and synonymous pairs?,
all_test_pairs_flag: With blocking, for the linkage function evaluation task, should the test
contain all possible pairs from test blocks, or the given number of pairs (test_pairs_size)
random_seed: random seed
load_name_counts: Whether or not to load name counts
n_jobs: number of cpus to use
preprocess: whether to preprocess the data (normalization, etc)
name_tuples: optionally pass in the already created set of name tuples, to avoid recomputation
can be None or "filtered" or a set of name tuples
use_orcid_id: whether to use the orcid id for (a) constraints as true if orcids match and
(b) subblocking so that any sigs with the same orcid are in the same subblock
use_sinonym_overwrite: if True, run a pre-step that batch-detects Chinese names per paper via
Sinonym and overwrites the corresponding signature name parts with Sinonym's normalized output.
Also applies Sinonym-normalized names to the per-paper author list so co-author features
(coauthor sets/blocks and n-grams) are derived from the normalized names as well.
"""
def __init__(
self,
signatures: Union[str, Dict],
papers: Union[str, Dict],
name: str,
mode: str = "train",
clusters: Optional[Union[str, Dict]] = None,
specter_embeddings: Optional[Union[str, Dict]] = None,
cluster_seeds: Optional[Union[str, Dict]] = None,
altered_cluster_signatures: Optional[Union[str, List, Set]] = None,
train_pairs: Optional[Union[str, List]] = None,
val_pairs: Optional[Union[str, List]] = None,
test_pairs: Optional[Union[str, List]] = None,
train_blocks: Optional[Union[str, List]] = None,
val_blocks: Optional[Union[str, List]] = None,
test_blocks: Optional[Union[str, List]] = None,
train_signatures: Optional[Union[str, List]] = None,
val_signatures: Optional[Union[str, List]] = None,
test_signatures: Optional[Union[str, List]] = None,
block_type: str = "s2",
unit_of_data_split: str = "blocks",
num_clusters_for_block_size: int = 1,
train_ratio: float = 0.8,
val_ratio: float = 0.1,
test_ratio: float = 0.1,
train_pairs_size: int = 30000,
val_pairs_size: int = 5000,
test_pairs_size: int = 5000,
pair_sampling_block: bool = True,
pair_sampling_balanced_classes: bool = False,
pair_sampling_balanced_homonym_synonym: bool = False,
all_test_pairs_flag: bool = False,
random_seed: int = 1111,
load_name_counts: Union[bool, Dict] = True,
n_jobs: int = 1,
preprocess: bool = True,
name_tuples: Optional[Union[Set[Tuple[str, str]], str]] = "filtered",
use_orcid_id: bool = True,
use_sinonym_overwrite: bool = False,
):
if mode == "train":
if train_blocks is not None and block_type != "original":
logger.warning("If you are passing in training/val/test blocks, then you may want original blocks.")
if unit_of_data_split == "blocks" and not pair_sampling_block:
raise Exception("Block-based cluster splits are not compatible with sampling stratgies 0 and 1.")
if (clusters is not None and train_pairs is not None) or (
clusters is None and train_pairs is None and train_blocks is None
):
raise Exception("Set exactly one of clusters and train_pairs")
if train_blocks is not None and train_pairs is not None:
raise Exception("Can't pass in both train_blocks and train_pairs")
if train_blocks is not None and clusters is None:
raise Exception("Train blocks still needs clusters")
logger.info("loading papers")
self.papers = self.maybe_load_json(papers)
# convert dictionary to namedtuples for memory reduction
for paper_id, paper in self.papers.items():
self.papers[paper_id] = Paper(
title=paper["title"],
has_abstract=paper["abstract"] not in {"", None},
in_signatures=None,
is_english=None,
is_reliable=None,
predicted_language=None,
title_ngrams_words=None,
authors=[
Author(
author_name=author["author_name"],
position=author["position"],
)
for author in paper["authors"]
],
venue=paper["venue"],
journal_name=paper["journal_name"],
title_ngrams_chars=None,
venue_ngrams=None,
journal_ngrams=None,
reference_details=None,
year=paper["year"],
references=paper.get("references", []),
paper_id=paper["paper_id"],
)
logger.info("loaded papers")
logger.info("loading signatures")
self.signatures = self.maybe_load_json(signatures)
# convert dictionary to namedtuples for memory reduction
for signature_id, signature in self.signatures.items():
self.signatures[signature_id] = Signature(
author_info_first=signature["author_info"]["first"],
author_info_first_normalized_without_apostrophe=None,
author_info_middle=signature["author_info"]["middle"],
author_info_middle_normalized_without_apostrophe=None,
author_info_last_normalized=None,
author_info_last=signature["author_info"]["last"],
author_info_suffix_normalized=None,
author_info_suffix=signature["author_info"]["suffix"],
author_info_first_normalized=None,
author_info_coauthors=None,
author_info_coauthor_blocks=None,
author_info_full_name=None,
author_info_affiliations=signature["author_info"]["affiliations"],
author_info_affiliations_n_grams=None,
author_info_coauthor_n_grams=None,
author_info_email=signature["author_info"]["email"],
author_info_orcid=(
signature["author_info"]["source_ids"][0]
if use_orcid_id
and "source_id_source" in signature["author_info"]
and signature["author_info"]["source_id_source"] == "ORCID"
else None
),
author_info_name_counts=None,
author_info_position=signature["author_info"]["position"],
author_info_block=signature["author_info"]["block"],
author_info_given_block=signature["author_info"].get("given_block", None),
author_info_estimated_gender=signature["author_info"].get("estimated_gender", None),
author_info_estimated_ethnicity=signature["author_info"].get("estimated_ethnicity", None),
paper_id=signature["paper_id"],
sourced_author_source=signature.get("sourced_author_source", None),
sourced_author_ids=signature.get("sourced_author_ids", []),
author_id=signature.get("author_id", None),
signature_id=signature["signature_id"],
)
logger.info("loaded signatures")
# Optional Sinonym pre-step: normalize Chinese names from papers and overwrite signatures
# This runs before other preprocessing so downstream steps use updated names
if use_sinonym_overwrite:
sinonym_results = sinonym_preprocess_papers_parallel(self.papers, n_jobs)
# Only allow block overwrites during inference to keep train/val/test splits reproducible
overwrite_count = apply_sinonym_overwrites(
self.signatures,
sinonym_results,
overwrite_blocks=(mode == "inference"),
)
logger.info(f"Sinonym overwrote {overwrite_count} signature name(s)")
# Update paper-level author strings so co-author features use Sinonym-normalized names
paper_overwrite_count = apply_sinonym_overwrites_to_papers(self.papers, sinonym_results)
logger.info(f"Sinonym overwrote {paper_overwrite_count} paper author name(s)")
self.name = name
self.mode = mode
logger.info("loading clusters")
self.clusters: Optional[Dict] = self.maybe_load_json(clusters)
logger.info("loaded clusters, loading specter")
self.specter_embeddings = self.maybe_load_specter(specter_embeddings)
# prevents errors during testing where we have no specter embeddings
if self.specter_embeddings is None:
self.specter_embeddings = {} # type: ignore
logger.info("loaded specter, loading cluster seeds")
cluster_seeds_dict = self.maybe_load_json(cluster_seeds)
self.altered_cluster_signatures = self.maybe_load_list(altered_cluster_signatures)
self.cluster_seeds_disallow = set()
self.cluster_seeds_require = {} # type: ignore
self.max_seed_cluster_id = None
if cluster_seeds_dict is not None:
cluster_num = 0
for signature_id_a, values in cluster_seeds_dict.items():
root_added = False
for signature_id_b, constraint_string in values.items():
if constraint_string == "disallow":
self.cluster_seeds_disallow.add((signature_id_a, signature_id_b))
elif constraint_string == "require":
if not root_added:
self.cluster_seeds_require[signature_id_a] = cluster_num
root_added = True
self.cluster_seeds_require[signature_id_b] = cluster_num
cluster_num += 1
self.max_seed_cluster_id = cluster_num
logger.info("loaded cluster seeds")
# check that all of the altered_clustere_signatures are in the cluster_seeds_require
if self.altered_cluster_signatures is not None:
for signature_id in self.altered_cluster_signatures:
if signature_id not in self.cluster_seeds_require:
raise Exception(f"Altered cluster signature {signature_id} not in cluster_seeds_require")
self.train_pairs = self.maybe_load_dataframe(train_pairs)
self.val_pairs = self.maybe_load_dataframe(val_pairs)
self.test_pairs = self.maybe_load_dataframe(test_pairs)
self.train_blocks = self.maybe_load_json(train_blocks)
self.val_blocks = self.maybe_load_json(val_blocks)
self.test_blocks = self.maybe_load_json(test_blocks)
self.train_signatures = self.maybe_load_json(train_signatures)
self.val_signatures = self.maybe_load_json(val_signatures)
self.test_signatures = self.maybe_load_json(test_signatures)
self.block_type = block_type
self.unit_of_data_split = unit_of_data_split
self.num_clusters_for_block_size = num_clusters_for_block_size
self.train_ratio = train_ratio
self.val_ratio = val_ratio
self.test_ratio = test_ratio
self.train_pairs_size = train_pairs_size
self.val_pairs_size = val_pairs_size
self.test_pairs_size = test_pairs_size
self.pair_sampling_block = pair_sampling_block
self.pair_sampling_balanced_classes = pair_sampling_balanced_classes
self.pair_sampling_balanced_homonym_synonym = pair_sampling_balanced_homonym_synonym
self.all_test_pairs_flag = all_test_pairs_flag
self.random_seed = random_seed
if self.clusters is None:
self.signature_to_cluster_id = None
if self.mode == "train":
if self.clusters is not None:
self.signature_to_cluster_id = {}
logger.info("making signature to cluster id")
for cluster_id, cluster_info in self.clusters.items():
for signature in cluster_info["signature_ids"]:
self.signature_to_cluster_id[signature] = cluster_id
logger.info("made signature to cluster id")
elif self.mode == "inference":
# sampling within blocks and exhaustive flag is turned on
self.pair_sampling_block = True
self.pair_sampling_balanced_classes = False
self.pair_sampling_balanced_homonym_synonym = False
self.all_test_pairs_flag = True
self.block_type = "s2" # pure inference is for S2 probably?
else:
raise Exception(f"Unknown mode: {self.mode}")
name_counts_loaded = False
if isinstance(load_name_counts, dict):
self.first_dict = load_name_counts["first_dict"]
self.last_dict = load_name_counts["last_dict"]
self.first_last_dict = load_name_counts["first_last_dict"]
self.last_first_initial_dict = load_name_counts["last_first_initial_dict"]
name_counts_loaded = True
elif load_name_counts:
logger.info("loading name counts")
with open(cached_path(NAME_COUNTS_PATH), "rb") as f:
(
first_dict,
last_dict,
first_last_dict,
last_first_initial_dict,
) = pickle.load(f)
self.first_dict = first_dict
self.last_dict = last_dict
self.first_last_dict = first_last_dict
self.last_first_initial_dict = last_first_initial_dict
name_counts_loaded = True
logger.info("loaded name counts")
self.n_jobs = n_jobs
self.signature_to_block = self.get_signatures_to_block()
papers_from_signatures = set([str(signature.paper_id) for signature in self.signatures.values()])
for paper_id, paper in self.papers.items():
self.papers[paper_id] = paper._replace(in_signatures=str(paper_id) in papers_from_signatures)
self.preprocess = preprocess
if name_tuples == "filtered":
self.name_tuples = set()
with open(os.path.join(PROJECT_ROOT_PATH, "data", "s2and_name_tuples_filtered.txt"), "r") as f2: # type: ignore
for line in f2:
line_split = line.strip().split(",") # type: ignore
self.name_tuples.add((line_split[0], line_split[1]))
elif name_tuples is None:
self.name_tuples = set()
with open(os.path.join(PROJECT_ROOT_PATH, "data", "s2and_name_tuples.txt"), "r") as f2: # type: ignore
for line in f2:
line_split = line.strip().split(",") # type: ignore
self.name_tuples.add((line_split[0], line_split[1]))
else:
self.name_tuples = name_tuples # type: ignore
logger.info("preprocessing papers")
self.papers = preprocess_papers_parallel(self.papers, self.n_jobs, self.preprocess)
logger.info("preprocessed papers")
logger.info("preprocessing signatures")
self.preprocess_signatures(name_counts_loaded)
logger.info("preprocessed signatures")
@staticmethod
def get_full_name_for_features(signature: Signature, include_last: bool = True, include_suffix: bool = True) -> str:
"""
Creates the full name from the name parts.
Parameters
----------
signature: Signature
the signature to create the full name for
include_last: bool
whether to include the last name
include_suffix: bool
whether to include the suffix
Returns
-------
string: the full name
"""
first = signature.author_info_first_normalized_without_apostrophe or signature.author_info_first
middle = signature.author_info_middle_normalized_without_apostrophe or signature.author_info_middle
last = signature.author_info_last_normalized or signature.author_info_last
suffix = signature.author_info_suffix_normalized or signature.author_info_suffix
list_of_parts = [first, middle]
if include_last:
list_of_parts.append(last)
if include_suffix:
list_of_parts.append(suffix)
name_parts = [part.strip() for part in list_of_parts if part is not None and len(part) != 0]
return " ".join(name_parts)
def preprocess_signatures(self, load_name_counts: bool):
"""
Preprocess the signatures, doing lots of normalization and feature creation
Parameters
----------
load_name_counts: bool
whether name counts were loaded (mostly just here so we can not load them when running tests)
Returns
-------
nothing, modifies self.signatures
"""
for signature_id, signature in tqdm(self.signatures.items(), desc="Preprocessing signatures"):
# our normalization scheme is to normalize first and middle separately,
# join them, then take the first token of the combined join
# TODO: we now have good normalization for chinese names with dashes in the first and surname
# BUT we currently DO NOT do anything with those dashes.
first_raw = signature.author_info_first or ""
middle_raw = signature.author_info_middle or ""
# Default normalization (keeps legacy behavior for counts/lookups)
first_normalized = normalize_text(first_raw)
middle_normalized = normalize_text(middle_raw)
first_middle_normalized_split = (first_normalized + " " + middle_normalized).split(" ")
if first_middle_normalized_split and first_middle_normalized_split[0] in NAME_PREFIXES:
first_middle_normalized_split = first_middle_normalized_split[1:]
# Hyphen-preserving split for the "without_apostrophe" canonical fields
# Centralize in s2and.text for reuse by other scripts
from s2and.text import split_first_middle_hyphen_aware
first_without_apostrophe, middle_without_apostrophe = split_first_middle_hyphen_aware(first_raw, middle_raw)
coauthors: Optional[List[str]] = None
if len(self.papers) != 0:
paper = self.papers[str(signature.paper_id)]
coauthors = [
author.author_name for author in paper.authors if author.position != signature.author_info_position
]
signature = signature._replace(
# need this for name counts (legacy single-token behavior)
author_info_first_normalized=first_middle_normalized_split[0] if first_middle_normalized_split else "",
# canonical fields used across featurization, prediction, etc.
author_info_first_normalized_without_apostrophe=first_without_apostrophe,
author_info_middle_normalized_without_apostrophe=middle_without_apostrophe,
author_info_last_normalized=normalize_text(signature.author_info_last),
author_info_suffix_normalized=normalize_text(signature.author_info_suffix or ""),
author_info_coauthors=set(coauthors) if coauthors is not None else None,
author_info_coauthor_blocks=(
set([compute_block(author) for author in coauthors]) if coauthors is not None else None
),
)
if self.preprocess:
affiliations = [normalize_text(affiliation) for affiliation in signature.author_info_affiliations]
affiliations_n_grams = get_text_ngrams_words(
" ".join(affiliations),
AFFILIATIONS_STOP_WORDS,
)
if load_name_counts:
# Backward-compatibility for name count keys:
# - Historically, counts used the legacy single-token `author_info_first_normalized`.
# - With Sinonym, `author_info_first_normalized_without_apostrophe` can contain multiple tokens
# for hyphenated Chinese given names (e.g., "qi xin"). For counts only, we heuristically
# join internal spaces to form a single token ("qixin") IF the raw first contained a hyphen.
# - This preserves old behavior for most names while improving lookups for hyphenated cases.
# TODO: revisit once we re-extract name_counts using Sinonym-aware canonicalization.
first_for_counts = signature.author_info_first_normalized or ""
raw_first = signature.author_info_first or ""
if "-" in raw_first:
joined = (signature.author_info_first_normalized_without_apostrophe or "").replace(" ", "")
if joined:
first_for_counts = joined
first_last_for_count = (first_for_counts + " " + signature.author_info_last_normalized).strip()
first_initial = first_for_counts if len(first_for_counts) > 0 else ""
last_first_initial_for_count = (signature.author_info_last_normalized + " " + first_initial).strip()
counts = NameCounts(
first=(self.first_dict.get(first_for_counts, 1) if len(first_for_counts) > 1 else np.nan), # type: ignore
last=self.last_dict.get(signature.author_info_last_normalized, 1),
first_last=(
self.first_last_dict.get(first_last_for_count, 1) # type: ignore
if len(first_for_counts) > 1
else np.nan
),
last_first_initial=self.last_first_initial_dict.get(last_first_initial_for_count, 1),
)
else:
counts = NameCounts(first=None, last=None, first_last=None, last_first_initial=None)
signature = signature._replace(
author_info_full_name=ANDData.get_full_name_for_features(signature).strip(),
author_info_affiliations=affiliations,
author_info_affiliations_n_grams=affiliations_n_grams,
author_info_coauthor_n_grams=(
get_text_ngrams(" ".join(coauthors), stopwords=None, use_bigrams=True)
if coauthors is not None
else Counter()
),
author_info_name_counts=counts,
)
# we need a regex to extract the 16 digits, keeping in mind the last digit could be X
if signature.author_info_orcid is not None:
orcid = re.findall(ORCID_PATTERN, signature.author_info_orcid)
if len(orcid) > 0:
signature = signature._replace(author_info_orcid=orcid[0].upper().replace("-", ""))
else:
signature = signature._replace(author_info_orcid=None)
self.signatures[signature_id] = signature
@staticmethod
def maybe_load_json(path_or_json: Optional[Union[str, Union[List, Dict]]]) -> Any:
"""
Either loads a dictionary from a json file or passes through the object
Parameters
----------
path_or_json: string or Dict
the file path or the object
Returns
-------
either the loaded json, or the passed in object
"""
if isinstance(path_or_json, str):
with open(path_or_json) as _json_file:
output = json.load(_json_file)
return output
else:
return path_or_json
@staticmethod
def maybe_load_list(path_or_list: Optional[Union[str, list, Set]]) -> Optional[Union[list, Set]]:
"""
Either loads a list from a text file or passes through the object
Parameters
----------
path_or_list: string or list
the file path or the object
Returns
-------
either the loaded list, or the passed in object
"""
if isinstance(path_or_list, str):
with open(path_or_list, "r") as f:
return f.read().strip().split("\n")
else:
return path_or_list
@staticmethod
def maybe_load_dataframe(path_or_dataframe: Optional[Union[str, pd.DataFrame]]) -> Optional[pd.DataFrame]:
"""
Either loads a dataframe from a csv file or passes through the object
Parameters
----------
path_or_dataframe: string or dataframe
the file path or the object
Returns
-------
either the loaded dataframe, or the passed in object
"""
if type(path_or_dataframe) == str:
return pd.read_csv(path_or_dataframe, sep=",")
else:
return path_or_dataframe
@staticmethod
def maybe_load_specter(path_or_pickle: Optional[Union[str, Dict]]) -> Optional[Dict]:
"""
Either loads a dictionary from a pickle file or passes through the object
Parameters
----------
path_or_pickle: string or dictionary
the file path or the object
Returns
-------
either the loaded json, or the passed in object
"""
if isinstance(path_or_pickle, str):
with open(path_or_pickle, "rb") as _pickle_file:
X, keys = pickle.load(_pickle_file)
D = {}
for i, key in enumerate(keys):
D[key] = X[i, :]
return D
else:
return path_or_pickle
def get_original_blocks(self) -> Dict[str, List[str]]:
"""
Gets the block dict based on the blocks provided with the dataset
Returns
-------
Dict: mapping from block id to list of signatures in the block
"""
block = {}
for signature_id, signature in self.signatures.items():
block_id = signature.author_info_given_block
if block_id not in block:
block[block_id] = [signature_id]
else:
block[block_id].append(signature_id)
return block
def get_s2_blocks(self) -> Dict[str, List[str]]:
"""
Gets the block dict based on the blocks provided by Semantic Scholar data
Returns
-------
Dict: mapping from block id to list of signatures in the block
"""
block: Dict[str, List[str]] = {}
for signature_id, signature in self.signatures.items():
block_id = signature.author_info_block
if block_id not in block:
block[block_id] = [signature_id]
else:
block[block_id].append(signature_id)
return block
def get_blocks(self) -> Dict[str, List[str]]:
"""
Gets the block dict
Returns
-------
Dict: mapping from block id to list of signatures in the block
"""
if self.block_type == "s2":
return self.get_s2_blocks()
elif self.block_type == "original":
return self.get_original_blocks()
else:
raise Exception(f"Unknown block type: {self.block_type}")
def get_constraint(
self,
signature_id_1: str,
signature_id_2: str,
low_value: Union[float, int] = 0,
high_value: Union[float, int] = LARGE_DISTANCE,
dont_merge_cluster_seeds: bool = True,
incremental_dont_use_cluster_seeds: bool = False,
) -> Optional[float]:
"""Applies cluster_seeds and generates the default
constraints which are:
First we apply the passed-in cluster_seeds, then:
(1) if not a.prefix(b) or b.prefix(a) and (a, b) not in self.name_tuples:
distance(a, b) = high_value
(2) if len(a_middle) > 0 and len(b_middle) > 0 and
intersection(a_middle_chars, b_middle_chars) == 0:
distance(a, b) = high_value
There is currently no rule to assign low_value but it would be good
to potentially add an ORCID rule to use low_value
Parameters
----------
signature_id_1: string
one signature id in the pair
signature_id_2: string
the other signature id in the pair
low_value: float
value to assign to same person override
high_value: float
value to assign to different person overrid
dont_merge_cluster_seeds: bool
this flag controls whether to use cluster seeds to enforce "dont merge"
as well as "must merge" constraints
incremental_dont_use_cluster_seeds: bool
Are we clustering in incremental mode? If so, don't use the cluster seeds that came with the dataset
Returns
-------
float: the constraint value
"""
first_1 = self.signatures[signature_id_1].author_info_first_normalized_without_apostrophe
first_2 = self.signatures[signature_id_2].author_info_first_normalized_without_apostrophe
middle_1 = self.signatures[signature_id_1].author_info_middle_normalized_without_apostrophe.split()
paper_1 = self.papers[str(self.signatures[signature_id_1].paper_id)]
paper_2 = self.papers[str(self.signatures[signature_id_2].paper_id)]
orcid_1 = self.signatures[signature_id_1].author_info_orcid
orcid_2 = self.signatures[signature_id_2].author_info_orcid
# cluster seeds have precedence
if (signature_id_1, signature_id_2) in self.cluster_seeds_disallow or (
signature_id_2,
signature_id_1,
) in self.cluster_seeds_disallow:
return CLUSTER_SEEDS_LOOKUP["disallow"]
elif (
self.cluster_seeds_require.get(signature_id_1, -1) == self.cluster_seeds_require.get(signature_id_2, -2)
) and (not incremental_dont_use_cluster_seeds):
return CLUSTER_SEEDS_LOOKUP["require"]
elif (
dont_merge_cluster_seeds
and (signature_id_1 in self.cluster_seeds_require and signature_id_2 in self.cluster_seeds_require)
and (self.cluster_seeds_require[signature_id_1] != self.cluster_seeds_require[signature_id_2])
):
return CLUSTER_SEEDS_LOOKUP["disallow"]
# orcid is a very reliable indicator: if 2 orcids are present and equal, then they are the same person
# but if they are not equal, we can't say much
elif orcid_1 is not None and orcid_2 is not None and orcid_1 == orcid_2:
return low_value
# just-in-case last name constraint: if last names are different, then disallow
elif (
self.signatures[signature_id_1].author_info_last_normalized
!= self.signatures[signature_id_2].author_info_last_normalized
):
return high_value
# just-in-case first initial constraint: if first initials are different, then disallow
elif len(first_1) > 0 and len(first_2) > 0 and first_1[0] != first_2[0]:
return high_value
# and then language constraints
elif (paper_1.is_reliable and paper_2.is_reliable) and (
paper_1.predicted_language != paper_2.predicted_language
):
return high_value
# and then name based constraints
else:
signature_2 = self.signatures[signature_id_2]
# either a known alias or a prefix of the other
# if neither, then we'll say it's impossible to be the same person
# Backward-compatibility: `first_1`/`first_2` can now be multi-token (Sinonym output).
# Legacy name_tuples were curated over single-token first names. To remain compatible,
# try multiple forms for alias membership: exact, joined-without-spaces, and first-token only.
# TODO: revisit once we re-extract name_tuples aligned with Sinonym canonicalization.
f1_join = "".join(first_1.split()) if isinstance(first_1, str) else first_1
f2_join = "".join(first_2.split()) if isinstance(first_2, str) else first_2
f1_tok = first_1.split()[0] if isinstance(first_1, str) and len(first_1.split()) > 0 else first_1
f2_tok = first_2.split()[0] if isinstance(first_2, str) and len(first_2.split()) > 0 else first_2
known_alias = (
(first_1, first_2) in self.name_tuples
or (f1_join, f2_join) in self.name_tuples
or (f1_tok, f2_tok) in self.name_tuples
)
prefix = same_prefix_tokens(first_1, first_2)
if not prefix and not known_alias:
return high_value
# dont cluster together if there is no intersection between the sets of middle initials
# and both sets are not empty
elif len(middle_1) > 0:
middle_2 = signature_2.author_info_middle_normalized_without_apostrophe.split()
if len(middle_2) > 0:
overlapping_affixes = set(middle_2).intersection(middle_1).intersection(DROPPED_AFFIXES)
middle_1_all = [word for word in middle_1 if len(word) > 0 and word not in overlapping_affixes]
middle_2_all = [word for word in middle_2 if len(word) > 0 and word not in overlapping_affixes]
middle_1_words = set([word for word in middle_1_all if len(word) > 1])
middle_2_words = set([word for word in middle_2_all if len(word) > 1])
middle_1_firsts = set([word[0] for word in middle_1_all])
middle_2_firsts = set([word[0] for word in middle_2_all])
conflicting_initials = (
len(middle_1_firsts) > 0
and len(middle_2_firsts) > 0
and len(middle_1_firsts.intersection(middle_2_firsts)) == 0
)
conflicting_full_names = (
len(middle_1_words) > 0
and len(middle_2_words) > 0
and len(middle_1_words.intersection(middle_2_words)) == 0
and set("".join(middle_1_words)) != set("".join(middle_2_words))
)
if conflicting_initials or conflicting_full_names:
return high_value
return None
def get_signatures_to_block(self) -> Dict[str, str]:
"""
Creates a dictionary mapping signature id to block key
Returns
-------
Dict: the signature to block dictionary
"""
signatures_to_block: Dict[str, str] = {}
block_dict = self.get_blocks()
for block_key, signatures in block_dict.items():
for signature in signatures:
signatures_to_block[signature] = block_key
return signatures_to_block
def split_blocks_helper(
self, blocks_dict: Dict[str, List[str]]
) -> Tuple[Dict[str, List[str]], Dict[str, List[str]], Dict[str, List[str]]]:
"""
Splits the block dict into train/val/test blocks
Parameters
----------
blocks_dict: Dict
the full block dictionary
Returns
-------
train/val/test block dictionaries
"""
x = []
y = []
for block_id, signature in blocks_dict.items():
x.append(block_id)
y.append(len(signature))
# Explicitly set n_init to silence upcoming sklearn default-change warning
clustering_model = KMeans(
n_clusters=self.num_clusters_for_block_size,
random_state=self.random_seed,
n_init=10,
).fit(np.array(y).reshape(-1, 1))
y_group = clustering_model.labels_
train_blocks, val_test_blocks, _, val_test_length = train_test_split(
x,
y_group,
test_size=self.val_ratio + self.test_ratio,
stratify=y_group,
random_state=self.random_seed,
)
val_blocks, test_blocks = train_test_split(
val_test_blocks,
test_size=self.test_ratio / (self.val_ratio + self.test_ratio),
stratify=val_test_length,
random_state=self.random_seed,
)
train_block_dict = {k: blocks_dict[k] for k in train_blocks}
val_block_dict = {k: blocks_dict[k] for k in val_blocks}
test_block_dict = {k: blocks_dict[k] for k in test_blocks}
return train_block_dict, val_block_dict, test_block_dict
def group_signature_helper(self, signature_list: List[str]) -> Dict[str, List[str]]:
"""
creates a block dict containing a specific input signature list
Parameters
----------
signature_list: List
the list of signatures to include
Returns
-------
Dict: the block dict for the input signatures
"""
block_to_signatures: Dict[str, List[str]] = {}
for s in signature_list:
if self.signature_to_block[s] not in block_to_signatures:
block_to_signatures[self.signature_to_block[s]] = [s]
else:
block_to_signatures[self.signature_to_block[s]].append(s)
return block_to_signatures
def split_cluster_signatures(
self,
) -> Tuple[Dict[str, List[str]], Dict[str, List[str]], Dict[str, List[str]]]:
"""
Splits the block dict into train/val/test blocks based on split type requested.
Options for splitting are `signatures`, `blocks`, and `time`
Returns
-------
train/val/test block dictionaries
"""
blocks = self.get_blocks()
assert self.train_ratio + self.val_ratio + self.test_ratio == 1, "train/val/test ratio should add to 1"
if self.unit_of_data_split == "signatures":
signature_keys = list(self.signatures.keys())
train_signatures, val_test_signatures = train_test_split(
signature_keys,
test_size=self.val_ratio + self.test_ratio,
random_state=self.random_seed,
)
val_signatures, test_signatures = train_test_split(
val_test_signatures,
test_size=self.test_ratio / (self.val_ratio + self.test_ratio),
random_state=self.random_seed,
)
train_block_dict = self.group_signature_helper(train_signatures)
val_block_dict = self.group_signature_helper(val_signatures)
test_block_dict = self.group_signature_helper(test_signatures)
return train_block_dict, val_block_dict, test_block_dict
elif self.unit_of_data_split == "blocks":
(
train_block_dict,
val_block_dict,
test_block_dict,
) = self.split_blocks_helper(blocks)
return train_block_dict, val_block_dict, test_block_dict
elif self.unit_of_data_split == "time":
signature_to_year = {}
for signature_id, signature in self.signatures.items():
# paper_id should be kept as string, so it can be matched to papers.json
paper_id = str(signature.paper_id)
if self.papers[paper_id].year is None:
signature_to_year[signature_id] = 0
else: