-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_analyses.py
1475 lines (1149 loc) · 66.7 KB
/
run_analyses.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
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 12:52:00 2024
@author: Dr. William Raymond
"""
###############################################################################
# Description
###############################################################################
###############################################################################
# Imports
###############################################################################
import os
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
from matplotlib.colors import LogNorm
import numpy as np
import pandas as pd
import json
from sklearn import mixture
from pulearn import ElkanotoPuClassifier, BaggingPuClassifier
from sklearn.svm import SVC
from joblib import dump, load
from tqdm import tqdm
from rs_functions import * #functions to do feature extraction and other things
import pulearn
print('Using PUlearn version:')
print(pulearn.__version__)
###############################################################################
# Sanatize data
###############################################################################
print('______________________________________')
print('Loading and sanatizing data files....')
# Get data files
# first we have the UTR data file, UTR data file is built from "make_initial_UTR_csv.py"
# Using the 5UTRaspic.Hum.fasta
# most important headers: GENE ID SEQ CCDS_ID STARTPLUS25 NUPACK_25 NUPACK_25_MFE
# Gene - uniprot Gene ID
# ID - original UTRdb 1.0 ID sequence, defunct
# SEQ - Cleaned sequence
# CCDS_ID - CCDS_id for the 25 nucleotides added to the 5'UTR
# STARTPLUS25 - sequence of the 5'UTR + 25 nt
# NUPACK_25 - nupack MFE dot structure for 100 foldings of the dot structure
# NUPACK_25_MFE - energy of the MFE structure
fname = './data_files/5primeUTR_final_db_3.csv'
UTR_db = pd.read_csv(fname)
print('UTR data file loaded: %s'%fname)
# Riboswitch data file
# ID - ID within RNA central
# DESC - Text description scraped from this given entry
# EUKARYOTIC - 1 or 0 is this a eukaryotic sequence
# LIGAND - Ligand scraped for this given entry
# SEQ - Sequence of the entry
# NUPACK_DOT - NUPACK dot structure of 100 foldings
# NUPACK_MFE - NUPACK mfe of the structure of 100 foldings
# Kmers aaa.... kmer counts for each triplet
fname = './data_files/RS_final_with_euk2.csv'
RS_db = pd.read_csv(fname)
print('RS data file loaded: %s'%fname)
## We have to apply some patches to the UTR data file to remove 3'UTR sequences and duplicate IDs
## since some UTRs have multiple isoforms and UTRdb didnt handle this
# remove 3prime sequences
UTR_db = UTR_db[['3' != x[0] for x in UTR_db['ID']]]
# rename duplicate ids to ID-N
ids_to_update = {}
ids = UTR_db['ID'].values.tolist()
for i in range(len(UTR_db)):
if ids.count(UTR_db['ID'].iloc[i]) > 1:
if UTR_db['ID'].iloc[i] not in ids_to_update.keys():
ids_to_update[UTR_db['ID'].iloc[i]] = [i,]
else:
ids_to_update[UTR_db['ID'].iloc[i]] = ids_to_update[UTR_db['ID'].iloc[i]] + [i,]
for id in ids_to_update.keys():
for i in range(len(ids_to_update[id])):
UTR_db.iloc[ids_to_update[id][i],4] = id + '-' + str(i)
## patch out a typo space in guanidine
for i in range(len(RS_db)):
if RS_db.iloc[i,2] == 'guanidine ':
RS_db.iloc[i,2] = 'guanidine'
## patch to combine adocobalamin with cobalamin since these are very similar
for i in range(len(RS_db)):
if RS_db.iloc[i,2] == 'adocbl':
RS_db.iloc[i,2] = 'cobalamin'
print('Riboswitch database size:' + str(RS_db.shape))
print('UTR database size:' + str(UTR_db.shape))
###############################################################################
# FEATURE EXTRACTION
###############################################################################
# This block generates X_RS and X_UTR for 74 features used for the machine learning ensembles
include_mfe = True
include_3mer = True
include_dot = True
include_gc = True
be = BEARencoder(); # Custom bear encoder for counting the dot structural features.
ccds_length = 'STARTPLUS25' #select the start plus 25 sequences to use
#max_mfe = np.min([np.min(UTR_db['NUPACK_25_MFE']), np.min(RS_df['NUPACK_MFE'])])
print('Using:')
print(ccds_length)
#########################
# UTRs
#########################
print('processing UTRs......')
X_UTR = np.zeros([len(UTR_db),66+8])
dot_UTR = []
ids_UTR = []
k = 0
# get the size first X_UTR
X_utr_size = 0
for i in range(len(UTR_db)):
if not pd.isna(UTR_db[ccds_length].iloc[i]):
if len(clean_seq(UTR_db[ccds_length].iloc[i])) > 25:
X_utr_size+=1
# fill up the X_UTR with extracted features
X_UTR =np.zeros([X_utr_size, 66+8])
for i in tqdm(range(len(UTR_db))):
if not pd.isna(UTR_db[ccds_length].iloc[i]):
seq = clean_seq(UTR_db[ccds_length].iloc[i])
if len(seq) > 25:
kmerf = kmer_freq(seq)
X_UTR[k,:64] = kmerf/np.sum(kmerf)
X_UTR[k,64] = UTR_db['NUPACK_25_MFE'].iloc[i]
X_UTR[k,65] = get_gc(seq)
ids_UTR.append(UTR_db['ID'].iloc[i])
dot_UTR.append(UTR_db['NUPACK_25'].iloc[i])
X_UTR[k,-8:] = be.annoated_feature_vector(UTR_db['NUPACK_25'].iloc[i], encode_stems_per_bp=True)
k+=1
#########################
# RS full
#########################
print('processing all RS......')
full_RS_df = RS_db
print(len(full_RS_df))
X_RS_full = np.zeros([len(full_RS_df),66+8])
dot_RS_full = []
ids_RS_full = []
k = 0
# get the size first X_RS
X_RS_size = 0
for i in range(len(full_RS_df)):
seq = clean_seq(full_RS_df['SEQ'].iloc[i])
if len(seq) > 25:
X_RS_size+=1
X_RS_full = np.zeros([X_RS_size, 66+8])
# fill up the X_UTR with extracted features
for i in tqdm(range(len(full_RS_df))):
seq = clean_seq(full_RS_df['SEQ'].iloc[i])
if len(seq) > 25:
seq = clean_seq(full_RS_df['SEQ'].iloc[i])
kmerf = kmer_freq(seq)
X_RS_full[k,:64] = kmerf/np.sum(kmerf)
X_RS_full[k,64] = full_RS_df['NUPACK_MFE'].iloc[i]
X_RS_full[k,65] = get_gc(seq)
ids_RS_full.append(full_RS_df['ID'].iloc[i])
dot_RS_full.append(full_RS_df['NUPACK_DOT'].iloc[i])
X_RS_full[k,-8:] = be.annoated_feature_vector(full_RS_df['NUPACK_DOT'].iloc[i], encode_stems_per_bp=True)
k+=1
# Get the maximum values (minimum for mfe) across thte dataset to normalize against
max_mfe = min(np.min(X_RS_full[:,64]),np.min(X_UTR[:,64]))
X_RS_full[:,64] = X_RS_full[:,64]/max_mfe
X_UTR[:,64] = X_UTR[:,64]/max_mfe
max_ubs = np.max([np.max(X_UTR[:,66]),np.max(X_RS_full[:,66])])
max_bs = np.max([np.max(X_UTR[:,67]),np.max(X_RS_full[:,67])])
max_ill = np.max([np.max(X_UTR[:,68]),np.max(X_RS_full[:,68])])
max_ilr = np.max([np.max(X_UTR[:,69]),np.max(X_RS_full[:,69])])
max_lp = np.max([np.max(X_UTR[:,70]),np.max(X_RS_full[:,70])])
max_lb = np.max([np.max(X_UTR[:,71]),np.max(X_RS_full[:,71])])
max_rb = np.max([np.max(X_UTR[:,72]),np.max(X_RS_full[:,72])])
# normalize both data sets by their largest values
X_UTR[:,66] = X_UTR[:,66]/max_ubs
X_UTR[:,67] = X_UTR[:,67]/max_bs
X_UTR[:,68] = X_UTR[:,68]/max_ill
X_UTR[:,69] = X_UTR[:,69]/max_ilr
X_UTR[:,70] = X_UTR[:,70]/max_lp
X_UTR[:,71] = X_UTR[:,71]/max_lb
X_UTR[:,72] = X_UTR[:,72]/max_rb
X_RS_full[:,66] = X_RS_full[:,66]/max_ubs
X_RS_full[:,67] = X_RS_full[:,67]/max_bs
X_RS_full[:,68] = X_RS_full[:,68]/max_ill
X_RS_full[:,69] = X_RS_full[:,69]/max_ilr
X_RS_full[:,70] = X_RS_full[:,70]/max_lp
X_RS_full[:,71] = X_RS_full[:,71]/max_lb
X_RS_full[:,72] = X_RS_full[:,72]/max_rb
#########################
# RS ligand specific
#########################
# now we will split up the X_RS by ligand type for structural cross validation
print('Generating RS Ligand DFs......')
def make_ligand_df(df, ligand):
witheld_df = RS_db[RS_db['LIGAND'] ==ligand]
X_witheld = np.zeros([len(witheld_df),66+8])
dot_witheld = []
ids_witheld = []
k = 0
for i in tqdm(range(len(witheld_df))):
seq = clean_seq(witheld_df['SEQ'].iloc[i])
if len(seq) > 25:
if i == 0:
X_witheld = np.zeros([1,66+8])
else:
X_witheld = np.vstack( [X_witheld, np.zeros([1,66+8]) ])
seq = clean_seq(witheld_df['SEQ'].iloc[i])
kmerf = kmer_freq(seq)
X_witheld[k,:64] = kmerf/np.sum(kmerf)
X_witheld[k,64] = witheld_df['NUPACK_MFE'].iloc[i]/max_mfe
X_witheld[k,65] = get_gc(seq)
ids_witheld.append(witheld_df['ID'].iloc[i])
dot_witheld.append(witheld_df['NUPACK_DOT'].iloc[i])
X_witheld[k,-8:] = be.annoated_feature_vector(witheld_df['NUPACK_DOT'].iloc[i], encode_stems_per_bp=True)
X_witheld[k,66] = X_witheld[k,66]/max_ubs
X_witheld[k,67] = X_witheld[k,67]/max_bs
X_witheld[k,68] = X_witheld[k,68]/max_ill
X_witheld[k,69] = X_witheld[k,69]/max_ilr
X_witheld[k,70] = X_witheld[k,70]/max_lp
X_witheld[k,71] = X_witheld[k,71]/max_lb
X_witheld[k,72] = X_witheld[k,72]/max_rb
k+=1
return X_witheld, ids_witheld, dot_witheld
set(RS_db['LIGAND'])
witheld_ligands = ['cobalamin', 'guanidine', 'TPP','SAM','glycine','FMN','purine','lysine','fluoride','zmp-ztp',]
RS_df = RS_db[~RS_db['LIGAND'].isin( witheld_ligands)]
print(len(RS_df))
ligand_dfs = []
for i in range(len(witheld_ligands)):
print('making %s....'%witheld_ligands[i])
ligand_dfs.append(make_ligand_df(RS_db, witheld_ligands[i]))
X_RS = np.zeros([len(RS_df),66+8])
dot_RS = []
ids_RS = []
k = 0
X_RS_size = 0
for i in range(len(RS_df)):
seq = clean_seq(RS_df['SEQ'].iloc[i])
if len(seq) > 25:
X_RS_size+=1
X_RS = np.zeros([X_RS_size, 66+8])
for i in tqdm(range(len(RS_df))):
seq = clean_seq(RS_df['SEQ'].iloc[i])
if len(seq) > 25:
seq = clean_seq(RS_df['SEQ'].iloc[i])
kmerf = kmer_freq(seq)
X_RS[k,:64] = kmerf/np.sum(kmerf)
X_RS[k,64] = RS_df['NUPACK_MFE'].iloc[i]/max_mfe
X_RS[k,65] = get_gc(seq)
ids_RS.append(RS_df['ID'].iloc[i])
dot_RS.append(RS_df['NUPACK_DOT'].iloc[i])
X_RS[k,-8:] = be.annoated_feature_vector(RS_df['NUPACK_DOT'].iloc[i], encode_stems_per_bp=True)
X_RS[k,66] = X_RS[k,66]/max_ubs
X_RS[k,67] = X_RS[k,67]/max_bs
X_RS[k,68] = X_RS[k,68]/max_ill
X_RS[k,69] = X_RS[k,69]/max_ilr
X_RS[k,70] = X_RS[k,70]/max_lp
X_RS[k,71] = X_RS[k,71]/max_lb
X_RS[k,72] = X_RS[k,72]/max_rb
k+=1
save_feature_sets = False
if save_feature_sets:
maxes = np.array([max_mfe, max_ubs, max_bs, max_ill, max_ilr, max_lp, max_lb, max_rb])
np.save('feature_maxes.npy', maxes)
np.save('X_UTR.npy',X_UTR)
np.save('X_RS.npy',X_RS_full)
###############################################################################
# FEATURE PLOTS
# Plots of various aspects of the X_UTR and X_RS we just constructed
###############################################################################
#@title plotting options
from cycler import cycler
########################################
dark = False
if not dark:
colors = ['#ef476f', '#073b4c','#06d6a0','#7400b8','#073b4c', '#118ab2',]
else:
plt.style.use('dark_background')
plt.rcParams.update({'axes.facecolor' : '#131313' ,
'figure.facecolor' : '#131313' ,
'figure.edgecolor' : '#131313' ,
'savefig.facecolor' : '#131313' ,
'savefig.edgecolor' :'#131313'})
colors = ['#118ab2','#57ffcd', '#ff479d', '#ffe869','#ff8c00','#04756f']
font = {
'weight' : 'bold',
'size' : 12}
save = False
plt.rcParams.update({'font.size': 12, 'font.weight':'bold' } )
plt.rcParams.update({'axes.prop_cycle':cycler(color=colors)})
plt.rcParams.update({'axes.prop_cycle':cycler(color=colors)})
plt.rcParams.update({'axes.prop_cycle':cycler(color=colors)})
plt.rcParams.update({'xtick.major.width' : 2.8 })
plt.rcParams.update({'xtick.labelsize' : 12 })
plt.rcParams.update({'ytick.major.width' : 2.8 })
plt.rcParams.update({'ytick.labelsize' : 12})
plt.rcParams.update({'axes.titleweight' : 'bold'})
plt.rcParams.update({'axes.titlesize' : 10})
plt.rcParams.update({'axes.labelweight' : 'bold'})
plt.rcParams.update({'axes.labelsize' : 12})
plt.rcParams.update({'axes.linewidth':2.8})
plt.rcParams.update({'axes.labelpad':8})
plt.rcParams.update({'axes.titlepad':10})
plt.rcParams.update({'figure.dpi':120})
###############################################################################
# Pie Chart of ligand representation
##############################################################################
amino_acids = ['arginine','histidine','lysine','aspartate','glutamine','serine','threonine','asparagine','cystine','glycine','proline',
'alanine','valine','isoleucine','leucine','methionine','phenylalanine','tyrosine','tryptophan']
aa = False
ligand_list = RS_db[RS_db['ID'].isin(ids_RS_full)]['LIGAND'].values.tolist()
count_list = ligand_list
ligand_names = list(set(count_list))
counts = np.array([count_list.count(x) for x in ligand_names])
idx = np.argsort(counts)[::-1]
sorted_counts = counts[idx]
sorted_names = [ligand_names[i] for i in idx.tolist()]
explode = [0.02]*len(sorted_names)
sub1 = sorted_counts/np.sum(sorted_counts) < .01
colors = cm.Spectral_r(np.linspace(.05,.95,len(sorted_names)))
plt.figure(dpi=300)
_,f,t = plt.pie(sorted_counts, labels = sorted_names, explode = explode, autopct='%1.1f%%',
shadow=False, startangle=90, colors=colors, labeldistance =1.05, pctdistance=.53, textprops={'fontsize': 7})
missing_labels = []
subsum = 0
for i in range(len( t)):
txt = t[i]
label = f[i]
if float(txt._text[:-1]) < 2:
txt.set_visible(False)
label.set_visible(False)
missing_labels.append(label._text)
subsum += float(txt._text[:-1])
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.text(0.17,.4,'16.9%',color='r', size=7)
s = (.74/.4185)
xx,yy = .614,.88
plt.plot([xx,yy], [xx/s,yy/s],'r',alpha=.5)
plt.plot([0,0], [.71,1.01],'r',alpha=.5)
plt.text(.6,1,'Other (33 types)',color='r')
plt.text(.7,.85,'<2% each',color='r')
plt.text(1.1,-1.1,'N = %0.0f'%len(count_list))
plt.title('RS ligand representation')
###############################################################################
# Length distribution of the X_RS and X_UTR
###############################################################################
nbins = 40
UTR_lens = np.array([len(x) for x in dot_UTR])
RS_lens = np.array([len(x) for x in dot_RS_full])
x,bins = np.histogram(RS_lens, bins=nbins)
x2,_ = np.histogram(UTR_lens,bins=bins)
plt.hist(RS_lens, bins=bins, density=True, alpha=1, histtype='step', lw=3)
plt.hist(UTR_lens,bins=bins, density=True, alpha=1, histtype='step', lw=3)
plt.xlim([0,325])
plt.xlabel('Length (NT)')
plt.ylabel('Probability')
plt.legend(['RS n=%s'%str(len(RS_lens)),'UTR n=%s'%str(len(UTR_lens))], loc='upper left')
plt.title('Length distributions')
###############################################################################
# Sequence comparison plot of the 3-mers
###############################################################################
plt.errorbar(np.linspace(0,63,64),np.mean(X_RS[:,:64],axis=0), yerr=np.std(X_RS[:,:64],axis=0),ls='', marker='o', capsize=1)
plt.errorbar(np.linspace(0,63,64),np.mean(X_UTR[:,:64],axis=0), yerr=np.std(X_UTR[:,:64],axis=0),ls='', marker='o', capsize=1)
plt.title('3-mer distribution comparisons')
plt.legend(['RS','UTR'])
plt.figure()
plt.errorbar(np.linspace(0,9,10),np.mean(X_RS[:,-10:],axis=0), yerr=np.std(X_RS[:,-10:],axis=0),ls='', marker='o', capsize=1)
plt.errorbar(np.linspace(0,9,10),np.mean(X_UTR[:,-10:],axis=0), yerr=np.std(X_UTR[:,-10:],axis=0),ls='', marker='o', capsize=1)
plt.title('Other feature distribution comparisons')
plt.legend(['RS','UTR'])
###############################################################################
# KS distances of the X_RS and X_UTR
###############################################################################
from scipy.stats import ks_2samp
kses = [ks_2samp(X_RS[:,i], X_UTR[:,i])[0] for i in range(66+8)]
plt.figure()
plt.bar(np.linspace(0,65+8,66+8),kses)
plt.ylabel('KS distance')
plt.xlabel('Feature')
###############################################################################
# PCA of the X_RS and X_UTR
###############################################################################
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
p = pca.fit(np.vstack([X_UTR, X_RS]))
print(pca.explained_variance_ratio_)
p = pca.fit(np.vstack([X_UTR, X_RS_full]))
x_utr_t = p.transform(X_UTR)
x_rs_t = p.transform(X_RS_full)
plt.figure()
plt.scatter(x_utr_t[:,0], x_utr_t[:,1], s=5,alpha=.2)
plt.scatter(x_rs_t[:,0], x_rs_t[:,1],s=5, alpha=.2)
plt.legend(['UTR','RS'])
plt.xlabel(f'PC1 ({pca.explained_variance_ratio_[0]*100:.3f}%)')
plt.ylabel(f'PC2 ({pca.explained_variance_ratio_[1]*100:.3f}%)')
1/0
###############################################################################
# TRAIN CLASSIFIER ENSEMBLE
###############################################################################
# The ensemble is trained in 3 parts: The "Other" set first (ligands with <2% representation)
# single drop out ligands second, double drop out ligands last.
# OPTIONS:
retrain = False #retrain the ensemble
save = False #save the ensemble after retraining
model_name = "EKmodel_witheld_w_struct_features_9_26" #name for the model files, they will add "_ligand" to the end for each
# Train the "Other" classifier
# preallocate the accuracies, and predicted outputs of the training / validation
witheld_acc_other = []
RS_acc_other = []
UTR_acc_other = []
predicted_RSs_other = []
predicted_withelds_other = []
predicted_UTRs_other = []
estimators_other = []
for i in tqdm(range(1)):
witheld_ligands[:i]
X = np.vstack([X_UTR,] + [x[0] for x in ligand_dfs])
X_witheld = X_RS
if retrain:
svc = SVC(C=10, kernel='rbf', gamma=0.4, probability=True)
pu_estimator = ElkanotoPuClassifier(estimator=svc, hold_out_ratio=0.2)
y = np.zeros(len(X))
y[len(X_UTR):] = 1
pu_estimator.fit(X, y)
else:
pu_estimator =load('./elkanoto_models/%s_%s.joblib'%(model_name, 'other'))
X_t = np.vstack([ X_RS, ] + [x[0] for x in ligand_dfs] )
predicted_RS_other = pu_estimator.predict_proba(X_t)
predicted_witheld_other = pu_estimator.predict_proba(X_witheld)
predicted_UTR_other = pu_estimator.predict_proba(X_UTR)
UTR_acc_other.append( np.sum((predicted_UTR_other[:,1] < .5))/len(X_UTR) )
RS_acc_other.append( np.sum((predicted_RS_other[:,1] > .5))/len(X_t) )
witheld_acc_other.append( np.sum((predicted_witheld_other[:,1] > .5))/len(X_witheld) )
predicted_RSs_other.append(predicted_RS_other)
predicted_withelds_other.append(predicted_witheld_other)
predicted_UTRs_other.append(predicted_UTR_other)
if retrain:
if save:
dump(pu_estimator,'./elkanoto_models/%s_%s.joblib'%(model_name, 'other'))
estimators_other.append(pu_estimator)
# Single drop out classifiers
witheld_acc = []
RS_acc = []
UTR_acc = []
predicted_RSs = []
predicted_withelds = []
predicted_UTRs = []
estimators = []
for i in tqdm(range(len(witheld_ligands))):
witheld_ligands[:i]
X = np.vstack([X_UTR, X_RS, ] + [x[0] for x in ligand_dfs[:i]] + [x[0] for x in ligand_dfs[i+1:]] )
X_witheld = ligand_dfs[i][0]
if retrain:
svc = SVC(C=10, kernel='rbf', gamma=0.4, probability=True)
pu_estimator = ElkanotoPuClassifier(estimator=svc, hold_out_ratio=0.2)
y = np.zeros(len(X))
y[len(X_UTR):] = 1
pu_estimator.fit(X, y)
else:
pu_estimator =load('./elkanoto_models/%s_%s.joblib'%(model_name, witheld_ligands[i]))
X_t = np.vstack([ X_RS, ] + [x[0] for x in ligand_dfs[:i]] + [x[0] for x in ligand_dfs[i+1:]] )
predicted_RS = pu_estimator.predict_proba(X_t)
predicted_witheld = pu_estimator.predict_proba(X_witheld)
predicted_UTR = pu_estimator.predict_proba(X_UTR)
UTR_acc.append( np.sum((predicted_UTR[:,1] < .5))/len(X_UTR) )
RS_acc.append( np.sum((predicted_RS[:,1] > .5))/len(X_t) )
witheld_acc.append( np.sum((predicted_witheld[:,1] > .5))/len(X_witheld) )
predicted_RSs.append(predicted_RS)
predicted_withelds.append(predicted_witheld)
predicted_UTRs.append(predicted_UTR)
if retrain:
if save:
dump(pu_estimator,'./elkanoto_models/%s_%s.joblib'%(model_name, witheld_ligands[i]))
estimators.append(pu_estimator)
# Double drop out ligands
pairs = [('SAM', 'cobalamin'), ('TPP','glycine'),('SAM','TPP'),('glycine','cobalamin'),('TPP','cobalamin'),
('FMN','cobalamin'),('FMN','TPP'),('FMN','SAM'),('FMN','glycine')]
witheld_acc_2 = []
RS_acc_2 = []
UTR_acc_2 = []
predicted_RSs_2 = []
predicted_withelds_2 = []
predicted_UTRs_2 = []
estimators_2 = []
for i in tqdm(range(len(pairs))):
witheld_1 = pairs[i][0]
witheld_2 = pairs[i][1]
ind_1 = witheld_ligands.index(witheld_1)
ind_2 = witheld_ligands.index(witheld_2)
witheld_ligands[:i]
X = np.vstack([X_UTR, X_RS, ] + [ligand_dfs[i][0] for i in range(len(ligand_dfs)) if i not in [ind_1,ind_2]])
X_witheld = np.vstack([ligand_dfs[ind_1][0], ligand_dfs[ind_2][0]])
if retrain:
svc = SVC(C=10, kernel='rbf', gamma=0.4, probability=True)
pu_estimator = ElkanotoPuClassifier(estimator=svc, hold_out_ratio=0.2)
y = np.zeros(len(X))
y[len(X_UTR):] = 1
pu_estimator.fit(X, y)
else:
pu_estimator =load('./elkanoto_models/%s_%s_%s.joblib'%(model_name,witheld_1, witheld_2))
X_t = np.vstack([ X_RS, ] + [ligand_dfs[i][0] for i in range(len(ligand_dfs)) if i not in [ind_1,ind_2]])
predicted_RS_2 = pu_estimator.predict_proba(X_t)
predicted_witheld_2 = pu_estimator.predict_proba(X_witheld)
predicted_UTR_2 = pu_estimator.predict_proba(X_UTR)
UTR_acc_2.append( np.sum((predicted_UTR_2[:,1] < .5))/len(X_UTR) )
RS_acc_2.append( np.sum((predicted_RS_2[:,1] > .5))/len(X_t) )
witheld_acc_2.append( np.sum((predicted_witheld_2[:,1] > .5))/len(X_witheld) )
predicted_RSs_2.append(predicted_RS_2)
predicted_withelds_2.append(predicted_witheld_2)
predicted_UTRs_2.append(predicted_UTR_2)
if retrain:
if save:
dump(pu_estimator,'./elkanoto_models/%s_%s_%s.joblib'%(model_name,witheld_1, witheld_2))
estimators_2.append(pu_estimator)
#combine the ensemble classifiers into a list
ensemble = estimators + estimators_2 + estimators_other
ensemble = estimators + predicted_RS_2 + estimators_other
ensemble = estimators + predicted_witheld_2 + estimators_other
ensemble = estimators + predicted_UTR_2 + estimators_other
ensemble = estimators + UTR_acc_2 + estimators_other
ensemble = estimators + RS_acc_2 + estimators_other
ensemble = estimators + witheld_acc_2 + estimators_other
#normalization vector for the outputs to the max of the training
#ensemble_norm = np.load('./%s'%model_norm)
redo_importance = False
if redo_importance:
#PERMUTATION IMPORTANCE
from sklearn.inspection import permutation_importance
rs = []
X = np.vstack([X_RS_full[:5000], X_UTR[:5000]])
y = np.zeros(len(X))
y[len(X_UTR[:5000]):] = 1
for i in range(len(ensemble)):
print(i)
rs.append(permutation_importance(ensemble[i], X, y,
n_repeats=10,
random_state=0))
else:
importances = np.load('importances.npy')
#plt.boxplot(r.importances.T, vert=False, showfliers=False); plt.xlabel('accuracy loss'); plt.ylabel('feature')
plt.figure(figsize=(5,10), dpi=300); #plt.boxplot(r.importances.T, vert=False, showfliers=False); plt.xlabel('accuracy loss'); plt.ylabel('feature'); plt.yticks(rotation=90, fontsize=6); plt.grid(True)
import itertools
#importances = np.array([x.importances.T for x in rs])
plt.figure(figsize=(5,10),dpi=300);
from matplotlib import cm
for i in range(20):
plt.boxplot(importances[i], vert=False, showfliers=False, boxprops={'alpha':.8, 'color':cm.viridis(i/20)},
capprops={'alpha':.8, 'color':cm.viridis(i/40)},
whiskerprops={'alpha':.8, 'color':cm.viridis(i/40)},
medianprops={'alpha':.8, 'color':cm.viridis(i/40)},
meanprops={'alpha':.8, 'color':cm.viridis(i/40)},
);
plt.xlabel('accuracy loss'); plt.ylabel('feature'); plt.yticks(rotation=90, fontsize=6); plt.grid(True)
ls = ['',] + [''.join(x) for x in itertools.product(['a','c','u','g'], repeat=3)] + ['GC%', 'M=FE', 'UBS', 'BS', 'LL','RL','L','RB','LB','%UP']
ax = plt.gca()
ax.set_yticks([x for x in range(75)])
ax.set_yticklabels(ls)
ax.yaxis.set_tick_params(rotation=0)
plt.figure(figsize=(5,10),dpi=300);
from matplotlib import cm
i=0
plt.boxplot(importances.reshape(200,74), vert=False, showfliers=False, boxprops={'alpha':1, 'color':cm.viridis(i/20)},
capprops={'alpha':1, 'color':cm.viridis(i/20)},
whiskerprops={'alpha':1, 'color':cm.viridis(i/20)},
medianprops={'alpha':1, 'color':cm.viridis(i/20)},
meanprops={'alpha':1, 'color':cm.viridis(i/20)},
);
plt.xlabel('accuracy loss'); plt.ylabel('feature'); plt.yticks(rotation=90, fontsize=6); plt.grid(True)
ls = ['',] + [''.join(x) for x in itertools.product(['a','c','u','g'], repeat=3)] + ['GC%', 'M=FE', 'UBS', 'BS', 'LL','RL','L','RB','LB','%UP']
ax = plt.gca()
ax.set_yticks([x for x in range(75)])
ax.set_yticklabels(ls)
ax.yaxis.set_tick_params(rotation=0)
plt.figure(figsize=(5,13),dpi=300);
from matplotlib import cm
i=0
plt.boxplot(importances.reshape(200,74), vert=False, showfliers=False, boxprops={'alpha':1, 'color':cm.viridis(i/20), 'label':'_nolegend_'},
capprops={'alpha':1, 'color':cm.viridis(i/20), 'label':'_nolegend_'},
whiskerprops={'alpha':1, 'color':cm.viridis(i/20), 'label':'_nolegend_'},
medianprops={'alpha':1, 'color':cm.viridis(i/20), 'label':'_nolegend_'},
meanprops={'alpha':1, 'color':cm.viridis(i/20), 'label':'_nolegend_'},
);
colors = ['#ef476f', '#073b4c','#06d6a0','#7400b8','#073b4c', '#118ab2',]
for i in range(74):
plt.scatter(np.mean(importances,axis=1)[:,i], [i+1]*20, marker='o', color=colors[0], s=4)
plt.xlabel('accuracy loss'); plt.ylabel('feature'); plt.yticks(rotation=90, fontsize=6); plt.grid(True)
ls = ['',] + [''.join(x) for x in itertools.product(['a','c','u','g'], repeat=3)] + ['GC%', 'MFE', 'UBS', 'BS', 'LL','RL','L','RB','LB','%UP']
ax = plt.gca()
ax.set_yticks([x for x in range(75)])
ax.set_yticklabels(ls, fontsize=9)
ax.yaxis.set_tick_params(rotation=0)
plt.title('Feature importance across the final ensemble')
plt.legend(['single classifier mean (n=10)'], loc='lower left')
plt.plot([0,0],[1,74],'k-',lw=1)
plt.savefig('./SIfigure2.png')
import random
random.seed(42)
def generate_key():
STR_KEY_GEN = 'augc'
return ''.join(random.choice(STR_KEY_GEN) for _ in range(600))
rand_30 = [generate_key() for i in range(60000)]
h,xx = np.histogram(RS_lens, bins = np.max(RS_lens), density=True);
cdf = np.cumsum(h*np.diff(xx))
rand_lens = []
for i in range(60000):
rand_lens.append(np.where(np.random.rand() > cdf)[0][-1] + 25)
plt.hist(lens,bins = 100, density=True, alpha=.4)
plt.hist(RS_lens, bins=100, density=True, alpha=.4)
RAND_RS_features = []
for i in range(len(rand_30)):
mfe,hr = get_mfe_nupack(rand_30[i][:rand_lens[i]])
RAND_RS_features.append([rand_30[i][:rand_lens[i]], str(mfe[0][0]), mfe[0][1]])
X_RAND =np.zeros([len(rand_30), 66+8])
k = 0
for i in range(len(rand_30)):
seq = clean_seq(rand_30[i])
if len(seq) > 25:
#seq = clean_seq(RS_df['SEQ'].iloc[i])
kmerf = kmer_freq(seq)
X_RAND[k,:64] = kmerf/np.sum(kmerf)
X_RAND[k,64] = RAND_RS_features[i][-1]/max_mfe
X_RAND[k,65] = get_gc(seq)
#ds_RS.append(RS_df['ID'].iloc[i])
#dot_RS.append(RS_df['NUPACK_DOT'].iloc[i])
X_RAND[k,-8:] = be.annoated_feature_vector(RAND_RS_features[i][-2])
X_RAND[k,66] = X_RAND[k,66]/max_ubs
X_RAND[k,67] = X_RAND[k,67]/max_bs
X_RAND[k,68] = X_RAND[k,68]/max_ill
X_RAND[k,69] = X_RAND[k,69]/max_ilr
X_RAND[k,70] = X_RAND[k,70]/max_lp
X_RAND[k,71] = X_RAND[k,71]/max_lb
X_RAND[k,72] = X_RAND[k,72]/max_rb
k+=1
reload_X_RAND = True
if reload_X_RAND:
X_RAND = np.load('./X_RAND.npy')
predicted_rand = np.zeros([len(X_RAND), 20])
ensemble = estimators + estimators_2 + estimators_other
for j in range(20):
predicted_rand[:,j] = ensemble[j].predict_proba(X_RAND)[:,1]
plt.plot(np.sum(predicted_rand > .5, axis =1)/20,'o')
###############################################################################
# 20 fold k cross validation without structural holdouts
###############################################################################
import sklearn
save = True
retrain = True
model_name = 'EKmodel_witheld_20kfcv_2'
X = np.vstack([X_UTR, X_RS_full,])
y = np.zeros(len(X))
y[len(X_UTR):] = 1
kf = sklearn.model_selection.KFold(n_splits=20, shuffle=True, random_state=42)
X_RAND = np.load('./X_RAND.npy')
X_EXONS = np.load('./X_EXONS.npy')
ensemble_2 = []
witheld_RS_acc_2 = []
for i, (train_index, test_index) in enumerate(kf.split(X,y)):
print(i)
X_train, X_test, y_train, y_test = X[train_index], X[test_index], y[train_index], y[test_index]
if retrain:
svc = SVC(C=15, kernel='rbf', gamma=0.2, probability=True)
pu_estimator = ElkanotoPuClassifier(estimator=svc, hold_out_ratio=0.2)
pu_estimator.fit(X_train, y_train)
if save:
dump(pu_estimator,'./elkanoto_models/%s_%s.joblib'%(model_name,i))
else:
svc = SVC(C=10, kernel='rbf', gamma=0.4, probability=True)
pu_estimator = ElkanotoPuClassifier(estimator=svc, hold_out_ratio=0.2)
pu_estimator =load('./elkanoto_models/%s_%s.joblib'%(model_name,str(i)))
predicted_RS = pu_estimator.predict_proba(X_test[y_test==1])
witheld_RS_acc_2.append(np.sum(predicted_RS > .5 )/ (len(X_test[y_test==1])))
print(np.sum(predicted_RS > .5 )/ (len(X_test[y_test==1])))
ensemble_2.append(pu_estimator)
kf = sklearn.model_selection.KFold(n_splits=20, shuffle=True, random_state=42)
train_ens2_acc = []
test_ens2_acc = []
found_UTR_ens2 = []
random_ens2_acc = []
structured_ens2_acc = []
rands_2 = []
exons_2 = []
for i, (train_index, test_index) in enumerate(kf.split(X,y)):
X_train, X_test, y_train, y_test = X[train_index], X[test_index], y[train_index], y[test_index]
p = ensemble_2[i].predict_proba((X_test[y_test==1]))
t = ensemble_2[i].predict_proba((X_train[y_train==1]))
u = ensemble_2[i].predict_proba(X_UTR)
r = ensemble_2[i].predict_proba(X_RAND)
ex = ensemble_2[i].predict_proba(X_EXONS)
rands_2.append(r)
exons_2.append(ex)
test_ens2_acc.append(np.sum(p[:,1] > .5 )/ (len(X_test[y_test==1])))
train_ens2_acc.append(np.sum(t[:,1] > .5 )/ (len(X_train[y_train==1])))
found_UTR_ens2.append(np.sum(u[:,1] > .5 )/ (len(X_UTR)))
random_ens2_acc.append(np.sum(r[:,1] > .5 )/ (len(X_RAND)))
structured_ens2_acc.append(np.sum(ex[:,1] > .5 )/ (len(X_EXONS)))
train_ens_acc = []
test_ens_acc = []
found_UTR_ens = []
random_ens_acc = []
structured_ens_acc = []
for i in range(len(ensemble)):
r = ensemble[i].predict_proba(X_RAND)
ex = ensemble[i].predict_proba(X_EXONS)
random_ens_acc.append(np.sum(r[:,1] > .5 )/ (len(X_RAND)))
structured_ens_acc.append(np.sum(ex[:,1] > .5 )/ (len(X_EXONS)))
data = np.array([RS_acc + RS_acc_2 + RS_acc_other,
witheld_acc + witheld_acc_2 + witheld_acc_other,
UTR_acc + UTR_acc_2 + UTR_acc_other,
random_ens_acc,
structured_ens_acc])
data[2,:] = 1 - data[2,:]
plt.matshow(data)
ax = plt.gca()
for (i, j), z in np.ndenumerate(data):
ax.text(j, i, '{:0.3f}'.format(z), ha='center', va='center')
ax.set_xticks([x for x in range(20)])
ax.set_xticklabels([x for x in range(20)])
ax.set_yticklabels(['','Train', 'Test', 'UTR', 'RAND', 'EXON'])
data = np.array([train_ens2_acc,
test_ens2_acc,
found_UTR_ens2,
random_ens2_acc,
structured_ens2_acc])
plt.figure()
plt.matshow(data)
ax = plt.gca()
for (i, j), z in np.ndenumerate(data):
ax.text(j, i, '{:0.3f}'.format(z), ha='center', va='center')
ax.set_xticks([x for x in range(20)])
ax.set_xticklabels([x for x in range(20)])
ax.set_yticklabels(['', 'Train', 'Test', 'UTR', 'RAND', 'EXON'])
testens=[]
for i in range(len(ensemble)):
ex = ensemble[i].predict_proba(X_EXONS)
testens.append(np.sum(ex[:,1] > .95 )/ (len(X_EXONS)))
1/0
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
#p = pca.fit(np.vstack([X_UTR, X_RS, X_RAND, X_EXONS]))
p = pca.fit(np.vstack([X_UTR, X_RS_full])) # X_RAND, X_EXONS]))
print(pca.explained_variance_ratio_)
x_utr_t = p.transform(X_UTR)
x_rs_t = p.transform(X_RS_full)
x_rand_t = p.transform(X_RAND)
x_exon_t = p.transform(X_EXONS)
plt.figure()
plt.scatter(x_utr_t[:,0], x_utr_t[:,1], s=5,alpha=.2)
plt.scatter(x_rs_t[:,0], x_rs_t[:,1],s=5, alpha=.2)
#plt.scatter(x_rand_t[:,0], x_rand_t[:,1],s=5, alpha=.2)
#plt.scatter(x_exon_t[:,0], x_exon_t[:,1],s=5, alpha=.2)
plt.legend(['UTR','RS'])#, 'RAND', 'EXON'])
plt.xlabel(f'PC1 ({pca.explained_variance_ratio_[0]*100:.3f}%)')
plt.ylabel(f'PC2 ({pca.explained_variance_ratio_[1]*100:.3f}%)')
with open('./final_set.json', 'r') as f:
UTR_hit_list = json.load(f)
x_hits = x_utr_t[[ids_UTR.index(x) for x in ids_UTR if x not in UTR_hit_list]]
thresh = .25
fx = lambda t: (np.sum((x_utr_t[:,0] > t) == 1) + np.sum((x_rs_t[:,0] <= t) == 1)) / (len(x_utr_t) + len(x_rs_t))
y = []
for t in np.linspace(-.25,5,1000):
y.append(fx(t))
thresh = np.linspace(-.25,5,1000)[np.argmax(y)]