-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_analyses.py
2640 lines (2139 loc) · 116 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
###############################################################################
'''
This file runs all the analyses for the paper:
Identification of potential riboswitch elements in Homo
Sapiens mRNA 5’UTR sequences using Positive-Unlabeled
machine learning
By Dr. William Raymond, Dr. Jacob DeRoo, and Dr. Brian Munsky
File sections:
Data generation
Load both RS and UTR CSVs and convert them to feature vectors for machine learning
and visualization.
Data visualization
generate several plots:
PCA plots of the features
KS distances of the feature sets
length distributions of the sequences
ligand representation of the riboswitches
Main ensemble training
20 fold cross validation on withheld ligand sets
save the results / hits
testing on sub sequences
Ensemble validation
circular plot of ensemble results
Other ensemble training(s)
20 fold cross validation on random sets, no ligand hold out
retraining 20 fold cross validation with ligand hold out but with also negative random and exon sequences
synthetic riboswitch testing
Accessory validations
eukaryotic riboswitch testing
'''
###############################################################################
# OPTIONS
###############################################################################
# filenames for the RS dataset and UTR dataset
RS_fname = './data_files/RS_final_with_euk2.csv'
UTR_fname = './data_files/5primeUTR_final_db_3.csv'
# Plotting options:
dark = False # use a dark theme when available?
global_dpi = 300 # plot dpi
save_plots = False # resave the plots?
# main ensemble options:
retrain_main_ensemble = False #retrain the ensemble
save_main_ensemble = False #save the ensemble after retraining
main_ensemble_name = "EKmodel_witheld_w_struct_features_9_26" #name for the model files, they will add "_ligand" to the end for each
save_feature_sets = False #save the X_UTR and X_RS and their maxes to feature_npy_files
resave_ensemble_hits = False # resave/remake all the hit data files and alignment matrices
redo_levdist = False # redo the levenstien distance array this is very slow.
model_norm = 'utr_proba_norm.npy'
plot_format = '.png' #format to save the plots, either .svg or .png, you need the period!
# remake feature sets or reload them?
reload_X_syn = False
reload_X_RAND = True
# Redo the feature importances (SI Figure 2) with sklearn, otherwise load in the saved run.
# Redoing this will take a very long time, up to a week.
redo_importance = False
# Substring analyses (Figure 6)
reload_X_SUB = True # otherwise this will regenrate X_sub which will take a long time
save_substrings = False # save the X_SUB if you regenerated it
reload_prediction_sub = True # reload the ensemble prediction
# second ensemble with no structural hold out, just random cross validation
save_20_fold_cross_validation_ensemble = False
retrain_20_fold_cross_validation_ensemble = False
fold_cv_model_name = 'EKmodel_witheld_20kfcv_2'
# third ensemble using structural hold out but including explicit negative examples
# Exon sequences and Random sequences.
save_rand_exon_ensemble = False
retrain_rand_exon_ensemble = False
rand_exon_model_name = 'EKmodel_witheld_w_exon_rand'
###############################################################################
# Imports
###############################################################################
#standard libraries, plotting, numpy pandas
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 tqdm import tqdm
from cycler import cycler
import itertools
from scipy import stats
# Machine learning libraries
from sklearn import mixture
from pulearn import ElkanotoPuClassifier, BaggingPuClassifier
from sklearn.svm import SVC
from joblib import dump, load
from sklearn.inspection import permutation_importance
import sklearn
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
UTR_db = pd.read_csv(UTR_fname)
print('UTR data file loaded: %s'%UTR_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
RS_db = pd.read_csv(RS_fname)
print('RS data file loaded: %s'%RS_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 1.0 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 idx in ids_to_update.keys():
for i in range(len(ids_to_update[idx])):
UTR_db.iloc[ids_to_update[idx][i],3] = idx + '-' + 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
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_npy_files/feature_maxes.npy', maxes)
np.save('./feature_npy_files/X_UTR.npy',X_UTR)
np.save('./feature_npy_files/X_RS.npy',X_RS_full)
###############################################################################
# FEATURE PLOTS
# Plots of various aspects of the X_UTR and X_RS we just constructed
###############################################################################
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}
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
colors2 = cm.Spectral_r(np.linspace(.05,.95,len(sorted_names)))
plt.figure(dpi=global_dpi)
_,f,t = plt.pie(sorted_counts, labels = sorted_names, explode = explode, autopct='%1.1f%%',
shadow=False, startangle=90, colors=colors2, 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')
if save_plots:
plt.savefig('./plots/RS_ligand_representation_chart%s'%plot_format)
###############################################################################
# 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.figure(dpi=global_dpi)
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')
if save_plots:
plt.savefig('./plots/data_length_distributions%s'%plot_format)
###############################################################################
# Sequence comparison plot of the 3-mers
###############################################################################
plt.figure(dpi=global_dpi)
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'])
if save_plots:
plt.savefig('./plots/3mer_distributions%s'%plot_format)
plt.figure(dpi=global_dpi)
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'])
if save_plots:
plt.savefig('./plots/struct_features_distributions%s'%plot_format)
###############################################################################
# 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(dpi=global_dpi)
plt.bar(np.linspace(0,65+8,66+8),kses, color = [colors[0]]*64 + [colors[1]] + [colors[2]] + [colors[3]]*8)
plt.ylabel('KS distance')
plt.xlabel('Feature')
plt.title('KS distance between RS and UTR data set for each feature')
custom_lines = [Line2D([0], [0], color=colors[0], lw=4),
Line2D([0], [0], color=colors[1], lw=4),
Line2D([0], [0], color=colors[2], lw=4),
Line2D([0], [0], color=colors[3], lw=4)]
ax = plt.gca()
ax.legend(custom_lines, ['3-mers (64)','GC content', 'MFE', 'Structural features (8)'], prop={'size':8})
if save_plots:
plt.savefig('./plots/KS_distances_of_features%s'%plot_format)
###############################################################################
# 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}%)')
if save_plots:
plt.savefig('./plots/PCA_plot_data%s'%plot_format)
###############################################################################
# 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.
# 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_main_ensemble:
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'%(main_ensemble_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_main_ensemble:
if save_main_ensemble:
dump(pu_estimator,'./elkanoto_models/%s_%s.joblib'%(main_ensemble_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_main_ensemble:
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'%(main_ensemble_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_main_ensemble:
if save_main_ensemble:
dump(pu_estimator,'./elkanoto_models/%s_%s.joblib'%(main_ensemble_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_main_ensemble:
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'%(main_ensemble_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_main_ensemble:
if save_main_ensemble:
dump(pu_estimator,'./elkanoto_models/%s_%s_%s.joblib'%(main_ensemble_name,witheld_1, witheld_2))
estimators_2.append(pu_estimator)
#combine the ensemble classifiers into a list
ensemble = estimators + estimators_2 + estimators_other
predicted_RS_all = predicted_RSs + predicted_RSs_2 + predicted_RSs_other
predicted_witheld_all = predicted_withelds + predicted_withelds_2 + predicted_withelds_other
predicted_UTR_all = predicted_UTRs + predicted_UTRs_2 + predicted_UTRs_other
UTR_acc_all = UTR_acc + UTR_acc_2 + UTR_acc_other
RS_acc_all = RS_acc + RS_acc_2 + RS_acc_other
witheld_acc_all = witheld_acc + witheld_acc_2 + witheld_acc_other
#normalization vector for the outputs to the max of the training
ensemble_norm = np.load('./elkanoto_models/%s'%model_norm)
all_utr_predicitions = np.array(predicted_UTRs + predicted_UTRs_2 + predicted_UTRs_other).T[1]
###############################################################################
# Save the ensemble outputs and alignment matrices (for the website)
###############################################################################
def lev_dist(token1, token2):
distances = np.zeros((len(token1) + 1, len(token2) + 1))
for t1 in range(len(token1) + 1):
distances[t1][0] = t1
for t2 in range(len(token2) + 1):
distances[0][t2] = t2
a = 0
b = 0
c = 0
for t1 in range(1, len(token1) + 1):
for t2 in range(1, len(token2) + 1):
if (token1[t1-1] == token2[t2-1]):
distances[t1][t2] = distances[t1 - 1][t2 - 1]
else:
a = distances[t1][t2 - 1]
b = distances[t1 - 1][t2]
c = distances[t1 - 1][t2 - 1]
if (a <= b and a <= c):
distances[t1][t2] = a + 1
elif (b <= a and b <= c):
distances[t1][t2] = b + 1
else:
distances[t1][t2] = c + 1
return distances[len(token1)][len(token2)]
if resave_ensemble_hits:
match_indexes = [np.where(all_utr_predicitions[:,i] >.95)[0].tolist() for i in range(20)]
all_hits_indexes = list(set([item for sublist in match_indexes for item in sublist]))
hits1533 = sorted([ids_UTR[x] for x in list(all_hits_indexes)])
all_set = hits1533
print('total hits: %i'%len(all_set))
with open('./ensemble_predictions/final_set_1533.json','w') as f:
json.dump(all_set,f)
UTR_hit_list = all_set
utr_proba = all_utr_predicitions[[ids_UTR.index(x) for x in UTR_hit_list],:]
np.save('./ensemble_predictions/utr_proba_1533.npy', utr_proba.T)
np.save('./ensemble_predictions/ENS_count.npy',np.sum(all_utr_predicitions[[ids_UTR.index(x) for x in UTR_hit_list],:] > .95, axis=1))
encode_bear_RS = []
print('saving bear_rs_dots, bear_utr_dots....')
be = BEARencoder()
encoded_bears_hits = []
encoded_array_hits = []
for id in tqdm(range(len(UTR_hit_list))):
en = be.encode(UTR_db[UTR_db['ID'] == UTR_hit_list[id]]['NUPACK_25'].iloc[0])
a = be.annoated_feature_vector(UTR_db[UTR_db['ID'] == UTR_hit_list[id]]['NUPACK_25'].iloc[0], encode_stems_per_bp=True)
encoded_bears_hits.append(en)
encoded_array_hits.append(a)
with open('./ensemble_predictions/bear_encoded_hits_1533.json','w') as f:
json.dump(encoded_bears_hits,f)
np.save('./ensemble_predictions/encode_array_hits_1533.npy',encoded_array_hits)
UTR_hit_list = all_set
be = BEARencoder()
encoded_bears_hits = []
encoded_array_hits = []
for id in tqdm(range(len(UTR_hit_list))):
en = UTR_db[UTR_db['ID'] == UTR_hit_list[id]]['NUPACK_25'].iloc[0]
a = be.annoated_feature_vector(UTR_db[UTR_db['ID'] == UTR_hit_list[id]]['NUPACK_25'].iloc[0], encode_stems_per_bp=True)
encoded_bears_hits.append(en)
encoded_array_hits.append(a)
with open('./ensemble_predictions/utr_dot_hits_1533.json','w') as f:
json.dump(encoded_bears_hits,f)
encode_bear_RS = []
encoded_array_RS = []
for id in tqdm(range(len(ids_RS_full))):
en = RS_db[RS_db['ID'] == ids_RS_full[id]]['NUPACK_DOT'].iloc[0]
a = be.annoated_feature_vector(RS_db[RS_db['ID'] == ids_RS_full[id]]['NUPACK_DOT'].iloc[0], encode_stems_per_bp=True)
encode_bear_RS.append(en)
encoded_array_RS.append(a)
mses = np.zeros([len(UTR_hit_list), len(encoded_array_RS)])
for i in tqdm(range(len(encoded_array_hits))):
mses[i,:] = np.sum( np.square(np.subtract(encoded_array_RS,encoded_array_hits[i])) ,axis=1)
np.save('./alignment_matrices/utr_hits_mse_1533.npy',mses)
len_hits = []
len_RS = []
for id in tqdm(range(len(UTR_hit_list))):
len_hits.append(len(UTR_db[UTR_db['ID'] == UTR_hit_list[id]]['NUPACK_25'].iloc[0]))
for id in tqdm(range(len(ids_RS_full))):
len_RS.append(len(RS_db[RS_db['ID'] == ids_RS_full[id]]['NUPACK_DOT'].iloc[0]))
ldiff = np.zeros([len(UTR_hit_list), len(encoded_array_RS)])
len_hits = np.array(len_hits)
len_RS = np.array(len_RS)
for i in tqdm(range(len(encoded_array_hits))):
ldiff[i,:] = np.square(len_RS - len_hits[i])
np.save('./alignment_matrices/utr_hits_ldiff_mse_1533.npy',ldiff)
if redo_levdist:
levdists = np.zeros([len(UTR_hit_list), len(encoded_array_RS)])
len_hits = np.array(len_hits)
len_RS = np.array(len_RS)
for i in tqdm(range(len(UTR_hit_list))):
for j in range(len(encoded_array_hits)):
ldiff[i,j] = lev_dist(encoded_bears_hits[i],encode_bear_RS[j])
np.save('./alignment_matrices/utr_hits_ldiff_mse_1533.npy',ldiff)
# DETECT IF NUPACK IS INSTALLED
try:
import nupack
nupack_installed = True
except:
nupack_installed = False
print('NUPACK is not installed on your system!! Please go to https://www.nupack.org/ and obtain a liscence to install it in your environment.')
print('skipping the base pair matrices')
if nupack_installed:
def get_mfe_nupack(seq, n=100):
model1 = Model(material='rna', celsius=37)
example_hit = seq
example_hit = Strand(example_hit, name='example_hit')
t1 = Tube(strands={example_hit: 1e-8}, complexes=SetSpec(max_size=1), name='t1')
hit_results = tube_analysis(tubes=[t1], model=model1,
compute=['pairs', 'mfe', 'sample', 'ensemble_size'],
options={'num_sample': n}) # max_size=1 default
mfe = hit_results[list(hit_results.complexes.keys())[0]].mfe
return mfe, hit_results
def matching_parentheses(string, idx):
if idx < len(string) and string[idx] == "(":
opening = [i for i, c in enumerate(string[idx + 1 :]) if c == "("]
closing = [i for i, c in enumerate(string[idx + 1 :]) if c == ")"]
for i, j in enumerate(closing):
if i >= len(opening) or j < opening[i]:
return j + idx + 1
return -1
k = 0
# save the base pair matrices for every hit
outputs = []
hrs = []
bp_strs = []
bp_arr = np.ones([len(UTR_hit_list),300,300])*-1
bp_ids = []
max_window = 300
mfes = []
bpm_bound_all = np.ones([len(UTR_hit_list),300,300])*-1
bpm_unbound_all = np.ones([len(UTR_hit_list),300,300])*-1
for i in trange(0,len(UTR_hit_list)):
sdf = UTR_db[UTR_db['ID'] == UTR_hit_list[i]]
utr_seq = sdf['SEQ'].iloc[0]
if not pd.isnull(sdf['CCDS'].iloc[0]):
ccds = sdf['CCDS'].iloc[0]
mature_mrna = utr_seq + ccds
### UTR + 25 NT near start
if len(utr_seq) > max_window-25:
seq = utr_seq[-max_window+25:] + ccds[:25]
else:
seq = utr_seq + ccds[:25]
mfe,hr = get_mfe_nupack(seq, n=1000)
bp_m = hr.complexes[list(hr.complexes.keys())[0]].pairs.to_array()
bp_arr[k,:len(bp_m),:len(bp_m)] = bp_m
bp_ids.append(sdf['ID'].iloc[0])
mfes.append(mfe)
# SPLIT INTO Bound unbound
dots = [str(x) for x in hr.complexes[list(hr.complexes.keys())[0]].sample]
aug_bound = []
aug_unbound = []
for i in range(len(dots)):
if '(' in dots[i][-25:-22] or ')' in dots[i][-25:-22] :
aug_bound.append(dots[i])
else:
aug_unbound.append(dots[i])
L = len(dots[i])
bound_bpm = np.zeros([L,L])
unbound_bpm = np.zeros([L,L])
for j in range(len(aug_bound)):
for n in range(L):
m = matching_parentheses(aug_bound[j], n)
if m != -1:
bound_bpm[n,m] += 1
bound_bpm[m,n] += 1
else:
bound_bpm[n,n] += 1
for j in range(len(aug_unbound)):
for n in range(L):
m = matching_parentheses(aug_unbound[j], n)
if m != -1:
unbound_bpm[n,m] += 1
unbound_bpm[m,n] += 1
else:
unbound_bpm[n,n] += 1
bpm_unbound_all[k,:L,:L] = unbound_bpm
bpm_bound_all[k,:L,:L] = bound_bpm
k+=1
np.save('./ensemble_predictions/hits_1533_bpmat.npy',bp_arr)
np.save('./ensemble_predictions/hits_1533_bpmat_unbound.npy',bpm_unbound_all)
np.save('./ensemble_predictions/hits_1533_bpmat_bound.npy',bpm_bound_all)
###############################################################################
# LEARN SINGULAR FEATURE IMPORTANCES
###############################################################################
# For more information on singular permutation feature importances see:
# https://scikit-learn.org/1.5/modules/permutation_importance.html
# please note that these are SINGULAR permutations and do not consider features in relation
# to one another. Also a low feature importance does not necessarily mean that feature
# isnt informative, rather that that feature is not used for this particular model.
if redo_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)):