-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSHAL.py
179 lines (160 loc) · 6.56 KB
/
CSHAL.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
from Bio import Entrez, SeqIO
import numpy as np
import pandas as pd
import os
import pickle
import torch
import torch.optim as optim
import torch.nn as nn
import torch.utils.data as Data
import torch.nn.functional as F
import time
from sklearn.metrics import *
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pickle
import sys
from pyfiglet import Figlet
f = Figlet(font='slant')
print(f.renderText('C-SHAL'))
print(" -------- CHROMATIN-SEQUENCE HOT ENCODED ANALYSIS PIPLINE WITH DEEPSEA --------")
import click
@click.command()
@click.option("--ss", prompt="Summary Statistics File",help = "A summary statistics tab seperated file with columns and headers as SNP,CHR,BP,A1,A2. The columns containing Single Nulceotide Polymorphisms, chormosome, base pair locations, primary allele and secondary allele.")
@click.option("--w",prompt = "BP top obtain from SNP position",default = 500, type =int, help="The upstream and downstream width from base pair")
@click.option("--email",prompt="email id",help = "Email for the Entrez ID to obtain sequences")
@click.option("--ak",prompt="API KEY",help="API key")
@click.option("--det",prompt="Detail Level of output (log,all,both)",help="Options for the detail in the output file. log only gives basic log terms;all provides all 919 labels and values; both provides both the files")
def process_cshal(ss,w,email,ak,det):
igap_thresholded_snp_list = pd.read_csv(ss,sep=",")
sequences = {}
Entrez.email = email
Entrez.api_key = ak
w = w
for i in range(0,len(igap_thresholded_snp_list)):
start_pos = int(igap_thresholded_snp_list["BP"][i]) - 500
end_pos = int(igap_thresholded_snp_list["BP"][i]) + 499
chr = str(igap_thresholded_snp_list["CHR"][i])
rsid = igap_thresholded_snp_list["SNP"][i]
act_allele = igap_thresholded_snp_list["A1"][i]
alt_allele = igap_thresholded_snp_list["A2"][i]
seq = Get_seq(start_pos,end_pos,chr)
sequences[rsid] = [seq,act_allele,alt_allele]
print("Completed obtaining sequences. Stored in Sequences.pkl")
output = open('Sequences.pkl','wb')
pickle.dump(sequences,output)
output.close()
CNN = DeepSEA().to(device)
best_model = torch.load("deepsea_bestmodel.pkl")
CNN.load_state_dict(best_model)
cost_function = nn.BCEWithLogitsLoss().to(device)
seq_list = pickle.load(open("Sequences.pkl","rb"))
final_results = {}
detailed_final_results = {}
for rsid in seq_list.keys():
print(f"Running ... {rsid}")
seq = seq_list[rsid][0]
a1 = seq_list[rsid][1]
a2 = seq_list[rsid][2]
if seq != None:
if 'N' not in seq and 'R' not in seq:
log_changes,P_ref,P_alt = Run_Deepsea(seq,a1,a2,w,CNN)
detailed_final_results[rsid] = [P_ref,P_alt]
final_results[rsid] = log_changes
if det == "both":
print("Final output files are present in pkl format")
output = open('Final_Output.pkl','wb')
pickle.dump(final_results,output)
output.close()
output2 = open('Detailed_Final_Output.pkl','wb')
pickle.dump(detailed_final_results,output2)
output2.close()
elif det == "all":
print("Final output file are present in pkl format")
output2 = open('Detailed_Final_Output.pkl','wb')
pickle.dump(detailed_final_results,output2)
output2.close()
else:
print("Final output file are present in pkl format")
output = open('Final_Output.pkl','wb')
pickle.dump(final_results,output)
output.close()
print("Process Completed")
def one_hot_encode(seq):
seq = seq.lower()
mat_list = [np.eye(4)[i] for i in range(4)]
mapping = dict(zip(['a','c','g','t'],mat_list))
seq_one_hot = np.stack([mapping[i] for i in seq]).T
return(mapping,seq_one_hot)
# Define the DeepSEA CNN model
class DeepSEA(nn.Module):
def __init__(self, ):
super(DeepSEA, self).__init__()
self.Conv1 = nn.Conv1d(in_channels=4, out_channels=320, kernel_size=8)
self.Conv2 = nn.Conv1d(in_channels=320, out_channels=480, kernel_size=8)
self.Conv3 = nn.Conv1d(in_channels=480, out_channels=960, kernel_size=8)
self.Maxpool = nn.MaxPool1d(kernel_size=4, stride=4)
self.Drop1 = nn.Dropout(p=0.2)
self.Drop2 = nn.Dropout(p=0.5)
self.Linear1 = nn.Linear(53*960, 925)
self.Linear2 = nn.Linear(925, 919)
def forward(self, input):
x = self.Conv1(input)
x = F.relu(x)
x = self.Maxpool(x)
x = self.Drop1(x)
x = self.Conv2(x)
x = F.relu(x)
x = self.Maxpool(x)
x = self.Drop1(x)
x = self.Conv3(x)
x = F.relu(x)
x = self.Drop2(x)
x = x.view(-1, 53*960)
x = self.Linear1(x)
x = F.relu(x)
x = self.Linear2(x)
return x
def log_change(P_ref,P_alt):
term1 = np.log(P_ref/(1-P_ref))
term2 = np.log(P_alt/(1-P_alt))
return (term1-term2)
def Run_Deepsea(seq,a1,a2,w,CNN):
seq_ref = seq[0:w] + a1 + seq[(w+1):]
mapping,seq_one_hot_ref = one_hot_encode(seq_ref)
x_ref = torch.tensor(seq_one_hot_ref.reshape(1,4,1000),dtype=torch.float).to(device) #reshaping, converting to tensor and putting on GPU. We nee shape (1,4,1000) since 1st shape represents no of data points
seq_alt = seq[0:w] + a2 +seq[(w+1):]
mapping, seq_one_hot_alt = one_hot_encode(seq_alt)
x_alt = torch.tensor(seq_one_hot_alt.reshape(1,4,1000),dtype=torch.float).to(device)
with torch.no_grad():
y_pred_ref = CNN(x_ref)
y_pred_alt = CNN(x_alt)
P_ref = torch.sigmoid(y_pred_ref.data)
P_alt = torch.sigmoid(y_pred_alt.data)
P_ref = P_ref.detach().cpu().reshape(-1).numpy()
P_alt = P_alt.detach().cpu().reshape(-1).numpy()
LC = log_change(P_ref,P_alt)
sorted_LC = np.sort(LC)[::-1]
return sorted_LC,P_ref,P_alt
def Get_seq(start_pos,end_pos,chr):
try:
if int(chr) < 10:
id_chr = "".join(["NC_00000",chr])
else:
id_chr = "".join(["NC_0000",chr])
handle = Entrez.efetch(db="nucleotide",
id = id_chr,
rettype = "fasta",
strand = 1,
seq_start = start_pos,
seq_stop = end_pos)
record = SeqIO.read(handle,"fasta")
return str(record.seq)
except:
print("No proper chromosome found ...")
if __name__ == '__main__':
print("GPU successfully detected - ")
print(torch.cuda.get_device_name(0))
device = torch.device("cuda:0")
process_cshal()