forked from MatteoPS/EasyPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEasyPrimer.py
452 lines (372 loc) · 20.2 KB
/
EasyPrimer.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
#! /usr/bin/env python3
# command line to run the example analysis:
# python3 EasyPrimer.py -in Example.fas
# If you are using EasyPrimer for an article or scientfic publication Please cite M. Perini et al. 2019 (doi: https://doi.org/10.1101/679001)
# TEST FILE ==> https://skynet.unimi.it/wp-content/uploads/easy_primer/pgi.fas
# OUTPUT EXAMPLE ==> https://skynet.unimi.it/wp-content/uploads/easy_primer/pgi_HRM_analysis.pdf
# Online version of the tool: https://skynet.unimi.it/index.php/tools/easyprimer/
# Developed by Matteo Perini, 2018
from Bio import SeqIO
import os
import csv
import pandas as pd
import numpy as np
import logging
from datetime import date
import time
import subprocess
import argparse
start_time = time.time()
def primerHRM(out_folder, tmp_folder, inputfile, conslimit, prilen, amplen, prim_thr, amp_thr, n_adj, w_adj, alg, jobname, snp, minpri, maxpri, minamp, maxamp):
cwd = os.getcwd() + '/'
path_scripts = cwd + "Scripts_and_tools/"
# the following will create the folders needed if they don't exist already
if not os.path.exists(cwd + tmp_folder):
os.makedirs(cwd + tmp_folder)
os.makedirs(cwd + tmp_folder + '/log')
os.makedirs(cwd + tmp_folder + '/tmp')
if not os.path.exists(cwd + out_folder):
os.makedirs(cwd + out_folder)
os.chdir(cwd + tmp_folder)
# ########setting log file###################################################
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a file handler
date1 = "{:%m-%d-%Y}".format(date.today())
handler = logging.FileHandler('log/MAIN_LOG_EasyPrimer_' + date1 + '.txt')
handler.setLevel(logging.INFO)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(handler)
########log file set########################################################
logger.info(jobname + " " + os.path.basename(inputfile) + ' analysis starts'+"======================================")
logger.info('Consensus limit set at ' + str(conslimit))
logger.info('Primer lenght ranges from ' + str(min(prilen)) + ' to ' + str(max(prilen)) + ' nts')
logger.info('Amplicon lengh ranges from ' + str(min(amplen)) + ' to ' + str(max(amplen)) + ' nts')
# to get just the gene name
genename_ext = os.path.basename(inputfile) #mdh.fas
genename = os.path.splitext(genename_ext)[0] #mdh
tmp_path = cwd + tmp_folder + "/tmp/"
#++++++++++++++++muscle alignment+++++++++++++++++++++++++++++++++++++
#makes muscle executable
subprocess.run("chmod 777 " + path_scripts + 'muscle3.8.31_i86linux64', shell=True)
if alg != 'n':
check_algn = False
mcomand = path_scripts + 'muscle3.8.31_i86linux64 -in '+ cwd + inputfile + ' -out '+ cwd + tmp_folder +'/tmp/'+ genename_ext + ' -loga '+ cwd + tmp_folder +'/log/muscle_log.txt -quiet'
logger.info('muscle called with the command: ' + mcomand)
subprocess.run(mcomand, shell=True)
#change the inputfile path to perform the analysis on the aligned sequences inyo the tmp folder
inputpath = cwd + tmp_folder + "/tmp/"
else:
check_algn = True
inputpath = cwd
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
logger.info('Anlysis STARTS on ' + genename)
# apre il file e crea una lista delle sequenze
allseq = []
k = 0
with open(inputpath + genename_ext, "r") as handle:
for record in SeqIO.parse(handle, "fasta"):
myseq = record.seq
allseq.append(myseq.upper())
k = k+1
#check sequences lenght
if check_algn == True:
logger.info('MUSCLE alignment avoided, checking if all sequences have the same lenght....')
the_len = len(allseq[0])
if not all(len(l) == the_len for l in allseq):
logger.info('PROGRAM HAS STOPPED ###ERROR######ERROR######ERROR######ERROR######ERROR###')
logger.info('The alignement provided contains sequences of different lenghts')
quit('###ERROR### PROGRAM HAS STOPPED' + '\n' + '---> the alignement provided contains sequences of different lenghts')
else:
logger.info('Check passed: all sequences have the same lenght')
snptab = np.zeros((len(allseq[0]), 15), dtype=object)
consensus = ''
conscode = ''
consdic = { # dictionary of consensus IUPAC ambiguous characters
'1000': 'A',
'0100': 'T',
'0010': 'G',
'0001': 'C',
'1010': 'R', # A or G
'0101': 'Y', # C or T
'0011': 'S', # C or G
'1100': 'W', # A or T
'0110': 'K', # T or G
'1001': 'M', # A or C
'0111': 'B', # not A (C or G or T)
'1110': 'D', # not C (A or G or T)
'1101': 'H', # not G (A or C or T)
'1011': 'V', # not T (A or C or G)
'1111': 'N', # any base
'0000': '-', # gap
'*': '*' # base insertion in few genes in the alinment
}
logger.info('Building the table with residue frequencies...')
# handler = string with all the bases for the position k
for k in range(len(allseq[0])):
handler = ''
# selection of all the bases in position k in the alignment
for currSeq in allseq:
handler += (currSeq[k])
snptab[k][0] = handler.count("A")
snptab[k][1] = handler.count("T")
snptab[k][2] = handler.count("G")
snptab[k][3] = handler.count("C")
snptab[k][4] = handler.count("-")
totalleles = sum(snptab[k][0:4])
snptab[k][5] = float(snptab[k][0]) / totalleles # freqA
snptab[k][6] = float(snptab[k][1]) / totalleles # freqT
snptab[k][7] = float(snptab[k][2]) / totalleles # freqG
snptab[k][8] = float(snptab[k][3]) / totalleles # freqC
snptab[k][9] = float(snptab[k][4]) / totalleles # freq-
# consensus
conscode = ''
# A
if snptab[k][5] >= conslimit:
conscode += '1'
else:
conscode += '0'
# T
if snptab[k][6] >= conslimit:
conscode += '1'
else:
conscode += '0'
# G
if snptab[k][7] >= conslimit:
conscode += '1'
else:
conscode += '0'
# C
if snptab[k][8] >= conslimit:
conscode += '1'
else:
conscode += '0'
# gaps with frequencies > than 1 - thr get the '*'
if snptab[k][9] >= (1-conslimit):
conscode = '*'
consensus += consdic.get(conscode)
snptab[k][14] = consdic.get(conscode)
if snptab[k][13] != '*':
# fHRM+ (frequency of HRM detectable SNPs)
snptab[k][10] = np.multiply(snptab[k][5], snptab[k][7]) + \
np.multiply(snptab[k][5], snptab[k][8]) + \
np.multiply(snptab[k][6], snptab[k][7]) + \
np.multiply(snptab[k][6], snptab[k][8])
snptab[k][11] = np.multiply(snptab[k][5], snptab[k][7]) + \
np.multiply(snptab[k][5], snptab[k][8]) + \
np.multiply(snptab[k][6], snptab[k][7]) + \
np.multiply(snptab[k][6], snptab[k][8]) + \
np.multiply(snptab[k][6], snptab[k][5]) + \
np.multiply(snptab[k][7], snptab[k][8])
# Shannon index
shannon = 0
for j in range(5, 10):
if snptab[k][j] != 0:
shannon += snptab[k][j] * (np.log(snptab[k][j]))
snptab[k][12] = -(shannon)
# Simpson index
simpson = 0
N = sum(snptab[k][0:5])
for j in range(0, 5):
simpson += (snptab[k][j]*(snptab[k][j]-1))/(N*(N-1))
snptab[k][13] = 1 - simpson
# add headers
header1 = ['Position', 'A', 'T', 'G', 'C', 'gap', 'fA', 'fT', 'fG',
'fC', 'fgap', 'fHRM+', 'fSNP', 'Shannon', 'Simpson', 'consensus']
header2 = np.arange(1, len(allseq[0]) + 1)
snptab = np.insert(snptab, 0, header2, axis=1)
snptab = np.insert(snptab, 0, header1, axis=0)
arrayFile = str(tmp_path+ jobname + genename + '_TAB.csv')
with open(arrayFile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writerows(snptab)
logger.info('The table of residue frequencies is in: ' + arrayFile)
# .txt file with consensus seq of the alignment
consensusFile = str(tmp_path + jobname + genename + '_consensus.txt')
hand = open(consensusFile, 'w')
hand.write(consensus + '\n')
hand.close()
# .txt file with consensus threshold
consensusTHR = str(tmp_path+ jobname + genename + '_consensus_threshold.txt')
hand = open(consensusTHR, 'w')
hand.write('Consenus_Threshold\t' + str(conslimit) + '\n')
hand.close()
logger.info('consensus sequence file: '+ consensusFile)
# Building the Dataframe of all the possible combinations of primers
logger.info('Building the Dataframe of all the possible combinations of primers and their scores...')
scoreset = []
scoreset.append(['ID', 'p1', 'p2', 'p3', 'p4',
'Score_primer1', 'Score_primer2', 'Score_MaxPrimer', 'Score_amplicon',
'Primer_Lenght', 'Amplicon_Lenght',
'Primer1_consensus', 'Primer2_consensus', 'Pri1_amb ', 'Pri2_amb', 'amp_HRMamb'])
if snp == 'HRM':
selector = 11
if snp == 'ALL':
selector = 12
ID = 0
pri_count = 0
for pri in prilen:
# list of weight for mean primer shannon score caluclation
w_list = []
# this loops will weight the mean shannon index in the primer according to the distance from the amplicon
for xx in range(prilen[pri_count]-n_adj):
w_list.append((1-w_adj)/(prilen[pri_count]-n_adj))
for xx in range(n_adj):
w_list.append(w_adj/n_adj)
pri_count += 1
for amp in amplen:
setlen = pri + amp + pri # total lenght of the current combination of primer1 + amplicon + primer2
for k in range(1, len(snptab) - setlen):
ID += 1 # 'ID': univocal ascending identifier
pri1score = float(0) # 'Score_primer1' mean shannon index for primer1 region
pri2score = float(0) # 'Score_primer2'mean shannon index for primer2 region
max_pri = float(0) # 'Score_MaxPrimer': max between 'Score_primer1', 'Score_primer2' (the wrose score between them)
ampscore = float(0) # 'Score_amplicon': mean FHRM+ in amplicon region
pri1cons = '' # 'Primer1 consensus': consensus seq for primer 1
pri2cons = '' # 'Primer2 consensus': consensus seq for primer 2
pri1_amb = int # 'Pri1_amb ': number of consensus IUPAC ambiguous characters in primer1
pri2_amb = int # 'Pri2_amb': number of consensus IUPAC ambiguous characters in primer2
amp_HRMamb = int # 'ampHRMamb': number of consensus IUPAC ambiguous characters that represent a HRM-detectable substitution
handamp = '' # handler
currset = [] # list of values for current combination
# key positions of scanning window:
# combination scheme: 'p1'__primer1__'p2'__amplicon__'p3'__primer2__'p4'
p1 = k # p1: primer1 start position
p2 = p1 + pri # p2: primer1 end position
p3 = p2 + amp # p3: primer2 start position
p4 = p3 + pri # p4: primer2 end position
# 'Score_primer1
w_count = 0
for j in range(p1, p2):
pri1score += (float(snptab[j][13]) * w_list[w_count]) # Shannon index
pri1cons = pri1cons + snptab[j][15]
w_count += 1
# 'Score_primer2'
w_count = 0
rw_list=list(reversed(w_list))
rw_count = 0
for jj in range(p3, p4):
pri2score += (float(snptab[j][13]) * rw_list[rw_count]) # Shannon index
pri2cons = pri2cons + snptab[jj][15]
rw_count += 1
# 'Score_amplicon'
for h in range(p2, p3):
ampscore += (float(snptab[h][selector])) # fSNP (average of frequencies of the ALL SNPs inside the amplicon)
ampscore = ampscore/amp # fHRM+ (average of frequencies of the HRM detectable SNPs inside the amplicon)
max_pri = max(pri1score, pri2score)
pri1_amb = pri1cons.count("R") + pri1cons.count("Y") + \
pri1cons.count("S") + pri1cons.count("W") + \
pri1cons.count("K") + pri1cons.count("M") + \
pri1cons.count("B") + pri1cons.count("D") + \
pri1cons.count("H") + pri1cons.count("V") + pri1cons.count("N")
pri2_amb = pri2cons.count("R") + pri2cons.count("Y") + \
pri2cons.count("S") + pri2cons.count("W") + \
pri2cons.count("K") + pri2cons.count("M") + \
pri2cons.count("B") + pri2cons.count("D") + \
pri2cons.count("H") + pri2cons.count("V") + pri2cons.count("N")
amp_HRMamb = pri2cons.count("R") + pri2cons.count("M") + \
pri2cons.count("K") + pri2cons.count("Y")
currset = [ID, p1, p2, p3, p4,
pri1score, pri2score, max_pri, ampscore,
pri, amp,
pri1cons, pri2cons,
pri1_amb, pri2_amb, amp_HRMamb]
scoreset.append(currset)
arrayFile = str(tmp_path+ jobname + genename + '_SCORES.csv')
with open(arrayFile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writerows(scoreset)
logger.info('The Dataframe with all the combinations of scores is in: '+ arrayFile)
if not jobname:
jobname_flag = 'empty'
else:
jobname_flag = jobname
#++++++++++++++++Plotting in R++++++++++++++++++++++++++++++++++++++
#rcomand = "Rscript " + path_scripts + "Plot_OUTPUT.R "+tmp_folder+" "+ genename +" "+ out_folder +" " + cwd +" "+ snp +" "+ str(prim_thr) +" "+ str(amp_thr) +" "+ jobname_flag+" "+ str(conslimit)
rcomand = "Rscript " + path_scripts + "Plot_OUTPUT.R "+ genename +" "+ out_folder +" " + cwd + \
" "+ snp +" "+ str(prim_thr) +" "+ str(amp_thr) +" "+ jobname_flag+" "+ str(conslimit)+ \
" "+str(minpri)+" "+str(maxpri)+" "+str(minamp)+" "+str(maxamp)+" "+ tmp_folder
try:
subprocess.check_call(rcomand, shell=True)
logger.info('Rscript called with the command: ' + rcomand)
logger.info('Selecting and plotting data...')
logger.info('final PDF graph file written in '+ cwd+out_folder)
except subprocess.CalledProcessError:
logger.info('PROGRAM HAS STOPPED ###ERROR######ERROR######ERROR######ERROR######ERROR###')
logger.info('Failing to write the final PDF graph, problems found calling the command: ' + rcomand)
quit('###ERROR### PROGRAM HAS STOPPED' + '\n' + '---> Failing to write the final PDF graph')
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
finaltime = (time.time() - start_time)
runtime = str(round(finaltime, 2)) + ' s'
developed_by = "MP"
footer = {'Runtime':runtime,
'Run on':date1,
'Version':'1.0_linux',
'Developed by':developed_by}
df_footer = pd.DataFrame.from_dict(footer, columns=[''], orient='index')
logger.info(df_footer)
logger.info(jobname + " " + os.path.basename(inputfile) + ' analysis ends'+"========================================"+ '\n')
print('==================DONE!=================\nYour Analysis on '+ genename +' is in '+ out_folder+' folder.'+'\n========================================')
print(df_footer)
def run(args):
out_folder = args.out_folder
tmp_folder = args.tmp_folder
alg = args.aln
inputfile= args.inputfile
conslimit = args.consensus_limit
minpri = args.minpri
maxpri = args.maxpri
minamp = args.minamp
maxamp = args.maxamp
prim_thr = args.prim_thr
amp_thr = args.amp_thr
n_adj = args.n_adj
w_adj = args.w_adj
jobname = args.jobname
snp = args.snp
alg = alg.lower()
prilen = list(range(minpri, maxpri + 1)) # range of possible primer lenghts
amplen = list(range(minamp, maxamp + 1)) # range of possible amplicon lenghts
if not jobname:
jobname = jobname
else:
jobname = jobname + '_'
########## MAIN FUNCTION ##########
primerHRM(out_folder, tmp_folder, inputfile, conslimit, prilen, amplen, prim_thr, amp_thr, n_adj, w_adj, alg, jobname, snp, minpri, maxpri, minamp, maxamp)
###################################
def main():
parser=argparse.ArgumentParser(description="**********"+"\n" +\
"EasyPrimer was developed to assist pan-PCR and "+"\n" +\
"High Resolution Melting (HRM) primer design"+"\n"+\
"**********"+ '\n\n' +\
"TEST FILE ==> https://skynet.unimi.it/wp-content/uploads/easy_primer/pgi.fas"+ '\n' +\
"OUTPUT EXAMPLE ==> https://skynet.unimi.it/wp-content/uploads/easy_primer/pgi_HRM_analysis.pdf",
epilog = "If you are using EasyPrimer for an article or scientfic publication"+ '\n' + \
"Please cite M. Perini et al. 2019 (doi: https://doi.org/10.1101/679001)"+ '\n\n' +\
"Online version of the tool: https://skynet.unimi.it/index.php/tools/easyprimer/",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-out",help="Output Folder. Default = 'Out'" ,dest="out_folder" , type=str, default='Out')
parser.add_argument("-tmp",help="folder with tmp and log files, created automatically if it doesn't exist. Default = 'tmp'" ,dest="tmp_folder" , type=str, default='tmp')
parser.add_argument("-aln",help="write 'n' to skip sequence alignment. In this case the sequences must be already aligned and the file in the Current Working Directory" ,dest="aln" , type=str, default='y')
parser.add_argument("-consthr",help="Consensus sequence limit, positive real number between 0 and 1. Default = 0.05" ,dest="consensus_limit" , type=float, default=0.05)
parser.add_argument("-minpri",help="Minimum primer lenght. Default = 15" ,dest="minpri" , type=int, default=15)
parser.add_argument("-maxpri",help="Maxium primer lenght. Default = 25" ,dest="maxpri" , type=int, default=25)
parser.add_argument("-minamp",help="Minimum amplicon lenght. Default = 70" ,dest="minamp" , type=int, default=70)
parser.add_argument("-maxamp",help="Maximum amplicon lenght. Default = 100" ,dest="maxamp" , type=int, default=100)
parser.add_argument("-prithr",help="Variability threshold for the selection of the primers, positive real number between 0 and 1. Default = 0.2" ,dest="prim_thr" , type=float, default=0.2)
parser.add_argument("-ampthr ",help="Variability threshold for the selection of the amplicon, positive real number between 0 and 1. Default = 0.95" ,dest="amp_thr" , type=float, default=0.95)
parser.add_argument("-npri",help="Number of primer residues next to the aplicon considered fundamental for primer anneling. default = 5" ,dest="n_adj" , type=int, default=5)
parser.add_argument("-wnpri",help="Weight for the adjustment in the '-npri' residues, positive real number between 0 and 1. default = 0.7" ,dest="w_adj" , type=float, default=0.7)
parser.add_argument("-prefix",help="Job name to be added as a prefix in final PDF and in tmp files as well" ,dest="jobname" , type=str, default="")
parser.add_argument("-snp",help="Either 'HRM' or 'ALL', dafault is 'HRM'" ,dest="snp" , choices=['HRM', 'ALL'], default="HRM")
requiredNamed = parser.add_argument_group('required arguments')
requiredNamed.add_argument("-in",help="REQUIRED ARGUMENT: fasta file of the gene to be analyzed" ,dest="inputfile" , type=str, required=True)
parser.set_defaults(func=run)
args=parser.parse_args()
args.func(args)
if __name__=="__main__":
main()
#python3.6 EasyPrimer.py -in Example.fas