-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDislncRF.py
3331 lines (2914 loc) · 132 KB
/
DislncRF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import gzip
from collections import Counter
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm, grid_search
import numpy as np
import pdb
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import normalize
from sklearn.feature_selection import RFE
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import matplotlib.pyplot as plt
#plt.rcParams['font.size'] = 15.0
from matplotlib_venn import venn3, venn3_circles
from matplotlib_venn import venn2, venn2_circles
#from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from scipy import stats
import random
import cPickle
import argparse
import stringrnautils
from math import*
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.cluster import KMeans
from sklearn import cross_validation
#import xgboost as xgb
import pandas as pd
import math
from sklearn.neighbors.kde import KernelDensity
from sklearn.cross_validation import train_test_split
from sklearn import mixture
from collections import Counter
from sklearn.cross_validation import KFold
from parseobo import obo_object
import scipy.spatial.distance as ssd
from scipy.stats import spearmanr as spearman
from scipy.sparse import issparse
from scipy.sparse import csr_matrix
import venn
CUTOFF = 0.001#np.log2(1+0.5)
TRAIN_NUM = 50
SCALEUP = 1.0
SCALEDOWN = 1.0
WINDOW_SIZE = 35
parser = argparse.ArgumentParser(description="""infer disease-associated lncRNAs based on lncRNA and mRNA co-expression from RNAseq""")
parser.add_argument('-ratio',
type=int, help='ratio is number of negative subsets to ensemble learning',
default=5) # LJJ said to use this number instead :D
parser.add_argument('-file', help='input expression file', default='')
parser.add_argument('-outfile', help='outfile for infered disease associated lncRNAs')
parser.add_argument('-type', default='mRNA', help='cross-validation using mRNA or predict for lncRNA')
parser.add_argument('-data', default=0, type=int, help='0: gencode; 1: GSE43520; 2:GSE30352; 3:GTEx')
parser.add_argument('-conf', help='extract mRNA-disease pair with at least this confidence', type=int, default=2)
args = parser.parse_args()
'''
def allindices(string, sub, listindex=[], offset=0):
i = string.find(sub, offset)
while i >= 0:
listindex.append(i)
i = string.find(sub, i + 1)
return listindex
import re
starts = [match.start() for match in re.finditer(re.escape('GG'), sss)]
'''
""" return euclidean distance between two lists """
def point_overlap(min1, max1, min2, max2):
return max(0, min(max1, max2) - max(min1, min2))
def euclidean_distance(x,y):
return sqrt(sum(pow(a-b,2) for a, b in zip(x, y)))
def calculate_performace(test_num, pred_y, labels):
tp =0
fp = 0
tn = 0
fn = 0
for index in range(test_num):
if labels[index] ==1:
if labels[index] == pred_y[index]:
tp = tp +1
else:
fn = fn + 1
else:
if labels[index] == pred_y[index]:
tn = tn +1
else:
fp = fp + 1
acc = float(tp + tn)/test_num
precision = float(tp)/(tp+ fp)
sensitivity = float(tp)/ (tp+fn)
specificity = float(tn)/(tn + fp)
MCC = float(tp*tn-fp*fn)/(np.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)))
return acc, precision, sensitivity, specificity, MCC
def get_normalized_values_by_column(array, fea_length):
max_col =[-100000] * fea_length
min_col = [100000] * fea_length
#for key in array.keys():
# indvidual_fea = array[key]
for values in array:
for index in range(len(values)):
if values[index] > max_col[index]:
max_col[index] = values[index]
if values[index] < min_col[index]:
min_col[index] = values[index]
for values in array:
for index in range(len(values)):
#print values[index],min_col[index], max_col[index]
values[index] = float(values[index] - min_col[index])/(max_col[index] - min_col[index])
fw = open('saved_min_max', 'w')
for val in min_col:
fw.write('%f\t' %val)
fw.write('\n')
for val in max_col:
fw.write('%f\t' %val)
fw.write('\n')
fw.close()
def get_normalized_given_max_min(array):
normalized_data = np.zeros(array.shape)
tmp_data = np.loadtxt('saved_min_max')
min_col = tmp_data[0, :]
max_col = tmp_data[1, :]
for x in xrange(array.shape[0]):
for y in xrange(array.shape[1]):
#print values[index],min_col[index], max_col[index]
normalized_data[x][y] = float(array[x][y] - min_col[y])/(max_col[y] - min_col[y])
return normalized_data
def transfer_probability_class(result):
y_pred = []
for val in result:
if val >= 0.5:
y_pred.append(1)
else:
y_pred.append(0)
return y_pred
def train_model(train_data, train_label, save_model_file, SVM = False):
if SVM:
parameters = {'kernel': ['linear', 'rbf'], 'C': [1, 2, 3, 4, 5, 6, 10], 'gamma': [0.5,1,2,4, 6, 8]}
svr = svm.SVC(probability = True)
clf = grid_search.GridSearchCV(svr, parameters, cv=3)
else:
clf = RandomForestClassifier(n_estimators=10)
clf.fit(train_data, train_label)
with open(save_model_file, 'wb') as f:
cPickle.dump(clf, f)
def predict_new_data(test_data, save_model_file, SVM = False):
get_normalized_given_max_min(test_data)
with open(save_model_file, 'rb') as f:
clf = cPickle.load(f)
preds = clf.predict_proba(test_data)
return preds[:, 1]
def get_banlanced_data(data, label, ratio = 1):
inner_data = []
inner_label = []
posi_itemindex = np.where(label==1)[0]
nega_item_index = np.where(label==0)[0]
posi_size = len(posi_itemindex)
random.shuffle(nega_item_index)
nega_size = int(ratio * posi_size)
extrated_ind = np.append(posi_itemindex, nega_item_index[:nega_size])
random.shuffle(extrated_ind)
inner_label = label[extrated_ind]
inner_data = data[extrated_ind]
return inner_data, inner_label
def get_multiple_data(data, label, ratio = 5):
inner_data = []
inner_label = []
posi_itemindex = np.where(label==1)[0]
nega_item_index = np.where(label==0)[0]
posi_size = len(posi_itemindex)
random.shuffle(nega_item_index)
nega_size = int(ratio * posi_size)
#nega_id = nega_item_index[:nega_size]
extrated_ind = np.append(posi_itemindex, nega_item_index[:nega_size])
#random.shuffle(extrated_ind)
inner_label = label[extrated_ind]
inner_data = data[extrated_ind]
return inner_data, inner_label, posi_size
def element_count(a):
results = {}
for x in a:
if x not in results:
results[x] = 1
else:
results[x] += 1
return results
def check_lncRNA_mRNA_position(mRNA_list, lncRNA_list, gene_coordinate_dict, DIS_GAP = 500000, strand_speific = True):
#pdb.set_trace()
dist = 0
nearby_flag = False
locate_next_to_mRNA_list = []
for lncRNA in lncRNA_list:
lncRNA_chr_name, lncRNA_strand, lncRNA_start, lncRNA_end = gene_coordinate_dict[lncRNA]
for mRNA in mRNA_list:
mRNA_chr_name, mRNA_strand, mRNA_start, mRNA_end = gene_coordinate_dict[mRNA]
if strand_speific:
if lncRNA_chr_name + lncRNA_strand != mRNA_chr_name + mRNA_strand:
continue
else:
if lncRNA_chr_name != mRNA_chr_name:
continue
start_gap = mRNA_start - lncRNA_start
end_gap = lncRNA_end - mRNA_end
if (start_gap >= 0 and start_gap <= DIS_GAP) or (end_gap >= 0 and end_gap <= DIS_GAP):
#pdb.set_trace()
locate_next_to_mRNA_list.append(lncRNA)
break
return locate_next_to_mRNA_list
def read_snp_dataset(snp_file = 'SNP/snp142Common.txt.gz'):
snp_dict = {}
with gzip.open(snp_file, 'r') as fp:
for line in fp:
values = line.rstrip('\r\n').split('\t')
key = values[1] + values[6]
snp_dict.setdefault(key, set()).add(int(values[2]))
return snp_dict
def read_snp_coordinate(snp_file = 'SNP/snp142Common.txt.gz'):
snp_dict = {}
with gzip.open(snp_file, 'r') as fp:
for line in fp:
values = line.rstrip('\r\n').split('\t')
#key = values[1] + values[6]
snp_dict[values[4]] = values[1] + '_' + values[2] + '_' + values[6]
return snp_dict
def read_GWAS_catalog(gwas_file = 'SNP/gwascatalog.txt', down_up_stream = False, cutoff=5000):
gwas_snp = {}
with open(gwas_file, 'r') as fp:
head = True
for line in fp:
if head:
head = False
continue
values = line.rstrip('\r\n').split('\t')
chr_name = 'chr' + values[11]
snp_id = values[21]
coor = int(values[12])
if down_up_stream: # upstream and downstream 500kb
new_start = coor - cutoff
new_end = coor + cutoff
for val in range(new_start, new_end):
gwas_snp.setdefault(chr_name, set()).add(val)
else:
gwas_snp.setdefault(chr_name, set()).add(coor)
return gwas_snp
def read_GWAS_catalog_disease(gwas_file = 'SNP/gwas_catalog_ensembl_mapping_v1.0-downloaded_2015-10-09.tsv'):
gwas_dis = {}
with open(gwas_file, 'r') as fp:
head = True
for line in fp:
if head:
head = False
continue
values = line.rstrip('\r\n').split('\t')
if values[7] == '' or values[-13] == '':
continue
disease = values[7]
#except:
# pdb.set_trace()
#if values[21] == '' or values[11] == '' or values[12] == '':
# continue
#snp_id = values[21]
#chr_name = 'chr' + values[11]
#coor = int(values[12])
#except:
#pdb.set_trace()
gwas_dis.setdefault(disease.upper(), set()).add(values[-13])
#gwas_snp_coor[snp_id] = chr_name + '_' + values[12]
#pdb.set_trace()
return gwas_dis
def read_gwas_ld_region(gwas_ld_file = 'SNP/GWAS-LD-region-snps.csv'):
#gwas_dis ={}
snp_dis = {}
with open(gwas_ld_file, 'r') as fp:
head = True
for line in fp:
if head:
head = False
continue
try:
if '"' in line:
values = line.rstrip('\r\n').split('"')
SNP,GWAS_SNP,PMID = values[0][:-1].split(',')
diseases = values[1].split(',')
for dis in diseases:
snp_dis.setdefault(dis.upper(), []).append(SNP)
#gwas_dis.setdefault(dis.upper(), set()).add(GWAS_SNP)
else:
SNP,GWAS_SNP,PMID,disease = line.rstrip('\r\n').split(',')
snp_dis.setdefault(disease.upper(), []).append(SNP)
#gwas_dis.setdefault(disease.upper(), set()).add(GWAS_SNP)
except:
pdb.set_trace()
return snp_dis
def get_all_snp_disease_assoc():
all_disease_snp = {}
snp_coor_dict = read_snp_coordinate()
ld_snp_dis = read_gwas_ld_region()
gwas_dis = read_GWAS_catalog_disease()
#pdb.set_trace()
for key, val in gwas_dis.iteritems():
for snp in val:
if snp_coor_dict.has_key(snp):
all_disease_snp.setdefault(key, set()).add(snp_coor_dict[snp])
for key, val in ld_snp_dis.iteritems():
for snp in val:
if snp_coor_dict.has_key(snp):
all_disease_snp.setdefault(key, set()).add(snp_coor_dict[snp])
return all_disease_snp
def get_lcnRNA_disease_snp_assoc(gene_coordinate_dict, lncRNA_list, disease, dis_cutff = 250000):
disease_snp_lncRNA = []
all_disease_snp = get_all_snp_disease_assoc()
#pdb.set_trace()
disease = disease.upper()
if all_disease_snp.has_key(disease):
snp_coors = all_disease_snp[disease]
for lncRNA in lncRNA_list:
lncRNA_chr_name, lncRNA_strand, lncRNA_start, lncRNA_end = gene_coordinate_dict[lncRNA]
for snp in snp_coors:
chr_name, posi, strand = snp.split('_')
#pdb.set_trace()
lncRNA_chr_name = 'chr' + lncRNA_chr_name
if chr_name != lncRNA_chr_name:
continue
#pdb.set_trace()
posi_start, posi_end = int(posi) - dis_cutff, int(posi) + dis_cutff
if point_overlap(posi_start, posi_end, lncRNA_start, lncRNA_end) > 0:
print 'overlpa snps'
disease_snp_lncRNA.append(lncRNA)
return disease_snp_lncRNA
def exist_snp_in_lncRNA(gene_coordinate_dict, lncRNA_list, gwas = False, down_up_stream = False):
if gwas:
snp_dict = read_GWAS_catalog(down_up_stream = down_up_stream)
else:
snp_dict = read_snp_dataset()
snp_exist_in_lncRNA_list = []
for lncRNA in lncRNA_list:
lncRNA_chr_name, lncRNA_strand, lncRNA_start, lncRNA_end = gene_coordinate_dict[lncRNA]
if gwas:
key = lncRNA_chr_name
else:
key = lncRNA_chr_name + lncRNA_strand
coor_set = set(range(lncRNA_start, lncRNA_end + 1))
snp_coor_set = snp_dict[key]
overlap_set = snp_coor_set & coor_set
if len(overlap_set):
snp_exist_in_lncRNA_list.append(1)
else:
snp_exist_in_lncRNA_list.append(0)
return snp_exist_in_lncRNA_list
def get_kmeans_k_biggest_cluster(cluster_centers, labels, num_cluster):
freq_dict = element_count(labels)
freq_list = []
for key, val in freq_dict.iteritems():
freq_list.append((val, key))
freq_list.sort(reverse= True)
new_array = []
for val in freq_list[:num_cluster]:
new_array.append(cluster_centers[val[1]])
return np.array(new_array)
def get_multiple_data_based_clustering(data, label, ratio = 5):
posi_itemindex = np.where(label==1)[0]
nega_item_index = np.where(label==0)[0]
posi_size = len(posi_itemindex)
nega_data = data[nega_item_index]
#nega_data = normalize(nega_data, axis=0)
num_cluster = ratio*posi_size
kmeans = KMeans(init='k-means++', n_clusters=num_cluster*4)
kmeans.fit(nega_data)
nega_new = kmeans.cluster_centers_
cluster_labels = kmeans.labels_
#new_nega_ind = range(len(nega_new))
#random.shuffle(new_nega_ind)
#random.shuffle(nega_new)
posi_data = data[posi_itemindex]
nega_select = get_kmeans_k_biggest_cluster(nega_new, cluster_labels, num_cluster)
#pdb.set_trace()
inner_data = np.concatenate((posi_data, nega_select), axis=0)
inner_label = [1]*posi_size + [0]*num_cluster
#pdb.set_trace()
return inner_data, inner_label, posi_size
def get_multiple_data_based_mRNAs(mRNA_list, data, label, ensg_ensp_map, ratio = 5, other_mRNA_list = None, negative_sampe_set = None,
gene_position_dict = None):
#print 'nultiuple mRNA uniq'
inner_data = []
inner_label = []
posi_itemindex = np.where(label==1)[0]
nega_item_index = np.where(label==0)[0]
posi_size = len(posi_itemindex)
random.shuffle(nega_item_index)
#nega_size = int(2*ratio * posi_size)
#nega_index = nega_item_index[:nega_size]
tmp_ensp = set()
new_nega_ind = []
if other_mRNA_list is None:
print 'should excluding other mRNAs with low confidence related to disease'
for ind in nega_item_index:
mrna = mRNA_list[ind]
mrna_ensp = ''
if ensg_ensp_map.has_key(mrna):
mrna_ensp = ensg_ensp_map[mrna]
if mrna_ensp not in negative_sampe_set:
continue
if mrna_ensp in tmp_ensp:
print mrna
continue
if mrna_ensp in other_mRNA_list:
print mrna
continue
else:
new_nega_ind.append(ind)
if mrna_ensp != '':
tmp_ensp.add(mrna_ensp)
if len(new_nega_ind) >= ratio * posi_size:
#print 'multiuple mRNA uniq'
break
extrated_ind = np.append(posi_itemindex, np.array(new_nega_ind))
inner_label = label[extrated_ind]
inner_data = data[extrated_ind, :]
return inner_data, inner_label, posi_size
'''
X -= np.mean(X, axis = 0) # zero-center
X /= np.std(X, axis = 0)
'''
def preprocess_data(X, scaler=None, minmax = True):
if not scaler:
if minmax:
scaler = MinMaxScaler()
else:
scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)
return X, scaler
def preprocess_data_tissue(X):
new_col = np.sum(X,1).reshape((X.shape[0],1))
X_new = X/X.sum(axis=1)[:, None]
X_new[np.isnan(X_new)] = 0
X_new = np.append(X_new,new_col, axis=1)
return X_new
def gmm_kl(gmm_p, gmm_q, n_samples=10**5):
'''KL divergence between GMM'''
X = gmm_p.sample(n_samples)
log_p_X, _ = gmm_p.score_samples(X)
log_q_X, _ = gmm_q.score_samples(X)
return log_p_X.mean() - log_q_X.mean()
def fit_gmm(data):
gmm = mixture.GMM(n_components=1)
gmm.fit(data)
return gmm
def plot_gaussian_distribution(h1, h2):
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
h1.sort()
hmean1 = np.mean(h1)
hstd1 = np.std(h1)
pdf1 = stats.norm.pdf(h1, hmean1, hstd1)
ax.plot(h1, pdf1, label="lncRNA")
h2.sort()
hmean2 = np.mean(h2)
hstd2 = np.std(h2)
pdf2 = stats.norm.pdf(h2, hmean2, hstd2)
ax.plot(h2, pdf2, label="PCG")
legend = ax.legend(loc='upper right')
plt.xlabel('FPKM')
#plt.xlim(0,0.2)
plt.show()
def get_gene_expression_in_tissue(expdata, tissues=None):
'''
cutoff value for RNA-seq 1 10 20 FPKMs
'''
fpkm_cutoff = 1
result = []
gmm = fit_gmm(expdata)
#kde = KernelDensity(kernel='gaussian', bandwidth=0.2).fit(X)
def calculate_pcc_old(data, data_source):
print 'calculating PCC distance'
rows, cols = data.shape
#data_pcc = np.zeros(rows, cols)
pcc_list = []
#data = normalize(data, axis=0)
scaler = StandardScaler()
#scaler = MinMaxScaler()
scaler.fit(data)
data = scaler.transform(data)
print data.shape
for i in xrange(rows): # rows are the number of rows in the matrix.
pcc_list = pcc_list + [stats.pearsonr(data[i],data[j])[0] for j in range(i) if j != i]
#pdb.set_trace()
'''for j in xrange(i, rows):
if i == j:
continue
rval = stats.pearsonr(data[i,:], data[j,:])[0]
abs_rval = np.absolute(rval)
pcc_list.append(abs_rval)
'''
#pdb.set_trace()
print len(pcc_list)
plot_hist_distance(pcc_list, 'PCC', data_source)
return pcc_list
def calculate_pcc_hist(mRNA_data, lncRNA_data):
print 'calculating PCC distance'
corr_pval = []
corr_ind = []
#pdb.set_trace()
for i, mval in enumerate(lncRNA_data):
tmp = []
ind_j = []
for j, lncval in enumerate(mRNA_data):
rval, pval = stats.pearsonr(mval, lncval)
abs_rval = np.absolute(rval)
if abs_rval > 0.3 and pval <= 0.01:
corr_pval.append(abs_rval)
#corr_pval.append(tmp)
#print len(corr_pval)
#plot_hist_distance(corr_pval, 'PCC', 'gencode') #corr_ind.append(ind_j)
return corr_pval
def calculate_cc(X, Y):
if X is Y:
X = Y = np.asanyarray(X)
else:
X = np.asanyarray(X)
Y = np.asanyarray(Y)
if X.shape[1] != Y.shape[1]:
raise ValueError("Incompatible dimension for X and Y matrices")
XY = ssd.cdist(X, Y, 'correlation')
return 1 - XY
def calculate_pcc_fast(A, B):
#pdb.set_trace()
A = A.T
B = B.T
N = B.shape[0]
# Store columnw-wise in A and B, as they would be used at few places
sA = A.sum(0)
sB = B.sum(0)
# Basically there are four parts in the formula. We would compute them one-by-one
#p1 = N*np.einsum('ij,ik->kj',A,B)
p1 = N*np.dot(B.T,A)
p2 = sA*sB[:,None]
p3 = N*((B**2).sum(0)) - (sB**2)
p4 = N*((A**2).sum(0)) - (sA**2)
# Finally compute Pearson Correlation Coefficient as 2D array
pcorr = ((p1 - p2)/np.sqrt(p4*p3[:,None]))
return pcorr
def calculate_pcc(mRNA_data, lncRNA_data):
print 'calculating PCC distance'
corr_pval = []
corr_ind = []
#pdb.set_trace()
for i, mval in enumerate(lncRNA_data):
tmp = []
ind_j = []
for j, lncval in enumerate(mRNA_data):
rval, pval = stats.pearsonr(mval, lncval)
abs_rval = np.absolute(rval)
if abs_rval > 0.3 and pval <= 0.01:
tmp.append(abs_rval)
ind_j.append(j)
corr_pval.append(tmp)
corr_ind.append(ind_j)
return corr_pval, corr_ind
def coexpression_hist_fig(disease_mRNA_data, mRNAlabels, disease_lncRNA_data, lncRNA_list, mRNA_list, fw):
posi_itemindex = np.where(mRNAlabels==1)[0]
inner_data = disease_mRNA_data[posi_itemindex, :]
corr_pval = calculate_pcc_hist(inner_data, disease_lncRNA_data)
return corr_pval
def coexpression_based_prediction(disease_mRNA_data, mRNAlabels, disease_lncRNA_data, lncRNA_list, mRNA_list, fw, k = 1):
print 'k:', k
posi_itemindex = np.where(mRNAlabels==1)[0]
inner_data = disease_mRNA_data[posi_itemindex, :]
corr_pval, corr_ind = calculate_pcc(inner_data, disease_lncRNA_data)
y_ensem_pred = []
for val in corr_pval:
if not len(val):
y_ensem_pred.append(0)
else:
val.sort(reverse = True)
sel_vals = val[:k]
bigval = np.mean(sel_vals)
y_ensem_pred.append(bigval)
#pdb.set_trace()
fw.write('\t'.join(map(str, y_ensem_pred)))
fw.write('\n')
def coexpression_knn_based_prediction(disease_mRNA_data, mRNAlabels, disease_lncRNA_data, lncRNA_list, mRNA_list, fw, k = 15):
print 'k:', k
corr_pval= calculate_pcc_fast( disease_mRNA_data, disease_lncRNA_data)
y_ensem_pred = []
posi_itemindex = np.where(mRNAlabels==1)[0]
num_len = len(corr_pval[0])
#pdb.set_trace()
for ind in range(len(corr_pval)):
score = [abs(val) for val in corr_pval[ind]]
num_inds = np.argsort(score)
#val.sort(reverse = True)
sel_vals = num_inds[num_len - k:]
bigval = set(sel_vals) & set(posi_itemindex)
knn_prob = len(bigval)
y_ensem_pred.append(knn_prob)
#pdb.set_trace()
fw.write('\t'.join(map(str, y_ensem_pred)))
fw.write('\n')
def rf_parameter_select(X,y):
param_grid = {"min_samples_leaf": [1, 2, 3],
'max_features': ['auto', 'sqrt', 'log2'],
"n_estimators": [5, 10, 20, 50]}
gs = grid_search.GridSearchCV(RandomForestClassifier(), param_grid=param_grid)
gs.fit(X, y)
return gs
def cross_validataion_lncRNA_using_mRNA(disease_mRNA_data, mRNAlabels, disease_lncRNA_data, lncRNA_list, mRNA_list, fw, ensg_ensp_map={},
ratio = 5, SVM = False, roc_plot=False, weight =1, other_mRNA_list=None, gene_position_dict = None,
overlap_disease_mRNA_list = None, negative_from_other_disease = None, f_imp = None):
#data, labels, posi_size = get_multiple_data(disease_mRNA_data, mRNAlabels, ratio=ratio)
posi_nega_ratio = 1
#posi_data, nega_data, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map, ratio=posi_nega_ratio*ratio)
#data, labels, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map, ratio=posi_nega_ratio*ratio, other_mRNA_list = other_mRNA_list)
if negative_from_other_disease is not None:
data, labels, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map,
ratio=ratio*posi_nega_ratio, other_mRNA_list = other_mRNA_list, negative_sampe_set = negative_from_other_disease,
gene_position_dict = gene_position_dict)
else:
raise 'should select negative from other disease'
#posi_data, nega_data, posi_size = get_multiple_data_based_clustering(disease_mRNA_data, mRNAlabels, ratio = ratio)
#data = normalize(data, axis=0)
'''
data, scaler = preprocess_data(data.transpose())
data = data.transpose()
disease_lncRNA_data, scaler = preprocess_data(disease_lncRNA_data.transpose())
disease_lncRNA_data = disease_lncRNA_data.transpose()
'''
data = preprocess_data_tissue(data)
disease_lncRNA_data = preprocess_data_tissue(disease_lncRNA_data)
fea_len = len(data[0])
#get_normalized_values_by_column(data, fea_len)
#data, scaler = preprocess_data(data, minmax = False)
#disease_lncRNA_data, scaler = preprocess_data(disease_lncRNA_data, scaler = scaler, minmax = False)
get_normalized_values_by_column(data, fea_len)
disease_lncRNA_data = get_normalized_given_max_min(disease_lncRNA_data)
posi_data = data[:posi_size]
nega_data = data[posi_size:]
#ntress = 10
print len(posi_data), len(nega_data)
#y_ensem_pred = [0] * len(disease_lncRNA_data)
y_impotance = np.zeros(fea_len)
y_ensem_pred = np.zeros(len(disease_lncRNA_data))
nega_size = posi_size * posi_nega_ratio
#y_ensem_pred = []
for ind in range(ratio):
#train = np.vstack((data[:posi_size], data[(ind + 1)*posi_size:(ind+2)*posi_size]))
#pdb.set_trace()
train = np.vstack((posi_data, nega_data[ind*nega_size:(ind + 1)*nega_size]))
#print train.shape
train_label = [1] *posi_size + [0] * nega_size
if SVM:
parameters = {'kernel': ['linear', 'rbf'], 'C': [1, 2, 3, 4, 5, 6, 10], 'gamma': [0.5,1,2,4, 6, 8]}
svr = svm.SVC(probability = True)
clf = grid_search.GridSearchCV(svr, parameters, cv=3)
else:
#clf = RandomForestClassifier(n_estimators=ntress)
gs = rf_parameter_select(train, train_label)
#clf = RandomForestClassifier().set_params(**clf.best_params_)
clf = gs.best_estimator_
#loo = cross_validation.LeaveOneOut(len(train_label))
#this_scores = cross_validation.cross_val_score(clf, train, np.array(train_label), cv = loo)
#weight = np.mean(this_scores)
#pdb.set_trace()
#clf.fit(train, train_label)
y_impotance = y_impotance + clf.feature_importances_
#if roc_plot:
# y_pred = clf.predict_proba(disease_lncRNA_data)[:, 1]
#else:
y_pred = clf.predict_proba(disease_lncRNA_data)[:, 1]
#pdb.set_trace()
y_ensem_pred = y_ensem_pred + y_pred/ratio
#y_ensem_pred = [x + y/ratio for x,y in zip(y_ensem_pred, y_pred)]
'''y_ensem_pred = [x + (weight*y + (1-weight)*(1-y))/ratio for x,y in zip(y_ensem_pred, y_pred)]
max_val = max(y_ensem_pred)
min_val = min(y_ensem_pred)
gap_Val = max_val - min_val
y_ensem_pred = [(float(i) - min_val)/gap_Val for i in y_ensem_pred]
'''
#y_ensem_pred.append(y_pred)
if overlap_disease_mRNA_list is not None:
overlap_lncRNA = check_lncRNA_mRNA_position(overlap_disease_mRNA_list, lncRNA_list, gene_position_dict, DIS_GAP = 500000, strand_speific = True)
print len(overlap_lncRNA)
y_ensem_pred_new = []
for score, lncRNA in zip(y_ensem_pred, lncRNA_list):
if lncRNA in overlap_lncRNA:
new_score = score*SCALEUP
y_ensem_pred_new.append(new_score)
else:
y_ensem_pred_new.append(score*SCALEDOWN)
y_ensem_pred = y_ensem_pred_new
#snp_exist_in_lncRNA_list = exist_snp_in_lncRNA(gene_position_dict, lncRNA_list, gwas = True, down_up_stream = False)
y_impotance = y_impotance/ratio
fw.write('\t'.join(map(str, y_ensem_pred)))
fw.write('\n')
if f_imp is not None:
f_imp.write('\t'.join(map(str, y_impotance)))
f_imp.write('\n')
#return y_real_all, y_pred_all
def cross_validataion_lncRNA_using_mRNA_xgtboost(disease_mRNA_data, mRNAlabels, disease_lncRNA_data, lncRNA_list,
mRNA_list, fw, ensg_ensp_map={}, ratio = 5, SVM = False, roc_plot=False, weight =1, other_mRNA_list=None):
#data, labels, posi_size = get_multiple_data(disease_mRNA_data, mRNAlabels, ratio=ratio)
posi_nega_ratio = 1
#posi_data, nega_data, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map, ratio=posi_nega_ratio*ratio)
data, labels, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map,
ratio=posi_nega_ratio*ratio, other_mRNA_list = other_mRNA_list)
fea_len = len(data[0])
get_normalized_values_by_column(data, fea_len)
#get_normalized_values_by_column(data, fea_len)
normalized_data = get_normalized_given_max_min(disease_lncRNA_data)
#normalized_data = xgb.DMatrix( normalized_data, label=np.random.randint(2, size=normalized_data.shape[0]))
normalized_data = xgb.DMatrix( normalized_data)
posi_data = data[:posi_size]
nega_data = data[posi_size:]
param = {'bst:max_depth':2, 'bst:eta':1, 'silent':1, 'objective':'binary:logistic' }
param['nthread'] = 4
plst = param.items()
#plst += [('eval_metric', 'auc')] # Multiple evals can be handled in this way
#y_ensem_pred = [0] * len(disease_lncRNA_data)
y_ensem_pred = np.zeros(len(disease_lncRNA_data))
nega_size = posi_size * posi_nega_ratio
#y_ensem_pred = []
for ind in range(ratio):
train = np.vstack((posi_data, nega_data[ind*nega_size:(ind + 1)*nega_size]))
#print train.shape
train_label = [1] *posi_size + [0] * nega_size
train = xgb.DMatrix( train, label=np.array(train_label))
evallist = [(train,'train')]
num_round = 10
clf = xgb.train( plst, train, num_round, evallist )
y_pred = clf.predict(normalized_data)
#y_pred = clf.predict_proba(normalized_data)[:, 1]
#pdb.set_trace()
y_ensem_pred = y_ensem_pred + y_pred/ratio
fw.write('\t'.join(map(str, y_ensem_pred)))
fw.write('\n')
def validataion_multiple_mRNA(disease_mRNA_data, mRNAlabels, mRNA_list, fw, ensg_ensp_map ={}, ratio = 5, SVM = False, roc_plot=False,
other_mRNA_list=None, negative_from_other_disease = None):
posi_nega_ratio = 1
if negative_from_other_disease is not None:
data, labels, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map,
ratio=ratio*posi_nega_ratio, other_mRNA_list = other_mRNA_list, negative_sampe_set = negative_from_other_disease)
else:
raise 'should select negative from other disease'
#data, labels, posi_size = get_multiple_data_based_clustering(disease_mRNA_data, mRNAlabels, ratio = ratio* posi_nega_ratio)
print 'data size: ', data.shape
'''
data = data.transpose()
data, scaler = preprocess_data_tissue(data)
data = data.transpose()
'''
data = preprocess_data_tissue(data)
#pdb.set_trace()
fea_len = len(data[0])
#pdb.set_trace()
get_normalized_values_by_column(data, fea_len)
posi_data = data[:posi_size]
ntress = 10
nega_data = data[posi_size:]
nega_size = posi_size * ratio
#1/5 as testing, 4/5 as training
test_posi_num = int(0.2*posi_size)
test_nega_num = int(0.2*nega_size)
random.shuffle(posi_data)
random.shuffle(nega_data)
test_posi = posi_data[:test_posi_num]
test_nega = nega_data[:test_nega_num]
train_posi = posi_data[test_posi_num:]
train_nega = nega_data[test_nega_num:]
len_nega = len(train_nega)/ratio
#posi_kf = KFold(len(train_posi), n_folds=ratio)
#nega_kf = KFold(len(train_nega), n_folds=ratio)
#X_train, X_test, y_train, y_test = train_test_split(posi_data, y, test_size=0.2, random_state=42)
y_pred_all = []
#y_pred_prob = []
#test_data = np.concatenate((posi_data, nega_data[:nega_size]), axis=0)
#test_labels = [1] *posi_size + [0] * nega_size
X_test = np.concatenate((test_posi, test_nega), axis=0)
print X_test.shape
y_real_all = [1] *len(test_posi) + [0] * len(test_nega)
y_pred_prob = [0] * len(y_real_all)
print 'independent testing'
# other ratio -1 negative subset data
for ind in range(ratio):
#nega_data = data[(ind + 2)*posi_size:(ind + 3)*posi_size, :]
X_train = []
if ind != ratio -1:
x_nega_data = train_nega[ind*len_nega : len_nega*(ind + 1)]
else:
x_nega_data = train_nega[ind*len_nega:]
#tmp_nega = nega_data[ind*posi_size:(ind + 1)*posi_size]
#test = []
X_train = np.concatenate((train_posi, x_nega_data), axis=0)
y_train = [1] *len(train_posi) + [0] * len(x_nega_data)
#print X_train.shape
#sub_nega_data = nega_data[(ind + 1)*nega_size:(ind + 2)*nega_size]
#new_data = []
#new_data = np.vstack((sub_posi_data, sub_nega_data))
#print new_data.shape
#new_data = np.vstack((posi_data, nega_data))
#clf = RandomForestClassifier(n_estimators=ntress)
#clf.fit(X_train, y_train)
gs = rf_parameter_select(X_train, y_train)
clf = gs.best_estimator_
#clf = RandomForestClassifier().set_params(**clf.best_params_)
#clf = gs.best_estimator_
y_pred = clf.predict_proba(X_test)[:, 1]
y_pred_prob = [val1 + val2/ratio for val1, val2 in zip(y_pred_prob, y_pred)]
y_pred_all = [ 1 if x>=0.5 else 0 for x in y_pred_prob]
#if y_ensemb >= 0.5:
# y_pred_all.append(1)
#else:
# y_pred_all.append(0)
#y_pred_prob.append(y_ensemb)
if not roc_plot:
acc, precision, sensitivity, specificity, MCC = calculate_performace(len(y_real_all), y_pred_all, y_real_all)
fw.write('\t'.join(map(str, [acc, precision, sensitivity, specificity, MCC])))
fw.write('\nROC_label\t')
fw.write('\t'.join(map(str, y_real_all)))
fw.write('\nROC_probability\t')
fw.write('\t'.join(map(str, y_pred_prob)))
fw.write('\n')
def cross_validataion_multiple_mRNA(disease_mRNA_data, mRNAlabels, mRNA_list, fw, ensg_ensp_map ={}, ratio = 5, SVM = False, roc_plot=False,
other_mRNA_list=None, negative_from_other_disease = None):
#data, labels = get_banlanced_data(data, labels)
#data, labels, posi_size = get_multiple_data(disease_mRNA_data, mRNAlabels, ratio=ratio)
#data, labels, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map, ratio=ratio)
posi_nega_ratio = 1
if negative_from_other_disease is not None:
data, labels, posi_size = get_multiple_data_based_mRNAs(mRNA_list, disease_mRNA_data, mRNAlabels, ensg_ensp_map,
ratio=ratio*posi_nega_ratio, other_mRNA_list = other_mRNA_list, negative_sampe_set = negative_from_other_disease)
else:
raise 'should select negative from other disease'
#data, labels, posi_size = get_multiple_data_based_clustering(disease_mRNA_data, mRNAlabels, ratio = ratio* posi_nega_ratio)
print 'data size: ', data.shape
data = data.transpose()
data, scaler = preprocess_data(data)
data = data.transpose()
fea_len = len(data[0])
#pdb.set_trace()
get_normalized_values_by_column(data, fea_len)
posi_data = data[:posi_size]
ntress = 10
nega_data = data[posi_size:]
'''std_scale = preprocessing.StandardScaler().fit(X_train)
X_train = std_scale.transform(X_train)
X_test = std_scale.transform(X_test)
'''
'''get_normalized_values_by_column(np.vstack((posi_data, nega_data)), fea_len)
normalized_data = get_normalized_given_max_min(disease_lncRNA_data)
posi_data = get_normalized_given_max_min(posi_data)
nega_data = get_normalized_given_max_min(nega_data)
'''
#data = normalize(data, axis=0)
y_pred_all = []
y_real_all = []
y_pred_prob = []
#test_data = data[:2*posi_size, :]
#test_labels = labels[:2*posi_size]
nega_size = posi_size * posi_nega_ratio
test_data = np.concatenate((posi_data, nega_data[:nega_size]), axis=0)
test_labels = [1] *posi_size + [0] * nega_size
for fold in range(len(test_data)):
train = []
test = []
train = [x for i, x in enumerate(test_data) if i != fold]
test = [x for i, x in enumerate(test_data) if i == fold]
train_label = [x for i, x in enumerate(test_labels) if i != fold]
test_label = [x for i, x in enumerate(test_labels) if i == fold]
if SVM:
parameters = {'kernel': ['linear', 'rbf'], 'C': [1, 2, 3, 4, 5, 6, 10], 'gamma': [0.5,1,2,4, 6, 8]}
svr = svm.SVC(probability = True)
clf = grid_search.GridSearchCV(svr, parameters, cv=3)
else:
clf = RandomForestClassifier(n_estimators=ntress)
#pdb.set_trace()