forked from menchelab/Analytics_Module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tables.py
2013 lines (1772 loc) · 72.6 KB
/
tables.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 random
import datetime
import time
import sys
import os
import json
try:
from db_config import DATABASE as dbconf
from table_utils.taxonomy import *
import populate_db_data_agnostic
except:
from .db_config import DATABASE as dbconf
from .table_utils.taxonomy import *
from .populate_db_data_agnostic import *
import logging
import pymysql
import pymysql.cursors
import random
import networkx as nx
import numpy as np
import pandas as pd
from collections import defaultdict
#from fisher import pvalue
import scipy.stats as stats
# Cache database call for attribute taxonomy to prevent repeated queries.
def get_cached_edges(cache, db_namespace):
zkey = "edges_" + db_namespace
dtc = cache.get(zkey)
if dtc is None:
# print("!!!!!!! querying")
query = """
SELECT edges.node1_id, edges.node2_id
FROM %s.edges
""" % db_namespace
cursor = Base.execute_query(query)
edges = cursor.fetchall()
dtc = [[x["node1_id"], x["node2_id"]] for x in edges]
cache.set(zkey, dtc, timeout=5 * 60 * 60 * 24)
return dtc
class Base:
@staticmethod
def execute_query(query, db = None):
if not db:
db = dbconf['database']
# print(db)
connection = pymysql.connect(host=dbconf["host"],
user=dbconf["user"],
password=dbconf["password"],
db=db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
#print(query)
cursor.execute(query)
connection.commit()
connection.close()
return cursor
def execute_queries(queries, db = None):
if not db:
db = dbconf['database']
connection = pymysql.connect(host=dbconf["host"],
user=dbconf["user"],
password=dbconf["password"],
db=db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
#print(query)
for query in queries:
cursor.execute(query)
connection.commit()
connection.close()
return cursor
@staticmethod
def sanitize_string(string):
string = string.replace("'", r"\'")
return string
class Data:
@staticmethod
def describe_namespace(db_namespace):
# print(db_namespace)
query = """
SELECT DISTINCT namespace from %s.layouts
""" % db_namespace
cursor = Base.execute_query(query)
layouts = cursor.fetchall()
query = """
SELECT DISTINCT namespace from %s.labels
""" % db_namespace
cursor = Base.execute_query(query)
labels = cursor.fetchall()
return {"namespace": db_namespace,
"layouts": [x["namespace"] for x in layouts],
"labels": [x["namespace"] for x in labels]}
@staticmethod
def summary():
query = """
SELECT name FROM Vrnetzer_meta.namespaces
"""
cursor = Base.execute_query(query)
namespaces = [x["name"] for x in cursor.fetchall()]
# print(namespaces)
return [Data.describe_namespace(namespace) for namespace in namespaces]
class Node:
@staticmethod
def all(db_namespace):
query = """
SELECT DISTINCT name, symbol, id FROM %s.nodes
""" % db_namespace
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def get(db_namespace, node_ids):
query = """
SELECT DISTINCT name, symbol, id FROM %s.nodes where id in (%s)
""" % (db_namespace, ",".join(node_ids))
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def get_sym_name(db_namespace, node_ids):
# print('get functions gets:', node_ids)
# print('and makes sql strg:', ",".join(node_ids))
spc = [str(x)+',' for x in node_ids]
spl_str = ''
spl_str = spl_str.join(spc)
spl_str = '(' + spl_str[:-1] + ')'
# print(spl_str)
query = """
SELECT DISTINCT name, symbol, id as node_id FROM %s.nodes where id in %s
""" % (db_namespace,spl_str)
cursor = Base.execute_query(query)
return cursor.fetchall()
# CS: get single one
@staticmethod
def get_single_sym_name(db_namespace, node_id):
# print('get functions gets:', node_id)
query = """
SELECT DISTINCT name, symbol, id as node_id FROM %s.nodes where id = %s
""" % (db_namespace,node_id)
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def get_neighbors(db_namespace, node_ids):
query = """
SELECT DISTINCT name, symbol, nodes.id FROM %s.nodes
JOIN %s.edges on nodes.id = edges.node1_id
WHERE edges.node2_id in (%s)
""" % (db_namespace, db_namespace, ",".join(node_ids))
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def get_by_external_ids(db_namespace, external_ids):
query = """
SELECT DISTINCT name, symbol, id FROM %s.nodes where external_id in (%s)
""" % (db_namespace, ",".join(external_ids))
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def get_by_symbols(db_namespace, symbols):
query = """
SELECT DISTINCT name, symbol, id FROM %s.nodes where symbol in ('%s')
""" % (db_namespace, "','".join(symbols))
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def show_random(num_to_show, db_namespace):
query = "SELECT name, symbol, id FROM %s.nodes ORDER BY RAND() LIMIT %d" % (db_namespace, num_to_show)
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def nodes_for_attribute(db_namespace, attr_id):
#JOIN %s.attribute_taxonomies ON nodes_attributes.attribute_id = attribute_taxonomies.child_id
# AND attribute_taxonomies.parent_id in (%s)
query = """
SELECT DISTINCT nodes.id AS node_id, nodes.name, nodes.symbol
FROM %s.nodes
JOIN %s.nodes_attributes ON nodes.id = nodes_attributes.node_id
JOIN %s.attribute_taxonomies at on at.child_id = attribute_id
AND parent_id in (%s)
""" % (db_namespace, db_namespace, db_namespace, ",".join(attr_id))
cursor = Base.execute_query(query)
return {"nodes": cursor.fetchall()}
@staticmethod
def nodes_for_autocomplete(db_namespace, name_prefix):
query = """
SELECT nodes.id, nodes.symbol, nodes.name
FROM %s.nodes
WHERE LOWER(nodes.symbol) like LOWER('%s')
OR LOWER(nodes.name) like LOWER('%s')
""" % (db_namespace, Base.sanitize_string(name_prefix) + '%', Base.sanitize_string(name_prefix) + '%')
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def gene_card(namespace, node, cache):
# num_trials = 100000
query = """
SELECT * FROM %s.gene_card WHERE node_id = %s
""" %(namespace,node)
cursor = Base.execute_query(query)
data = cursor.fetchall()
# print(data)
nid = [x["node_id"] for x in data][0]
symbol = [x["symbol"] for x in data][0]
name = [x["gene_name"] for x in data][0]
k = [x["degree"] for x in data][0]
funs = [x["functions"] for x in data][0]
dis = [x["diseases"] for x in data][0]
# print(nid,symbol,name,k)
# print(funs)
l_functions = []
if funs != None:
for fs in funs.split('|'):
l_functions.append(fs)
l_diseases = []
if dis != None:
for ds in dis.split('|'):
l_diseases.append(ds)
# print('gene_data', gene_data)
query2 = """
SELECT
aa.external_id symbol,
na.value value
FROM %s.nodes_attributes na
INNER JOIN %s.attributes aa
ON na.attribute_id = aa.id
WHERE na.node_id = %s
AND aa.namespace = 'GTEx'
""" %(namespace,namespace,node)
cursor = Base.execute_query(query2)
data2 = cursor.fetchall()
gene_data = [{'node_id': nid,'symbol': symbol,'name': name, 'degree': k,
'functions': l_functions, 'diseases': l_diseases,
'tissue': data2}]
# print('gene_data', gene_data)
return gene_data
## IP_CELINE: implement GSEA
@staticmethod
def gsea(namespace, selectionNodes, currAnno):
if selectionNodes is None:
selectionNodes = (1,2,3,4,5,6,7,8)
if currAnno is None:
query = """
SELECT DISTINCT namespace FROM %s.attributes
"""%(namespace)
cursor = Base.execute_query(query)
allAnnos = cursor.fetchall()
annos_string = "('" + "', '".join([item['namespace'] for item in allAnnos]) + "')"
else:
annos_string = "('" + currAnno + "')"
# print('the anno string is ' + annos_string)
nodes_string = "(" + ",".join([str(node) for node in selectionNodes]) + ")"
# print('the nodes string is ' + nodes_string)
# for currAnno, make dictionary of terms > gene, genes > term
t00 = time.time()
query = """
SELECT n_att.node_id, n_att.attribute_id
FROM %s.attributes att INNER JOIN %s.nodes_attributes n_att
ON att.id = n_att.attribute_id
WHERE att.namespace IN %s;
"""%(namespace, namespace, annos_string)
cursor = Base.execute_query(query)
data_background = cursor.fetchall()
# print(len(data_background))
att2node = defaultdict(list)
node2att = defaultdict(list)
for eaItem in data_background:
att = eaItem['attribute_id']
node = eaItem['node_id']
att2node[att].append(node)
node2att[node].append(att)
# print('time to make background dictionaries: ' + str(time.time() - t00))
# print(len(att2node))
# collect set of annoTerms in selectionNodes
# also make translation dictionary between attribute ID and human readable
# also make translation dictionary between attribute ID and annotype
t01 = time.time()
query = """
SELECT n_att.node_id, n_att.attribute_id, att.name, att.namespace
FROM %s.attributes att INNER JOIN %s.nodes_attributes n_att
ON att.id = n_att.attribute_id
WHERE n_att.node_id IN %s
AND att.namespace IN %s;
""" %(namespace, namespace, nodes_string, annos_string)
cursor = Base.execute_query(query)
data_sample = cursor.fetchall()
att2node_s = defaultdict(list)
node2att_s = defaultdict(list)
dict_attType2attID = defaultdict(list)
dict_attID2humanreadable = {}
dict_attID2annoType = {}
for eaItem in data_sample:
att_id = eaItem['attribute_id']
att_human = eaItem['name']
att_type = eaItem['namespace']
node_id = eaItem['node_id']
att2node_s[att_id].append(node_id)
node2att_s[node].append(att_id)
dict_attID2humanreadable[att_id] = att_human
dict_attID2annoType[att_id] = att_type
dict_attType2attID[att_type].append(att_id)
# print('time to make sample dictionaries: ' + str(time.time() - t01))
# print('time to make dictionaries: ' + str(time.time() - t00))
# print(dict_attType2attID['DISEASE'])
# fisher tests!
fisherPs_attributes = []
allTerms = []
allPs = []
annoList = []
numTests = []
for eaTerm in att2node_s:
# count # of selectionNodes with eaTerm
a = len(att2node_s[eaTerm])
# count # of selectionNodes wo eaTerm
b = len(node2att_s) - a
# count # of unSelectionNodes w eaTerm
c = len(set(att2node[eaTerm]) - set(att2node_s[eaTerm]))
# count # of unSelectionNodes wo eaTerm
d = len(node2att) - a - b - c
# calculate fisher test, number of tests (#annotations)
allTerms.append(dict_attID2humanreadable[eaTerm])
oddsratio, pvalue = stats.fisher_exact([[a, b], [c, d]])
allPs.append(pvalue)
annoList.append(dict_attID2annoType[eaTerm])
numTests.append(len(dict_attType2attID[dict_attID2annoType[eaTerm]]))
# make dataframe
d = {'term': allTerms,
'pval': allPs,
'annoType': annoList,
'numTests': numTests}
df = pd.DataFrame(data=d)
# bonferroni correction
df['corrected'] = df.apply(lambda x: min(x['pval']*x['numTests'], 1), axis=1)
df['toPlot'] = 1 - df['corrected']
# sort and return top values
toReport = df.sort_values(by=['toPlot'], ascending=False)
toReport = toReport[:20]
for index, row in toReport.iterrows():
fisherPs_attributes.append({'term': row['term'],
'annoType': row['annoType'],
'toPlot': row['toPlot'],
'pval': row['pval'],
'numTests': row['numTests']})
#print(fisherPs_attributes)
return fisherPs_attributes
@staticmethod
def random_walk(namespace, starting_nodes, variants, restart_probability, max_elements, cache):
num_trials = 100000
edges = get_cached_edges(cache, namespace)
neighbors = {}
for edge in edges:
if edge[0] not in neighbors.keys():
neighbors[edge[0]] = [edge[1]]
else:
neighbors[edge[0]].append(edge[1])
visited_nodes = [0] * 20000
starting_node = random.choice(starting_nodes)
for i in range (num_trials):
if random.random() < restart_probability:
starting_node = random.choice(starting_nodes)
else:
starting_node = random.choice(neighbors[starting_node])
visited_nodes[starting_node] += 1
query2 = """
SELECT DISTINCT name, symbol, id FROM %s.nodes
""" % namespace
cursor = Base.execute_query(query2)
d_i_name = cursor.fetchall()
d_i_name = {x["id"]: x["symbol"] for x in d_i_name}
# set group 0 for seed, group 2 for genes matching with given variant list, 1 else
d_node2group = {}
# print('visited nodes',visited_nodes )
for i, x in enumerate(visited_nodes):
if i in starting_nodes:
d_node2group[i] = 0
elif i in variants:
d_node2group[i] = 2
else:
d_node2group[i] = 1
min_frequency = 0
kept_values = [{'id': i,'symbol': d_i_name[i],'group': d_node2group[i], 'frequency': 1.0*x/num_trials} for i, x in enumerate(visited_nodes) if x > min_frequency*num_trials]
# print('kept_values:', kept_values)
kept_values.sort(key=lambda x: x['frequency'], reverse=True)
kept_values = kept_values[:max_elements]
# add variants if not empty
if len(variants)>0:
add_variants = [{'id': i,'symbol': d_i_name[i],'group': d_node2group[i], 'frequency': 1.0*x/num_trials} for i, x in enumerate(visited_nodes) if i in variants]
add_variants.sort(key=lambda x: x['frequency'], reverse=True)
# print('added variants', add_variants)
kept_values += add_variants
# print('added variants', add_variants)
kept_node_ids = [x['id'] for x in kept_values]
edges_kept = [(x,y) for x,y in edges if (x in kept_node_ids and y in kept_node_ids)]
# print('edges:', edges_kept)
l_edges_kept = [{'source':s,'target':t,'value':1} for s,t in edges_kept]
d_data_kept = {'nodes': kept_values,'links': l_edges_kept}
return d_data_kept
@staticmethod
def shortest_path(db_namespace, from_id, to_id):
#DB query for edges
# print("Path from ", from_id," to ",to_id)
query = """
SELECT edges.node1_id, edges.node2_id
FROM %s.edges
""" % db_namespace
cursor = Base.execute_query(query)
edges = cursor.fetchall()
G = nx.Graph()
for x in edges:
s = x['node1_id']
t = x['node2_id']
G.add_edge(s,t)
sp = nx.shortest_path(G, source=int(from_id), target=int(to_id))
# print('path nodes:', sp)
# get symbol and name, but in order (CSedit: 20200710)
# TODO: do this in not stupid way.
out_str = ''
for eaSp in sp:
sym_name_data = Node.get_single_sym_name(db_namespace, eaSp)
out_str += str(json.dumps(sym_name_data))[1:-1] + ','
json_out = '{"nodes":[' + out_str[:-1] + ']}'
return json_out
@staticmethod
def connect_set_dfs(db_namespace, seeds, variants, cache):
edges = get_cached_edges(cache, db_namespace)
G = nx.Graph()
for x in edges:
# s = x['node1_id']
# t = x['node2_id']
s = x[0]
t = x[1]
G.add_edge(s,t)
l_linkerset = []
for start_variant in variants:
# start_variant = list(l_vars_onppi)[1]
# print('start at variant: %s (k = %s)' %(start_variant,G_ppi.degree(start_variant)))
cc = 1
for path in nx.dfs_edges(G,start_variant,2):
if path[0] in seeds:
# print(cc,set(path),'SEED REACHED at d=1')
l_linkerset.append(path[0])
if path[1] in seeds:
# print(cc,set(path),'SEED REACHED at d=2')
l_linkerset.append(path[0])
l_linkerset.append(path[1])
else:
pass
# print(cc,set(path))
cc += 1
set_linkers = set(l_linkerset) - set(seeds)
out_str = '{"seeds":['
for x in seeds:
out_str += str(json.dumps(x)) + ','
out_str = out_str[:-1] + '],"variants":['
for x in variants:
out_str += str(json.dumps(x)) + ','
out_str = out_str[:-1] + '],"linker":['
for x in set_linkers:
out_str += str(json.dumps(x)) + ','
out_str = out_str[:-1] + ']}'
return out_str
################################################################################
################################################################################
@staticmethod
def random_walk_dock2(namespace, starting_nodes, variants, restart_probability, max_elements, cache):
num_trials = 100000
edges = get_cached_edges(cache, namespace)
neighbors = {}
for edge in edges:
if edge[0] not in neighbors.keys():
neighbors[edge[0]] = [edge[1]]
else:
neighbors[edge[0]].append(edge[1])
visited_nodes = [0] * 20000
starting_node = random.choice(starting_nodes)
for i in range (num_trials):
if random.random() < restart_probability:
starting_node = random.choice(starting_nodes)
else:
starting_node = random.choice(neighbors[starting_node])
visited_nodes[starting_node] += 1
query2 = """
SELECT DISTINCT name, symbol, id FROM %s.nodes
""" % namespace
cursor = Base.execute_query(query2)
d_i_name = cursor.fetchall()
d_i_name = {x["id"]: x["symbol"] for x in d_i_name}
# set group 0 for seed, group 2 for genes matching with given variant list, 1 else
d_node2group = {}
# print('visited nodes',visited_nodes )
for i, x in enumerate(visited_nodes):
if i in starting_nodes:
d_node2group[i] = 0
elif i in variants:
d_node2group[i] = 2
else:
d_node2group[i] = 1
min_frequency = 0
kept_values = [{'id': i,'symbol': d_i_name[i],'group': d_node2group[i], 'frequency': 1.0*x/num_trials} for i, x in enumerate(visited_nodes) if x > min_frequency*num_trials]
# print('kept_values:', kept_values)
kept_values.sort(key=lambda x: x['frequency'], reverse=True)
kept_values = kept_values[:max_elements]
# add variants if not empty
if len(variants)>0:
add_variants = [{'id': i,'symbol': d_i_name[i],'group': d_node2group[i], 'frequency': 1.0*x/num_trials} for i, x in enumerate(visited_nodes) if i in variants]
add_variants.sort(key=lambda x: x['frequency'], reverse=True)
# print('added variants', add_variants)
kept_values += add_variants
##########################
# Attach variants to seeds with deep-first-search
G = nx.Graph()
for x in edges:
# s = x['node1_id']
# t = x['node2_id']
s = x[0]
t = x[1]
G.add_edge(s,t)
# print(G.number_of_nodes())
# print(G.number_of_edges())
seeds = starting_nodes
# print(seeds)
l_linkerset = []
for start_variant in variants:
# start_variant = list(l_vars_onppi)[1]
# print('start at variant: %s (k = %s)' %(start_variant,G_ppi.degree(start_variant)))
cc = 1
for path in nx.dfs_edges(G,start_variant,2):
if path[0] in seeds:
# print(cc,set(path),'SEED REACHED at d=1')
l_linkerset.append(path[0])
if path[1] in seeds:
# print(cc,set(path),'SEED REACHED at d=2')
l_linkerset.append(path[0])
l_linkerset.append(path[1])
else:
pass
# print(cc,set(path))
cc += 1
set_nodes = set(l_linkerset) | set(seeds) | set(variants)
edges_kept = [(x,y) for x,y in edges if (x in set_nodes and y in set_nodes)]
# joerg anfang
# adding all nodes in set_nodes to the list of kept_values
# find missing nodes:
missing_nodes = set_nodes - set([x['id'] for x in kept_values])
#print ("%s %s %s nodes report" % (len(missing_nodes),len(set_nodes),len(set([x['id'] for x in kept_values]))))
# add the missing nodes with correct info (hardcoding 0 as frequency:
missing_nodes_with_info = [{'id': i,'symbol': d_i_name[i],'group': d_node2group[i], 'frequency': 0.0} for i in missing_nodes]
kept_values += missing_nodes_with_info
#print ( missing_nodes_with_info)
# joerg ende
l_edges_kept = [{'source':s,'target':t,'value':1} for s,t in edges_kept]
d_data_kept = {'nodes': kept_values,'links': l_edges_kept}
return d_data_kept
################################################################################
################################################################################
@staticmethod
def layout(db_namespace, nodes,cache):
edges = get_cached_edges(cache, db_namespace)
G = nx.Graph()
for x in edges:
s = x[0]
t = x[1]
G.add_edge(s,t)
G_sub = nx.subgraph(G,nodes)
Glcc = G_sub.subgraph(max(nx.connected_components(G_sub), key=len)) # extract lcc graph
pos = nx.spring_layout(Glcc,dim=3,iterations=50)
# NORMALIZAION
l_x = [xyz[0] for k, xyz in sorted(pos.items())]
l_y = [xyz[1] for k, xyz in sorted(pos.items())]
l_z = [xyz[2] for k, xyz in sorted(pos.items())]
x_min = min(l_x)
x_max = max(l_x)
y_min = min(l_y)
y_max = max(l_y)
z_min = min(l_z)
z_max = max(l_z)
l_xn = [(x-x_min)/(x_max-x_min) for x in l_x]
l_yn = [(y-y_min)/(y_max-y_min) for y in l_y]
l_zn = [(z-z_min)/(z_max-z_min) for z in l_z]
pos_norm = {}
for i,gene in enumerate(sorted(pos.keys())):
pos_norm[gene] = (l_xn[i],l_yn[i],l_zn[i])
result = [{'a': [str(i)], 'v': [xyz[0],xyz[1],xyz[2],0,0,0,0]} for i, xyz in pos_norm.items()]
# print('result:', result)
return result
@staticmethod
def scale_selection(db_namespace, nodes,layout,cache):
a = .2
str_nodes = ",".join(nodes)
# print(str_nodes)
query = """
SELECT
node_id,
x_loc,
y_loc,
z_loc
FROM %s.layouts
WHERE namespace = '%s'
AND node_id in (%s)
""" %(db_namespace,layout,str_nodes)
cursor = Base.execute_query(query)
data = cursor.fetchall()
# print(data)
d_node_xyz = {x["node_id"]: (x["x_loc"],x["y_loc"],x["z_loc"]) for x in data}
xm = np.mean([x['x_loc'] for x in data])
ym = np.mean([x['y_loc'] for x in data])
zm = np.mean([x['z_loc'] for x in data])
d_node_xyz_scaled = {}
for node, xyz in d_node_xyz.items():
x = xyz[0]
xs = a*x + (1-a)*xm
y = xyz[1]
ys = a*y + (1-a)*ym
z = xyz[2]
zs = a*z + (1-a)*zm
d_node_xyz_scaled[node] = (xs,ys,zs)
result = [{'a': [str(i)], 'v': [xyz[0],xyz[1],xyz[2],0,0,0,0]} for i, xyz in d_node_xyz_scaled.items()]
return result
@staticmethod
def search(db_namespace, clauses):
# print(clauses)
have_name = False
have_attributes = False
filter_clauses = []
select_clauses = []
def filter_clause(subject, object):
# print(subject)
if subject == "name_like":
have_name = True
return [" LOWER(nodes.symbol) like LOWER('%s') " % (Base.sanitize_string(object) + "%"),
["name", object.lower()]]
column = ""
else:
# column = "attribute_id"
column = "parent_id"
have_attributes = True
return ["%s = '%s'" % (column, object),
[column, object]]
# def get_summary_stats(gene_set):
# query = """
# SELECT attributes.name, prevalence, count(distinct jgenes.id) as gene_number
# FROM attributes
# JOIN attribute_taxonomies on diseases.id = parent_id
# JOIN nodes_attributes ON nodes_attibutes.attriute_id = child_id
# JOIN (select * from nodes where id in (%s)) jgenes ON jgenes.id = nodes_attributes.node_id
# JOIN disease_counts on disease_counts.disease_id = diseases.id
# WHERE prevalence > 25
# GROUP BY 1, 2
# ORDER BY 3 DESC
# LIMIT 200
# """ % ",".join([str(gene["entrez_id"]) for gene in gene_set])
# cursor = Base.execute_query(query)
# results = cursor.fetchall()
# results = [{"name": x["name"], "gene_number": round(x["gene_number"]/x["prevalence"]* len(results), 2)} for x in results]
# results.sort(reverse=True, key=lambda x: x["gene_number"])
# return results[:10]
for x in range(5):
andor = clauses["predicate%d" % x] if "predicate%d" % x in clauses else "AND"
if "subject%d" % x not in clauses or clauses["subject%d" % x] == "undefined" \
or "object%d" % x not in clauses or clauses["object%d" % x] == "undefined":
break
if clauses["subject%d" % x] == "name_like":
have_name = True
else:
have_attributes = True
new_clause = filter_clause(clauses["subject%d" % x], clauses["object%d" % x] )
if andor == "AND":
filter_clauses.append(new_clause[0])
select_clauses.append([new_clause[1]])
else:
filter_clauses[-1]= filter_clauses[-1] + " OR " + new_clause[0]
select_clauses[-1].append(new_clause[1])
if not filter_clauses:
print("no filter clauses!")
return({"nodes": [], "summary_stats": []})
if have_name and not have_attributes:
name_select_clause = """
SELECT id AS node_id, name, symbol FROM %s.nodes WHERE
""" % db_namespace
query = name_select_clause + " AND ".join(filter_clauses)
cursor = Base.execute_query(query)
nodes = cursor.fetchall()
return({"nodes": nodes})
# print(filter_clauses)
# print(have_attributes)
nodes_to_names = {}
nodes_to_attributes = {}
if have_attributes:
name_attribute_select_clause = """
SELECT DISTINCT node_id, nodes.name, nodes.symbol,
GROUP_CONCAT(DISTINCT attribute_taxonomies.parent_id) as attribute_id
FROM %s.nodes
JOIN %s.nodes_attributes ON nodes.id = nodes_attributes.node_id
JOIN %s.attribute_taxonomies ON nodes_attributes.attribute_id = attribute_taxonomies.child_id
WHERE %s
GROUP BY 1, 2, 3
""" % (db_namespace, db_namespace, db_namespace, " OR ".join(filter_clauses))
query = name_attribute_select_clause
#print(query)
cursor = Base.execute_query(query)
attr_table = cursor.fetchall()
nodes_to_attributes = {x["node_id"]: x["attribute_id"].split(",") for x in attr_table}
nodes_to_names = {x["node_id"]: {'name': x['name'], 'symbol': x['symbol']} for x in attr_table}
#nodes_to_attributes = {**nodes_to_attributes, **nodes_to_attributes_d}
candidate_nodes = set(nodes_to_attributes.keys())
#print("candidate_nodes", candidate_nodes)
print(len(candidate_nodes))
for clause in select_clauses:
keep_nodes = set()
for subclause in clause:
# print(clause)
# print(subclause)
if subclause[0] == "name":
new_candidates = [x for x in candidate_nodes if subclause[1].lower() in nodes_to_names[x]["name"]]
else:
new_candidates = [x for x in candidate_nodes if subclause[1] in nodes_to_attributes[x]]
for x in new_candidates:
keep_nodes.add(x)
candidate_nodes = keep_nodes
nodes = [{"node_id": x, "name": nodes_to_names[x]["name"], "symbol": nodes_to_names[x]["symbol"]} for x in candidate_nodes]
return({"nodes": nodes})
class Attribute:
@staticmethod
def attributes_for_node(db_namespace, node_id, attr_namespace=None):
namespace_clause = " AND a.namespace = \"%s\"" % attr_namespace if attr_namespace else ""
query = """
SELECT DISTINCT a.id, a.external_id, a.name, a.description, a.namespace, distance, na.value
FROM %s.attributes a
JOIN %s.attribute_taxonomies at ON a.id = at.parent_id
JOIN %s.nodes_attributes na ON na.attribute_id = at.child_id
WHERE node_id = %s
%s
""" % (db_namespace, db_namespace, db_namespace, node_id, namespace_clause)
cursor = Base.execute_query(query)
results = cursor.fetchall()
attributes = {}
for result in results:
if result["id"] in attributes:
attributes[result["id"]] = attributes[result["id"]] + [""] * (result["distance"] + 1 - len(attributes[result["id"]]))
attributes[result["id"]][result["distance"]] = result["name"]
else:
attributes[result["id"]] = [""] * (result["distance"]) + [result["name"]]
return [{"id": result["id"],
"full_name": "/".join(attributes[result["id"]][:-1][::-1]),
"external_id": result["external_id"],
"name": result["name"],
"value": result["value"],
"description": result["description"]} for result in results]
@staticmethod
def children(db_namespace, attr_id):
query = """
SELECT nodes.id, nodes.name, nodes.symbol
FROM %s.nodes n JOIN %s.attribute_taxonomies at on %s.id = at.child_id
WHERE parent_id = %s
""" % (db_namespace, attr_id)
@staticmethod
def delete(db_namespace, attribute_id):
query1 = """
DELETE from %s.attribute_taxonomies
WHERE parent_id = %d or child_id = %d;
""" %(db_namespace, attribute_id, attribute_id)
query2 = """
DELETE from %s.nodes_attributes
WHERE attribute_id = %d;
""" %(db_namespace, attribute_id)
query3 = """
DELETE from %s.attributes
WHERE id = %d;
""" %(db_namespace, attribute_id)
cursor = base.execute_queries([query1, query2, query3])
@staticmethod
def attributes_for_autocomplete(db_namespace, name_prefix, attr_namespace=None):
namespace_clause = " AND namespace = \"%s\"" % attr_namespace if attr_namespace else ""
query = """
SELECT attributes.id, attributes.external_id, attributes.name, namespace
FROM %s.attributes
WHERE LOWER(attributes.name) like LOWER('%s')
%s
""" % (db_namespace, Base.sanitize_string(name_prefix) + '%', namespace_clause)
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def attributes_for_external_ids(db_namespace, external_ids, attr_namespace=None):
namespace_clause = " AND namespace = \"%s\"" % attr_namespace if attr_namespace else ""
query = """
SELECT attributes.id, attributes.external_id, attributes.name, namespace
FROM %s.attributes
WHERE attributes.external_id in ('%s')
%s
""" % (db_namespace, "','".join(external_ids), namespace_clause)
#print(query)
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def all_attribute_names(db_namespace, attr_namespace=None):
namespace_clause = " WHERE namespace = \"%s\"" % attr_namespace if attr_namespace else ""
query = """
SElECT DISTINCT attributes.id, attributes.external_id, attributes.name, namespace
FROM %s.attributes
%s
""" % (db_namespace, namespace_clause)
cursor = Base.execute_query(query)
return cursor.fetchall()
@staticmethod
def get_attribute_namespaces(db_namespace):
query = """
SElECT DISTINCT namespace
FROM %s.attributes
""" % (db_namespace)
cursor = Base.execute_query(query)
namespaces = cursor.fetchall()
return [x["namespace"] for x in namespaces]
@staticmethod
def create_selection(db_namespace, selection_name, node_ids):
#Validate that the namespace is new
query = """
SELECT * FROM %s.attributes
WHERE namespace = "SELECTION"
AND LOWER(name) like "%s"
LIMIT 1
""" %(db_namespace, selection_name.lower())
cursor = Base.execute_query(query)
namespaces = cursor.fetchall()
if namespaces:
return({"status": "FAIL", "reason": "selection with that name already exists"})
# Validate node IDs.
node_ids = set(node_ids)
query = """
SELECT id FROM %s.nodes
WHERE id in (%s)
""" %(db_namespace, ",".join([str(x) for x in node_ids]))
cursor = Base.execute_query(query)
matched_ids = {x["id"] for x in cursor.fetchall()}
print(matched_ids)
if len(matched_ids) < len(node_ids):
unmatched = set(node_ids) - matched_ids
return({"status": "FAIL", "reason": "invalid node IDs in query: %s" % ",".join([str(x) for x in unmatched])})
query = """
INSERT INTO %s.attributes(name, namespace)
VALUES ("%s", "SELECTION")
""" %(db_namespace, selection_name)
cursor = Base.execute_query(query)
query = """
SELECT id
FROM %s.attributes
ORDER BY id desc
LIMIT 1
""" %(db_namespace)
cursor = Base.execute_query(query)
attr_id = cursor.fetchone()["id"]
query = """
INSERT INTO %s.attribute_taxonomies(child_id, parent_id, distance, namespace)
VALUES (%d, %d, 0, "SELECTION")
""" % (db_namespace, attr_id, attr_id)
cursor = Base.execute_query(query)
query = """
INSERT INTO %s.nodes_attributes(node_id, attribute_id)
VALUES %s
""" %(db_namespace, ",".join(['(%s, %d)' % (x, attr_id) for x in node_ids]))
cursor = Base.execute_query(query)
return {"status":"OK"}
@staticmethod
def attribute2attribute(db_namespace,att_id):
query = """
SELECT
# aa1.external_id,
# aa1.name,
aa2.id int_id,
aa2.name phenotype
FROM %s.attribute_relations ar
INNER JOIN %s.attributes aa1
ON aa1.id = ar.attr1_id
INNER JOIN %s.attributes aa2
ON aa2.id = ar.attr2_id
WHERE ar.attr1_id = '%s'
""" % (db_namespace,db_namespace,db_namespace,att_id)
cursor = Base.execute_query(query)
data = cursor.fetchall()
# print(data)
# return [x["namespace"] for x in namespaces]
return data