forked from aakechin/NGS-PrimerPlex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNGS_primerplex.py
4377 lines (4331 loc) · 255 KB
/
NGS_primerplex.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/python3
# This script constructs primers for multiplex NGS panels
import argparse
import re
import os
import sys
import math
import random
import primer3
import logging
import pysam
import xlrd
import numpy
import statistics as stat
from copy import deepcopy
from multiprocessing.pool import ThreadPool
from multiprocessing import Pool
from Bio import SeqIO,Seq,pairwise2
import subprocess as sp
from operator import itemgetter
import xlsxwriter as xls
import networkx as nx
import networkx.algorithms.clique as clique
import networkx.algorithms.shortest_paths.weighted as weighted_shortest_paths
from itertools import islice
from collections import Counter
global thisDir,nameToNum,numToName
thisDir=os.path.dirname(os.path.realpath(__file__))+'/'
# Section of functions
def chrToChr(args,refFa):
global nameToNum,numToName
nameToNum={}
numToName={}
## refFa=pysam.FastaFile(args.wholeGenomeRef)
for i,ch in enumerate(refFa.references):
nameToNum[ch]=i+1
numToName[i+1]=ch
return(nameToNum,numToName)
def readInputFile(regionsFile):
global nameToNum,numToName
allRegions={}
regionsNames={}
regionNameToChrom={}
regionsCoords={}
regionNameToMultiplex={}
regionNameToPrimerType={}
uniquePointRegions=0
totalPointInputRegions=0
for string in regionsFile:
if ('Chrom' in string or
'Start\tEnd' in string or
string=='' or string=='\n'):
continue
cols=string.replace('\n','').split('\t')
# chrom is a name of chromosome (e.g. chr1, chr2 etc)
# chromInt is a number of chromosome in the reference genome file (e.g. 1,2,3 etc)
# But the last one can be different from names (e.g. chr1 can be chromosome #2)
# So the user shouldn't see this numbers in order not to shock him or her
chrom=cols[0]
try:
chromInt=int(chrom)
except ValueError:
if chrom in nameToNum.keys():
chromInt=nameToNum[chrom]
else:
print('ERROR (56)! Incorrect format of chromosome!')
print(cols)
print('According to the defined reference genome, chromosome names are:')
print(sorted(nameToNum.keys()))
print('Or you can use numbers of chromosome, and they correspond to the following names:')
for num,name in sorted(numToName.items(),
key=lambda item:item[0]):
print(num,name)
exit(56)
try:
regStart=int(cols[1])
regEnd=int(cols[2])
except ValueError:
print('ERROR: Incorrect format of input file!')
print('It should have the following format:')
print('Chromosome{Tab}Start_Position{Tab}End_Position{Tab}Amplicon_Name{Tab}\n'
'Desired_Multiplex_Numbers(optional){Tab}Type_Of_Primers(only left/only right/both)(optional){Tab}'
'Use_Whole_Region(optional)')
print('But your file have the following format:')
print(string)
exit(1)
# Check that region is written in the right way
if regStart>regEnd:
temp=regStart
regStart=regEnd
regEnd=temp
regionName=cols[3]
# We split any region onto list of poses
for i in range(regStart,regEnd+1):
totalPointInputRegions+=1
try:
if chromInt not in regionsCoords.keys() or i not in regionsCoords[chromInt]:
if regionName not in regionsNames.keys():
regionsNames[regionName]=[regionName+'_1']
else:
prevNum=regionsNames[regionName][-1].split('_')[-1]
regionsNames[regionName].append(regionName+'_'+str(int(prevNum)+1))
curRegionName=regionsNames[regionName][-1]
regionNameToChrom[curRegionName]=chrom
if len(cols)>4 and cols[4]!='':
regionNameToMultiplex[curRegionName]=cols[4].split(',')
if len(cols)>5 and cols[5]!='':
if cols[5] not in ['L','R','B']:
print('ERROR! Unknown type of primers is necessary to be designed for the following line of input file:')
print(string)
print('This value can be only "L" (only left primer), "R" (only right primer), "B" (both primers) or nothing (both primers)')
exit(2)
regionNameToPrimerType[curRegionName]=cols[5]
if len(cols)>6 and cols[6]!='':
if cols[6]=='W':
endShift=regEnd-regStart
print('ATTENTION! For region',regionName,'whole region was chosen!')
logger.info('ATTENTION! For region '+regionName+' whole region was chosen!')
else:
endShift=0
else:
endShift=0
if chrom not in allRegions.keys():
if endShift>0:
allRegions[chrom]={curRegionName:[chrom,regStart,regStart+endShift,curRegionName]}
else:
allRegions[chrom]={curRegionName:[chrom,i,i+endShift,curRegionName]}
regionsCoords[chromInt]=[i]
uniquePointRegions+=1
else:
# Addtionally check that all input regions are unique
if endShift>0:
if [chrom,regStart,regStart+endShift,curRegionName] not in allRegions[chrom].values():
allRegions[chrom][curRegionName]=[chrom,regStart,regStart+endShift,curRegionName]
regionsCoords[chromInt].append(regStart)
uniquePointRegions+=1
else:
if [chrom,i,i+endShift,curRegionName] not in allRegions[chrom].values():
allRegions[chrom][curRegionName]=[chrom,i,i+endShift,curRegionName]
regionsCoords[chromInt].append(i)
uniquePointRegions+=1
if endShift>0:
for i in range(regStart+1,regEnd+1):
regionsCoords[chromInt].append(i)
break
except ValueError:
print('ERROR: Incorrect format of input file!')
print('It should have the following format:')
print('Chromosome{Tab}Start_Position{Tab}End_Position{Tab}Amplicon_Name{Tab}\n'
'Desired_Multiplex_Numbers(optional){Tab}Type_Of_Primers(only left/only right/both)(optional){Tab}'
'Use_Whole_Region(optional)')
print('But your file have the following format:')
print(string)
exit(4)
# Sort dict with regions coords
for chromInt in regionsCoords.keys():
regionsCoords[chromInt]=sorted(regionsCoords[chromInt])
print(' # Total number of input point regions:',totalPointInputRegions)
print(' # Number of unique input point regions:',uniquePointRegions)
logger.info(' # Total number of input point regions: '+str(totalPointInputRegions))
logger.info(' # Number of unique input point regions: '+str(uniquePointRegions))
# allRegions has chromosome names
# regionsCoords has chromosome numbers
# regionNameToChrom has chromosome names
return(allRegions,regionsNames,regionsCoords,regionNameToChrom,regionNameToMultiplex,regionNameToPrimerType)
def readPrimersFile(primersFile):
wb=xlrd.open_workbook(primersFile)
ws=wb.sheet_by_index(0)
internalPrimers=[]
amplifiedRegions={}
for i in range(ws.nrows):
row=ws.row_values(i)
if row[0]=='':
break
if i==0:
# Check that input file has necessary format
if row[:16]!='# Left_Primer_Seq Right_Primer_Seq Amplicon_Name Chrom Amplicon_Start Amplicon_End Amplicon_Length Amplified_Block_Start Amplified_Block_End Left_Primer_Tm Right_Primer_Tm Left_Primer_Length Right_Primer_Length Left_GC Right_GC'.split('\t'):
print('ERROR! Input file with primers has incorrect format. You can use only files with primers that has format of NGS-primerplex')
logger.error('Input file with primers has incorrect format. You can use only files with primers that has format of NGS-primerplex')
exit(5)
continue
# Make chromosome from excel cell
chrom=getChrNum(row[4])
if chrom not in amplifiedRegions.keys():
amplifiedRegions[chrom]=set(range(int(row[8]),int(row[9])+1))
else:
amplifiedRegions[chrom].update(set(range(int(row[8]),int(row[9])+1)))
internalPrimers.append(row[1:16])
return(internalPrimers,amplifiedRegions)
def createPrimer3_parameters(pointRegions,args,refFa,
designedInternalPrimers=None,
regionNameToPrimerType=None,
regionNameNeedToBeWholeLen=None,
regionNameToChrom={},
amplToStartCoord={}):
templatePrimerTags={'PRIMER_TASK':'generic',
'PRIMER_PICK_LEFT_PRIMER':1,
'PRIMER_PICK_RIGHT_PRIMER':1,
'PRIMER_MAX_NS_ACCEPTED':0,
'PRIMER_SALT_CORRECTIONS':1,
'PRIMER_TM_FORMULA':1,
'PRIMER_DNA_CONC':args.primerConc, # primer, in nM
'PRIMER_SALT_DIVALENT':args.dvConc, # Mg2+, in mM
'PRIMER_SALT_MONOVALENT':args.mvConc, # K+ or NH4+, in mM
'PRIMER_DNTP_CONC':args.dntpConc, # sum concentration of each dNTP, in mM
'PRIMER_THERMODYNAMIC_OLIGO_ALIGNMENT':1,
'PRIMER_WT_SELF_END':0.5,
'PRIMER_PAIR_WT_DIFF_TM':0.5,
'PRIMER_WT_GC_PERCENT_GT':0.5,
'PRIMER_WT_GC_PERCENT_LT':0.5,
'PRIMER_PAIR_WT_PRODUCT_SIZE_GT':2,
'PRIMER_PAIR_WT_PRODUCT_SIZE_LT':2,
'PRIMER_EXPLAIN_FLAG':1}
primer3Params={}
primerTags=deepcopy(templatePrimerTags)
# Writing primer design parameters that user defined
primerTags['PRIMER_MIN_SIZE']=args.minPrimerLen
primerTags['PRIMER_MAX_SIZE']=args.maxPrimerLen
primerTags['PRIMER_OPT_SIZE']=args.optPrimerLen
primerTags['PRIMER_MIN_TM']=args.minPrimerMelt
primerTags['PRIMER_MAX_TM']=args.maxPrimerMelt
primerTags['PRIMER_OPT_TM']=args.optPrimerMelt
primerTags['PRIMER_MIN_GC']=args.minPrimerGC
primerTags['PRIMER_MAX_GC']=args.maxPrimerGC
primerTags['PRIMER_OPT_GC_PERCENT']=args.optPrimerGC
primerTags['PRIMER_MAX_END_GC']=args.maxPrimerEndGC
primerTags['PRIMER_MIN_END_GC']=args.minPrimerEndGC
primerTags['PRIMER_MAX_POLY_X']=args.maxPrimerPolyN
primerTags['PRIMER_MAX_SELF_END']=args.maxPrimerComplEndTh
primerTags['PRIMER_MAX_SELF_ANY_TH']=args.maxPrimerComplAnyTh
primerTags['PRIMER_MAX_HAIRPIN_TH']=args.maxPrimerHairpinTh
primerTags['PRIMER_NUM_RETURN']=args.primernum1
if designedInternalPrimers==None:
if args.leftAdapter:
primerTags['PRIMER_LEFT_ADAPTER']=args.leftAdapter.upper()
if args.rightAdapter:
primerTags['PRIMER_RIGHT_ADAPTER']=args.rightAdapter.upper()
## primerTags['PRIMER_PAIR_MAX_COMPL_ANY_TH']=args.maxPrimerComplAnyTh ## Use of this value lead to mistake in primer3-py module. It begins to incorrectly calculate Tm
## primerTags['PRIMER_PAIR_MAX_COMPL_END_TH']=args.maxPrimerComplEndTh ## Use of this value lead to mistake in primer3-py module. It begins to incorrectly calculate Tm
# If we are going to design external primers for already created internal primers
if designedInternalPrimers:
for internalPrimers in designedInternalPrimers.values():
leftPrimer,rightPrimer,amplName,chrom,amplStart,amplEnd,amplLen,amplBlockStart,amplBlockEnd,leftPrimerTm,rightPrimerTm,leftPrimerLen,rightPrimerLen,leftGC,rightGC,targetName=internalPrimers
curRegionName=targetName[:targetName.rfind('_')]
if regionNameToPrimerType is None:
primerTags['PRIMER_PICK_LEFT_PRIMER']=1
primerTags['PRIMER_PICK_RIGHT_PRIMER']=1
elif curRegionName in regionNameToPrimerType.keys():
if regionNameToPrimerType[curRegionName]=='L':
primerTags['PRIMER_PICK_LEFT_PRIMER']=1
primerTags['PRIMER_PICK_RIGHT_PRIMER']=0
elif regionNameToPrimerType[curRegionName]=='R':
primerTags['PRIMER_PICK_LEFT_PRIMER']=0
primerTags['PRIMER_PICK_RIGHT_PRIMER']=1
elif regionNameToPrimerType[curRegionName]=='B':
primerTags['PRIMER_PICK_LEFT_PRIMER']=1
primerTags['PRIMER_PICK_RIGHT_PRIMER']=1
else:
print('ERROR #6: Unknown type of primers is necessary to be designed for the following region:')
logger.error('#6 Unknown type of primers is necessary to be designed for the following region:')
print(amplName)
logger.error(amplName)
print('This value can be only "L" (only left primer), "R" (only right primer), "B" (both primers) or nothing (both primers)')
logger.error('This value can be only "L" (only left primer), "R" (only right primer), "B" (both primers) or nothing (both primers)')
exit(6)
regionNameToChrom[amplName]=chrom
primer3Params[amplName]=[]
primerTags['PRIMER_PRODUCT_SIZE_RANGE']=[[amplLen+2*args.minPrimerShift,args.maxExtAmplLen]]
primerTags['PRIMER_PRODUCT_OPT_SIZE']=args.optExtAmplLen
# We can shift our external amplicon on the (maximal length of extAmpl) - (amplLen)-(minPrimerShift)
chrTargetSeqStart=amplBlockEnd-(args.maxExtAmplLen-args.minPrimerShift-args.minPrimerLen)
# In COSMIC database chromosome X and Y are designated as 23 and 24, respectively
## So we need to check if primers are designed for human genome and chromosomes may be 23 and 24 instead of X and Y
chromInt=nameToNum[chrom]
chromName=chrom
if (chrTargetSeqStart<0 or
amplBlockEnd+args.maxExtAmplLen-args.minPrimerShift-args.minPrimerLen<0):
print('ERROR #54: Unknown error with coordinates for sequence extraction from genome:')
logger.error('#54 Unknown error with coordinates for sequence extraction from genome:')
print(chromName,chrTargetSeqStart,amplBlockEnd,
args.maxExtAmplLen,args.minPrimerShift,
args.minPrimerLen)
logger.error(', '.join(map(str,[chromName,chrTargetSeqStart,amplBlockEnd,
args.maxExtAmplLen,args.minPrimerShift,
args.minPrimerLen])))
exit(54)
regionSeq=extractGenomeSeq(refFa,args.wholeGenomeRef,
chromName,chrTargetSeqStart,
amplBlockEnd+(args.maxExtAmplLen-args.minPrimerShift-args.minPrimerLen)+1)
targetRegion=str(amplBlockStart-args.minPrimerShift-chrTargetSeqStart)+','+str(amplBlockEnd-amplBlockStart+1+2*args.minPrimerShift)
targetRegionStart=amplBlockStart-args.minPrimerShift-chrTargetSeqStart
targetRegionEnd=targetRegionStart+(amplBlockEnd-amplBlockStart+1+2*args.minPrimerShift)-1
amplToStartCoord[amplName]=chrTargetSeqStart
seqTags={}
seqTags['SEQUENCE_TEMPLATE']=str(regionSeq)
seqTags['SEQUENCE_ID']='NGS_primerplex_'+amplName
# We create 3 sets of primer pairs, that will be located in three variants:
## --------------------Mut--------------------
## 1) -=======================-------------------
## 2) -------------------=======================-
## 3) Without forcing primer location
for i in range(3):
if i==0:
primerPairOkRegion=[[0,targetRegionStart-1,targetRegionEnd+1,len(regionSeq)-targetRegionEnd-1]]
elif i==1:
# Force location of the right primer to the close proximity to target
primerPairOkRegion=[[0,targetRegionStart-1,targetRegionEnd+1,args.maxPrimerLen+2]]
else:
# Force location of the left primer to the close proximity to target
primerPairOkRegion=[[targetRegionStart-args.maxPrimerLen-2,args.maxPrimerLen+2,targetRegionEnd+1,len(regionSeq)-targetRegionEnd-1]]
seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST']=primerPairOkRegion
primer3Params[amplName].append([deepcopy(seqTags),deepcopy(primerTags)])
return(primer3Params,regionNameToChrom,amplToStartCoord)
else:
primerTags['PRIMER_PRODUCT_SIZE_RANGE']=[[args.minAmplLen,args.maxAmplLen]]
primerTags['PRIMER_PRODUCT_OPT_SIZE']=args.optAmplLen
# prevEnd stores coordinate of the previous position
## If currently processed position is more than previous end by one position,
## we need to make only primers that are near to the current position
prevEnd=0
for chrom,regions in pointRegions.items():
for region in sorted(regions.values(),key=itemgetter(1)):
chrom,start,end,curRegionName=region
if regionNameToPrimerType is None:
primerTags['PRIMER_PICK_LEFT_PRIMER']=1
primerTags['PRIMER_PICK_RIGHT_PRIMER']=1
elif curRegionName in regionNameToPrimerType.keys():
if regionNameToPrimerType[curRegionName]=='L':
primerTags['PRIMER_PICK_LEFT_PRIMER']=1
primerTags['PRIMER_PICK_RIGHT_PRIMER']=0
elif regionNameToPrimerType[curRegionName]=='R':
primerTags['PRIMER_PICK_LEFT_PRIMER']=0
primerTags['PRIMER_PICK_RIGHT_PRIMER']=1
elif regionNameToPrimerType[curRegionName]=='B':
primerTags['PRIMER_PICK_LEFT_PRIMER']=1
primerTags['PRIMER_PICK_RIGHT_PRIMER']=1
else:
print('ERROR! Unknown type of primers is necessary to be designed for the following region:')
print(curRegionName)
print('This value can be only "0" (only left primer), "1" (only right primer), "2" (both primers) or nothing (both primers)')
exit(8)
# We do not need to split regions onto several blocks
## because previously we splited it onto point positions
primer3Params[curRegionName]=[]
# In COSMIC database chromosome X and Y are designated as 23 and 24, respectively
## So we need to check if primers are designed for human genome and chromosomes may be 23 and 24 instead of X and Y
chromInt=nameToNum[chrom]
chromName=chrom
seqTags={}
seqTags['SEQUENCE_ID']='NGS_primerplex_'+curRegionName
if (start-args.maxAmplLen<0 and
end+args.maxAmplLen>refFa.lengths[refFa.references.index(chromName)]):
print('ERROR (53)! The amplicon length is more than the chromosome length')
logger.error('(53) The amplicon length is more than the chromosome length')
print(chromName,start,args.maxAmplLen,end)
logger.error(', '.join([chromName,str(start),str(args.maxAmplLen),str(end)]))
elif start-args.maxAmplLen<0:
regionSeq=extractGenomeSeq(refFa,args.wholeGenomeRef,
chromName,1,end+args.maxAmplLen)
seqTags['SEQUENCE_TEMPLATE']=str(regionSeq)
prevEnd=end
primerPairOkRegion=[[0,start-1,
end+1,args.maxAmplLen-1]]
seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST']=primerPairOkRegion
primer3Params[curRegionName].append([deepcopy(seqTags),deepcopy(primerTags)])
elif end+args.maxAmplLen>refFa.lengths[refFa.references.index(chromName)]:
if start>refFa.lengths[refFa.references.index(chromName)]:
print('ERROR (60)! The following input region have start and end more than the chromosome length:')
logger.error('(60) The following input region have start and end more than the chromosome length:')
print(region)
logger.error(str(region))
print('The length of the chromosome is '+str(refFa.lengths[refFa.references.index(chromName)]))
logger.error('The length of the chromosome is '+str(refFa.lengths[refFa.references.index(chromName)]))
exit(60)
regionSeq=extractGenomeSeq(refFa,args.wholeGenomeRef,
chromName,max(1,start-args.maxAmplLen),
refFa.lengths[refFa.references.index(chromName)])
seqTags['SEQUENCE_TEMPLATE']=str(regionSeq)
prevEnd=end
primerPairOkRegion=[[0,args.maxAmplLen-args.maxPrimerLen-2,
args.maxAmplLen+1+end-start,
len(regionSeq)-args.maxAmplLen-1-(end-start)]]
seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST']=primerPairOkRegion
primer3Params[curRegionName].append([deepcopy(seqTags),deepcopy(primerTags)])
else:
regionSeq=extractGenomeSeq(refFa,args.wholeGenomeRef,
chromName,max(1,start-args.maxAmplLen),end+args.maxAmplLen)
seqTags['SEQUENCE_TEMPLATE']=str(regionSeq)
if start==prevEnd+1:
primerPairOkRegion=[[args.maxAmplLen-args.maxPrimerLen-2,args.maxPrimerLen+2,
args.maxAmplLen+1+end-start,len(regionSeq)-args.maxAmplLen-1-(end-start)]]
seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST']=primerPairOkRegion
primer3Params[curRegionName].append([deepcopy(seqTags),deepcopy(primerTags)])
else:
# We create 3 sets of primer pairs, that will be located in three variants:
## --------------------Mut--------------------
## 1) -=======================-------------------
## 2) -------------------=======================-
## 3) Without forcing primer location
for i in range(3):
# Extracting reference sequence
if i==0:
# Force location of the right primer to the close proximity to target
primerPairOkRegion=[[0,args.maxAmplLen-1,args.maxAmplLen+1+end-start,args.maxPrimerLen+2]]
elif i==1:
# Force location of the left primer to the close proximity to target
primerPairOkRegion=[[args.maxAmplLen-args.maxPrimerLen-2,args.maxPrimerLen+2,
args.maxAmplLen+1+end-start,
len(regionSeq)-args.maxAmplLen-1-(end-start)]]
else:
primerPairOkRegion=[[0,args.maxAmplLen-1,
args.maxAmplLen+1+end-start,
len(regionSeq)-args.maxAmplLen-1-(end-start)]]
seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST']=primerPairOkRegion
primer3Params[curRegionName].append([deepcopy(seqTags),deepcopy(primerTags)])
prevEnd=end
return(primer3Params)
def constructInternalPrimers(primer3Params,regionNameToChrom,
args,regionsCoords=None,
allRegions=None,primersInfo=None,
primersInfoByChrom=None,
amplNames=None,primersToAmplNames=None):
# chrom is string
p=Pool(args.threads)
# Dictionary for storing primers' info
# Contains chromosome names
if primersInfo==None:
primersInfo={}
# Dictionary for storing primers' info but primers are splitted by chromosome location
# Contains chromosome numbers
if primersInfoByChrom==None:
primersInfoByChrom={}
# Dictionary for making unique amplicon names
if amplNames==None:
amplNames={}
# Dictionary for converting primers' pairs to amplicon names
if primersToAmplNames==None:
primersToAmplNames={}
# Constructing primers for each region with primer3
totalPrimersNum=0
totalDifPrimersNum=0
regionsWithoutPrimers=[]
poolArgs=[]
wholeWork=0
for i,(regionName,inputParams) in enumerate(primer3Params.items()):
for inputParam in inputParams:
poolArgs.append((regionName,inputParam,False,args))
wholeWork+=1
doneWork=0
primerDesignExplains={}
internalExplainToWords=['left min end GC',
'right min end GC',
'left hairpin end3',
'right hairpin end3',
'left homodimer',
'right homodimer',
'heterodimer',
'left homodimer end3',
'right homodimer end3',
'heterodimer end3',
'absense of T for replacement with U']
for res in p.imap_unordered(runPrimer3,poolArgs):
doneWork+=1
showPercWork(doneWork,wholeWork,args.gui)
curRegionName,primerSeqs,primersCoords,primerTms,amplLens,amplScores,primer3File,designOutput=res#.get()
if curRegionName not in amplNames.keys():
amplNames[curRegionName]=[]
if primerSeqs==None:
explanation=''
if 'PRIMER_PAIR_EXPLAIN' in designOutput.keys():
explanation=designOutput['PRIMER_PAIR_EXPLAIN']
if explanation=='considered 0, ok 0':
explanation='considered 0 pairs, ok 0;'
if 'PRIMER_LEFT_EXPLAIN' in designOutput.keys():
if 'ok 0' in designOutput['PRIMER_LEFT_EXPLAIN']:
explanation+='\n Left: '+designOutput['PRIMER_LEFT_EXPLAIN']
if 'PRIMER_RIGHT_EXPLAIN' in designOutput.keys():
if 'ok 0' in designOutput['PRIMER_RIGHT_EXPLAIN']:
explanation+='\n Right: '+designOutput['PRIMER_RIGHT_EXPLAIN']
elif 'PRIMER_RIGHT_EXPLAIN' in designOutput.keys():
explanation=designOutput['PRIMER_RIGHT_EXPLAIN']
elif 'PRIMER_LEFT_EXPLAIN' in designOutput.keys():
explanation=designOutput['PRIMER_LEFT_EXPLAIN']
if 'INTERNAL_EXPLAIN' in designOutput.keys():
for k,filteredNum in enumerate(designOutput['INTERNAL_EXPLAIN']):
if filteredNum>0:
explanation+=' \n'+str(filteredNum)+' pairs were filtered due to '+internalExplainToWords[k]
explanation+=' \nYou can try to increase -primernum1 for this region'
if curRegionName not in primerDesignExplains:
primerDesignExplains[curRegionName]=[]
primerDesignExplains[curRegionName].append(explanation)
continue
chromName=regionNameToChrom[curRegionName]
chrom=chromName
chromInt=nameToNum[chromName]
if chromInt not in primersInfoByChrom.keys():
primersInfoByChrom[chromInt]={}
# Extract start and end of target region
try:
start,end=allRegions[chromName][curRegionName][1:3]
except KeyError:
print('ERROR!',allRegions.keys())
exit(10)
# Go through each pair of primers and save them and info about them
for i in range(int(len(primerSeqs)/2)):
totalPrimersNum+=i+1
# If this pair of primers has been already processed, then we save all possible info about it
## Including information that this primers cover other input positions
if '_'.join(primerSeqs[2*i:2*i+2]) in primersInfo.keys():
continue
# Calculating coordinates of primers on a chromosome
# If it is near the start of a chromosome
if start-args.maxAmplLen<0:
primersCoords[2*i][0]=primersCoords[2*i][0]
## If we constructed only left primer
if primersCoords[2*i+1][0]==0:
# We set coordinate of the right primer as the most right position of this amplicon
primersCoords[2*i+1][0]=args.maxAmplLen
else:
primersCoords[2*i+1][0]=primersCoords[2*i+1][0]
else:
primersCoords[2*i][0]=primersCoords[2*i][0]+start-args.maxAmplLen # We do not substract 1, because we want to get real coordinate, not number of symbol in coordinate
# We substract args.maxAmplLen because it is an addiotional part of chromosome that we wrote to primer3 input file as target sequence
# primersCoords[2*i+1][0] is a right coordinate of primer
## If we constructed only left primer
if primersCoords[2*i+1][0]==0:
# We set coordinate of the right primer as the most right position of this amplicon
primersCoords[2*i+1][0]=start+args.maxAmplLen
else:
primersCoords[2*i+1][0]=primersCoords[2*i+1][0]+start-args.maxAmplLen
# Calculate coordinates of amplified block that exclude primers
amplBlockStart=primersCoords[2*i][0]+primersCoords[2*i][1]
amplBlockEnd=primersCoords[2*i+1][0]-primersCoords[2*i+1][1]
# Save info about this pair
primersInfo['_'.join(primerSeqs[2*i:2*i+2])]=[primersCoords[2*i:2*i+2],primerTms[2*i:2*i+2],amplLens[i],amplScores[i],chrom]
if '_'.join(primerSeqs[2*i:2*i+2]) not in primersInfoByChrom[chromInt].keys():
primersInfoByChrom[chromInt]['_'.join(primerSeqs[2*i:2*i+2])]=primersCoords[2*i:2*i+2]
# Check if this pair of primers covers also other target input regions
coveredPointRegions=checkThisPrimerPairForCoveringOtherInputRegions(allRegions[chrom],amplBlockStart,amplBlockEnd)
for curRegionName in coveredPointRegions:
# Create name for this pair of primers and save it
if curRegionName not in amplNames.keys():
amplNames[curRegionName]=[curRegionName+'_1']
elif len(amplNames[curRegionName])==0:
amplNames[curRegionName].append(curRegionName+'_1')
else:
prevNum=amplNames[curRegionName][-1].split('_')[-1]
amplNames[curRegionName].append(curRegionName+'_'+str(int(prevNum)+1))
curAmplName=amplNames[curRegionName][-1]
# Each pair of primers can cover several input positions
if '_'.join(primerSeqs[2*i:2*i+2]) not in primersToAmplNames.keys():
primersToAmplNames['_'.join(primerSeqs[2*i:2*i+2])]=[curAmplName]
else:
primersToAmplNames['_'.join(primerSeqs[2*i:2*i+2])].append(curAmplName)
totalDifPrimersNum+=1
## TO DO:
### Check if this pair of primers has occured again due to genome repeat
print()
p.close()
p.join()
writeDraftPrimers(primersInfo,args.regionsFile[:-4]+'_all_draft_primers.xls')
regionsWithoutPrimers=[]
for curRegionName,ampls in amplNames.items():
if len(ampls)==0:
regionsWithoutPrimers.append(curRegionName)
if len(regionsWithoutPrimers)>0:
print(' # WARNING! For ',len(regionsWithoutPrimers),'regions primers could not be designed with the defined parameters. Here are these regions:')
logger.warn(' # WARNING! For '+str(len(regionsWithoutPrimers))+' regions primers could not be designed with the defined parameters. Here are these regions:')
for regionWithoutPrimer in sorted(regionsWithoutPrimers,
key=lambda key:splitNameForSorting(key)):
if args.skipUndesigned:
regionsCoords[nameToNum[regionNameToChrom[regionWithoutPrimer]]].remove(allRegions[regionNameToChrom[regionWithoutPrimer]][regionWithoutPrimer][1])
if len(regionsCoords[nameToNum[regionNameToChrom[regionWithoutPrimer]]])==0:
regionsCoords.pop(nameToNum[regionNameToChrom[regionWithoutPrimer]])
allRegions[regionNameToChrom[regionWithoutPrimer]].pop(regionWithoutPrimer)
if len(allRegions[regionNameToChrom[regionWithoutPrimer]])==0:
allRegions.pop(regionNameToChrom[regionWithoutPrimer])
regionNameToChrom.pop(regionWithoutPrimer)
amplNames.pop(regionWithoutPrimer)
print(' '+regionWithoutPrimer)
logger.info(' '+regionWithoutPrimer)
print(primer3Params[regionWithoutPrimer][0][0]['SEQUENCE_TEMPLATE'])
logger.info(primer3Params[regionWithoutPrimer][0][0]['SEQUENCE_TEMPLATE'])
if regionWithoutPrimer not in primerDesignExplains.keys():
print('All primer pairs were filtered out by non-primer3 parameters. '
"Try changing NGS-PrimerPlex parameters (e.g. homodimer stability with hybridized 3'-end)")
logger.info('All primer pairs were filtered out by non-primer3 parameters. '
"Try changing NGS-PrimerPlex parameters (e.g. homodimer stability with hybridized 3'-end)")
continue
for explanation in primerDesignExplains[regionWithoutPrimer]:
print(explanation)
logger.info(explanation)
if not args.skipUndesigned:
print(' You should use less stringent parameters')
logger.info(' You should use less stringent parameters')
exit(12)
print(' # Total number of constructed primers:',totalPrimersNum)
print(' # Total number of different constructed primers:',totalDifPrimersNum)
logger.info(' # Total number of constructed primers: '+str(totalPrimersNum))
logger.info(' # Total number of different constructed primers: '+str(totalDifPrimersNum))
return(primersInfo,primersInfoByChrom,amplNames,primersToAmplNames,regionsCoords,regionNameToChrom,allRegions)
def runPrimer3(poolArgs):
regionName,inputParams,extPrimer,args=poolArgs
autoAdjust=args.autoAdjust
extPrimerTryNum=0
seqTags,primerTags=inputParams
# Variable that stores, if we tried to set less stringent parameters for:
## polyN, GC-content of primers, length of primers,Tms of primers
if autoAdjust:
triedSofterParameters=[False,False,False,False,False]
else:
triedSofterParameters=[True,True,True,True,True]
softerParametersNames=['polyN',"primers 3'-end GC-content",'primers GC-content','length of primers','Tm of primers']
pParams=['PRIMER_MAX_POLY_X','PRIMER_MAX_END_GC','PRIMER_MIN_GC','PRIMER_MIN_SIZE','PRIMER_MIN_TM']
while(True):
try:
out=primer3.designPrimers(seqTags,primerTags)
except OSError as e:
print('ERROR (13)! '+str(e))
print(seqTags,primerTags)
logger.error('ERROR! '+str(e))
logger.error(seqTags,primerTags)
exit(13)
numReturned=out['PRIMER_PAIR_NUM_RETURNED']
out['INTERNAL_EXPLAIN']=[0]*11 # 11 because it is number of internal checks
if (primerTags['PRIMER_PICK_LEFT_PRIMER']==1 and
primerTags['PRIMER_PICK_RIGHT_PRIMER']==1 and
numReturned>0):
# Check that all found primers has necessary GC-content of the 3'-end
## And all primers do not form hairpin with 5'-overhang
minEndGC=primerTags['PRIMER_MIN_END_GC']
primers=[]
primersPoses=[]
primersTms=[]
primersProductSizes=[]
primersProductPenalty=[]
for i in range(numReturned):
primers.append(out['PRIMER_LEFT_'+str(i)+'_SEQUENCE'].upper())
primers.append(out['PRIMER_RIGHT_'+str(i)+'_SEQUENCE'].upper())
primersPoses.append(list(out['PRIMER_LEFT_'+str(i)]))
primersPoses.append(list(out['PRIMER_RIGHT_'+str(i)]))
primersTms.append(round(out['PRIMER_LEFT_'+str(i)+'_TM'],0))
primersTms.append(round(out['PRIMER_RIGHT_'+str(i)+'_TM'],0))
primersProductSizes.append(out['PRIMER_PAIR_'+str(i)+'_PRODUCT_SIZE'])
primersProductPenalty.append(out['PRIMER_PAIR_'+str(i)+'_PENALTY'])
# If after filtering no primers left and setting less stringent parameters did not solve the problem
## In the second iteration we do not filter primers by minimal GC-content of 3'-ends
## if False in triedSofterParameters:
i=0
while(i<int(len(primers)/2) and len(primers)>0):
leftEnd3_rc=str(Seq.Seq(primers[2*i][-4:]).reverse_complement())
rightEnd3_rc=str(Seq.Seq(primers[2*i+1][-4:]).reverse_complement())
if 'PRIMER_LEFT_ADAPTER' in primerTags.keys():
leftPrimer=primerTags['PRIMER_LEFT_ADAPTER']+primers[2*i]
else:
leftPrimer=primers[2*i]
if 'PRIMER_RIGHT_ADAPTER' in primerTags.keys():
rightPrimer=primerTags['PRIMER_RIGHT_ADAPTER']+primers[2*i+1]
else:
rightPrimer=primers[2*i+1]
leftHairpin=primer3.calcHairpin(leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
rightHairpin=primer3.calcHairpin(rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
leftHomodimer=primer3.calcHomodimer(leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
rightHomodimer=primer3.calcHomodimer(rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
heterodimer=primer3.calcHeterodimer(leftPrimer,rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
leftHairpinEnd3=calcThreeStrikeEndHairpin(leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'],
dna_conc=primerTags['PRIMER_DNA_CONC'])
rightHairpinEnd3=calcThreeStrikeEndHairpin(rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'],
dna_conc=primerTags['PRIMER_DNA_CONC'])
leftHomodimerEnd3=calcThreeStrikeEndDimer(leftPrimer,leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'])
rightHomodimerEnd3=calcThreeStrikeEndDimer(rightPrimer,rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'])
heterodimerEnd3=calcThreeStrikeEndDimer(leftPrimer,rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'])
if args.nucsForUridine:
uridinesCanBeInserted=checkPrimersForUridine(leftPrimer,rightPrimer,args)
else:
uridinesCanBeInserted=False
internalChecks=[primers[2*i][-5:].count('G')+primers[2*i][-5:].count('C')<minEndGC,
primers[2*i+1][-5:].count('G')+primers[2*i+1][-5:].count('C')<minEndGC,
leftHairpinEnd3<-2,
rightHairpinEnd3<-2,
leftHomodimer<args.minMultDimerdG2,
rightHomodimer<args.minMultDimerdG2,
heterodimer<args.minMultDimerdG2,
leftHomodimerEnd3<args.minMultDimerdG1,
rightHomodimerEnd3<args.minMultDimerdG1,
heterodimerEnd3<args.minMultDimerdG1,
uridinesCanBeInserted]
## if primers[2*i+1]=='TTGCACCTGTTTTGTTGTGTACAC':
## print(primers[2*i+1])
## print(internalChecks)
## print(rightHomodimerEnd3)
## print(rightHomodimer)
if True in internalChecks:
for k,check in enumerate(internalChecks):
if check:
out['INTERNAL_EXPLAIN'][k]+=1
break
primers.pop(2*i); primers.pop(2*i)
primersPoses.pop(2*i); primersPoses.pop(2*i)
primersTms.pop(2*i); primersTms.pop(2*i)
primersProductSizes.pop(i)
primersProductPenalty.pop(i)
numReturned-=1
else:
i+=1
elif (primerTags['PRIMER_PICK_LEFT_PRIMER']==1 and
out['PRIMER_LEFT_NUM_RETURNED']>0):
numReturned=out['PRIMER_LEFT_NUM_RETURNED']
minEndGC=primerTags['PRIMER_MIN_END_GC']
primers=[]
primersPoses=[]
primersTms=[]
primersProductSizes=[]
primersProductPenalty=[]
for i in range(numReturned):
primers.append(out['PRIMER_LEFT_'+str(i)+'_SEQUENCE'].upper())
primers.append('')
primersPoses.append(list(out['PRIMER_LEFT_'+str(i)]))
primersPoses.append([0,0])
primersTms.append(round(out['PRIMER_LEFT_'+str(i)+'_TM'],0))
primersTms.append(0)
primersProductSizes.append(0)
primersProductPenalty.append(out['PRIMER_LEFT_'+str(i)+'_PENALTY'])
i=0
while(i<int(len(primers)/2) and len(primers)>0):
if 'PRIMER_LEFT_ADAPTER' in primerTags.keys():
leftPrimer=primerTags['PRIMER_LEFT_ADAPTER']+primers[2*i]
else:
leftPrimer=primers[2*i]
leftEnd3_rc=str(Seq.Seq(primers[2*i][-4:]).reverse_complement())
leftHairpin=primer3.calcHairpin(leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
leftHomodimer=primer3.calcHomodimer(leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
leftHairpinEnd3=calcThreeStrikeEndHairpin(leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'],
dna_conc=primerTags['PRIMER_DNA_CONC'])
leftHomodimerEnd3=calcThreeStrikeEndDimer(leftPrimer,leftPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'])
if (primers[2*i][-5:].count('G')+primers[2*i][-5:].count('C')<minEndGC
or leftHairpinEnd3<-2
or leftHomodimer<args.minMultDimerdG2
or leftHomodimerEnd3<args.minMultDimerdG1):
primers.pop(2*i); primers.pop(2*i)
primersPoses.pop(2*i); primersPoses.pop(2*i)
primersTms.pop(2*i); primersTms.pop(2*i)
primersProductSizes.pop(i)
primersProductPenalty.pop(i)
numReturned-=1
else:
i+=1
elif (primerTags['PRIMER_PICK_RIGHT_PRIMER']==1 and
out['PRIMER_RIGHT_NUM_RETURNED']>0):
numReturned=out['PRIMER_RIGHT_NUM_RETURNED']
minEndGC=primerTags['PRIMER_MIN_END_GC']
primers=[]
primersPoses=[]
primersTms=[]
primersProductSizes=[]
primersProductPenalty=[]
for i in range(numReturned):
primers.append('')
primers.append(out['PRIMER_RIGHT_'+str(i)+'_SEQUENCE'].upper())
primersPoses.append([0,0])
primersPoses.append(list(out['PRIMER_RIGHT_'+str(i)]))
primersTms.append(0)
primersTms.append(round(out['PRIMER_RIGHT_'+str(i)+'_TM'],0))
primersProductSizes.append(0)
primersProductPenalty.append(out['PRIMER_RIGHT_'+str(i)+'_PENALTY'])
i=0
while(i<int(len(primers)/2) and len(primers)>0):
if 'PRIMER_RIGHT_ADAPTER' in primerTags.keys():
rightPrimer=primerTags['PRIMER_RIGHT_ADAPTER']+primers[2*i+1]
else:
rightPrimer=primers[2*i+1]
rightEnd3_rc=str(Seq.Seq(primers[2*i+1][-4:]).reverse_complement())
rightHairpin=primer3.calcHairpin(rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
rightHomodimer=primer3.calcHomodimer(rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC']).dg/1000
rightHairpinEnd3=calcThreeStrikeEndHairpin(rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'],
dna_conc=primerTags['PRIMER_DNA_CONC'])
rightHomodimerEnd3=calcThreeStrikeEndDimer(rightPrimer,rightPrimer,
mv_conc=primerTags['PRIMER_SALT_MONOVALENT'],
dv_conc=primerTags['PRIMER_SALT_DIVALENT'],
dna_conc=primerTags['PRIMER_DNA_CONC'],
dntp_conc=primerTags['PRIMER_DNTP_CONC'])
if (primers[2*i+1][-5:].count('G')+primers[2*i+1][-5:].count('C')<minEndGC
or rightHairpinEnd3<-2
or rightHomodimer<args.minMultDimerdG2
or rightHomodimerEnd3<args.minMultDimerdG1):
primers.pop(2*i); primers.pop(2*i)
primersPoses.pop(2*i); primersPoses.pop(2*i)
primersTms.pop(2*i); primersTms.pop(2*i)
primersProductSizes.pop(i)
primersProductPenalty.pop(i)
numReturned-=1
else:
i+=1
if numReturned==0:
# If there is some parameter that we haven't tried to set softer
if False in triedSofterParameters:
# Found this parameter
paramNum=triedSofterParameters.index(False)
if paramNum<=1:
curValue=primerTags[pParams[paramNum]]
newValue=min(5,curValue+1)
primerTags[pParams[paramNum]]=newValue
triedSofterParameters[paramNum]=True
continue
else:
pParamMin=pParams[paramNum]
pParamMax=pParams[paramNum].replace('MIN','MAX')
curValueMin=primerTags[pParamMin]
curValueMax=primerTags[pParamMax]
if paramNum==2:
newValueMin=max(0,curValueMin-5)
newValueMax=min(100,curValueMax+5)
elif paramNum==3:
newValueMin=max(15,curValueMin-1)
newValueMax=min(36,curValueMax+1)
elif paramNum==4:
newValueMin=max(40,curValueMin-1)
newValueMax=min(95,curValueMax+1)
primerTags[pParamMin]=newValueMin
primerTags[pParamMax]=newValueMax
triedSofterParameters[paramNum]=True
continue
elif seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST'][0][0]!=0:
seqTags['SEQUENCE_PRIMER_PAIR_OK_REGION_LIST'][0][0]=0
continue
else:
## print(primerTags)
## print(seqTags)
## print(sorted(seqTags.items()))
## print(out)
## input()
return(regionName,None,None,None,None,None,inputParams,out)
else:
return(regionName,primers,primersPoses,primersTms,primersProductSizes,primersProductPenalty,inputParams,out)
def checkPrimersForUridine(leftPrimer,rightPrimer,args,
returnPrimers=False):
# Returns True if uridines cannot be inserted
# Returns False if uridines can be inserted
# Check that T is in the last several nucleotides from the end
leftLastNucs=leftPrimer[-args.nucsForUridine:]
rightLastNucs=rightPrimer[-args.nucsForUridine:]
if ('T' not in leftLastNucs or
'T' not in rightLastNucs):
return(True)
# Get T position in the last nucleotides of left and right primers
leftPosT1=len(leftPrimer)-args.nucsForUridine+leftLastNucs.rfind('T')
rightPosT1=len(rightPrimer)-args.nucsForUridine+rightLastNucs.rfind('T')
# Check that 2nd T divides the left part of primer onto parts with equal Tm
leftLeftPrimerPart=leftPrimer[:leftPosT1]
rightLeftPrimerPart=rightPrimer[:rightPosT1]
# Check that the 2nd T is in the left part of primers
if ('T' not in leftLeftPrimerPart or
'T' not in rightLeftPrimerPart):
return(True)
# Go through all nucleotides and check if it is T and it divides to parts correctly
primerWithSuitableT=False
# Stores list of T positions to replace with U
leftPosesTvars=[]
for i,nuc in enumerate(leftLeftPrimerPart):
if nuc=='T':
# Get Tm of the left part of primer before uridine
tm=primer3.calcTm(leftLeftPrimerPart[:i],
mv_conc=args.mvConc,
dv_conc=args.dvConc,
dna_conc=args.primerConc,
dntp_conc=args.dntpConc)
if tm>args.maxPrimerPartByUridineTm:
continue
# Get Tm of the right part of primer before uridine
tm=primer3.calcTm(leftLeftPrimerPart[i+1:],
mv_conc=args.mvConc,
dv_conc=args.dvConc,
dna_conc=args.primerConc,
dntp_conc=args.dntpConc)
nuc2Num=None
if tm>args.maxPrimerPartByUridineTm:
# Trying to replace 3rd T to U
nuc2Num=i
for nuc2 in leftLeftPrimerPart[i+1:]:
nuc2Num+=1
if nuc2=='T':
# Get Tm of the left part of primer before uridine
tm=primer3.calcTm(leftLeftPrimerPart[i+1:nuc2Num],
mv_conc=args.mvConc,
dv_conc=args.dvConc,
dna_conc=args.primerConc,
dntp_conc=args.dntpConc)
if tm>args.maxPrimerPartByUridineTm:
continue
# Get Tm of the right part of primer before uridine
tm=primer3.calcTm(leftLeftPrimerPart[nuc2Num+1:],
mv_conc=args.mvConc,
dv_conc=args.dvConc,
dna_conc=args.primerConc,
dntp_conc=args.dntpConc)
if tm>args.maxPrimerPartByUridineTm:
continue
leftPosesTvars.append([i])
leftPosesTvars[-1].append(nuc2Num)
primerWithSuitableT=True
if returnPrimers==False:
break
else:
leftPosesTvars.append([i])
if nuc2Num!=None:
leftPosesTvars[-1].append(nuc2Num)
primerWithSuitableT=True
if returnPrimers==False:
break
if not primerWithSuitableT:
return(True)
# Go through all nucleotides and check if it is T and it divides part correctly
primerWithSuitableT=False
# Stores list of T positions to replace with U
rightPosesTvars=[]
for i,nuc in enumerate(rightLeftPrimerPart):
if nuc=='T':
# Get Tm of the left part of primer before uridine
tm=primer3.calcTm(rightLeftPrimerPart[:i],
mv_conc=args.mvConc,
dv_conc=args.dvConc,
dna_conc=args.primerConc,
dntp_conc=args.dntpConc)
if tm>args.maxPrimerPartByUridineTm:
continue
# Get Tm of the right part of primer before uridine
tm=primer3.calcTm(rightLeftPrimerPart[i+1:],