-
Notifications
You must be signed in to change notification settings - Fork 0
/
deep_operon.py
2045 lines (1664 loc) · 68.5 KB
/
deep_operon.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# CreateTime: 2016-09-21 16:51:48
import numpy as np
from Bio import SeqIO, Seq, SeqUtils
#from Bio.SeqUtils.CodonUsage import CodonAdaptationIndex
from Bio.SeqUtils import GC
from Bio.SeqUtils.CodonUsage import SynonymousCodons
import math
from math import log, sqrt
from collections import Counter
import pickle
import gc
# from sklearn import cross_validation, metrics # Additional scklearn
# functions
from sklearn import metrics # Additional scklearn functions
#from sklearn.metrics import f1_score, recall_score, precision_score
# from sklearn.grid_search import GridSearchCV # Perforing grid search
from sklearn.svm import LinearSVC as SVC
#from tensorflow.keras_adabound import AdaBound
import os
from copy import deepcopy
if 1:
# set backend
os.environ['KERAS_BACKEND'] = 'tensorflow'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
from tensorflow.keras import backend as K
# K.set_image_data_format('channels_first')
try:
import theano.ifelse
from theano.ifelse import IfElse, ifelse
except:
pass
try:
from tensorflow import set_random_seed
except:
set_random_seed = np.random.seed
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.utils.data as Data
import chainer
import chainer.functions as cF
import chainer.links as cL
from chainer import training
from chainer import Variable as Var
from chainer.training import extensions
from chainer import serializers
#from chainer_sklearn.links import SklearnWrapperClassifier
try:
import lightgbm as lgb
except:
pass
from tensorflow.python.keras import backend as K_tf
from tensorflow.python.keras.optimizers import Optimizer as Optimizer_tf
class AdaBound(Optimizer_tf):
"""AdaBound optimizer.
Default parameters follow those provided in the original paper.
Arguments:
lr: float >= 0. Learning rate.
beta_1: float, 0 < beta < 1. Generally close to 1.
beta_2: float, 0 < beta < 1. Generally close to 1.
final_lr: float >= 0. Final learning rate.
gamma: float >= 0. Convergence speed of the bound functions.
epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
decay: float >= 0. Learning rate decay over each update.
amsbound: boolean. Whether to use the AMSBound variant of this algorithm
from the paper "Adaptive Gradient Methods with Dynamic Bound of Learning Rate".
"""
def __init__(self,
lr=0.001,
beta_1=0.9,
beta_2=0.999,
final_lr=0.1,
gamma=0.001,
epsilon=1e-8,
decay=0.,
amsbound=False,
**kwargs):
super(AdaBound, self).__init__(**kwargs)
with K_tf.name_scope(self.__class__.__name__):
self.iterations = K_tf.variable(0, dtype='int64', name='iterations')
self.lr = K_tf.variable(lr, name='lr')
self.beta_1 = K_tf.variable(beta_1, name='beta_1')
self.beta_2 = K_tf.variable(beta_2, name='beta_2')
self.final_lr = K_tf.variable(final_lr, name='final_lr')
self.gamma = K_tf.variable(gamma, name='gamma')
self.decay = K_tf.variable(decay, name='decay')
self.amsbound = K_tf.variable(amsbound, name='amsbound')
if epsilon is None:
epsilon = K_tf.epsilon()
self.epsilon = K_tf.variable(epsilon)
self.initial_decay = decay
self.base_lr = lr
def get_updates(self, loss, params):
grads = self.get_gradients(loss, params)
self.updates = [state_ops.assign_add(self.iterations, 1)]
lr = self.lr
if self.initial_decay > 0:
lr = lr * (
1. / (1. + self.decay * math_ops.cast(self.iterations,
K_tf.dtype(self.decay))))
t = math_ops.cast(self.iterations, K_tf.floatx()) + 1
lr_t = lr * (
K_tf.sqrt(1. - math_ops.pow(self.beta_2, t)) /
(1. - math_ops.pow(self.beta_1, t)))
final_lr = self.final_lr * lr / self.base_lr
lower_bound = final_lr * (1. - 1. / (self.gamma * t + 1))
upper_bound = final_lr * (1. + 1. / (self.gamma * t))
ms = [K_tf.zeros(K_tf.int_shape(p), dtype=K_tf.dtype(p)) for p in params]
vs = [K_tf.zeros(K_tf.int_shape(p), dtype=K_tf.dtype(p)) for p in params]
if self.amsbound:
vhats = [K_tf.zeros(K_tf.int_shape(p), dtype=K_tf.dtype(p)) for p in params]
else:
vhats = [K_tf.zeros(1) for _ in params]
self.weights = [self.iterations] + ms + vs + vhats
for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats):
m_t = (self.beta_1 * m) + (1. - self.beta_1) * g
v_t = (self.beta_2 * v) + (1. - self.beta_2) * math_ops.square(g)
if self.amsbound:
vhat_t = math_ops.maximum(vhat, v_t)
p_t = p - m_t * K_tf.clip(lr_t / (K_tf.sqrt(vhat_t) + self.epsilon), lower_bound, upper_bound)
self.updates.append(state_ops.assign(vhat, vhat_t))
else:
p_t = p - m_t * K_tf.clip(lr_t / (K_tf.sqrt(v_t) + self.epsilon), lower_bound, upper_bound)
self.updates.append(state_ops.assign(m, m_t))
self.updates.append(state_ops.assign(v, v_t))
new_p = p_t
# Apply constraints.
if getattr(p, 'constraint', None) is not None:
new_p = p.constraint(new_p)
self.updates.append(state_ops.assign(p, new_p))
return self.updates
def get_config(self):
config = {
'lr': float(K_tf.get_value(self.lr)),
'beta1': float(K_tf.get_value(self.beta_1)),
'beta2': float(K_tf.get_value(self.beta_2)),
'final_lr': float(K_tf.get_value(self.final_lr)),
'gamma': float(K_tf.get_value(self.gamma)),
'decay': float(K_tf.get_value(self.decay)),
'epsilon': self.epsilon,
'amsbound': self.amsbound
}
base_config = super(AdaBound, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
from pickle import load, dump
from time import time
import sys
# global parameters:
try:
global_kmr = int(eval(sys.argv[5]))
except:
global_kmr = 4
global_len = 128
global_split_rate = 1/3.
global_epoch = 32
#global_epoch = 256
#global_kmr = 5
#global_len = 256
###############################################################################
# multiple-gpu support
###############################################################################
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
def f1_score_keras(y_true, y_pred):
#def f1_score(y_true, y_pred):
def recall(y_true, y_pred):
"""Recall metric.
Only computes a batch-wise average of recall.
Computes the recall, a metric for multi-label classification of
how many relevant items are selected.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
precision = precision(y_true, y_pred)
recall = recall(y_true, y_pred)
#print type(precision)
#if float(precision) > .87 and float(recall) > .87:
if 1:
return 2 * ((precision * recall) / (precision + recall))
#else:
# return 0
fbeta_score = f1_score_keras
#fbeta_score = f1_score
##########################################################################
# overlap of two gene
##########################################################################
overlap = lambda s0, e0, s1, e1: min(e0, e1) - max(s0, s1) + 1
##########################################################################
# share kmer between 2 sequence
##########################################################################
def pearson(x, y):
N, M = len(x), len(y)
assert N == M
x_m, y_m = sum(x) * 1. / N, sum(y) * 1. / M
a, b, c = 0., 0., 0.
for i in range(N):
xi, yi = x[i] - x_m, y[i] - y_m
a += xi * yi
b += xi ** 2
c += yi ** 2
try:
return a / sqrt(b * c)
except:
return 0
def sharekmer(s1, s2):
# SynonymousCodons
n1, n2 = list(map(len, [s1, s2]))
k1 = [s1[elem: elem + 3] for elem in range(0, n1, 3)]
k2 = [s1[elem: elem + 3] for elem in range(0, n2, 3)]
fq1 = Counter(k1)
fq2 = Counter(k2)
flag = 0
kmers = []
for i in SynonymousCodons:
j = SynonymousCodons[i]
if len(j) < 2:
continue
c1 = [[fq1[elem], elem] for elem in j]
best1 = max(c1, key=lambda x: x[0])
c2 = [[fq2[elem], elem] for elem in j]
best2 = max(c2, key=lambda x: x[0])
#c1.sort(key = lambda x: x[0], reverse = True)
#c2.sort(key = lambda x: x[0], reverse = True)
if best1[1] == best2[1]:
kmers.append(best1[1])
# for val in SynonymousCodons.values():
# if len(val) > 5:
# kmers.extend(val)
# print 'the kmer', kmers, len(kmers)
vec1 = [fq1[elem] for elem in kmers]
vec2 = [fq2[elem] for elem in kmers]
return pearson(vec1, vec2)
##########################################################################
# the motif found
##########################################################################
box_up10 = ['TATAAT', [77, 76, 60, 61, 56, 82]]
box_up35 = ['TTGACA', [69, 79, 61, 56, 54, 54]]
# find the best region that may be a candidate of a motif
def find_motif(seq, motif, bg=None):
if bg is None:
bg = {}
l = len(motif[0])
#best = float('-inf')
best = -100
idx = -1
for i in range(0, len(seq) - l + 1):
lmer = seq[i: i + l]
score = 0
for a, b, c in zip(lmer, motif[0], motif[1]):
if a == b:
score += log(float(c) / bg.get(a, 1.))
else:
score += log((100. - c) / bg.get(a, 1.))
# try:
# score += log((100. - c) / bg.get(a, 1.))
# except:
# print c, bg.get(a, 1.)
if score >= best:
idx = i
best = score
return [seq[idx: idx + l], len(seq) - idx, best]
##########################################################################
# cai, from biopython
##########################################################################
index = Counter({'GCT': 1, 'CGT': 1, 'AAC': 1, 'GAC': 1, 'TGC': 1, 'CAG': 1, 'GAA': 1, 'GGT': 1, 'CAC': 1, 'ATC': 1, 'CTG': 1, 'AAA': 1, 'ATG': 1, 'TTC': 1, 'CCG': 1, 'TCT': 1, 'ACC': 1, 'TGG': 1, 'TAC': 1, 'GTT': 1, 'ACT': 0.965, 'TCC': 0.744, 'GGC': 0.724, 'GCA': 0.586, 'TGT': 0.5, 'GTA': 0.495, 'GAT': 0.434, 'GCG': 0.424, 'AGC': 0.41, 'CGC': 0.356, 'TTT': 0.296, 'CAT': 0.291, 'GAG': 0.259,
'AAG': 0.253, 'TAT': 0.239, 'GTG': 0.221, 'ATT': 0.185, 'CCA': 0.135, 'CAA': 0.124, 'GCC': 0.122, 'ACG': 0.099, 'AGT': 0.085, 'TCA': 0.077, 'ACA': 0.076, 'CCT': 0.07, 'GTC': 0.066, 'AAT': 0.051, 'CTT': 0.042, 'CTC': 0.037, 'TTA': 0.02, 'TTG': 0.02, 'GGG': 0.019, 'TCG': 0.017, 'CCC': 0.012, 'GGA': 0.01, 'CTA': 0.007, 'AGA': 0.004, 'CGA': 0.004, 'CGG': 0.004, 'ATA': 0.003, 'AGG': 0.002})
def cai(seq):
if seq.islower():
seq = seq.upper()
N = len(seq)
cai_value, cai_length = 0, 0
for i in range(0, N, 3):
codon = seq[i: i + 3]
if codon in index:
if codon not in ['ATG', 'TGG']:
cai_value += math.log(index[codon])
cai_length += 1
elif codon not in ['TGA', 'TAA', 'TAG']:
continue
else:
continue
if cai_length > 0:
return math.exp(cai_value / cai_length)
else:
return 0
##########################################################################
# get the features
##########################################################################
# convert ATCG based kmer number
#code = {'A': 1, 'a': 1, 'T': 2, 't': 2, 'G': 3, 'g': 3, 'C': 4, 'c': 4}
code = [0] * 256
code5 = [0] * 256
flag = 0
for i in 'ATGC':
code[ord(i.lower())] = code[ord(i)] = flag
code5[ord(i.lower())] = code5[ord(i)] = flag + 1
flag += 1
# convert string to number
def s2n(s, code=code, scale=None):
if scale == None:
scale = max(code) + 1
N = 0
output = 0
for i in s[::-1]:
#output += code.get(i, 0) * scale ** N
output += code[ord(i)] * scale ** N
N += 1
return output
# reverse of s2n
def n2s(n, length, alpha='ATGC', scale=None):
if scale == None:
scale = max(code) + 1
N = n
s = []
for i in range(length):
s.append(alpha[N % scale])
N /= scale
return ''.join(s[::-1])
# convert the dna sequence to kmer-position matrix.
# if length of dna < given, then add NNN in the center of the sequence.
# else if length of dna > given, then trim the center of the sequence.
# the new kpm, reshape
def kpm(S, d=64, k=3, code=code, scale=None):
if scale == None:
scale = max(code) + 1
N = scale ** k
assert isinstance(d, int)
L = len(S)
if d < L:
F = d // 2
R = d - F
seq = ''.join([S[: F], S[-R:]])
elif d > L:
F = L // 2
R = L - F
seq = ''.join([S[: F], 'N' * (d - L), S[-R:]])
else:
seq = S
mat = [[0] * (d // k) for elem in range(N * k)]
for i in range(0, d - k + 1):
kmer = seq[i: i + k]
if 'N' in kmer or 'n' in kmer:
continue
R = s2n(kmer, code=code, scale=scale)
mat[R + i % k * N][i // k] = 1
mat = np.asarray(mat, 'int8')
return mat
def kpm0(S, d=64, k=3, code=code, scale=None):
if scale == None:
scale = max(code) + 1
N = scale ** k
assert isinstance(d, int)
L = len(S)
if d < L:
F = d // 2
R = d - F
seq = ''.join([S[: F], S[-R:]])
elif d > L:
F = L // 2
R = L - F
seq = ''.join([S[: F], 'N' * (d - L), S[-R:]])
else:
seq = S
mat = [[0] * (d // 3) for elem in range(N * 3)]
for i in range(0, d - k + 1):
kmer = seq[i: i + k]
if 'N' in kmer or 'n' in kmer:
continue
R = s2n(kmer, code=code, scale=scale)
mat[R + i % 3 * N][i // 3] = 1
mat = np.asarray(mat, 'int8')
return mat
# get features by give loc1, start and end:
# get xx
def get_xx(j, seq_dict, kmer=2, dim=128, mode='train', context=False):
loc1, scf1, std1, st1, ed1, loc2, scf2, std2, st2, ed2 = j[: 10]
if scf1 != scf2 or std1 != std2:
if context:
X0 = np.ones((4 ** kmer * kmer, dim // kmer * kmer))
else:
X0 = np.ones((4 ** kmer * kmer, dim // kmer))
X1 = [10**4] * 11
X2 = [127] * dim
return [X0], X1, X2
# get the sequence
st1, ed1, st2, ed2 = list(map(int, [st1, ed1, st2, ed2]))
st1 -= 1
st2 -= 1
if st1 > st2:
loc1, scf1, std1, st1, ed1, loc2, scf2, std2, st2, ed2 = loc2, scf2, std2, st2, ed2, loc1, scf1, std1, st1, ed1
seq1 = seq_dict[scf1][st1: ed1]
seq1 = std1 == '+' and seq1 or seq1.reverse_complement()
seq2 = seq_dict[scf2][st2: ed2]
seq2 = std1 == '+' and seq2 or seq2.reverse_complement()
start, end = ed1, st2
seq12 = seq_dict[scf1][start: end]
seq12 = std1 == '+' and seq12 or seq12.reverse_complement()
seq1, seq2, seq12 = list(map(str, [seq1.seq, seq2.seq, seq12.seq]))
seq1, seq2, seq12 = seq1.upper(), seq2.upper(), seq12.upper()
# 1D features such as gc, dist
cai1, cai2, cai12 = list(map(cai, [seq1, seq2, seq12]))
dist = st2 - ed1
distn = (st2 - ed1) * 1. / (ed2 - st1)
ratio = math.log((ed1 - st1) * 1. / (ed2 - st2))
ratio = std1 == '+' and ratio or -ratio
idx = -100
bgs = Counter(seq12[idx:])
up10, up35 = find_motif(seq12[idx:], box_up10, bgs), find_motif(
seq12[idx:], box_up35, bgs)
if seq12[idx:]:
gc = SeqUtils.GC(seq12[idx:])
try:
skew = SeqUtils.GC_skew(seq12[idx:])[0]
except:
skew = 0.
else:
gc = skew = 0.
bias = sharekmer(seq1, seq2)
if st1 == st2 == '+':
X1 = [cai1, cai2, bias, distn, ratio, gc, skew] + up10[1:] + up35[1:]
else:
X1 = [cai2, cai1, bias, distn, ratio, gc, skew] + up10[1:] + up35[1:]
# 2D features of kmer matrix
if context:
seqmat12 = kpm(seq12, d=dim, k=kmer, scale=4)
seqmat1 = kpm(seq1, d=dim, k=kmer, scale=4)
seqmat2 = kpm(seq2, d=dim, k=kmer, scale=4)
seqmat = np.concatenate((seqmat1, seqmat12, seqmat2), 1)
else:
seqmat = kpm(seq12, d=dim, k=kmer, scale=4)
if ed1 > st2:
seqmat[:] = 0
X0 = [seqmat]
n12 = len(seq12)
X2 = [s2n(seq12[elem: elem + kmer], code5)
for elem in range(n12 - kmer + 1)]
return X0, X1, X2
def get_xx0(j, seq_dict, kmer=2, dim=128, mode='train', context=False):
loc1, scf1, std1, st1, ed1, loc2, scf2, std2, st2, ed2 = j[: 10]
if scf1 != scf2 or std1 != std2:
if context:
X0 = np.ones((4 ** kmer * 3, dim // 3 * 3))
else:
X0 = np.ones((4 ** kmer * 3, dim // 3))
X1 = [10**4] * 11
X2 = [127] * dim
return [X0], X1, X2
# get the sequence
st1, ed1, st2, ed2 = list(map(int, [st1, ed1, st2, ed2]))
st1 -= 1
st2 -= 1
if st1 > st2:
loc1, scf1, std1, st1, ed1, loc2, scf2, std2, st2, ed2 = loc2, scf2, std2, st2, ed2, loc1, scf1, std1, st1, ed1
seq1 = seq_dict[scf1][st1: ed1]
seq1 = std1 == '+' and seq1 or seq1.reverse_complement()
seq2 = seq_dict[scf2][st2: ed2]
seq2 = std1 == '+' and seq2 or seq2.reverse_complement()
start, end = ed1, st2
seq12 = seq_dict[scf1][start: end]
seq12 = std1 == '+' and seq12 or seq12.reverse_complement()
seq1, seq2, seq12 = list(map(str, [seq1.seq, seq2.seq, seq12.seq]))
seq1, seq2, seq12 = seq1.upper(), seq2.upper(), seq12.upper()
# 1D features such as gc, dist
cai1, cai2, cai12 = list(map(cai, [seq1, seq2, seq12]))
dist = st2 - ed1
distn = (st2 - ed1) * 1. / (ed2 - st1)
ratio = math.log((ed1 - st1) * 1. / (ed2 - st2))
ratio = std1 == '+' and ratio or -ratio
idx = -100
bgs = Counter(seq12[idx:])
up10, up35 = find_motif(seq12[idx:], box_up10, bgs), find_motif(
seq12[idx:], box_up35, bgs)
if seq12[idx:]:
gc = SeqUtils.GC(seq12[idx:])
try:
skew = SeqUtils.GC_skew(seq12[idx:])[0]
except:
skew = 0.
else:
gc = skew = 0.
bias = sharekmer(seq1, seq2)
if st1 == st2 == '+':
X1 = [cai1, cai2, bias, distn, ratio, gc, skew] + up10[1:] + up35[1:]
else:
X1 = [cai2, cai1, bias, distn, ratio, gc, skew] + up10[1:] + up35[1:]
# 2D features of kmer matrix
if context:
seqmat12 = kpm(seq12, d=dim, k=kmer, scale=4)
seqmat1 = kpm(seq1, d=dim, k=kmer, scale=4)
seqmat2 = kpm(seq2, d=dim, k=kmer, scale=4)
seqmat = np.concatenate((seqmat1, seqmat12, seqmat2), 1)
else:
seqmat = kpm(seq12, d=dim, k=kmer, scale=4)
if ed1 > st2:
seqmat[:] = 0
X0 = [seqmat]
n12 = len(seq12)
X2 = [s2n(seq12[elem: elem + kmer], code5)
for elem in range(n12 - kmer + 1)]
return X0, X1, X2
# get single line of features
def get_xx_one(j, seq_dict, kmer=2, dim=128, mode='train'):
X0, X1, X2 = get_xx(j, seq_dict, kmer, dim, mode)
x0, x1, x2 = list(map(np.asarray, [[X0], [X1], [X2]]))
return x0, x1, X2
# generate training and testing data
def get_xxy(f, seq_dict, kmer=2, dim=128):
# get the training data
X0, X1, X2, y = [], [], [], []
for i in f:
j = i[:-1].split('\t')
x0, x1, x2 = get_xx(j, seq_dict, kmer, dim)
X0.append(x0)
X1.append(x1)
X2.append(x2)
y.append(j[-1] == 'True' and 1 or 0)
X0 = np.asarray(X0, 'int8')
X1 = np.asarray(X1, 'float32')
X2 = np.asarray(X2)
y = np.asarray(y, 'int8')
return X0, X1, X2, y
# split the X0, X1, y data to training and testing
def split_xxy(X0, X1, X2, y, train_size=1. / 3, seed=42):
N = X0.shape[0]
idx = np.arange(N)
np.random.seed(seed)
np.random.shuffle(idx)
start = int(train_size * N)
idx_train, idx_test = idx[: start], idx[start:]
X0_train, X1_train, X2_train, y_train = X0[
idx_train], X1[idx_train], X2[idx_train], y[idx_train]
X0_test, X1_test, X2_test, y_test = X0[idx_test], X1[
idx_test], X2[idx_test], y[idx_test]
return X0_train, X1_train, X2_train, y_train, X0_test, X1_test, X2_test, y_test
##########################################################################
# the lstm based
##########################################################################
# get lstm features by give loc1, start and end:
def get_lstm_xx(j, seq_dict, kmer=2, dim=128, mode='train'):
loc1, scf1, std1, st1, ed1, loc2, scf2, std2, st2, ed2 = j[: 10]
if scf1 != scf2 or std1 != std2:
#X0 = np.ones((4 ** kmer, dim))
X0 = [127] * dim
#X0 = None
X1 = [10**4] * 11
return X0, X1
# get the sequence
st1, ed1, st2, ed2 = list(map(int, [st1, ed1, st2, ed2]))
st1 -= 1
st2 -= 1
if st1 > st2:
loc1, scf1, std1, st1, ed1, loc2, scf2, std2, st2, ed2 = loc2, scf2, std2, st2, ed2, loc1, scf1, std1, st1, ed1
seq1 = seq_dict[scf1][st1: ed1]
seq1 = std1 == '+' and seq1 or seq1.reverse_complement()
seq2 = seq_dict[scf2][st2: ed2]
seq2 = std1 == '+' and seq2 or seq2.reverse_complement()
start, end = ed1, st2
seq12 = seq_dict[scf1][start: end]
# if len(seq12) > dim:
# seq12 = seq12[: dim // 2] + seq12[-dim // 2: ]
seq12 = std1 == '+' and seq12 or seq12.reverse_complement()
seq1, seq2, seq12 = list(map(str, [seq1.seq, seq2.seq, seq12.seq]))
seq1, seq2, seq12 = seq1.upper(), seq2.upper(), seq12.upper()
# 1D features such as gc, dist
cai1, cai2, cai12 = list(map(cai, [seq1, seq2, seq12]))
dist = st2 - ed1
distn = (st2 - ed1) * 1. / (ed2 - st1)
ratio = math.log((ed1 - st1) * 1. / (ed2 - st2))
ratio = std1 == '+' and ratio or -ratio
idx = -100
bgs = Counter(seq12[idx:])
up10, up35 = find_motif(seq12[idx:], box_up10, bgs), find_motif(
seq12[idx:], box_up35, bgs)
if seq12[idx:]:
gc = SeqUtils.GC(seq12[idx:])
try:
skew = SeqUtils.GC_skew(seq12[idx:])[0]
except:
skew = 0.
else:
gc = skew = 0.
bias = sharekmer(seq1, seq2)
if st1 == st2 == '+':
X1 = [cai1, cai2, bias, distn, ratio, gc, skew] + up10[1:] + up35[1:]
else:
X1 = [cai2, cai1, bias, distn, ratio, gc, skew] + up10[1:] + up35[1:]
#X1 = [cai1, cai2, bias, distn, ratio, gc, skew] + up10[1: ] + up35[1: ]
# 1D features of lstm
n12 = len(seq12)
'''
L = dim // 2
R = dim - L
if n12 > dim:
seq12 = seq12[: L] + seq12[-R: ]
else:
seq12 = seq12[: L] +'N' * (dim - n12) + seq12[-R: ]
'''
lstm_seq = [s2n(seq12[elem: elem + kmer], code5)
for elem in range(n12 - kmer + 1)]
#X0 = lstm_seq[::kmer]
#for i in xrange(kmer):
# X0.extend(lstm_seq[i::kmer])
#X0 = lstm_seq
X0 = [-1] * dim
ndim = len(lstm_seq)
if ndim == dim:
X0 = lstm_seq
#print 'X0 0', len(X0)
elif 2 <= ndim < dim:
ndim = ndim // 2
X0[:ndim] = lstm_seq[:ndim]
X0[-ndim:] = lstm_seq[-ndim:]
#print 'X0 1', len(X0)
elif ndim > dim:
ndim = dim // 2
X0[:ndim] = lstm_seq[:ndim]
X0[-ndim:] = lstm_seq[-ndim:]
#print 'X0 2', len(X0)
else:
pass
return X0, X1
# get single line of lstm features
def get_lstm_xx_one(j, seq_dict, kmer=2, dim=128, mode='train'):
X0, X1 = get_lstm_xx(j, seq_dict, kmer, dim, mode)
x0, x1 = list(map(np.asarray, [[X0], [X1]]))
return x0, x1
# generate training and testing data
def get_lstm_xxy(f, seq_dict, kmer=2, dim=128):
# get the training data
X0, X1, y = [], [], []
for i in f:
j = i[:-1].split('\t')
#print 'line', j
x0, x1 = get_lstm_xx(j, seq_dict, kmer, dim)
#print 'X0 is', len(x0)
# if len(x0) < 1 or x0[0] == -1:
# continue
cat = j[-1]
X0.append(x0)
X1.append(x1)
y.append(cat == 'True' and 1 or 0)
#print max(map(len, X0)), min(map(len, X0)), X0[: 2]
X0 = np.asarray(X0)
print(('X0 shape', X0.shape))
#print 'cat1, cat2, cai12, gc, skew, dist, distn, ratio, up10, up35'
#print 'X1', X1[0]
X1 = np.asarray(X1, 'float32')
y = np.asarray(y, 'int8')
#print 'X0', X0, X1, y
return X0, X1, y
# split lstm xxy
def split_lstm_xxy(X0, X1, y, train_size=1. / 3, seed=42):
#X = np.asarray(X)
#y = np.asarray(y)
N = X0.shape[0]
idx = np.arange(N)
np.random.seed(seed)
np.random.shuffle(idx)
start = int(train_size * N)
idx_train, idx_test = idx[: start], idx[start:]
X0_train, X1_train, y_train = X0[idx_train], X1[idx_train], y[idx_train]
X0_test, X1_test, y_test = X0[idx_test], X1[idx_test], y[idx_test]
return X0_train, X1_train, y_train, X0_test, X1_test, y_test
##########################################################################
# cnn based on pytorch
##########################################################################
class Net_torch(nn.Module):
#class Net_torch:
def __init__(self, shape=(-1,-1,-1), nb_filter=32, nb_conv=3, nb_pool=2, adaptive=True):
super(Net_torch, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel
channel, row, col = shape
self.nb_filter = nb_filter
self.nb_conv = nb_conv
self.nb_pool = nb_pool
self.conv2d0 = nn.Conv2d(channel, nb_filter, nb_conv)
if adaptive:
N, D = row//2, col//2
self.pool = nn.AdaptiveMaxPool2d((N, D))
else:
#N = (row-nb_conv+1) / nb_pool * (col-nb_conv+1) / nb_pool * nb_filter
N, D = (row-nb_conv+1) / nb_pool, (col-nb_conv+1) / nb_pool
#N = nb_filter * a * b
self.pool = nn.MaxPool2d(nb_pool, stride=(2, 2))
#print 'N size', N, nb_filter, a, b
self.relu = nn.ReLU()
#self.fc0 = nn.Linear(N, 128)
self.fc0 = nn.Linear(nb_filter*N*D, 128)
self.drop = nn.Dropout(.85)
self.fc1 = nn.Linear(128, 1)
self.fc2 = nn.Sigmoid()
# an affine operation: y = Wx + b
def forward(self, x):
# Max pooling over a (2, 2) window
#x = F.max_pool2d(F.relu(self.conv(x)), (self.nb_pool, self.nb_pool))
x = self.conv2d0(x)
x = self.relu(x)
x = self.pool(x)
#print 'pool shape', x.shape
#x = self.drop(x)
# If the size is a square you can only specify a single number
#print 'x0', x.size(), np.prod(x.size()[1:])
x = x.view(x.size(0), -1)
N, D = x.shape
#print 'x0 shape', D
#x = F.linear(x, (128, D))
x = self.fc0(x)
#x = F.dropout(x, training=self.training)
x = self.drop(x)
x = self.fc1(x)
x = self.fc2(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
#6for s in size:
num_features *= s
return num_features
# bceloss for chainer
def BCEloss(y, y_p, eps=1e-9):
#X = np.asarray(x.data, 'float32')
#T = np.asarray(t.data, 'float32')
try:
y.to_cpu()
except:
pass
Y = Var(np.asarray(y.data, 'float32'))
try:
y.to_gpu()
except:
pass
try:
y_p.to_cpu()
except:
pass
Y_p = Var(np.asarray(y_p.data, 'float32'))
try:
y_p.to_gpu()
except:
pass
N = y.shape[0]
print('Y_p', cF.log(1 - Y_p))
hs = Y*cF.log(Y_p+eps) + (1.-Y)*cF.log(1.-Y_p)
h = hs.data.sum() / -N
return h
class Net_ch(chainer.Chain):
def __init__(self, nb_filter=32, nb_conv=3, nb_pool=2, n_out=2):
super(Net_ch, self).__init__()
with self.init_scope():
self.nb_pool = nb_pool
self.conv1=cL.Convolution2D(None, nb_filter, ksize=nb_conv)
self.bn1 = cL.BatchNormalization(nb_filter)
self.incept0=cL.Inception(None, 64, 96, 128, 16, 32, 32)
self.incept1=cL.Inception(None, 128, 128, 192, 32, 96, 64)
self.conv2=cL.Convolution2D(None, nb_filter*2, ksize=nb_conv)
self.bn2 = cL.BatchNormalization(nb_filter*2)
#self.vgg = cL.VGG16Layers()
#self.google = cL.GoogLeNet()
self.fc0 = cL.Linear(None, 256)
self.fc1=cL.Linear(None, 128)
self.fc2=cL.Linear(None, n_out)
para = [nb_filter, nb_conv, nb_pool, n_out]
#self.add_persistent("n_out", n_out)
self.add_persistent("para", para)
def __call__(self, X, t=None):
#x = self.google(X)
x = self.conv1(X)
#x = self.incept0(x)
#x = self.incept1(x)
#x = self.bn1(x)
x = cF.relu(x)
#x = self.conv2(X)
#x = self.bn2(x)
#x = cF.relu(x)
x = cF.max_pooling_2d(x, ksize=self.nb_pool)
x = cF.dropout(x, .85)
x = self.fc0(x)
x = cF.relu(x)
x = cF.dropout(x, .85)
x = self.fc1(x)
x = cF.relu(x)
x = cF.dropout(x, .85)
x = self.fc2(x)
x = cF.sigmoid(x)
#x = cF.flatten(x)
if t is None:
#print 'x t shape', x.shape
return x
else:
#return cF.hinge(x, t)
#z = BCEloss(x, t)
z = cF.sigmoid_cross_entropy(x, t)
#print 'x, t, z, shape', x.shape, t.shape, z.shape
return z
# VGG 16 model
class Block(chainer.Chain):