-
Notifications
You must be signed in to change notification settings - Fork 3
/
run.py
1266 lines (1156 loc) · 51 KB
/
run.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 flask import Flask, render_template, request, jsonify, redirect, url_for
import os, sys, json
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from Bio import SearchIO
from Bio.Blast import NCBIXML
from matplotlib import cm
import pandas as pd
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
#sys.path.insert(1, 'static/predictor/')
#from precogxb_app.static.predictor import precogx
sentry_sdk.init(
dsn="https://6c93d4e351124e8db02e5526e334072b@o4505080802312192.ingest.sentry.io/4505081392726016",
integrations=[
FlaskIntegration(),
],
traces_sample_rate=1.0,
profiles_sample_rate=1.0
)
app = Flask(__name__)
##
path = os.getcwd()
path = app.root_path
sys.path.insert(1, path + '/static/predictor/')
import precogx
## Route to home page
@app.route('/', methods=['GET', 'POST'])
@app.route('/home', methods=['GET', 'POST'])
def home():
return render_template('index.html')
@app.route('/error', methods=['GET', 'POST'])
def error():
return render_template('error.html')
def sortPositions(positions):
data = []
for position in positions:
if position not in ['Nterm', 'Cterm']:
'''
if '.' in position:
base = position.split('.')[0]
#value = int(position.split('.')[1])
value = int(position.split('.')[1])*(10**(len(position.split('.')[1])*(-1)))
else:
base = position
value = 0
'''
if 'x' in position:
base = position.split('x')[0]
#value = int(position.split('.')[1])
value = int(position.split('x')[1])*(10**(len(position.split('x')[1])*(-1)))
else:
base = position
value = 0
if 'ICL' in base:
if base == 'ICL1':
order = 1.5
elif base == 'ICL2':
order = 3.5
else:
order = 5.5
elif 'ECL' in base:
if base == 'ECL1':
order = 2.5
elif base == 'ECL2':
order = 4.5
else:
order = 6.5
else:
order = int(base)
else:
if position == 'Nterm':
base = 0
order = 0
value = 0
else:
base = 9
order = 9
value = 0
#print (position, base, order, value)
row = []
row.append(position)
row.append(order)
row.append(base)
row.append(value)
data.append(row)
df = pd.DataFrame(data, columns = ['position', 'order', 'base', 'value'])
df = df.sort_values(['order','value'],ascending=[True, True])
#print (df.to_numpy())
positions = []
for row in df.to_numpy():
positions.append(row[0])
return (np.array(positions))
def extract_contacts(gprotein_given, cutoff, distance):
assay = ''
for line in open(path+'/data/contacts/gprotein_best_layer.txt', 'r'):
if gprotein_given == line.split('\t')[0]:
assay = line.split('\t')[1]
#print (gprotein_given)
dic = {}; positions = []; pair_positions = []; scores = [];
'''
for line in open(path+'/data/contacts/all_positions_count_'+assay+'_scaled_web_old.txt', 'r'):
gprotein_found = line.split('\t')[0]
if gprotein_given == gprotein_found:
#print ('here')
pos1 = line.split('\t')[-2]
pos2 = line.replace('\n', '').split('\t')[-1]
score = float(line.replace('\n','').split('\t')[1])
if score >= cutoff or score <= (-1.0)*cutoff:
if pos1 not in dic:
dic[pos1] = {}
dic[pos1][pos2] = score
if pos2 not in dic:
dic[pos2] = {}
dic[pos2][pos1] = score
if pos1 not in positions:
positions.append(pos1)
#positions.append(pos1)
if pos2 not in positions:
positions.append(pos2)
pair_positions.append(pos1+':'+pos2+':'+str(score))
scores.append(score)
'''
#for line in open(path+'/data/contacts/position_'+assay+'_scaled_web_new.txt', 'r'):
for line in open(path+'/data/contacts/position_'+assay+'_scaled_web_new2.txt', 'r'):
gprotein_found = line.split('\t')[0]
if gprotein_given == gprotein_found:
#print ('here')
#print (line)
pos1 = line.split('\t')[1]
pos2 = line.split('\t')[2]
score = float(line.split('\t')[3])
dis = line.replace('\n', '').split('\t')[-1]
if dis == '-':
dis = 1000.0 ## set by default a high value so that it is anyway selected
else:
dis = float(dis)
if score >= cutoff or score <= (-1.0)*cutoff and dis >= distance:
if pos1 not in dic:
dic[pos1] = {}
dic[pos1][pos2] = score
if pos2 not in dic:
dic[pos2] = {}
dic[pos2][pos1] = score
if pos1 not in positions:
positions.append(pos1)
#positions.append(pos1)
if pos2 not in positions:
positions.append(pos2)
pair_positions.append(pos1+':'+pos2+':'+str(score))
scores.append(score)
#print ('positions', len(positions))
#print ('distance', distance, dis)
scoresMax = max(scores)
scoresMin = min(scores)
positions = np.array(positions)
positions = sortPositions(positions)
#print ('----------------')
#print (positions)
#print ('----------------')
#sys.exit()
#positions = list(set(positions))
#positions = np.array(np.sort(positions))
data = []
num_contacts = []
for pos1 in positions:
row = []
for pos2 in positions:
if pos2 in dic[pos1]:
row.append(dic[pos1][pos2])
else:
#row.append(0)
row.append(None)
data.append(row)
num_contacts.append([round(len(dic[pos1]),2)])
#print (cutoff, gprotein_given)
#print ('positions', positions)
if num_contacts != []:
scaler = MinMaxScaler(feature_range=(0.35,1.0))
num_contacts = scaler.fit_transform(num_contacts)
num_contacts = num_contacts.flatten().tolist()
for i in range(0, len(num_contacts)):
num_contacts[i] = str(num_contacts[i])
#print (num_contacts)
return scoresMax, scoresMin, data, positions, pair_positions, num_contacts
@app.route('/fetchAttentionMap', methods=['GET', 'POST'])
def fetchAttentionMap():
if request.method == 'POST':
data = request.get_json(force=True)
#print (data['gpcr'])
gprotein_given = data['gprotein']
gpcr_given = data['gpcr']
uniq_id = data['uniq_id']
#scoresMax, scoresMin, scores, positions, pair_positions, num_contacts = extract_contacts(gprotein_given, cutoff, distance)
Xtest = np.load(path+'/static/predictor/output/'+uniq_id+'/attentions/'+gpcr_given+'_'+gprotein_given+'.npy')
seqPositions = [str(i) for i in range(1, len(Xtest[0])+1)]
#print (seqPositions)
#return jsonify({'fetch_contactsMin': scoresMin, 'fetch_contactsMax': scoresMax, 'fetch_contacts': scores, 'positions': positions.tolist()})
return jsonify({'zaxis': Xtest.tolist(), 'xaxis': seqPositions, 'yaxis': seqPositions})
else:
return ("<html><h3>It was a GET request</h3></html>")
#
@app.route('/fetchContactsHeatmap', methods=['GET', 'POST'])
def fetchContactsHeatmap():
if request.method == 'POST':
data = request.get_json(force=True)
#print (data['gpcr'])
gprotein_given = data['gprotein']
cutoff = float(data['cutoff'])
distance = float(data['distance'])
scoresMax, scoresMin, scores, positions, pair_positions, num_contacts = extract_contacts(gprotein_given, cutoff, distance)
for i in range(0, len(positions)):
positions[i] = str(positions[i]).replace('.', 'x')
return jsonify({'fetch_contactsMin': scoresMin, 'fetch_contactsMax': scoresMax, 'fetch_contacts': scores, 'positions': positions.tolist()})
else:
return ("<html><h3>It was a GET request</h3></html>")
def extract_pca(gprotein, assay, pca_type):
'''
if pca_type == 'Best PCA':
Xs_train_pca = np.load(path+'/static/best_PCA/'+gprotein+'.npy', allow_pickle=True)
elif pca_type == 'GPCRome':
Xs_train_pca = np.load(path+'/static/33layer_PCA/33layer.npy', allow_pickle=True)
else:
'''
Xs_train_pca = np.load(path+'/static/pca_all/'+pca_type+'.npy', allow_pickle=True)
#Xs_train_pca = np.load(path+'/static/best_PCA/GNAZ.npy', allow_pickle=True)
score_coupling, score_uncoupling, Xs_train_pca_coupling, Xs_train_pca_uncoupling, Xs_train_pca_grey, genes_to_consider_coupling, genes_to_consider_uncoupling, genes_to_consider_grey = filter_gpcr_list(Xs_train_pca, assay, gprotein)
#print ('train', Xs_train_pca_coupling)
score_coupling = score_coupling.tolist()
score_uncoupling = score_uncoupling.tolist()
x_train_coupling = Xs_train_pca_coupling[:,0].tolist()
x_train_uncoupling = Xs_train_pca_uncoupling[:,0].tolist()
x_train_grey = Xs_train_pca_grey[:,0].tolist()
y_train_coupling = Xs_train_pca_coupling[:,1].tolist()
y_train_uncoupling = Xs_train_pca_uncoupling[:,1].tolist()
y_train_grey = Xs_train_pca_grey[:,1].tolist()
return score_coupling, score_uncoupling, x_train_coupling, x_train_uncoupling, x_train_grey, y_train_coupling, y_train_uncoupling, y_train_grey, genes_to_consider_coupling, genes_to_consider_uncoupling, genes_to_consider_grey
def filter_gpcr_list(X, assay, gprotein):
genes_to_consider_coupling = []
score_coupling = []
score_uncoupling = []
genes_to_consider_uncoupling = []
#print (assay)
#assay = 'ebBRET'
if assay == 'TGF':
num = -1
for line in open(path+'/data/shedding.tsv', 'r'):
if line[0] != '#':
gene = line.split('\t')[0]
acc = line.split('\t')[1]
id = line.split('\t')[2]
name = line.split('\t')[3]
# Make the range -1 to +1
score = float(line.split('\t')[num+4]) + 1
#print (score)
#color = cm.get_cmap('RdYlGn', 100)
#r,g,b,a = color(score)
#print (score,r,g,b)
#if score >= -1.0:
# Move the center (-1.0) to 0.0
if score >= 0.0:
genes_to_consider_coupling.append(gene+'|'+acc)
color = cm.get_cmap('Greens', 100)
r,g,b,a = color(score)
score_coupling.append('rgb('+str(r)+','+str(g)+','+str(b)+')')
else:
genes_to_consider_uncoupling.append(gene+'|'+acc)
color = cm.get_cmap('Greys', 100)
score *= (-1.0)
# To bring the score from range 0 to 1
# to 0.25 to 0.75 so it is neither too white (low value)
# not too black (high value)
score = score/2 + 0.25
r,g,b,a = color(score)
score_uncoupling.append('rgb('+str(r)+','+str(g)+','+str(b)+')')
else:
flag = 0
# Replace GNAO1 by GoA
header = line.replace('\n', '').replace('GNAO1', 'GoA').split('\t')[4:]
for num, gprot in enumerate(header):
if gprot == gprotein:
flag = 1
break
#print (num, gprot)
#print (header)
if flag == 0:
num = -1
elif assay == 'GEMTA':
num = 0
for line in open(path+'/data/ebbret.tsv', 'r', encoding="utf-8"):
if line[0] != '#':
gene = line.split('\t')[0]
acc = line.split('\t')[1]
id = line.split('\t')[2]
name = line.split('\t')[3]
score = float(line.split('\t')[num+4])
if score > 0.0:
genes_to_consider_coupling.append(gene+'|'+acc)
color = cm.get_cmap('Greens', 100)
r,g,b,a = color(score)
score_coupling.append('rgb('+str(r)+','+str(g)+','+str(b)+')')
else:
genes_to_consider_uncoupling.append(gene+'|'+acc)
#score_uncoupling.append('rgb('+str(r)+','+str(g)+','+str(b)+')')
score_uncoupling.append('grey')
else:
header = line.replace('\n', '').split('\t')[4:]
for num, gprot in enumerate(header):
if gprot == gprotein:
#print (gprot)
break
elif assay == 'GtoPdb':
iuphar_map = {
'GNAS': 'Gs', 'GNAL': 'Gs',
'GNAI1': 'Gi/Go', 'GNAI2': 'Gi/Go', 'GNAI3': 'Gi/Go', 'GNAO1': 'Gi/Go', 'GNAZ': 'Gi/Go', 'GoA': 'Gi/Go', 'GoB': 'Gi/Go',
'GNA12': 'G12/G13', 'GNA13': 'G12/G13',
'GNAQ': 'Gq/G11', 'GNA11': 'Gq/G11', 'GNA14': 'Gq/G11', 'GNA15': 'Gq/G11'
}
gprotein_fam = iuphar_map[gprotein]
#print (gprotein_fam)
for line in open(path+'/data/iuphar.tsv', 'r'):
if line[0] != '#' and line.split('\t')[1] != '':
gene = line.split('\t')[0]
acc = line.split('\t')[1]
id = line.split('\t')[2]
name = line.split('\t')[3]
if gprotein_fam in line:
genes_to_consider_coupling.append(gene+'|'+acc)
if gprotein_fam in line.split('\t')[4]:
score_coupling.append('forestgreen')
else:
score_coupling.append('lightgreen')
else:
genes_to_consider_uncoupling.append(gene+'|'+acc)
score_uncoupling.append('grey')
elif assay == 'STRING':
string_map = {
'Barr1-GRK2': 'ARRB1',
'Barr2': 'ARRB2',
'Barr2-GRK2': 'ARRB2'
}
barr = string_map[gprotein]
num = -1
for line in open(path+'/data/string.tsv', 'r', encoding="utf-8"):
gene = line.split('\t')[0]
acc = line.split('\t')[1]
id = line.split('\t')[2]
name = line.split('\t')[3]
if barr in line:
genes_to_consider_coupling.append(gene+'|'+acc)
score_coupling.append('green')
else:
genes_to_consider_uncoupling.append(gene+'|'+acc)
score_uncoupling.append('green')
#print (genes_to_consider_coupling)
#print (genes_to_consider_uncoupling)
gpcr_list = []
for line in open(path+'/static/pca_all/gpcr_list_unscaled_all_layer_GN.txt', 'r'):
gene = line.replace('\n', '').split('\t')[1]
acc = line.replace('\n', '').split('\t')[0]
gpcr_list.append(gene + '|' + acc)
#gpcr_list.append(line.replace('\n', '').split('\t')[1])
X_pos = []
X_neg = []
X_grey = []
genes_to_consider_grey = []
for gene, row in zip(gpcr_list, X):
#if 'MC1R' in gene:
# print ('couple', gene, row[:2])
if gene in genes_to_consider_coupling:
X_pos.append(row)
elif gene in genes_to_consider_uncoupling:
X_neg.append(row)
else:
X_grey.append(row)
genes_to_consider_grey.append(gene)
#print (X_pos)
return (np.array(score_coupling), np.array(score_uncoupling), np.array(X_pos), np.array(X_neg), np.array(X_grey), genes_to_consider_coupling, genes_to_consider_uncoupling, genes_to_consider_grey)
@app.route('/fetchPCA', methods=['GET', 'POST'])
def fetchPCA():
if request.method == 'POST':
data = request.get_json(force=True)
assay_given = data['assay']
pca_type = data['pca_type']
gprotein_given = data['gprotein']
gpcr_given = data['gpcr']
#print (gprotein_given, gpcr_given)
uniq_id = data['uniq_id']
#if assay == '':
assay = '';
assayList = []
gemta = ['GNAS', 'GNAI1', 'GNAI2', 'GoB', 'GNAZ', 'GNA12', 'GNA13', 'GNAQ', 'GNA11', 'GNA14', 'GNA15', 'Barr1-GRK2', 'Barr2', 'Barr2-GRK2']
tgf = ['GNAS', 'GNAL', 'GNAI1', 'GNAI3', 'GNAZ', 'GNA12', 'GNA13', 'GNAQ', 'GNA14', 'GNA15']
both = ['GNAS', 'GNAI1', 'GNAZ', 'GNA12', 'GNA13', 'GNAQ', 'GNA14', 'GNA15', 'GoA']
if 'Barr' in gprotein_given:
assay = 'GEMTA'
assayList = ['GEMTA', 'STRING', 'Class']
elif gprotein_given in both:
assay = 'TGF'
assayList = ['TGF', 'GEMTA', 'GtoPdb', 'Class']
elif gprotein_given in tgf:
assay = 'TGF'
assayList = ['TGF', 'GtoPdb', 'Class']
elif gprotein_given in gemta:
assay = 'GEMTA'
assayList = ['GEMTA', 'GtoPdb', 'Class']
elif assay_given == 'Class':
assay = 'Class'
assayList = ['TGF', 'GEMTA', 'GtoPdb', 'Class']
if assay_given in assayList:
assay = assay_given
### MUT
'''
if pca_type == 'GPCRome':
Xs_test_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/33layer_'+gpcr_given+'.npy', allow_pickle=True)
elif pca_type == 'Best PCA':
Xs_test_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+gprotein_given+'_'+gpcr_given+'.npy', allow_pickle=True)
else:
'''
Xs_test_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+pca_type+'layer_'+gpcr_given+'.npy', allow_pickle=True)
#print ('test',Xs_test_pca)
x_test = Xs_test_pca[0].tolist()
y_test = Xs_test_pca[1].tolist()
#print (x_test)
#print (y_test)
### WT
if '_WT' not in gpcr_given:
wt = gpcr_given.split('_')[0] + '_WT'
'''
if pca_type == 'GPCRome':
Xs_wt_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/33layer_'+wt+'.npy', allow_pickle=True)
elif pca_type == 'Best PCA':
Xs_wt_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+gprotein_given+'_'+wt+'.npy', allow_pickle=True)
else:
'''
Xs_wt_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+pca_type+'layer_'+wt+'.npy', allow_pickle=True)
#print (Xs_wt_pca)
#x_test = Xs_test_pca[:,0].tolist()
#y_test = Xs_test_pca[:,1].tolist()
x_wt = Xs_wt_pca[0].tolist()
y_wt = Xs_wt_pca[1].tolist()
#print (x_wt)
#print (y_wt)
else:
x_wt = '-'
y_wt = '-'
score_coupling, score_uncoupling, x_train_coupling, x_train_uncoupling, x_train_grey, y_train_coupling, y_train_uncoupling, y_train_grey, genes_to_consider_coupling, genes_to_consider_uncoupling, genes_to_consider_grey = extract_pca(gprotein_given, assay, pca_type)
#print (x_train, y_train, x_test, y_test)
#print (assay,genes_to_consider_coupling)
minX = min(x_train_coupling + x_train_uncoupling + x_train_grey)
maxX = max(x_train_coupling + x_train_uncoupling + x_train_grey)
minY = min(y_train_coupling + y_train_uncoupling + x_train_grey)
maxY = max(y_train_coupling + y_train_uncoupling + x_train_grey)
#print(minY, maxY)
return jsonify({'x_train_coupling': x_train_coupling,
'x_train_uncoupling': x_train_uncoupling,
'y_train_coupling': y_train_coupling,
'y_train_uncoupling': y_train_uncoupling,
'x_train_grey': x_train_grey,
'y_train_grey': y_train_grey,
'score_coupling': score_coupling,
'score_uncoupling': score_uncoupling,
'assay': assay,
'genes_to_consider_coupling': genes_to_consider_coupling,
'genes_to_consider_uncoupling': genes_to_consider_uncoupling,
'genes_to_consider_grey': genes_to_consider_grey,
'x_test': x_test,
'y_test': y_test,
'x_wt': x_wt,
'y_wt': y_wt,
'minX': minX,
'maxX': maxX,
'minY': minY,
'maxY': maxY})
else:
return ("<html><h3>It was a GET request</h3></html>")
@app.route('/fetchPCA2', methods=['GET', 'POST'])
def fetchPCA2():
if request.method == 'POST':
data = request.get_json(force=True)
assay_given = data['assay']
pca_type = data['pca_type']
gprotein_given = data['gprotein']
gpcr_given = data['gpcr']
#print (gprotein_given, gpcr_given)
uniq_id = data['uniq_id']
#if assay == '':
assay = assay_given;
### MUT
'''
if pca_type == 'GPCRome':
Xs_test_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/33layer_'+gpcr_given+'.npy', allow_pickle=True)
elif pca_type == 'Best PCA':
Xs_test_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+gprotein_given+'_'+gpcr_given+'.npy', allow_pickle=True)
else:
'''
Xs_test_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+pca_type+'layer_'+gpcr_given+'.npy', allow_pickle=True)
#print ('test',Xs_test_pca)
x_test = Xs_test_pca[0].tolist()
y_test = Xs_test_pca[1].tolist()
#print (x_test)
#print (y_test)
### WT
if '_WT' not in gpcr_given:
wt = gpcr_given.split('_')[0] + '_WT'
'''
if pca_type == 'GPCRome':
Xs_wt_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/33layer_'+wt+'.npy', allow_pickle=True)
elif pca_type == 'Best PCA':
Xs_wt_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+gprotein_given+'_'+wt+'.npy', allow_pickle=True)
else:
'''
Xs_wt_pca = np.load(path+'/static/predictor/output/'+uniq_id+'/PCA/'+pca_type+'layer_'+wt+'.npy', allow_pickle=True)
#print (Xs_wt_pca)
#x_test = Xs_test_pca[:,0].tolist()
#y_test = Xs_test_pca[:,1].tolist()
x_wt = Xs_wt_pca[0].tolist()
y_wt = Xs_wt_pca[1].tolist()
#print (x_wt)
#print (y_wt)
else:
x_wt = '-'
y_wt = '-'
#score_coupling, score_uncoupling, x_train_coupling, x_train_uncoupling, x_train_grey, y_train_coupling, y_train_uncoupling, y_train_grey, genes_to_consider_coupling, genes_to_consider_uncoupling, genes_to_consider_grey = extract_pca(gprotein_given, assay, pca_type)
'''
if pca_type == 'Best PCA':
Xs_train_pca = np.load(path+'/static/best_PCA/'+gprotein_given+'.npy', allow_pickle=True)
elif pca_type == 'GPCRome':
Xs_train_pca = np.load(path+'/static/33layer_PCA/33layer.npy', allow_pickle=True)
else:
'''
Xs_train_pca = np.load(path+'/static/pca_all/'+pca_type+'.npy', allow_pickle=True)
classes = {}
#for line in open(path+'/data/classification.txt', 'r'):
for line in open(path+'/data/classification2.txt', 'r'):
if 'Uniprot_acc' not in line:
acc = line.split('\t')[0]
cls = line.split('\t')[-1].replace('\n', '')
classes[acc] = cls
gpcr_list = []
for line in open(path+'/static/pca_all/gpcr_list_unscaled_all_layer_GN.txt', 'r'):
gene = line.replace('\n', '').split('\t')[1]
acc = line.replace('\n', '').split('\t')[0]
gpcr_list.append(gene + '|' + acc)
#gpcr_list.append(line.replace('\n', '').split('\t')[1])
X_classA = []
classA = []
X_classB1 = []
classB1 = []
X_classB2 = []
classB2 = []
X_classC = []
classC = []
X_frizzeled = []
frizzeled = []
X_taste = []
taste = []
X_other = []
other = []
for gpcr, row in zip(gpcr_list, Xs_train_pca):
if 'MC1R' in gpcr:
print ('class', gpcr, row[:2])
acc = gpcr.split('|')[1]
if classes[acc] == 'classA':
X_classA.append(row.tolist())
classA.append(gpcr)
elif classes[acc] == 'classB1':
X_classB1.append(row)
classB1.append(gpcr)
elif classes[acc] == 'classB2':
X_classB2.append(row)
classB2.append(gpcr)
elif classes[acc] == 'classC':
X_classC.append(row)
classC.append(gpcr)
elif classes[acc] == 'Frizzeled':
X_frizzeled.append(row)
frizzeled.append(gpcr)
elif classes[acc] == 'Taste':
X_taste.append(row)
taste.append(gpcr)
else:
X_other.append(row.tolist())
other.append(gpcr)
X_classA = np.array(X_classA)
X_classB1 = np.array(X_classB1)
X_classB2 = np.array(X_classB2)
X_classC = np.array(X_classC)
X_frizzeled = np.array(X_frizzeled)
X_taste = np.array(X_taste)
X_other = np.array(X_other)
#print (X_classA)
x_classA = X_classA[:,0].tolist()
y_classA = X_classA[:,1].tolist()
x_classB1 = X_classB1[:,0].tolist()
y_classB1 = X_classB1[:,1].tolist()
x_classB2 = X_classB2[:,0].tolist()
y_classB2 = X_classB2[:,1].tolist()
x_classC = X_classC[:,0].tolist()
y_classC = X_classC[:,1].tolist()
x_frizzeled = X_frizzeled[:,0].tolist()
y_frizzeled = X_frizzeled[:,1].tolist()
x_taste = X_taste[:,0].tolist()
y_taste = X_taste[:,1].tolist()
x_other = X_other[:,0].tolist()
y_other = X_other[:,1].tolist()
'''
for gpcr, x, y in zip(classA, x_classA, y_classA):
if 'MC1R' in gpcr:
print ('classA', gpcr, x, y)
print (len(x_classA), len(y_classA))
'''
#print (y_classA)
#print (genes_to_consider_coupling)
minX = min(x_classA + x_classB1 + x_classB2 + x_classC + x_frizzeled + x_taste + x_other)
maxX = max(x_classA + x_classB1 + x_classB2 + x_classC + x_frizzeled + x_taste + x_other)
minY = min(y_classA + y_classB1 + y_classB2 + y_classC + y_frizzeled + y_taste + y_other)
maxY = max(y_classA + y_classB1 + y_classB2 + y_classC + y_frizzeled + y_taste + y_other)
#print(minX, maxX)
return jsonify({'x_classA': x_classA,
'x_classB1': x_classB1,
'x_classB1': x_classB2,
'x_classC': x_classC,
'x_frizzeled': x_frizzeled,
'x_taste': x_taste,
'x_other': x_other,
'y_classA': y_classA,
'y_classB1': y_classB1,
'y_classB2': y_classB2,
'y_classC': y_classC,
'y_frizzeled': y_frizzeled,
'y_taste': y_taste,
'y_other': y_other,
'assay': assay,
'classA': classA,
'classB1': classB1,
'classB2': classB2,
'classC': classC,
'frizzeled': frizzeled,
'taste': taste,
'other': other,
'x_test': x_test,
'y_test': y_test,
'x_wt': x_wt,
'y_wt': y_wt,
'minX': minX,
'maxX': maxX,
'minY': minY,
'maxY': maxY})
else:
return ("<html><h3>It was a GET request</h3></html>")
@app.route('/assignOptions', methods=['GET', 'POST'])
def assignOptions():
if request.method == 'POST':
data = request.get_json(force=True)
assay_given = data['assay']
pca_type = data['pca_type']
gprotein_given = data['gprotein']
gpcr_given = data['gpcr']
#print (gprotein_given, gpcr_given)
uniq_id = data['uniq_id']
for line in open(path+'/data/contacts/gprotein_best_layer.txt', 'r'):
if gprotein_given == line.split('\t')[0]:
assay = line.split('\t')[1]
bestPCA = line.split('\t')[2].replace('\n', '')
break
layers = [str(i) for i in range(0,34)]
'''
layers = []
for i in range(0,34):
if str(i) == bestPCA:
layers.append(str(i)+' ('+'best)')
else:
layers.append(str(i))
'''
return jsonify({'layers': layers})
def DoBLAST(uniq_id, gpcr_given):
handle = open(path + "/static/predictor/output/"+uniq_id+"/GPCRDBblast.txt", 'r')
blast_records = NCBIXML.parse(handle)
#print (blast_records)
GPCRDB2SEQ = {}
SEQ2GPCRDB = {}
for blast_record in blast_records:
#print (blast_record.query)
if gpcr_given == blast_record.query:
for alignment in blast_record.alignments:
for hsp in alignment.hsps:
bestHIT = alignment.title.split(' ')[1]
q_num = 0
s_num = 0
for num, (q, s) in enumerate(zip(hsp.query, hsp.sbjct)):
if q!='-' and s!='-':
GPCRDB2SEQ[s_num + hsp.sbjct_start] = q_num + hsp.query_start
SEQ2GPCRDB[q_num + hsp.query_start] = s_num + hsp.sbjct_start
q_num += 1
s_num += 1
elif q!='-':
q_num += 1
else:
s_num += 1
'''
for num, (q, s) in enumerate(zip(hsp.query, hsp.sbjct)):
if q!='-' and s!='-':
GPCRDB2SEQ[num + hsp.sbjct_start] = num + hsp.query_start
'''
break
break
#print (bestHIT)
#print (GPCRDB2SEQ)
break
return (GPCRDB2SEQ, SEQ2GPCRDB, bestHIT)
@app.route('/fetchContactsSequence', methods=['GET', 'POST'])
def fetchContactsSequence():
if request.method == 'POST':
data = request.get_json(force=True)
#print (data['gpcr'])
gprotein_given = data['gprotein']
gpcr_given = data['gpcr']
#print (gpcr_given)
#print (gpcr_given, gpcr_given.split('_')[1], 'sequence')
path_to_fasta = data['path_to_fasta']
uniq_id = data['uniq_id']
cutoff = float(data['cutoff'])
distance = float(data['distance'])
scoresMax, scoresMin, scores, positions, pair_positions, num_contacts = extract_contacts(gprotein_given, cutoff, distance)
#print ('fetch_seq', positions)
fasta_sequence = ''; flag = 0
for line in open(path_to_fasta):
if line[0] == '>':
if flag == 1:
break
flag = 0
#gpcr_found = line.split('>')[1].replace('\n', '').replace(' ', '')
gpcr_found = line.split('>')[1].replace('\n', '').lstrip().rstrip()
if gpcr_found == gpcr_given:
flag = 1
elif flag == 1:
fasta_sequence += line.replace('\n', '')
GPCRDB2SEQ, SEQ2GPCRDB, bestHIT = DoBLAST(uniq_id, gpcr_given)
bestHIT_ACC = bestHIT.split('|')[1]
#print (bestHIT)
BW2GPCRDB = {}
GPCRDB2BW = {}
for line in open(path + '/data/GPCRDB/GPCRDB.tsv', 'r'):
if 'Name' not in line.split('\t')[0]:
acc = line.split('\t')[0].split('_')[1]
if acc == bestHIT_ACC:
GPCRDB = int(line.split('\t')[1][1:])
#BW = line.split('\t')[2]
## convert . to x in GPCRDB numbering
BW = line.split('\t')[2].replace('.', 'x')
BW2GPCRDB[BW] = GPCRDB
GPCRDB2BW[GPCRDB] = BW
#print (BW2GPCRDB)
#print (GPCRDB2SEQ)
#print (positions)
seq_positions = []
bw_positions = []
for BW in positions:
if BW in BW2GPCRDB:
GPCRDB = BW2GPCRDB[BW]
if GPCRDB in GPCRDB2SEQ:
SEQ = GPCRDB2SEQ[GPCRDB]
seq_positions.append(int(SEQ))
bw_positions.append(BW)
#else:
# print (BW)
#print (list(set(seq_positions)))
#seq_positions = list(set(seq_positions))
#print (seq_positions)
#print (bw_positions)
## Insert mutation
mutation_position = gpcr_given.split('_')[-1]
if mutation_position not in seq_positions:
if mutation_position != 'WT':
SEQ = int(mutation_position[1:-1])
if SEQ in SEQ2GPCRDB:
GPCRDB = SEQ2GPCRDB[SEQ]
if GPCRDB in GPCRDB2BW:
BW = GPCRDB2BW[GPCRDB]
seq_positions.append(int(SEQ))
bw_positions.append(BW)
else:
seq_positions.append(int(SEQ))
bw_positions.append('-')
seq_positions = np.array(seq_positions)
bw_positions = np.array(bw_positions)
indexes = np.unique(seq_positions, return_index=True)[1]
seq_positions = seq_positions[indexes]
#print(bw_positions[indexes])
bw_positions = bw_positions[indexes]
#print (seq_positions)
#print (bw_positions)
'''
indexes = np.argsort(seq_positions)
print (indexes)
seq_positions = seq_positions[indexes]
print (seq_positions)
'''
seq_positions = seq_positions.tolist()
bw_positions = bw_positions.tolist()
#print (seq_positions)
#print (bw_positions)
'''
new_seq_positions = []
new_bw_positions = []
mutation_position = gpcr_given.split('_')[1]
if mutation_position != 'WT':
position = int(mutation_position[1:-1])
#print (position)
if position not in seq_positions:
for i in range(0, len(seq_positions)):
#print (seq_positions[i])
if seq_positions[i] < position:
if i == len(seq_positions)-1:
new_seq_positions.append(position)
new_bw_positions.append('-')
elif seq_positions[i+1] > position:
#print (seq_positions[i], position, seq_positions[i+1])
new_seq_positions.append(position)
new_bw_positions.append('-')
else:
new_seq_positions.append(seq_positions[i])
new_bw_positions.append(bw_positions[i])
else:
new_seq_positions.append(seq_positions[i])
new_bw_positions.append(bw_positions[i])
seq_positions = new_seq_positions
bw_positions = new_bw_positions
'''
#print (seq_positions)
#print (bw_positions)
return jsonify({'fetch_contacts': scores,
'seq_positions': seq_positions,
'bw_positions': bw_positions,
'sequence': fasta_sequence})
else:
return ("<html><h3>It was a GET request</h3></html>")
# Function to convert mutation position and given positions
# from BW to PDB (based on PDB ID)
@app.route('/convertPositionsBW2PDB', methods=['GET', 'POST'])
def convertPositionsBW2PDB():
if request.method == 'POST':
data = request.get_json(force=True)
pdbID = data['pdbID']
positions = data['positions']
pair_positions = data['pair_positions']
num_contacts = data['num_contacts']
gpcr_given = data['gpcr']
uniq_id = data['uniq_id']
#print (pdbID)
#print (pair_positions)
GPCRDB2PDB = {}
for line in open(path + '/data/PDB/GPCRDB/'+pdbID+'.txt', 'r'):
GPCRDB2PDB[int(line.split('\t')[3].replace('\n', ''))] = int(line.split('\t')[2])
bestHIT_ACC = line.replace('\n', '').split('\t')[4].split('|')[1]
BW2GPCRDB = {}
GPCRDB2BW = {}
for line in open(path + '/data/GPCRDB/GPCRDB.tsv', 'r'):
if 'Name' not in line.split('\t')[0]:
acc = line.split('\t')[0].split('_')[1]
if acc == bestHIT_ACC:
GPCRDB = int(line.split('\t')[1][1:])
#BW = line.split('\t')[2]
## convert . to x in GPCRDB numbering
BW = line.split('\t')[2].replace('.', 'x')
BW2GPCRDB[BW] = GPCRDB
GPCRDB2BW[GPCRDB] = BW
modified_positions = []
modified_positions_labels = []
modified_num_contacts = []
for num, BW in enumerate(positions.split(',')):
if BW in BW2GPCRDB:
GPCRDB = BW2GPCRDB[BW]
if GPCRDB in GPCRDB2PDB:
pdbPosition = GPCRDB2PDB[GPCRDB]
modified_positions.append(str(pdbPosition))
modified_positions_labels.append(str(BW))
modified_num_contacts.append(str(num_contacts.split(',')[num]))
#print (modified_positions_labels)
modified_pair_positions = []
if pair_positions.split() != []:
for pair in pair_positions.split(','):
BW1 = pair.split(':')[0]
BW2 = pair.split(':')[1]
score = pair.split(':')[2]
if BW1 in BW2GPCRDB and BW2 in BW2GPCRDB:
GPCRDB1 = BW2GPCRDB[BW1]
GPCRDB2 = BW2GPCRDB[BW2]
if GPCRDB1 in GPCRDB2PDB and GPCRDB2 in GPCRDB2PDB:
pdbPosition1 = str(GPCRDB2PDB[GPCRDB1])
pdbPosition2 = str(GPCRDB2PDB[GPCRDB2])
modified_pair_positions.append(pdbPosition1+':'+pdbPosition2+':'+score)
mutation_position = '-'
mutation_position_label = '-'
if '_WT' not in gpcr_given:
mutation_sequence_position = int(gpcr_given.split('_')[-1][1:-1])
handle = open(path + "/static/predictor/output/"+uniq_id+"/GPCRDBblast.txt", 'r')
blast_records = NCBIXML.parse(handle)
SEQ2GPCRDB = {}
for blast_record in blast_records:
#print (blast_record.query)
if gpcr_given == blast_record.query:
for alignment in blast_record.alignments:
bestHIT = alignment.title.split(' ')[1]
#print (bestHIT)
if bestHIT_ACC == bestHIT.split('|')[1]:
for hsp in alignment.hsps:
q_num = 0
s_num = 0
for num, (q, s) in enumerate(zip(hsp.query, hsp.sbjct)):
if q!='-' and s!='-':
SEQ2GPCRDB[q_num + hsp.query_start] = s_num + hsp.sbjct_start
q_num += 1
s_num += 1
elif q!='-':
q_num += 1
else:
s_num += 1
break