-
Notifications
You must be signed in to change notification settings - Fork 42
/
SSRidentificationPrimerDesignEpcrSummarizeAmplicon.py
executable file
·1328 lines (1163 loc) · 47.6 KB
/
SSRidentificationPrimerDesignEpcrSummarizeAmplicon.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 -*-
from __future__ import unicode_literals
from __future__ import division, with_statement
'''
Copyright 2017, 陈同 (chentong_biology@163.com).
===========================================================
'''
__author__ = 'chentong & ct586[9]'
__author_email__ = 'chentong_biology@163.com'
#=========================================================
desc = '''
Program description:
1. Identify SSRs of given sequences
2. Extract flanking sequences of identified SSRs
3. Design primers for each SSR regions
4. Check amplicon status of each primer
Program requirement:
1. MISA
2. primer3
3. eprimer32
4. primersearch
Fatsa seq:
>seq_id
ACGCTACGACCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCTGCAGAGAGTGAGATG
ACGCATTGAAAAAAAAAAAAAAAATTTTTTTTTTTTTTTTTTTTTTACGAAATAGGAA
SSR file (output by MISA)
ID SSR nr. SSR type SSR size start end
comp1_c0_seq1 1 p1 (A)15 15 495 509
comp16_c0_seq1 1 p2 (GA)11 22 1 22
comp16_c0_seq2 1 p2 (GA)11 22 1 22
comp18_c0_seq1 1 p1 (T)11 11 8 18
comp24_c0_seq1 1 p5 (TAGCC)5 25 558 582
'''
import sys
import os
import math
#import subprocess as sub
#from json import dumps as json_dumps
from time import localtime, strftime
timeformat = "%Y-%m-%d %H:%M:%S"
from optparse import OptionParser as OP
#from multiprocessing.dummy import Pool as ThreadPool
#from bs4 import BeautifulSoup
#reload(sys)
#sys.setdefaultencoding('utf8')
debug = 0
def outputMISA(misa="misa.pl"):
#if os.path.exists(misa):
# return
misa_fh = open(misa,'w')
print >>misa_fh, """#!/usr/bin/perl -w
# Author: Thomas Thiel
# Program name: misa.pl
###_______________________________________________________________________________
###
###Program name: misa.pl
###Author: Thomas Thiel
###Release date: 14/12/01 (version 1.0)
###
###_______________________________________________________________________________
###
## _______________________________________________________________________________
##
## DESCRIPTION: Tool for the identification and localization of
## (I) perfect microsatellites as well as
## (II) compound microsatellites (two individual microsatellites,
## disrupted by a certain number of bases)
##
## SYNTAX: misa.pl <FASTA file>
##
## <FASTAfile> Single file in FASTA format containing the sequence(s).
##
## In order to specify the search criteria, an additional file containing
## the microsatellite search parameters is required named "misa.ini", which
## has the following structure:
## (a) Following a text string beginning with 'def', pairs of numbers are
## expected, whereas the first number defines the unit size and the
## second number the lower threshold of repeats for that specific unit.
## (b) Following a text string beginning with 'int' a single number defines
## the maximal number of bases between two adjacent microsatellites in
## order to specify the compound microsatellite type.
## Example:
## definition(unit_size,min_repeats): 1-10 2-6 3-5 4-5 5-5 6-5
## interruptions(max_difference_for_2_SSRs): 100
##
## EXAMPLE: misa.pl seqs.fasta
##
## _______________________________________________________________________________
##
# Check for arguments. If none display syntax #
if (@ARGV == 0)
{
open (IN,"<$0");
while (<IN>) {if (/^\#\# (.*)/) {$message .= "$1\\n"}};
close (IN);
die $message;
};
# Check if help is required #
if ($ARGV[0] =~ /-help/i)
{
open (IN,"<$0");
while (<IN>) {if (/^\#\#\#(.*)/) {$message .= "$1\\n"}};
close (IN);
die $message;
};
# Open FASTA file #
open (IN,"<$ARGV[0]") || die ("\\nError: FASTA file doesn't exist !\\n\\n");
open (OUT,">$ARGV[0].misa");
print OUT "ID\\tSSR nr.\\tSSR type\\tSSR\\tsize\\tstart\\tend\\n";
# Reading arguments #
open (SPECS,"misa.ini") || die ("\\nError: Specifications file doesn't exist !\\n\\n");
my %typrep;
my $amb = 0;
while (<SPECS>)
{
%typrep = $1 =~ /(\d+)/gi if (/^def\S*\s+(.*)/i);
if (/^int\S*\s+(\d+)/i) {$amb = $1}
};
my @typ = sort { $a <=> $b } keys %typrep;
# CORE
$/ = ">";
my $max_repeats = 1; #count repeats
my $min_repeats = 1000; #count repeats
my (%count_motif,%count_class); #count
my ($number_sequences,$size_sequences,%ssr_containing_seqs); #stores number and size of all sequences examined
my $ssr_in_compound = 0;
my ($id,$seq);
while (<IN>)
{
next unless (($id,$seq) = /(.*?)\\n(.*)/s);
my ($nr,%start,@order,%end,%motif,%repeats); # store info of all SSRs from each sequence
$seq =~ s/[\d\s>]//g; #remove digits, spaces, line breaks,...
$id =~ s/^\s*//g; $id =~ s/\s*$//g;$id =~ s/\s/_/g; #replace whitespace with "_"
$number_sequences++;
$size_sequences += length $seq;
for ($i=0; $i < scalar(@typ); $i++) #check each motif class
{
my $motiflen = $typ[$i];
my $minreps = $typrep{$typ[$i]} - 1;
if ($min_repeats > $typrep{$typ[$i]}) {$min_repeats = $typrep{$typ[$i]}}; #count repeats
my $search = "(([acgt]{$motiflen})\\\\2{$minreps,})";
while ( $seq =~ /$search/ig ) #scan whole sequence for that class
{
my $motif = uc $2;
my $redundant; #reject false type motifs [e.g. (TT)6 or (ACAC)5]
for ($j = $motiflen - 1; $j > 0; $j--)
{
my $redmotif = "([ACGT]{$j})\\\\1{".($motiflen/$j-1)."}";
$redundant = 1 if ( $motif =~ /$redmotif/ )
};
next if $redundant;
$motif{++$nr} = $motif;
my $ssr = uc $1;
$repeats{$nr} = length($ssr) / $motiflen;
$end{$nr} = pos($seq);
$start{$nr} = $end{$nr} - length($ssr) + 1;
# count repeats
$count_motifs{$motif{$nr}}++; #counts occurrence of individual motifs
$motif{$nr}->{$repeats{$nr}}++; #counts occurrence of specific SSR in its appearing repeat
$count_class{$typ[$i]}++; #counts occurrence in each motif class
if ($max_repeats < $repeats{$nr}) {$max_repeats = $repeats{$nr}};
};
};
next if (!$nr); #no SSRs
$ssr_containing_seqs{$nr}++;
@order = sort { $start{$a} <=> $start{$b} } keys %start; #put SSRs in right order
$i = 0;
my $count_seq; #counts
my ($start,$end,$ssrseq,$ssrtype,$size);
while ($i < $nr)
{
my $space = $amb + 1;
if (!$order[$i+1]) #last or only SSR
{
$count_seq++;
my $motiflen = length ($motif{$order[$i]});
$ssrtype = "p".$motiflen;
$ssrseq = "($motif{$order[$i]})$repeats{$order[$i]}";
$start = $start{$order[$i]}; $end = $end{$order[$i++]};
next
};
if (($start{$order[$i+1]} - $end{$order[$i]}) > $space)
{
$count_seq++;
my $motiflen = length ($motif{$order[$i]});
$ssrtype = "p".$motiflen;
$ssrseq = "($motif{$order[$i]})$repeats{$order[$i]}";
$start = $start{$order[$i]}; $end = $end{$order[$i++]};
next
};
my ($interssr);
if (($start{$order[$i+1]} - $end{$order[$i]}) < 1)
{
$count_seq++; $ssr_in_compound++;
$ssrtype = 'c*';
$ssrseq = "($motif{$order[$i]})$repeats{$order[$i]}($motif{$order[$i+1]})$repeats{$order[$i+1]}*";
$start = $start{$order[$i]}; $end = $end{$order[$i+1]}
}
else
{
$count_seq++; $ssr_in_compound++;
$interssr = lc substr($seq,$end{$order[$i]},($start{$order[$i+1]} - $end{$order[$i]}) - 1);
$ssrtype = 'c';
$ssrseq = "($motif{$order[$i]})$repeats{$order[$i]}$interssr($motif{$order[$i+1]})$repeats{$order[$i+1]}";
$start = $start{$order[$i]}; $end = $end{$order[$i+1]};
#$space -= length $interssr
};
while ($order[++$i + 1] and (($start{$order[$i+1]} - $end{$order[$i]}) <= $space))
{
if (($start{$order[$i+1]} - $end{$order[$i]}) < 1)
{
$ssr_in_compound++;
$ssrseq .= "($motif{$order[$i+1]})$repeats{$order[$i+1]}*";
$ssrtype = 'c*';
$end = $end{$order[$i+1]}
}
else
{
$ssr_in_compound++;
$interssr = lc substr($seq,$end{$order[$i]},($start{$order[$i+1]} - $end{$order[$i]}) - 1);
$ssrseq .= "$interssr($motif{$order[$i+1]})$repeats{$order[$i+1]}";
$end = $end{$order[$i+1]};
#$space -= length $interssr
}
};
$i++;
}
continue
{
print OUT "$id\\t$count_seq\\t$ssrtype\\t$ssrseq\\t",($end - $start + 1),"\\t$start\\t$end\\n"
};
};
close (OUT);
open (OUT,">$ARGV[0].statistics");
# INFO
# Specifications
print OUT "Specifications\\n==============\\n\\nSequence source file: \\"$ARGV[0]\\"\\n\\nDefinement of microsatellites (unit size / minimum number of repeats):\\n";
for ($i = 0; $i < scalar (@typ); $i++) {print OUT "($typ[$i]/$typrep{$typ[$i]}) "};print OUT "\\n";
if ($amb > 0) {print OUT "\\nMaximal number of bases interrupting 2 SSRs in a compound microsatellite: $amb\\n"};
print OUT "\\n\\n\\n";
# OCCURRENCE OF SSRs
#small calculations
my @ssr_containing_seqs = values %ssr_containing_seqs;
my $ssr_containing_seqs = 0;
for ($i = 0; $i < scalar (@ssr_containing_seqs); $i++) {$ssr_containing_seqs += $ssr_containing_seqs[$i]};
my @count_motifs = sort {length ($a) <=> length ($b) || $a cmp $b } keys %count_motifs;
my @count_class = sort { $a <=> $b } keys %count_class;
for ($i = 0; $i < scalar (@count_class); $i++) {$total += $count_class{$count_class[$i]}};
# Overview
print OUT "RESULTS OF MICROSATELLITE SEARCH\\n================================\\n\\n";
print OUT "Total number of sequences examined: $number_sequences\\n";
print OUT "Total size of examined sequences (bp): $size_sequences\\n";
print OUT "Total number of identified SSRs: $total\\n";
print OUT "Number of SSR containing sequences: $ssr_containing_seqs\\n";
print OUT "Number of sequences containing more than 1 SSR: ",$ssr_containing_seqs - ($ssr_containing_seqs{1} || 0),"\\n";
print OUT "Number of SSRs present in compound formation: $ssr_in_compound\\n\\n\\n";
# Frequency of SSR classes
print OUT "Distribution to different repeat type classes\\n---------------------------------------------\\n\\n";
print OUT "Unit size\\tNumber of SSRs\\n";
my $total = undef;
for ($i = 0; $i < scalar (@count_class); $i++) {print OUT "$count_class[$i]\\t$count_class{$count_class[$i]}\\n"};
print OUT "\\n";
# Frequency of SSRs: per motif and number of repeats
print OUT "Frequency of identified SSR motifs\\n----------------------------------\\n\\nRepeats";
for ($i = $min_repeats;$i <= $max_repeats; $i++) {print OUT "\\t$i"};
print OUT "\\ttotal\\n";
for ($i = 0; $i < scalar (@count_motifs); $i++)
{
my $typ = length ($count_motifs[$i]);
print OUT $count_motifs[$i];
for ($j = $min_repeats; $j <= $max_repeats; $j++)
{
if ($j < $typrep{$typ}) {print OUT "\\t-";next};
if ($count_motifs[$i]->{$j}) {print OUT "\\t$count_motifs[$i]->{$j}"} else {print OUT "\\t"};
};
print OUT "\\t$count_motifs{$count_motifs[$i]}\\n";
};
print OUT "\\n";
# Frequency of SSRs: summarizing redundant and reverse motifs
# Eliminates %count_motifs !
print OUT "Frequency of classified repeat types (considering sequence complementary)\\n-------------------------------------------------------------------------\\n\\nRepeats";
my (%red_rev,@red_rev); # groups
for ($i = 0; $i < scalar (@count_motifs); $i++)
{
next if ($count_motifs{$count_motifs[$i]} eq 'X');
my (%group,@group,$red_rev); # store redundant/reverse motifs
my $reverse_motif = $actual_motif = $actual_motif_a = $count_motifs[$i];
$reverse_motif =~ tr/ACGT/TGCA/;
$reverse_motif = reverse $reverse_motif;
my $reverse_motif_a = $reverse_motif;
for ($j = 0; $j < length ($count_motifs[$i]); $j++)
{
if ($count_motifs{$actual_motif}) {$group{$actual_motif} = "1"; $count_motifs{$actual_motif}='X'};
if ($count_motifs{$reverse_motif}) {$group{$reverse_motif} = "1"; $count_motifs{$reverse_motif}='X'};
$actual_motif =~ s/(.)(.*)/$2$1/;
$reverse_motif =~ s/(.)(.*)/$2$1/;
$actual_motif_a = $actual_motif if ($actual_motif lt $actual_motif_a);
$reverse_motif_a = $reverse_motif if ($reverse_motif lt $reverse_motif_a)
};
if ($actual_motif_a lt $reverse_motif_a) {$red_rev = "$actual_motif_a/$reverse_motif_a"}
else {$red_rev = "$reverse_motif_a/$actual_motif_a"}; # group name
$red_rev{$red_rev}++;
@group = keys %group;
for ($j = 0; $j < scalar (@group); $j++)
{
for ($k = $min_repeats; $k <= $max_repeats; $k++)
{
if ($group[$j]->{$k}) {$red_rev->{"total"} += $group[$j]->{$k};$red_rev->{$k} += $group[$j]->{$k}}
}
}
};
for ($i = $min_repeats; $i <= $max_repeats; $i++) {print OUT "\\t$i"};
print OUT "\\ttotal\\n";
@red_rev = sort {length ($a) <=> length ($b) || $a cmp $b } keys %red_rev;
for ($i = 0; $i < scalar (@red_rev); $i++)
{
my $typ = (length ($red_rev[$i])-1)/2;
print OUT $red_rev[$i];
for ($j = $min_repeats; $j <= $max_repeats; $j++)
{
if ($j < $typrep{$typ}) {print OUT "\\t-";next};
if ($red_rev[$i]->{$j}) {print OUT "\\t",$red_rev[$i]->{$j}}
else {print OUT "\\t"}
};
print OUT "\\t",$red_rev[$i]->{"total"},"\\n";
};
"""
misa_fh.close()
#----outputMISA---------------------------------------------------------------------
def output_misa_ini(misa_ini="misa.ini"):
#if os.path.exists(misa_ini):
# return
misa_ini_fh = open(misa_ini,'w')
print >>misa_ini_fh, """definition(unit_size,min_repeats): 1-10 2-6 3-5 4-5 5-5 6-5
interruptions(max_difference_between_2_SSRs): 0"""
misa_ini_fh.close()
#--------------END of output_misa_ini------------------
def fprint(content):
"""
This is a Google style docs.
Args:
param1(str): this is the first param
param2(int, optional): this is a second param
Returns:
bool: This is a description of what is returned
Raises:
KeyError: raises an exception))
"""
print json_dumps(content,indent=1)
#-------------------------------------------------------
def cmdparameter(argv):
if len(argv) == 1:
global desc
print >>sys.stderr, desc
cmd = 'python ' + argv[0] + ' -h'
os.system(cmd)
sys.exit(1)
usages = "%prog -i file"
parser = OP(usage=usages)
parser.add_option("-i", "--input-file", dest="filein",
metavar="FILEIN", help="FASTA file used for SSR identification. Blanks in FASTA id will be transferred into '_'.")
parser.add_option("-d", "--databse-file", dest="database",
help="FASTA file containing multiple speceis info")
parser.add_option("-s", "--ssr-file", dest="ssr",
help="Optional. SSR file generated by misa.pl. If not given, SSR will be first identified.")
parser.add_option("-S", "--amplicon-size", dest="amplicon_size",
default = "200,100,280",
help="Amplicon size. Default <200,100,280> represents <optampliconsize,minampliconsize,maxampliconsize>. It will affect both SSR region extracttion and primer design.")
parser.add_option("-f", "--flank", dest="flank",
default = "13,250",
help="Length of flank regions to be extracted along each SSR. Default <13,250> meaning at least 13 nt and at most 250 nt will be extracted.")
parser.add_option("-P", "--primer-size", dest="primer_size",
default = "20,15,25",
help="Default <20,15,25> represents <optsize,minsize,maxsize> respectively")
parser.add_option("-T", "--tm", dest="primer_tm",
default = "50,45,55",
help="Default <50,45,55> represents <opttm,mintm,maxtm> respectively")
parser.add_option("-p", "--output-prefix", dest="op",
help="Output prefix. Optional")
parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", help="Show process information")
parser.add_option("-D", "--debug", dest="debug",
default=False, action="store_true", help="Debug the program")
(options, args) = parser.parse_args(argv[1:])
assert options.filein != None, "A filename needed for -i"
return (options, args)
#--------------------------------------------------------------------
def readmisaSSR(misa_ssr):
"""
ssrDict = {'scaffold':
[
{
ssr_type: "p1",
ssr: "(A)15",
size: 15,
start: 495,
end: 509
},
{
ssr_type: "p1",
ssr: "(A)15",
size: 15,
start: 495,
end: 509
},
]
}
"""
header = 1
ssrDict = {}
for line in open(misa_ssr):
if header:
header -= 1
continue
#-------------------
lineL = line.split('\t')
seqId = lineL[0]
ssr_type = lineL[2]
ssr = lineL[3]
size = int(lineL[4])
# Original: 1 -start, both included
# Transfer to : 0-start, start but not end included
start = int(lineL[5]) - 1
end = int(lineL[6])
if seqId not in ssrDict:
ssrDict[seqId] = []
subD = {}
subD["ssr_type"] = ssr_type
subD["ssr"] = ssr
subD["size"] = size
subD["start"] = start
subD["end"] = end
ssrDict[seqId].append(subD)
#--------------------------------
return ssrDict
#-------------END readmisaSSR--------------
#"""
# amplicon size between 100
# and 280 bp; minimum, optimum, and maximum annealing
# temperature (TM) of 45, 50, and 55, respectively, minimum,
# optimum, and maximum primer size of 15, 20, and 25 bp,
# respectively.
#"""
def extractSeq(output_seqfh,key,seq,ssrL,flankMin,flankMax, am_size_min, am_size_max):
"""
ssrL =
[
{
ssr_type: "p1",
ssr: "(A)15",
size: 15,
start: 495,
end: 509
},
{
ssr_type: "p1",
ssr: "(A)15",
size: 15,
start: 495,
end: 509
},
]
"""
len_seq = len(seq)
for ssrDsub in ssrL:
start = ssrDsub['start']
end = ssrDsub['end']
ssr_type = ssrDsub['ssr_type']
ssr = ssrDsub['ssr']
size = ssrDsub['size']
# Deplete very short sequences
if len_seq < am_size_min:
continue
# Delete too small upstream and down stream sequences
if start < flankMin or end + flankMin > len_seq:
continue
# Re-asign length
up_potential = start
end_potential = len_seq - end
half_am_size_max = am_size_max/2
if up_potential >= half_am_size_max and end_potential >=half_am_size_max:
flank_max = half_am_size_max
elif up_potential <= half_am_size_max and end_potential >= half_am_size_max:
flank_max = am_size_max - up_potential
elif up_potential >= half_am_size_max and end_potential <= half_am_size_max:
flank_max = am_size_max - end_potential
#--------------------------------------
ssr_seq = seq[start:end].lower()
up_start = start - flankMax
if up_start < 0:
up_start = 0
up_end = start
#print >>sys.stderr, up_start,up_end
ssr_up_seq = seq[up_start:up_end]
dw_start = end
dw_end = dw_start + flankMax
if dw_end > len_seq:
dw_end = len_seq
ssr_dw_seq = seq[dw_start:dw_end]
#-----------------------------------
print >>output_seqfh, ">{} {} {}".format(key, up_end-up_start-1,dw_start-up_start+1)
#print seq
#print "#"
#print ssr_up_seq
#print "##"
#print ssr_seq
#print "###"
#print ssr_dw_seq
print >>output_seqfh, ''.join([ssr_up_seq, ssr_seq, ssr_dw_seq])
#-----------extractSeq--------------------
def extractFlankSeq(file, output_seqFile, ssrDict, flankMin, flankMax, am_size_min, am_size_max):
"""
ssrDict = {'scaffold':
[
{
ssr_type: "p1",
ssr: "(A)15",
size: 15,
start: 495,
end: 509
},
{
ssr_type: "p1",
ssr: "(A)15",
size: 15,
start: 495,
end: 509
},
]
}
"""
output_seqfh = open(output_seqFile, 'w')
seqL = []
for line in open(file):
line = line.strip()
if line[0]== '>':
if seqL:
seq = ''.join(seqL)
ssrL = ssrDict.get(key,[])
if not ssrL:
key2 = key.replace(' ','_')
ssrL = ssrDict.get(key2,[])
if ssrL:
extractSeq(output_seqfh,key,seq,ssrL,flankMin,flankMax, am_size_min, am_size_max)
key = line[1:]
seqL = []
else:
seqL.append(line)
#--------------------------------------
#-------------------------------------
if seqL:
seq = ''.join(seqL)
ssrL = ssrDict.get(key,[])
if not ssrL:
key2 = key.replace(' ','_')
ssrL = ssrDict.get(key2,[])
if ssrL:
extractSeq(output_seqfh, key,seq,ssrL,flankMin,flankMax, am_size_min, am_size_max)
#---------------------------------------
output_seqfh.close()
#-------------------------------------------------------
def transferPrimer3OutputToPrimersearchInput(primer3, primersearch_fh):
fh = open(primer3)
#fh_out = open(primersearch,'w')
line = fh.readline()
line = fh.readline()
assert line.find("EPRIMER32 RESULTS FOR") != -1, "Wrong format" + primer3
seq_name = line.strip()[24:]
#primerL = []
count = 1
for line in fh:
if line.find("FORWARD PRIMER") != -1:
forward = line.strip().split()[-1]
if line.find("REVERSE PRIMER") != -1:
reverse = line.strip().split()[-1]
#tmpL = [seq_name+'@'+str(count), forward, reverse]
print >>primersearch_fh, "{}@{}\t{}\t{}".format(seq_name,count,forward, reverse)
#primerL.add(tmpL)
count += 1
#------------------------------------------
fh.close()
#fh_out.close()
#---------------------------------------------------
def deisgnPrimerForEachSeq(output_seq, primersearch_fh, optsize, minsize, maxsize, opttm, mintm, maxtm, am_size_opt, am_size_min, am_size_max):
"""
Single line FASTA file
"""
count = 1
for line in open(output_seq):
if line[0] == '>':
id,start,end = line.strip().split(' ')
fileid = str(count)
count += 1
else:
output_file = output_seq + fileid + '.fa'
output_file_fh = open(output_file, 'w')
print >>output_file_fh, "{}\n{}".format(id, line.strip())
output_file_fh.close()
cmd = ["eprimer32 -sequence", output_file, '-outfile', output_file+'.primer',
"-targetregion", start+','+end, '-optsize', optsize, "-numreturn 3",
'-minsize', minsize, '-maxsize', maxsize, "-opttm", opttm, "-mintm", mintm, "-maxtm", maxtm,
"-psizeopt", str(am_size_opt), "-prange", str(am_size_min)+'-'+str(am_size_max),
'-die -auto']
cmd = ' '.join(cmd)
#print >>sys.stderr, cmd
#p = sub.Popen(cmd, stdout=sub.PIPE,stderr=sub.PIPE)
#output, errors = p.communicate()
#print >>sys.stderr,output
#print >>sys.stderr,errors
#os.system("pwd")
if os.system(cmd):
print >>sys.stderr, cmd + ' Wrong'
sys.exit(1)
#--------------------------------------------------
transferPrimer3OutputToPrimersearchInput(output_file+'.primer', primersearch_fh)
#-------------END for-----------------------------
#-----------------------------------------------------
def readInPrimerSearch(file, primerDict, species=''):
'''
Primer name SRR037890___comp24_c0_seq1@1
Amplimer 1
Sequence: SRR037890___comp24_c0_seq1
TATTTTCCTATGTTGCTACC hits forward strand at 433 with 0 mismatches
ACTATTAGCTGTAAAGCAAA hits reverse strand at [23] with 0 mismatches
Amplimer length: 200 bp
primerDict = {
primerName : {
# Record amplicon info
# amplicon_start, amplicon_end: 0-started, second excluded
'species': [
[targetseq1, AmpliconSize, (amplicon_start, amplicon_end), (forward_mismatch, reverse_mismatch)]
[targetseq2, AmpliconSize, (amplicon_start, amplicon_end), (forward_mismatch, reverse_mismatch)]
],
# Summary amplicon info
# Compute number of amplicons for each size of each species
'sta':{
species1: {
200: 1,
300, 1
},
species2: {
200: 2,
300, 1
}
}
}
}
'''
seqD = {}
for line in open(file):
if line.find("Primer name") == 0:
primer_name = line[12:-1]
if primer_name not in primerDict:
primerDict[primer_name] = {}
primerDict[primer_name]['sta'] = {}
elif line.find("Sequence:") != -1:
targetSeq = line.strip().split()[1]
seqD[targetSeq] = 1
if not species:
species = targetSeq.split('___')[0]
seq_name = targetSeq
if species not in primerDict[primer_name]:
primerDict[primer_name][species] =[]
primerDict[primer_name]['sta'][species] ={}
elif line.find("hits forward strand at") != -1:
lineL = line.strip().split()
forward_mismatch = int(lineL[-2])
amplicon_start = int(lineL[-4])-1
elif line.find("hits reverse strand at") != -1:
lineL = line.strip().split()
reverse_mismatch = int(lineL[-2])
amplicon_end = (-1) * int(lineL[-4][1:-1])+1
elif line.find("Amplimer length") != -1:
ampliconSize = int(line.strip().split()[2])
primerDict[primer_name][species].append([seq_name, ampliconSize, (amplicon_start, amplicon_end), (forward_mismatch, reverse_mismatch)])
primerDict[primer_name]['sta'][species][ampliconSize] = primerDict[primer_name]['sta'][species].get(ampliconSize,0)+1
#----------------------------------------------------------
#print >>sys.stderr,primerDict
#------------------END for---------------------
return seqD
#-------------------------------------------------------
def gamma(x, t, k=2):
b = 1.0 / t
x = x * k
c = 0.0
for i in range(0, k):
c += (math.exp(-b * x) * (b * x) ** i) / math.factorial(i)
return c
#-------END gamma-------------------
def readInGelFile(file):
'''
Molecular weight or amplicon size
SIZE samp1 samp2 samp3 samp4
size1 0 0 0 0
size2 200 0 0 0
size3 200 200 0 200
size4 0 0 200 0
'''
header = 1
aDict = {}
for line in open(file):
if header:
sampleL = line.split()
for sample in sampleL[1:]:
aDict[sample] = []
header -= 1
continue
#_-----------------------
lineL = line.split()
key = float(lineL[0])
for sample, concentration in zip(sampleL[1:], lineL[1:]):
concentration = int(concentration)
if concentration:
aDict[sample].append([key,concentration])
#----------------------------------------------
return aDict,sampleL[1:]
#----------------------------
def plot(band_matrix, xpositionS, xvalueS, markerPositionS, markerSizeS):
output = band_matrix + '.r'
output_fh = open(output, 'w')
print >>output_fh, """
usePackage <- function(p) {{
if (!is.element(p, installed.packages()[,1]))
install.packages(p, dep = TRUE)
require(p, character.only = TRUE)
}}
usePackage("ggplot2")
usePackage("reshape2")
data <- read.table(file="{file}", sep="\t", header=T, row.names=1,
check.names=F, quote="")
data$id <- rownames(data)
idlevel <- as.vector(rownames(data))
idlevel <- rev(idlevel)
data.m <- melt(data, c("id"))
data.m$id <- factor(data.m$id, levels=idlevel, ordered=T)
p <- ggplot(data=data.m, aes(x=variable, y=id)) + geom_tile(aes(fill=value))
midpoint = 0
p <- p + scale_fill_gradient2(low="black", mid="grey",
high="white", midpoint=midpoint, name=" ",
na.value="grey")
p <- p + theme(axis.ticks=element_blank()) + theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), panel.border = element_blank()) + xlab("") +
ylab("") + labs(title="")
p <- p + theme(axis.text.x=element_text(angle=45,hjust=0, vjust=0))
none='none'
legend_pos_par <- none
p <- p + theme(legend.position=legend_pos_par)
xtics_pos <- {xpositionS}
xtics_value <- {xvalueS}
p <- p + scale_x_discrete(breaks=xtics_pos, labels=xtics_value, position="top")
ytics_pos <- {markerPositionS}
ytics_value <- {markerSizeS}
p <- p + scale_y_discrete(breaks=ytics_pos, labels=ytics_value, position="right")
p <- p + theme(text=element_text(size=14))
ggsave(p, filename="{file}.png", dpi=300, width=10, height=20, units=c("cm"))
""".format(file=band_matrix, xvalueS=xvalueS, xpositionS=xpositionS, markerSizeS=markerSizeS,
markerPositionS=markerPositionS)
output_fh.close()
if os.system("Rscript "+output):
print >>sys.stderr, "Wrong in running plot"
#----------------------plot----------------------------------------------
def gel_main(file, gel_concentration=2, voltage=20, time=40):
'''
gel_concentration: Default <2> represents 2%
voltage: 20 v
time: 40 minutes
'''
optimum_DNA_length = 2000 / gel_concentration ** 3
sampleD, nameL = readInGelFile(file)
# Add ladder
nameL.append("Markers")
sampleD["Markers"] = [(50,200), (100,200),(150,200),(200,200),(250,200),(300,200),(350,200),(400,200),(500,200),(1000,200)]
len_sampleD = len(sampleD)
# Number of lanes
lane_count = len_sampleD
# Width and height of dingle lane
lane_width = 30
lane_height = 3
# Intervals between neighboring lanes
lane_interval = 6
gel_border = 12
gel_width = 2 * gel_border + lane_count * lane_width + (lane_count-1) * lane_interval
#gel_height = gel_width
# Generate empty lanes
# Every 1 unit from up_border to all height
strandD = {}
# Loading samples
# position: represents start position, loaing hole
for name in nameL:
strandD[name] = []
dnaL = sampleD[name]
for dna in dnaL:
band = {"size": float(dna[0]), 'conc': dna[1]*1.0/lane_height, 'position': gel_border+5}
strandD[name].append(band)
# Run
# Move loaded DNA down the gel at a rate dependent on voltage, DNA length and agarose concentration.
time = time
voltage = voltage
max_dist = 0.25 * time * voltage
maxposition = 0
for name in nameL:
for bandD in strandD[name]:
g = gamma(bandD['size']/20, int(optimum_DNA_length/20))
bandD['position'] += max_dist * g
if maxposition < bandD['position']:
maxposition = bandD['position']
#print >>sys.stderr, bandD
#-----------------------------------------------------
maxposition = int(maxposition+gel_border+1)
# Determines where in the concentration of DNA in every part of the gel
# Generate an empty lane, O represents no band
markerSize = [str(int(bandD["size"])) for bandD in strandD["Markers"]]
markerSize.reverse()
markerSizeS = "c("+','.join(["'"+i+"'" for i in markerSize])+ ")"
markerPosition = ['CT'+str(int(bandD["position"]+0.5)) for bandD in strandD["Markers"]]
markerPosition.reverse()
markerPositionS = "c("+','.join(["'"+i+"'" for i in markerPosition])+ ")"
#print >>sys.stderr, markerSizeS
#print >>sys.stderr, markerPositionS
#laneL = [[-1 for j in range(maxposition)] for i in range(len_sampleD)]
laneL = []
for i in range(len_sampleD):
tmpL = [-1000 for j in range(maxposition)]
tmpL[gel_border] = -10
tmpL[gel_border-1] = 0
tmpL[gel_border-2] = -10
laneL.append(tmpL)
#-------------------------------------
band_count = maxposition
for i in range(len_sampleD):
name = nameL[i]
for bandD in strandD[name]:
for y in range(lane_height-2):
pos = int(bandD['position'])+y
if pos < band_count - 4:
laneL[i][pos-1] += 0.12 * bandD['conc'] * bandD['size']
laneL[i][pos] += 0.2 * bandD['conc'] * bandD['size']
laneL[i][pos+1] += 0.12 * bandD['conc'] * bandD['size']
#-----Blur edges-----------------------------
#---------------------------
#_--------------------------
#-------------------------------
max_value = max([max(i) for i in laneL])
min_value = -1 * max_value
for i in range(len_sampleD):
for j in range(maxposition):
if laneL[i][j] == -1000:
laneL[i][j] = min_value
#print laneL
# Expose
# print "ID\t{}".format("\t".join(nameL))
newCol = len(nameL) * 8 + 2
xposition = ['ct'+str(i) for i in range(3, newCol,8)]
xpositionS = "c("+','.join(["'"+i+"'" for i in xposition])+ ")"
xvalueS = "c("+','.join(["'"+i+"'" for i in nameL])+ ")"
#print >>sys.stderr, xpositionS
#print >>sys.stderr, '\t'.join(nameL)
# Plot data
band_matrix = file + '.virtualGel.data'
band_matrix_fh = open(band_matrix, 'w')
print >>band_matrix_fh, "ID\t{}".format('\t'.join(['ct'+str(i) for i in range(newCol)]))
for i in range(maxposition):
tmpL = ["CT"+str(i)]
tmpL.append(str(min_value))
tmpL.append(str(min_value))
for lane in laneL:
# Blur edges, 6 main lane, two margin lane
if lane[i] > 0:
tmpL.append(str(0.8*lane[i]))
tmpL.append(str(0.9*lane[i]))
else:
tmpL.append(str(lane[i]))
tmpL.append(str(lane[i]))
tmpL.append(str(lane[i]))
tmpL.append(str(lane[i]))