forked from jacobvsdanniel/pubmedkb_web
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kb_utils.py
1837 lines (1530 loc) · 62.3 KB
/
kb_utils.py
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
import os
import csv
import sys
import html
import json
import heapq
import asyncio
import difflib
import logging
import argparse
import unicodedata
from collections import defaultdict
import requests
import retriv
from retriv import DenseRetriever
try:
from gpt_utils import async_run_qa, run_qa, run_qa_stream, run_qka_stream, run_pqa_stream
except ModuleNotFoundError:
pass
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s - %(process)d - %(name)s - %(message)s",
datefmt="%Y/%m/%d %H:%M:%S",
level=logging.INFO,
force=True,
)
csv.register_dialect(
"csv", delimiter=",", quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True,
escapechar=None, lineterminator="\n", skipinitialspace=False,
)
csv.register_dialect(
"tsv", delimiter="\t", quoting=csv.QUOTE_NONE, quotechar=None, doublequote=False,
escapechar=None, lineterminator="\n", skipinitialspace=False,
)
ner_gvdc_mapping = {
"Gene": "gene",
"Disease": "disease",
"Chemical": "drug",
"ProteinMutation": "mutation",
"DNAMutation": "mutation",
"SNP": "mutation",
"DNAAcidChange": "mutation",
"CopyNumberVariant": "mutation",
"Mutation": "mutation",
}
entity_type_to_real_type_mapping = {
"VARIANT": [
"ProteinMutation",
"DNAMutation",
"SNP",
"DNAAcidChange",
"CopyNumberVariant",
"Mutation",
],
}
def read_lines(file, line_by_line=False, write_log=True):
if write_log:
logger.info(f"Reading {file}")
with open(file, "r", encoding="utf8") as f:
if line_by_line:
line_list = [line[:-1] for line in f]
else:
line_list = f.read().splitlines()
if write_log:
lines = len(line_list)
logger.info(f"Read {lines:,} lines")
return line_list
def read_json(file, is_jsonl=False, write_log=True):
if write_log:
logger.info(f"Reading {file}")
with open(file, "r", encoding="utf8") as f:
if is_jsonl:
data = []
for line in f:
datum = json.loads(line[:-1])
data.append(datum)
else:
data = json.load(f)
if write_log:
objects = len(data)
logger.info(f"Read {objects:,} objects")
return data
def read_csv(file, dialect, write_log=True):
if write_log:
logger.info(f"Reading {file}")
with open(file, "r", encoding="utf8", newline="") as f:
reader = csv.reader(f, dialect=dialect)
row_list = [row for row in reader]
if write_log:
rows = len(row_list)
logger.info(f"Read {rows:,} rows")
return row_list
class DiskDict:
def __init__(self, key_file, value_file, key_process=None):
self.key_file = key_file
self.value_file = value_file
self.key_process = key_process
self.key_to_offset = {}
self.value_fp = None
if key_file and value_file:
self.load_data()
return
def load_data(self):
self.value_fp = open(self.value_file, "r", encoding="utf8")
logger.info(f"Reading {self.key_file}")
self.key_to_offset = {}
with open(self.key_file, "r", encoding="utf8") as f:
for line in f:
key, value_offset = json.loads(line)
if self.key_process:
key = self.key_process(key)
self.key_to_offset[key] = value_offset
keys = len(self.key_to_offset)
logger.info(f"Read {keys:,} keys")
return
def get(self, key, default_value=None):
try:
offset = self.key_to_offset[key]
except KeyError:
return default_value
self.value_fp.seek(offset)
value = self.value_fp.readline()
value = json.loads(value)
return value
def intersection_of_key_to_set(dict_list):
if len(dict_list) <= 1:
return dict_list[0]
dict_list = sorted(dict_list, key=lambda d: len(d))
smallest_dict, other_dict_list = dict_list[0], dict_list[1:]
del dict_list
key_to_value_set = {}
for key, value_set in smallest_dict.items():
if any(
key not in other_dict
for other_dict in other_dict_list
):
continue
value_set = set(
value
for value in value_set
if all(
value in other_dict[key]
for other_dict in other_dict_list
)
)
if value_set:
key_to_value_set[key] = value_set
return key_to_value_set
def union_of_key_to_set(dict_list):
if len(dict_list) <= 1:
return dict_list[0]
key_set = set(
key
for key_to_value_set in dict_list
for key in key_to_value_set
)
key_to_value_set = {
key: set(
value
for key_to_value_set in dict_list
for value in key_to_value_set.get(key, set())
)
for key in key_set
}
return key_to_value_set
def query_variant(query):
response = requests.get(
"https://www.ncbi.nlm.nih.gov/research/litvar2-api/variant/autocomplete/",
params={"query": query},
)
result_list = response.json()
variant_list = []
for result in result_list:
id_list = []
if "rsid" in result:
id_list.append("RS#:" + result["rsid"][2:])
if "hgvs" in result:
id_list.append("HGVS:" + result["hgvs"])
name_list = [result["name"]]
if "match" in result:
match = result["match"]
prefix = "<m>"
suffix = "</m>"
i = match.find(prefix) + len(prefix)
j = match.find(suffix, i)
match = match[i:j]
if match != name_list[0]:
name_list.append(match)
gene_list = result.get("gene", [])
variant = (id_list, name_list, gene_list)
variant_list.append(variant)
return variant_list
def filter_frequency(name_to_frequency, ratio=0):
if not name_to_frequency:
return name_to_frequency
result = {}
threshold = 0
for name, frequency in name_to_frequency.items():
if not result:
result[name] = frequency
threshold = frequency * ratio
continue
if frequency < threshold:
break
result[name] = frequency
return result
class NEN:
def __init__(self, data_dir):
self.typeid_name_frequency = None
self.typeid_to_most_frequent_name = None
self.name_type_id_frequency = None
self.length_name = None
if data_dir:
k_file = os.path.join(data_dir, "typeid_name_frequency_key.jsonl")
v_file = os.path.join(data_dir, "typeid_name_frequency_value.jsonl")
self.typeid_name_frequency = DiskDict(k_file, v_file)
kv_file = os.path.join(data_dir, "typeid_to_most_frequent_name.json")
self.typeid_to_most_frequent_name = read_json(kv_file)
k_file = os.path.join(data_dir, "name_type_id_frequency_key.jsonl")
v_file = os.path.join(data_dir, "name_type_id_frequency_value.jsonl")
self.name_type_id_frequency = DiskDict(k_file, v_file)
k_file = os.path.join(data_dir, "length_name_key.jsonl")
v_file = os.path.join(data_dir, "length_name_value.jsonl")
self.length_name = DiskDict(k_file, v_file)
return
def get_names_by_query(self, query, case_sensitive=False, max_length_diff=1, min_similarity=0.85, max_names=20):
# exact match
exact_match_list = [(query, 1.0)] if self.name_type_id_frequency.get(query) else []
if len(exact_match_list) >= max_names:
return exact_match_list
max_non_exact_matches = max_names - len(exact_match_list)
# set up matcher
if min_similarity == 1:
if case_sensitive:
return exact_match_list
else:
matcher = query.lower()
else:
if case_sensitive:
matcher = difflib.SequenceMatcher(a=query, autojunk=False)
else:
matcher = difflib.SequenceMatcher(a=query.lower(), autojunk=False)
query_length = len(query)
name_to_similarity = {}
perfect_matches = 0
for length_diff in range(max_length_diff + 1):
sign_list = [0] if length_diff == 0 else [1, -1]
for sign in sign_list:
name_length = query_length + sign * length_diff
if name_length < 1:
continue
if sign == 0:
sign_string = ""
elif sign == 1:
sign_string = f" ({query_length}+{length_diff})"
else:
sign_string = f" ({query_length}-{length_diff})"
logger.info(f"[{query}]: searching names with length {name_length}{sign_string} ...")
for name in self.length_name.get(name_length, []):
# skip exact match
if name == query:
continue
# compute similarity
if min_similarity == 1:
# must be case-insensitive
similarity = 1 if name.lower() == matcher else 0
else:
if case_sensitive:
matcher.set_seq2(name)
else:
matcher.set_seq2(name.lower())
similarity = matcher.ratio()
if similarity >= min_similarity:
name_to_similarity[name] = similarity
if similarity == 1:
perfect_matches += 1
if perfect_matches >= max_non_exact_matches:
break
if perfect_matches >= max_non_exact_matches:
break
if perfect_matches >= max_non_exact_matches:
break
name_similarity_list = heapq.nlargest(max_non_exact_matches, name_to_similarity.items(), key=lambda x: x[1])
name_similarity_list = exact_match_list + name_similarity_list
return name_similarity_list
def get_ids_by_name(self, name):
type_id_frequency_list = [
[_type, _id, frequency]
for _type, id_to_frequency in self.name_type_id_frequency.get(name, {}).items()
for _id, frequency in id_to_frequency.items()
]
type_id_frequency_list = sorted(type_id_frequency_list, key=lambda x: x[2], reverse=True)
return type_id_frequency_list
def get_aliases_by_id(self, _type, _id, max_aliases=20):
alias_frequency_list = [
[alias, frequency]
for alias, frequency in self.typeid_name_frequency.get(f"{_type}_{_id}", {}).items()
]
alias_frequency_list = alias_frequency_list[:max_aliases]
return alias_frequency_list
def get_most_frequent_name_by_id(self, _type, _id):
return self.typeid_to_most_frequent_name.get(f"{_type}_{_id}")
def get_variant_in_kb(self, id_list, name_list):
type_id_name_frequency = []
for _type in entity_type_to_real_type_mapping["VARIANT"]:
for _id in id_list:
for name in name_list:
frequency = self.typeid_name_frequency.get(f"{_type}_{_id}", {}).get(name, None)
if frequency is not None:
type_id_name_frequency.append((_type, _id, name, frequency))
type_id_name_frequency = sorted(type_id_name_frequency, key=lambda tidf: tidf[3], reverse=True)
return type_id_name_frequency
class V2G:
def __init__(self, variant_dir, gene_dir):
if variant_dir:
self.hgvs_frequency = read_json(os.path.join(variant_dir, "hgvs_frequency.json"))
self.rs_frequency = read_json(os.path.join(variant_dir, "rs_frequency.json"))
# self.geneid_frequency = read_json(os.path.join(variant_dir, "gene_frequency.json"))
self.hgvs_rs_frequency = read_json(os.path.join(variant_dir, "hgvs_rs_frequency.json"))
self.rs_hgvs_frequency = read_json(os.path.join(variant_dir, "rs_hgvs_frequency.json"))
self.hgvs_geneid_frequency = read_json(os.path.join(variant_dir, "hgvs_gene_frequency.json"))
self.geneid_hgvs_frequency = read_json(os.path.join(variant_dir, "gene_hgvs_frequency.json"))
self.rs_geneid_frequency = read_json(os.path.join(variant_dir, "rs_gene_frequency.json"))
self.geneid_rs_frequency = read_json(os.path.join(variant_dir, "gene_rs_frequency.json"))
if gene_dir:
self.gene_geneid_frequency = read_json(os.path.join(gene_dir, "gene_id_frequency.json"))
self.geneid_gene_frequency = read_json(os.path.join(gene_dir, "id_gene_frequency.json"))
return
def query(self, query):
if query.startswith("HGVS:"):
hgvs_frequency, rs_frequency, gene_frequency = self.query_hgvs(query)
elif query.startswith("RS#:"):
hgvs_frequency, rs_frequency, gene_frequency = self.query_rs(query)
else:
hgvs_frequency, rs_frequency, gene_frequency = self.query_gene(query)
return hgvs_frequency, rs_frequency, gene_frequency
def query_hgvs(self, hgvs):
hgvs_frequency = {hgvs: self.hgvs_frequency.get(hgvs, 0)}
rs_frequency = self.hgvs_rs_frequency.get(hgvs, {})
gene_frequency = {}
for geneid, frequency in self.hgvs_geneid_frequency.get(hgvs, {}).items():
for gene, _ in self.geneid_gene_frequency.get(geneid, {}).items():
if gene not in gene_frequency:
gene_frequency[gene] = frequency
break
hgvs_frequency = filter_frequency(hgvs_frequency)
rs_frequency = filter_frequency(rs_frequency)
gene_frequency = filter_frequency(gene_frequency)
return hgvs_frequency, rs_frequency, gene_frequency
def query_rs(self, rs):
hgvs_frequency = self.rs_hgvs_frequency.get(rs, {})
rs_frequency = {rs: self.rs_frequency.get(rs, 0)}
gene_frequency = {}
for geneid, frequency in self.rs_geneid_frequency.get(rs, {}).items():
for gene, _ in self.geneid_gene_frequency.get(geneid, {}).items():
if gene not in gene_frequency:
gene_frequency[gene] = frequency
break
hgvs_frequency = filter_frequency(hgvs_frequency)
rs_frequency = filter_frequency(rs_frequency)
gene_frequency = filter_frequency(gene_frequency)
return hgvs_frequency, rs_frequency, gene_frequency
def query_gene(self, gene):
geneid = ""
frequency = 0
for geneid, frequency in self.gene_geneid_frequency.get(gene, {}).items():
break
if not geneid:
hgvs_frequency = {}
rs_frequency = {}
else:
hgvs_frequency = self.geneid_hgvs_frequency.get(geneid, {})
rs_frequency = self.geneid_rs_frequency.get(geneid, {})
gene_frequency = {gene: frequency}
hgvs_frequency = filter_frequency(hgvs_frequency)
rs_frequency = filter_frequency(rs_frequency)
gene_frequency = filter_frequency(gene_frequency)
return hgvs_frequency, rs_frequency, gene_frequency
class NCBIGene:
def __init__(self, gene_dir):
self.id_to_name = {}
self.name_to_id = {}
self.alias_to_id = {}
if gene_dir:
ncbi_file = os.path.join(gene_dir, "ncbi_protein_gene.csv")
ncbi_data = read_csv(ncbi_file, "csv")
ncbi_header, ncbi_data = ncbi_data[0], ncbi_data[1:]
assert ncbi_header == ["tax_id", "gene_id", "gene_name", "gene_alias"]
alias_to_id = defaultdict(lambda: [])
for _tax_id, gene_id, gene_name, gene_alias_list in ncbi_data:
self.id_to_name[gene_id] = gene_name
self.name_to_id[gene_name] = gene_id
if gene_alias_list == "-":
continue
for gene_alias in gene_alias_list.split("|"):
alias_to_id[gene_alias].append(gene_id)
for alias, id_list in alias_to_id.items():
if len(id_list) == 1:
self.alias_to_id[alias] = id_list[0]
return
class VariantNEN:
def __init__(self, variant_dir):
self.id_to_name = defaultdict(lambda: [])
self.name_to_id = defaultdict(lambda: [])
if variant_dir:
# RS
rs_file = os.path.join(variant_dir, f"rs.jsonl")
rs_prefix = "RS#:"
rs_prefix_len = len(rs_prefix)
with open(rs_file, "r", encoding="utf8") as f:
for line in f:
_id = json.loads(line)
name = "rs" + _id[rs_prefix_len:]
self.id_to_name[_id].append(name)
self.name_to_id[name].append(_id)
# HGVS
hgvs_file = os.path.join(variant_dir, f"hgvs.jsonl")
with open(hgvs_file, "r", encoding="utf8") as f:
for line in f:
_id, name_to_count = json.loads(line)
name_set = set()
for name in name_to_count:
name = name.lower()
if name in name_set:
continue
name_set.add(name)
self.id_to_name[_id].append(name)
self.name_to_id[name].append(_id)
return
class KB:
def __init__(self, data_dir):
self.data_dir = data_dir
self.data = {}
self.key = {}
self.value = {}
return
def load_data(self, data_type=("sentence", "annotation")):
for name in data_type:
file = os.path.join(self.data_dir, f"{name}.jsonl")
self.data[name] = open(file, "r", encoding="utf8")
return
def load_index(self, index_type=("pmid", "type_id", "type_name")):
for name in index_type:
value_file = os.path.join(self.data_dir, f"{name}_value.jsonl")
self.value[name] = open(value_file, "r", encoding="utf8")
key_file = os.path.join(self.data_dir, f"{name}_key.jsonl")
logger.info(f"Reading {key_file}")
self.key[name] = {}
with open(key_file, "r", encoding="utf8") as f:
if name == "pmid":
for line in f:
key, value_offset = json.loads(line[:-1])
self.key[name][key] = value_offset
else:
for line in f:
key, value_offset = json.loads(line[:-1])
self.key[name][tuple(key)] = value_offset
keys = len(self.key[name])
logger.info(f"Read {keys:,} keys")
return
def get_sentence(self, sentence_file_offset):
"""
:param sentence_file_offset: int
:return: [sentence_index: int, sentence: str, mention_list: list]
mention: [name: str, type: str, id_list: list, start_position_in_sentence: int]
"""
self.data["sentence"].seek(sentence_file_offset)
sentence = self.data["sentence"].readline()[:-1]
sentence = json.loads(sentence)
return sentence
def get_annotation(self, annotation_file_offset):
"""
:param annotation_file_offset: int
:return: [
sentence_file_offset: int,
h_list: list[int],
t_list: list[int],
annotator: str,
annotation: dict,
]
"""
self.data["annotation"].seek(annotation_file_offset)
annotation = self.data["annotation"].readline()[:-1]
annotation = json.loads(annotation)
return annotation
def query_annotation_list_by_pmid(self, pmid):
"""
:param pmid: str
:return: [(annotation_file_offset, annotation_score), ...]
"""
value_offset = self.key["pmid"].get(pmid, None)
if value_offset is None:
return []
self.value["pmid"].seek(value_offset)
ann_list = self.value["pmid"].readline()[:-1]
ann_list = json.loads(ann_list)
return ann_list
def query_ht_pmid_annlist_by_type_idname(self, idname, key):
"""
:param idname: "type_id" / "type_name"
:param key: (_type, id/name)
:return: {
"head": ...
"tail": {
pmid: [(annotation_file_offset, annotation_score), ...],
...
}
}
"""
value_offset = self.key[idname].get(key, None)
if value_offset is None:
return {"head": {}, "tail": {}}
self.value[idname].seek(value_offset)
ht_pmid_ann = self.value[idname].readline()[:-1]
ht_pmid_ann = json.loads(ht_pmid_ann)
return ht_pmid_ann
def query_ht_pmid_annset_by_entity(self, entity_spec, pmid, idname_key_ht_pmid_ann=None):
"""
:param entity_spec: (
"OR",
("type_id", ("VARIANT", "RS#:113488022")),
(
"AND",
("type_id", ("ProteinMutation", "HGVS:p.V600E")),
("type_id", ("CorrespondingGene", "673")),
),
)
:param pmid: None / "35246262"
:param idname_key_ht_pmid_ann: "type_id"/"type_name" -> (type, id/name) -> "head"/"tail" -> pmid -> ann_list
ann_list: [(annotation_file_offset, annotation_score), ...]
:return: "head"/"tail" -> pmid -> ann_set
"""
# shared storage to avoid repeated self.query_annotation_by_type_idname()
if idname_key_ht_pmid_ann is None:
idname_key_ht_pmid_ann = {
idname: {}
for idname in ["type_id", "type_name"]
}
op, arg = entity_spec
if op in ["AND", "OR"]:
ht_to_list_of_pmid_ann = {"head": [], "tail": []}
for sub_entity_spec in arg:
ht_pmid_ann = self.query_ht_pmid_annset_by_entity(sub_entity_spec, pmid, idname_key_ht_pmid_ann)
for ht, pmid_to_ann in ht_pmid_ann.items():
ht_to_list_of_pmid_ann[ht].append(pmid_to_ann)
if op == "AND" and not ht_pmid_ann["head"] and not ht_pmid_ann["tail"]:
break # early stop when the intersection is already sure be empty
if op == "AND":
merge_function = intersection_of_key_to_set
else:
merge_function = union_of_key_to_set
ht_pmid_ann = {
ht: merge_function(list_of_pmid_ann)
for ht, list_of_pmid_ann in ht_to_list_of_pmid_ann.items()
}
return ht_pmid_ann
elif op in ["type_id", "type_name"]:
idname = op
_type, idname_key = arg
real_type_list = entity_type_to_real_type_mapping.get(_type, [_type])
if len(real_type_list) > 1:
expanded_entity_spec = ("OR", (
(idname, (real_type, idname_key))
for real_type in real_type_list
))
return self.query_ht_pmid_annset_by_entity(expanded_entity_spec, pmid, idname_key_ht_pmid_ann)
else:
_type = real_type_list[0]
key = (_type, idname_key)
if key in idname_key_ht_pmid_ann[idname]:
# use result cached in shared storage
ht_pmid_ann = idname_key_ht_pmid_ann[idname][key]
else:
# query type_id/name, filter by pmid, and then save to shared storage
ht_pmid_ann = self.query_ht_pmid_annlist_by_type_idname(idname, key)
if pmid:
ht_single_pmid_ann = {}
for ht, pmid_to_ann in ht_pmid_ann.items():
if pmid in pmid_to_ann:
ht_single_pmid_ann[ht] = {pmid: pmid_to_ann[pmid]}
else:
ht_single_pmid_ann[ht] = {}
ht_pmid_ann = ht_single_pmid_ann
idname_key_ht_pmid_ann[idname][key] = ht_pmid_ann
# make ann_set from ann_list
ht_pmid_ann = {
ht: {
pmid: set(tuple(ann) for ann in ann_list)
for pmid, ann_list in pmid_to_ann.items()
}
for ht, pmid_to_ann in ht_pmid_ann.items()
}
return ht_pmid_ann
else:
assert False
def query_pmid_to_annotation_list(self, e1_spec, e2_spec, pmid):
"""
:param e1_spec: ...
:param e2_spec: None / (
"OR",
("type_id", ("VARIANT", "RS#:113488022")),
(
"AND",
("type_id", ("ProteinMutation", "HGVS:p.V600E")),
("type_id", ("CorrespondingGene", "673")),
),
)
:param pmid: None / str
:return: [
pmid: [(annotation_file_offset, annotation_score), ...],
...
]
"""
if e1_spec and e2_spec:
e1_ht_pmid_annset = self.query_ht_pmid_annset_by_entity(e1_spec, pmid)
e2_ht_pmid_annset = self.query_ht_pmid_annset_by_entity(e2_spec, pmid)
h1t2_pmid_annset = intersection_of_key_to_set([
e1_ht_pmid_annset["head"], e2_ht_pmid_annset["tail"],
])
h2t1_pmid_annset = intersection_of_key_to_set([
e1_ht_pmid_annset["tail"], e2_ht_pmid_annset["head"],
])
del e1_ht_pmid_annset, e2_ht_pmid_annset
pmid_to_ann = union_of_key_to_set([h1t2_pmid_annset, h2t1_pmid_annset])
del h1t2_pmid_annset, h2t1_pmid_annset
pmid_to_ann = {
pmid: sorted(ann_set)
for pmid, ann_set in pmid_to_ann.items()
}
elif e1_spec or e2_spec:
entity_spec = e1_spec if e1_spec else e2_spec
ht_pmid_annset = self.query_ht_pmid_annset_by_entity(entity_spec, pmid)
pmid_to_ann = union_of_key_to_set([ht_pmid_annset["head"], ht_pmid_annset["tail"]])
pmid_to_ann = {
pmid: sorted(ann_set)
for pmid, ann_set in pmid_to_ann.items()
}
else:
pmid_to_ann = {pmid: self.query_annotation_list_by_pmid(pmid)}
return pmid_to_ann
class PaperKB:
def __init__(self, data_dir):
self.data_dir = data_dir
self.pmid_to_offset = {}
self.data_file = None
if data_dir:
self.load_data()
return
def load_data(self):
data_file = os.path.join(self.data_dir, f"pmid_value.jsonl")
self.data_file = open(data_file, "r", encoding="utf8")
key_file = os.path.join(self.data_dir, f"pmid_key.jsonl")
logger.info(f"Reading {key_file}")
self.pmid_to_offset = {}
with open(key_file, "r", encoding="utf8") as f:
for line in f:
key, value_offset = json.loads(line[:-1])
self.pmid_to_offset[key] = value_offset
papers = len(self.pmid_to_offset)
logger.info(f"Read {papers:,} papers")
return
def query_data(self, pmid):
try:
offset = self.pmid_to_offset[pmid]
except KeyError:
return {
"pmid": pmid,
"title": "",
"abstract": "",
"sentence_list": [],
}
self.data_file.seek(offset)
paper_datum = self.data_file.readline()[:-1]
paper_datum = json.loads(paper_datum)
return paper_datum
class GeVarToGLOF:
def __init__(self, data_dir):
self.data_dir = data_dir
self.type_key_offset = {}
self.type_to_value_file = {}
self.type_list = ["Gene", "VARIANT"]
if data_dir:
self.load_data()
return
def load_data(self):
for _type in self.type_list:
value_file = os.path.join(self.data_dir, f"{_type}_value.jsonl")
self.type_to_value_file[_type] = open(value_file, "r", encoding="utf8")
key_file = os.path.join(self.data_dir, f"{_type}_key.jsonl")
logger.info(f"Reading {key_file}")
self.type_key_offset[_type] = {}
with open(key_file, "r", encoding="utf8") as f:
for line in f:
key, value_offset = json.loads(line[:-1])
self.type_key_offset[_type][key] = value_offset
keys = len(self.type_key_offset[_type])
logger.info(f"Read {keys:,} {_type} keys")
return
def query_data(self, _type, key):
try:
offset = self.type_key_offset[_type][key]
except KeyError:
return {"gof": [], "lof": []}
value_file = self.type_to_value_file[_type]
value_file.seek(offset)
value = value_file.readline()[:-1]
value = json.loads(value)
return value
def get_normalized_journal_name(name):
name = unicodedata.normalize("NFKC", name)
name = name.lower()
term_list = []
for c in name:
if c.isalnum() or c == " ":
term_list.append(c)
elif c == "&":
term_list.append(" and ")
else:
term_list.append(" ")
name = "".join(term_list)
name = " ".join(name.split())
return name
class Meta:
def __init__(self, meta_dir):
self.meta_dir = meta_dir
self.pmid_to_meta = None
self.journal_to_impact = None
if meta_dir:
self.load_data()
return
def load_data(self):
# pmid_to_meta
meta_key_file = os.path.join(self.meta_dir, "meta_key.jsonl")
meta_value_file = os.path.join(self.meta_dir, "meta_value.jsonl")
self.pmid_to_meta = DiskDict(meta_key_file, meta_value_file)
# journal_to_impact
self.journal_to_impact = {}
journal_impact_file = os.path.join(self.meta_dir, "journal_impact.csv")
with open(journal_impact_file, "r", encoding="utf8", newline="") as f:
reader = csv.reader(f, dialect="csv")
header = next(reader)
assert header == [
"journal", "articles", "match_ratio", "match_substring", "match_journal", "match_impact",
]
for journal, _articles, match_ratio, match_substring, _match_journal, match_impact in reader:
match_ratio = int(match_ratio[:-1])
if match_ratio >= 70 or match_substring == "True":
self.journal_to_impact[journal] = match_impact
return
def get_meta_by_pmid(self, pmid):
pmid = str(pmid)
meta = self.pmid_to_meta.get(
pmid,
{
"title": "", "author": "", "year": "", "journal": "",
"doi": "", "publication_type_list": [], "citation": 0,
},
)
journal = get_normalized_journal_name(meta["journal"])
meta["journal_impact"] = self.journal_to_impact.get(journal, "")
return meta
def get_paper_meta_html(pmid, meta):
title = meta["title"]
if title and title[-1] not in [".", "?", "!"]:
title = title + "."
title_html = html.escape(title)
title_html = f'<a href="https://pubmed.ncbi.nlm.nih.gov/{pmid}">[{html.escape(pmid)}]</a> {title_html}'
year = meta["year"]
if year:
year = year + "."
year = html.escape(year)
journal = meta["journal"]
if journal and journal[-1] not in [".", "?", "!"]:
journal = journal + "."
journal_html = html.escape(journal)
journal_html = f"<em>{journal_html}</em>"
doi = meta["doi"]
if doi:
doi_html = html.escape(f"doi.org/{doi}")
doi_html = f'<a href="https://doi.org/{doi}">{doi_html}</a>'
else:
doi_html = ""
publication_type = meta["publication_type_list"]
publication_type = ", ".join(html.escape(_type) for _type in publication_type)
if publication_type:
publication_type += "."
citation = meta["citation"]
citation_html = html.escape(f"Cited by {citation}.")
paper_meta_html = f"{title_html} {year} {journal_html} {doi_html} {publication_type} {citation_html}"
return paper_meta_html
class GVDScore:
def __init__(self, data_dir, type_list=("gdas", "dgas", "vdas", "dvas")):
self.data_dir = data_dir
self.type_to_dict = {}
self.type_list = type_list
if data_dir:
self.load_data()
return
def load_data(self):
for _type in self.type_list:
key_file = os.path.join(self.data_dir, f"{_type}_key.jsonl")
value_file = os.path.join(self.data_dir, f"{_type}_value.jsonl")
self.type_to_dict[_type] = DiskDict(key_file, value_file)
return
def query_data(self, _type, g, v, d):
if _type == "gd":
value = self.type_to_dict["gdas"].get(g, {}).get(d, {})
elif _type == "vd":
value = self.type_to_dict["vdas"].get(v, {}).get(d, {})
elif _type == "g":
value = self.type_to_dict["gdas"].get(g, {})
elif _type == "v":
value = self.type_to_dict["vdas"].get(v, {})
elif _type == "d2g":
value = self.type_to_dict["dgas"].get(d, {})
elif _type == "d2v":
value = self.type_to_dict["dvas"].get(d, {})
else:
assert False
return value
class GDScore:
def __init__(self, mesh_gene_score_file):
self.mesh_gene_score_file = mesh_gene_score_file
self.dgs = {}
self.gds = {}