This repository has been archived by the owner on May 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
2177 lines (1945 loc) · 87.3 KB
/
main.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
from __future__ import division
import os
import re
from collections import Counter, deque, defaultdict
from copy import deepcopy
from datetime import datetime
from difflib import SequenceMatcher
import community
import jmespath
import networkx as nx
import numpy as np
import requests
from addict import Dict
from elasticsearch import Elasticsearch, helpers
# from elasticsearch_xpack import XPackClient
from flask import Flask, request, jsonify, render_template, url_for
from flask import Markup
from flask_cors import CORS
from flask_env import MetaFlaskEnv
from networkx.readwrite import json_graph
from rope.base.codeanalyze import ChangeCollector
from BioStopWords import DOMAIN_STOP_WORDS
from bio_lexicon import lex as lex_dict
# def is_gae():
# if 'SERVER_SOFTWARE' in os.environ and (os.environ['SERVER_SOFTWARE'].startswith('Google App Engine/') or
# os.environ['SERVER_SOFTWARE'].startswith('Development/')):
# from google.appengine.api import urlfetch
# urlfetch.set_default_fetch_deadline(60)
#
# return True
#
# if is_gae():
# import requests_toolbelt.adapters.appengine
# # Use the App Engine Requests adapter. This makes sure that Requests uses
# # URLFetch.
# requests_toolbelt.adapters.appengine.monkeypatch()
class Configuration(object):
__metaclass__ = MetaFlaskEnv
ENV_PREFIX = 'LIBRARY_'
NONWORDCHARS_REGEX = re.compile(r'\W+', flags=re.IGNORECASE | re.UNICODE)
ES_MAIN_URL = os.environ["ES_MAIN_URL"].split(',')
ES_GRAPH_URL = os.environ["ES_GRAPH_URL"].split(',')
PUB_INDEX_LAMBDA = 'pubmed-20'
PUB_DOC_TYPE = 'publication'
PUB_INDEX = 'pubmed-20'
# PUB_DOC_TYPE = 'publication'
CONCEPT_INDEX = 'pubmed-20-concept'
CONCEPT_DOC_TYPE = 'concept'
MARKED_INDEX = 'pubmed-20-taggedtext'
MARKED_DOC_TYPE = 'taggedtext'
BIOENTITY_INDEX = 'pubmed-20-bioentity'
BIOENTITY_DOC_TYPE = 'bioentity'
es_graph = Elasticsearch(ES_GRAPH_URL,
# sniff_on_start=True,
# connection_class=RequestsHttpConnection
)
# xpack = XPackClient(es_graph)
#
# xpack.info()
es = Elasticsearch(ES_MAIN_URL,
timeout=300,
# sniff_on_start=True,
# connection_class=RequestsHttpConnection
)
app = Flask(__name__)
app.config.from_object(Configuration)
CORS(app)
gene_names = []
session = requests.Session()
FILTERED_NODES = ['antibody',
'function',
'phenotype',
'Mice',
'CROMOLYN SODIUM',
'sign or symptom',
'AMINO ACIDS',
'GLYCINE',
'SODIUM CHLORIDE',
'WATER',
'RASAGILINE',
'FELBINAC',
'TCHP',
'Moderate',
'Sporadic',
'Positive',
'Negative',
'Chronic',
'Position',
'Borderline',
'Profound',
'Laterality',
'Bilateral',
'Unilateral',
'Right',
'Right-sided',
'Left',
'Left-sided',
'Generalized',
'Generalised',
'Localized',
'Localised',
'Distal',
'Outermost',
'Proximal',
'Severity',
'Intensity',
'Mild',
'Severe',
'Frequency',
'Frequent',
'Episodic',
'Acute',
'Peripheral',
'Chronic',
'Heterogeneous',
'Prolonged',
'disease',
'cancer',
'cancers',
'neoplasm',
'neoplasms',
'tumor',
'tumors',
'tumour',
'tumours',
'Central',
'Onset',
'Refractory',
'Progressive',
'target',
'Spastic paraplegia - epilepsy - intellectual disability',
'Sex',
'review',
'Transient',
'findings'
]
FILTERED_NODES.extend(DOMAIN_STOP_WORDS)
def _ratio(str1, str2):
s = SequenceMatcher(None, str1, str2)
return s.quick_ratio()
# =============== PORTED FROM TEXTACY ======================
# ported from textacy https://github.com/chartbeat-labs/textacy
# to allow code to run in google app engine and aws lambda
def token_sort_ratio(str1, str2):
"""
Measure of similarity between two strings based on minimal edit distance,
where ordering of words in each string is normalized before comparing.
Args:
str1 (str)
str2 (str)
Returns:
float: similarity between ``str1`` and ``str2`` in the interval [0.0, 1.0],
where larger values correspond to more similar strings.
"""
if not str1 or not str2:
return 0
str1 = _force_unicode(str1)
str2 = _force_unicode(str2)
str1_proc = _process_and_sort(str1)
str2_proc = _process_and_sort(str2)
return _ratio(str1_proc, str2_proc)
def aggregate_term_variants(terms,
acro_defs=None,
fuzzy_dedupe=True):
"""
Take a set of unique terms and aggregate terms that are symbolic, lexical,
and ordering variants of each other, as well as acronyms and fuzzy string matches.
Args:
terms (Set[str]): set of unique terms with potential duplicates
acro_defs (dict): if not None, terms that are acronyms will be
aggregated with their definitions and terms that are definitions will
be aggregated with their acronyms
fuzzy_dedupe (bool): if True, fuzzy string matching will be used
to aggregate similar terms of a sufficient length
Returns:
List[Set[str]]: each item is a set of aggregated terms
Notes:
Partly inspired by aggregation of variants discussed in
Park, Youngja, Roy J. Byrd, and Branimir K. Boguraev.
"Automatic glossary extraction: beyond terminology identification."
Proceedings of the 19th international conference on Computational linguistics-Volume 1.
Association for Computational Linguistics, 2002.
"""
agg_terms = []
seen_terms = set()
for term in sorted(terms, key=len, reverse=True):
if term in seen_terms:
continue
variants = set([term])
seen_terms.add(term)
# symbolic variations
if '-' in term:
variant = term.replace('-', ' ').strip()
if variant in terms.difference(seen_terms):
variants.add(variant)
seen_terms.add(variant)
if '/' in term:
variant = term.replace('/', ' ').strip()
if variant in terms.difference(seen_terms):
variants.add(variant)
seen_terms.add(variant)
# lexical variations
term_words = term.split()
# last_word = term_words[-1]
# # assume last word is a noun
# last_word_lemmatized = lemmatizer.lemmatize(last_word, 'n')
# # if the same, either already a lemmatized noun OR a verb; try verb
# if last_word_lemmatized == last_word:
# last_word_lemmatized = lemmatizer.lemmatize(last_word, 'v')
# # if at least we have a new term... add it
# if last_word_lemmatized != last_word:
# term_lemmatized = ' '.join(term_words[:-1] + [last_word_lemmatized])
# if term_lemmatized in terms.difference(seen_terms):
# variants.add(term_lemmatized)
# seen_terms.add(term_lemmatized)
# if term is an acronym, add its definition
# if term is a definition, add its acronym
if acro_defs:
for acro, def_ in acro_defs.items():
if acro.lower() == term.lower():
variants.add(def_.lower())
seen_terms.add(def_.lower())
break
elif def_.lower() == term.lower():
variants.add(acro.lower())
seen_terms.add(acro.lower())
break
# if 3+ -word term differs by one word at the start or the end
# of a longer phrase, aggregate
if len(term_words) > 2:
term_minus_first_word = ' '.join(term_words[1:])
term_minus_last_word = ' '.join(term_words[:-1])
if term_minus_first_word in terms.difference(seen_terms):
variants.add(term_minus_first_word)
seen_terms.add(term_minus_first_word)
if term_minus_last_word in terms.difference(seen_terms):
variants.add(term_minus_last_word)
seen_terms.add(term_minus_last_word)
# check for "X of Y" <=> "Y X" term variants
if ' of ' in term:
split_term = term.split(' of ')
variant = split_term[1] + ' ' + split_term[0]
if variant in terms.difference(seen_terms):
variants.add(variant)
seen_terms.add(variant)
# intense de-duping for sufficiently long terms
if fuzzy_dedupe is True and len(term) >= 13:
for other_term in sorted(terms.difference(seen_terms), key=len, reverse=True):
if len(other_term) < 13:
break
tsr = token_sort_ratio(term, other_term)
if tsr > 0.93:
variants.add(other_term)
seen_terms.add(other_term)
break
agg_terms.append(variants)
return agg_terms
def _force_unicode(s):
"""Force ``s`` into unicode, or die trying."""
if isinstance(s, unicode):
return s
else:
return unicode(s)
def _process_and_sort(s):
"""Return a processed string with tokens sorted then re-joined."""
return ' '.join(sorted(_process(s).split()))
def _process(s):
"""
Remove all characters but letters and numbers, strip whitespace,
and force everything to lower-case.
"""
if not s:
return ''
return NONWORDCHARS_REGEX.sub(' ', s).lower().strip()
# =============== END TEXTACY ======================
def agf_opt_merge(lists):
"""merge lists
https://stackoverflow.com/questions/9110837/python-simple-list-merging-based-on-intersections
agf (optimized)
"""
sets = deque(set(lst) for lst in lists if lst)
results = []
disjoint = 0
if sets:
current = sets.pop()
while True:
merged = False
newsets = deque()
for _ in range(disjoint, len(sets)):
this = sets.pop()
if not current.isdisjoint(this):
current.update(this)
merged = True
disjoint = 0
else:
newsets.append(this)
disjoint += 1
if sets:
newsets.extendleft(sets)
if not merged:
results.append(current)
try:
current = newsets.pop()
except IndexError:
break
disjoint = 0
sets = newsets
return results
return sets
# =============== FLASK METHODS ======================
@app.after_request
def add_header(response):
response.cache_control.max_age = 300
return response
@app.route('/document/<string:doc_id>', methods=['GET'])
def document_get(doc_id):
document = session.get('/'.join((ES_MAIN_URL[0], PUB_INDEX, PUB_DOC_TYPE, doc_id)),
).json()
return jsonify(document)
@app.route('/document-more-like-this/<string:doc_id>', methods=['GET'])
def document_mlt(doc_id):
query_body = {
"query": {
"more_like_this": {
"fields": ["title", "abstract", "keywords", "mesh_headings.label"],
"like": [
{
"_index": PUB_INDEX,
"_type": PUB_DOC_TYPE,
"_id": doc_id
},
],
"min_term_freq": 1,
"max_query_terms": 25
}
}
}
data = session.post(ES_MAIN_URL[0] + '/' + PUB_INDEX + '/_search/',
json=query_body
).json()
return jsonify(data)
@app.route('/search', methods=['GET'])
def search_get():
query = request.args.get('query')
size = request.args.get('size') or 10
sort = request.args.get('sort') or [{"pub_date": "desc"}]
search_after = request.args.get('search_after') or []
search_after_id = request.args.get('search_after_id')
aggs = request.args.get('aggs')
if not isinstance(search_after, list):
search_after = [search_after]
if search_after_id:
search_after.append(search_after_id)
sort.append({"pub_id": "desc"})
query_body = {
"query": {
"query_string": {
"query": query
},
},
"size": size,
"sort": sort,
# "_source": False,
"_source": {
"excludes": ["*_sentences", 'filename', 'text_mined*']
},
# "highlight": {
# "fields": {
# "*": {},
# },
# "require_field_match": False,
# }
}
if aggs:
query_body['aggregations'] = { # "abstract_significant_terms": {
# "significant_terms": {"field": "abstract"}
# },
# "title_significant_terms": {
# "significant_terms": {"field": "title"}
# },
# "mesh_headings_label_significant_terms": {
# "significant_terms": {"field": "mesh_headings.label"}
# },
# "keywords_significant_terms": {
# "significant_terms": {"field": "keywords"}
# },
"journal_abbr_significant_terms": {
"significant_terms": {"field": "journal.medlineAbbreviation"}
},
# "chemicals_name_significant_terms": {
# "significant_terms": {"field": "chemicals.name"}
# },
"authors_significant_terms": {
"significant_terms": {"field": "authors.short_name"}
},
"pub_date_histogram": {
"date_histogram": {
"field": "pub_date",
"interval": "year"
}
},
"acronym_significant_terms": {
"significant_terms": {"field": "text_mined_entities.nlp.named_entities",
# "mutual_information": {
# "include_negatives": False
# },
"size": 20
},
},
"genes": {
"significant_terms": {
"field": "text_mined_entities.nlp.tagged_entities_grouped.GENE|OPENTARGETS.reference",
"size": 20,
"mutual_information": {}
},
"aggs": {
"gene_hits": {
"top_hits": {
"_source": {
"includes": ["text_mined_entities.nlp.tagged_entities_grouped.GENE|OPENTARGETS.label",
"text_mined_entities.nlp.tagged_entities_grouped.GENE|OPENTARGETS.reference"]
},
"size": 5
}
}
}
},
"diseases": {
"significant_terms": {
"field": "text_mined_entities.nlp.tagged_entities_grouped.DISEASE|OPENTARGETS.reference",
"size": 20,
"mutual_information": {}
},
"aggs": {
"disease_hits": {
"top_hits": {
"_source": {
"includes": [
"text_mined_entities.nlp.tagged_entities_grouped.DISEASE|OPENTARGETS.label",
"text_mined_entities.nlp.tagged_entities_grouped.DISEASE|OPENTARGETS.reference"]
},
"size": 5
}
}
}
},
"drugs": {
"significant_terms": {
"field": "text_mined_entities.nlp.tagged_entities_grouped.DRUG|CHEMBL.reference",
"size": 20,
"mutual_information": {}
},
"aggs": {
"drug_hits": {
"top_hits": {
"_source": {
"includes": ["text_mined_entities.nlp.tagged_entities_grouped.DRUG|CHEMBL.label",
"text_mined_entities.nlp.tagged_entities_grouped.DRUG|CHEMBL.reference"]
},
"size": 5
}
}
}
},
"phenotypes": {
"significant_terms": {
"field": "text_mined_entities.nlp.tagged_entities_grouped.PHENOTYPE|HPO.reference",
"size": 20,
"mutual_information": {}
},
"aggs": {
"phenotype_hits": {
"top_hits": {
"_source": {
"includes": ["text_mined_entities.nlp.tagged_entities_grouped.PHENOTYPE|HPO.label",
"text_mined_entities.nlp.tagged_entities_grouped.PHENOTYPE|HPO.reference"]
},
"size": 5
}
}
}
},
"top_chunks_significant_terms": {
"significant_terms": {"field": "text_mined_entities.nlp.top_chunks",
"mutual_information": {
"include_negatives": False
},
"size": 20
},
"aggs": {
# "sample": {
# # "diversified_sampler": {
# # "shard_size": 100,
# # "field": "text_mined_entities.nlp.abbreviations.short"
# # },
# "sampler": {
# "shard_size": 500000,
# },
# "aggs": {
"top_chunk_hits": {
"top_hits": {
"sort": [
{
"text_mined_entities.nlp.abbreviations.long": {
"order": "desc"
}
}
],
"_source": {
"includes": ["text_mined_entities.nlp.abbreviations",
"text_mined_entities.nlp.acronyms"]
},
"size": 10
}
}
# }
# },
# "chunks_significant_terms": {
# "significant_terms": {"field": "text_mined_entities.noun_phrases.chunks",
# "jlh": {
# "include_negatives": False
# }
# }
# },
}
}
}
if search_after:
query_body['search_after'] = search_after
data = session.post(ES_MAIN_URL[0] + '/' + PUB_INDEX + '/_search/',
json=query_body
).json()
if '_shards' in data:
del data['_shards']
if 'aggregations' in data:
# if data['aggregations']['acronym_significant_terms']['buckets']:
# new_gene_buckets = []
# # genes = set(json.load(open('/Users/andreap/work/code/pubmine/human_gene_names_hgnc_lower.json')))
# acronyms = set([i['key'].lower() for i in data['aggregations']['acronym_significant_terms']['buckets']])
# gene_acronyms = acronyms # & genes
#
# for bucket in data['aggregations']['acronym_significant_terms']['buckets']:
# if bucket['key'].lower() in gene_acronyms:
# new_gene_buckets.append(bucket)
#
# data['aggregations']['gene_significant_terms'] = dict(buckets=new_gene_buckets)
terms = []
term_weight = defaultdict(lambda: 0)
abbreviations = {}
inverted_abbreviations = {}
for i in data['aggregations']['top_chunks_significant_terms']['buckets']:
terms.append(i['key'])
term_weight[i['key']] = i['bg_count']
for hit in i['top_chunk_hits']['hits']['hits']:
for a in hit['_source']['text_mined_entities']['nlp']['abbreviations']:
short_name = a['short'].lower()
long_name = a['long'].lower()
abbreviations[short_name] = long_name
if long_name not in inverted_abbreviations:
inverted_abbreviations[long_name] = []
if short_name not in inverted_abbreviations[long_name]:
inverted_abbreviations[long_name].append(short_name)
'merge similar abbreviations'
synonyms = {}
for acronyms in inverted_abbreviations.values():
if len(acronyms) > 1:
for acronym in acronyms:
if acronym not in synonyms:
synonyms[acronym] = []
# synonyms[acronym].extend(acronyms)
synonyms[acronym] = list((set(synonyms[acronym]) | set(acronyms)))
# for pair in list(itertools.combinations(list(set(acronyms)), 2)):
# if pair[0]!=pair[1]:
# synonyms[pair[0]]=pair[1]
for k, v in synonyms.items():
v.pop(v.index(k))
# pprint(synonyms)
for t in terms:
if t.lower() in abbreviations:
terms.append(abbreviations[t.lower()])
# pprint(terms)
groups = aggregate_term_variants(set(terms), abbreviations)
groups_with_syn = []
for g in groups:
new_g = deepcopy(g)
for i in g:
if i in synonyms:
new_g = new_g | set(synonyms[i])
groups_with_syn.append(new_g)
# pprint(groups_with_syn)
groups_merge = agf_opt_merge(groups_with_syn)
# pprint(groups_merge)
filtered_terms = {max(list(group), key=lambda x: term_weight[x]): group for group in groups_merge}
# pprint(filtered_terms)
filtered_agg = []
for bucket in data['aggregations']['top_chunks_significant_terms']['buckets']:
if bucket['key'] in filtered_terms:
bucket.pop('top_chunk_hits')
bucket['alternative_terms'] = list(filtered_terms[bucket['key']] - set([bucket['key']]))
filtered_agg.append(bucket)
data['aggregations']['top_chunks_significant_terms']['buckets'] = filtered_agg[:15]
for i in data['aggregations']['genes']['buckets']:
for hit in i['gene_hits']['hits']['hits']:
for entity in hit['_source']['text_mined_entities']['nlp']['tagged_entities_grouped'][
'GENE|OPENTARGETS']:
if entity['reference'] == i['key']:
i['label'] = entity['label'].replace('_', ' ')
break
del i['gene_hits']
for i in data['aggregations']['diseases']['buckets']:
for hit in i['disease_hits']['hits']['hits']:
for entity in hit['_source']['text_mined_entities']['nlp']['tagged_entities_grouped'][
'DISEASE|OPENTARGETS']:
if entity['reference'] == i['key']:
i['label'] = entity['label'].replace('_', ' ')
break
del i['disease_hits']
for i in data['aggregations']['drugs']['buckets']:
for hit in i['drug_hits']['hits']['hits']:
for entity in hit['_source']['text_mined_entities']['nlp']['tagged_entities_grouped']['DRUG|CHEMBL']:
if entity['reference'] == i['key']:
i['label'] = entity['label'].replace('_', ' ')
break
del i['drug_hits']
for i in data['aggregations']['phenotypes']['buckets']:
for hit in i['phenotype_hits']['hits']['hits']:
for entity in hit['_source']['text_mined_entities']['nlp']['tagged_entities_grouped']['PHENOTYPE|HPO']:
if entity['reference'] == i['key']:
i['label'] = entity['label'].replace('_', ' ')
break
del i['phenotype_hits']
# if data['aggregations']['acronym_significant_terms']['buckets']:
# new_gene_buckets = []
# genes = set(json.load(open('/Users/andreap/work/code/pubmine/human_gene_names_hgnc_lower.json')))
# acronyms = set([i['key'].lower() for i in data['aggregations']['acronym_significant_terms']['buckets']])
# gene_acronyms = acronyms & genes
#
# for bucket in data['aggregations']['acronym_significant_terms']['buckets']:
# if bucket['key'].lower() in gene_acronyms:
# new_gene_buckets.append(bucket)
#
# data['aggregations']['gene_significant_terms'] = dict(buckets=new_gene_buckets)
return jsonify(data)
@app.route('/graph/explore', methods=['POST'])
def graph_proxy_post():
data = session.post(ES_GRAPH_URL[0] + '/' + PUB_INDEX_LAMBDA + '/_xpack/_graph/_explore', json=request.json).json()
if data and 'vertices' in data and data['vertices']:
data, topics = get_topics_from_graph(data)
return jsonify(dict(graph=data,
topics=topics))
return jsonify({})
# return jsonify(xpack.graph.explore(index=PUB_INDEX,
# body=request.json))
def build_graph(data):
'''
builds a networkX graph from a response of the elasticsearch Ghraph API
:param data:
:return:
'''
if data and data['vertices']:
'''build graph'''
G = nx.Graph()
node_names = {}
node_class = []
node_classes = []
gene_nodes = []
for i, vertex in enumerate(data['vertices']):
G.add_node(i,
term=vertex['term'],
weight=vertex['weight'],
flat_weight=1.
)
if vertex['term'].lower() in gene_names:
gene_nodes.append(i)
node_names[i] = vertex['term']
if vertex['field'] not in node_classes:
node_classes.append(vertex['field'])
node_class.append(node_classes.index(vertex['field']))
edge_sizes = []
for i, edge in enumerate(data['connections']):
G.add_edge(edge['source'],
edge['target'],
# weight=edge['weight'],
flat_weight=1.,
doc_count=edge['doc_count'])
edge_sizes.append(edge['doc_count'])
return G
@app.route('/search/topic', methods=['GET'])
def topic_graph():
index_name = request.args.get('index') or PUB_INDEX_LAMBDA
query = request.args.get('query')
verbose = request.args.get('verbose') or False
result_count = 0
count_query = {"query": {"query_string": {"query": query}},
"size": 0}
r = session.post(ES_GRAPH_URL[0] + '/' + index_name + '/_search/', json=count_query)
if r.ok:
result_count = r.json()['hits']['total']
if result_count > 0:
if result_count < 50:
field_default = ["text_mined_entities.nlp.chunks"]
size_default = 50
specificity_Default = 1
sample_size_default = 1000
timeout_default = 1000
elif result_count < 100:
field_default = ["text_mined_entities.nlp.top_chunks"]
size_default = 100
specificity_Default = 2
sample_size_default = 2000
timeout_default = 3000
elif result_count < 500:
field_default = ["text_mined_entities.nlp.top_chunks"]
size_default = 100
specificity_Default = 3
sample_size_default = 2000
timeout_default = 3000
else:
field_default = ["text_mined_entities.nlp.top_chunks"]
size_default = 200
specificity_Default = 5
sample_size_default = 5000
timeout_default = 10000
size = request.args.get('size') or size_default
specificity = request.args.get('specificity') or specificity_Default
field = request.args.getlist('field') or field_default
if len(field) == 1 and isinstance(field[0], (str, unicode)):
field = field[0].split(',')
vertices_query = []
for f in field:
vertices_query.append({"field": f, "min_doc_count": int(specificity), "size": int(size)})
es_query = {"query": {"query_string": {"query": query}},
"controls": {"use_significance": True, "sample_size": sample_size_default,
"timeout": timeout_default},
"connections": {"vertices": vertices_query},
"vertices": vertices_query}
r = session.post(ES_GRAPH_URL[0] + '/' + index_name + '/_xpack/_graph/_explore', json=es_query)
if r.ok:
data = r.json()
if data and 'vertices' in data and data['vertices']:
data, topics = get_topics_from_graph(data, verbose)
return jsonify(dict(graph=data,
topics=topics))
return jsonify({})
def get_topics_from_graph(data, verbose=False, min_topic_size=1):
G = build_graph(data)
# first compute the best partition
node_terms = nx.get_node_attributes(G, 'term')
node_weights = nx.get_node_attributes(G, 'weight')
node_centralities = nx.degree_centrality(G)
partition = community.best_partition(G, weight='flat_weight', resolution=.33)
topics = []
count = 0
nodes_to_delete = []
for topic_id, com in enumerate(set(partition.values())):
count += 1.
com_nodes = [nodes for nodes in partition.keys()
if partition[nodes] == com]
if len(com_nodes) > min_topic_size:
topic = []
for node in com_nodes:
topic.append((node_centralities[node], node_terms[node], node))
data['vertices'][node]['topic'] = topic_id
topic = sorted(topic, reverse=True)
subtopics = dict(top=[],
total=0)
subtopic_list = [dict(centrality=node_centralities[i[2]],
topic_label=node_terms[i[2]],
weight=node_weights[i[2]],
vertex=i[2],
topic=topic_id
) for i in topic[1:]]
if verbose:
subtopics = dict(top=[i for i in subtopic_list[0:10]],
total=len(subtopic_list))
else:
subtopics = dict(top=[i['vertex'] for i in subtopic_list[0:10]],
total=len(subtopic_list))
topics.append(dict(topic_label=topic[0][1],
connected_topics=subtopics,
weight=node_weights[topic[0][2]],
centrality=node_centralities[topic[0][2]],
vertex=topic[0][2],
topic=topic_id
)
)
else:
nodes_to_delete.extend(com_nodes)
if nodes_to_delete:
nodes_to_delete = sorted(nodes_to_delete)
new_node_map = {}
offset = 0
for i, node in enumerate(data['vertices']):
if i in nodes_to_delete:
offset += 1
else:
new_node_map[i] = i - offset
data['vertices'] = [v for i, v in enumerate(data['vertices']) if i not in nodes_to_delete]
new_connections = []
for c in data['connections']:
if c['source'] not in nodes_to_delete and c['target'] not in nodes_to_delete:
c['source'] = new_node_map[c['source']]
c['target'] = new_node_map[c['target']]
new_connections.append(c)
data['connections'] = new_connections
for topic in topics:
topic['vertex'] = new_node_map[topic['vertex']]
# if 'topic' not in node:
# print i,nodes_to_delete.index(i)+1
# del data['vertices'][]
topics = sorted(topics, key=lambda x: (x['centrality'], x['weight']), reverse=True)
if not verbose:
for t in topics:
del t['centrality']
del t['weight']
del t['topic_label']
return data, topics
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def angle_between(v1, v2):
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
# print np.degrees(np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)))
return np.degrees((np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))))
@app.route('/trends')
def trends2():
query = request.args.get('query')
years_to_consider = 15
query_body = {
"query": {
"bool": {
"must": [
{"query_string": {"query": query}},
{"range": {
"pub_date": {"gte": "now-%sy/y" % years_to_consider,
"le": "now-1y/y"}
}
}
]
}
},
"aggs": {
# "sample": {
# "diversified_sampler": {
# "shard_size": 300000,
# "field" : "journal.medlineAbbreviation"#TODO: index the first and the last authors as single value
# to allow for a proper diversification here
# },
# "sampler": {
# "shard_size": 500000,
# },
# "aggs": {
"docs_per_year": {
"date_histogram": {
"field": "pub_date",
"interval": "year",
"format": "yyyy",
"keyed": True
},
"aggs": {
"global_moving_average": {
"moving_avg": {"buckets_path": "_count",
"window": 3,
"model": "holt",
"settings": {
"alpha": .8,
"beta": 0.3
},
"predict": 2
}
}
}
},
"entities": {
"terms": {
"field": "text_mined_entities.noun_phrases.top_chunks",
# "jlh": {
# "include_negatives": False,
# },
# "min_doc_count":2*years_to_consider,
# "background_filter": {
# "query_string": {"query": query},
# },
"size": 1000,