-
Notifications
You must be signed in to change notification settings - Fork 1
/
msatfinder
executable file
·2670 lines (2470 loc) · 81.5 KB
/
msatfinder
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/perl
# Copyright 2005 Milo Thurston ([email protected]) and Dawn Field ([email protected])
######################################################
# A reasonably simple application to search for all #
# mono-hexanucleotide repeats in Genbank or #
# fasta formatted files, and provide detailed output #
######################################################
#############################################################################
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
#############################################################################
use strict;
use CGI;
use Cwd;
use Bio::Location::Split;
use Bio::SeqIO;
use Config::Simple;
use File::Copy;
use Getopt::Std;
use List::Util qw(min max);
use Term::ReadLine;
my $version = "2.0.9";
#####################
# usage information #
#####################
my $usage="
Usage:
msatfinder [options] files
msatfinder -b *.gbk
msatfinder -b -l examples.list
Options:
-b backup your old data directories (adds date & time suffix)
-d delete most recent data directories, don't search for microsatellites
-e <1-3> engine to use - see the manual (default 1)
-f set flank size, overriding config file (default 300)
-h list these options
-i check for interrupted msats (not checked by default)
-l <list_file> read a list of genomes from a text file
-s silence most output to screen (overrides config file)
-x delete all data directories, don't search for microsatellites
By default, msatfinder will take the list of files given on the command
line as the files to read. Instead you may use the -l option, and tell
it to read a list of the genomes you would like to be processed.
Use options \"-d\" and \"-x\" with caution.
";
################
# idendify cwd #
################
my $cwd = getcwd;
#######################
# date related things #
#######################
my $date = `date`;
chomp($date);
my %dtrans = ( "JAN" => "01",
"FEB" => "02",
"MAR" => "03",
"APR" => "04",
"MAY" => "05",
"JUN" => "06",
"JUL" => "07",
"AUG" => "08",
"SEP" => "09",
"OCT" => "10",
"NOV" => "11",
"DEC" => "12" );
my $datestring = `date +%j%H%M%S`;
chomp($datestring);
####################################
# import settings from config file #
####################################
my $config = &getconfig($cwd,@ARGV);
############################
# various global variables #
############################
my $override = $config->{'FINDER.override'};
my $artemis = $config->{'FINDER.artemis'};
my $mine = $config->{'FINDER.mine'};
my $fastafile = $config->{'FINDER.fastafile'};
my $sumswitch = $config->{'FINDER.sumswitch'};
my $screendump = $config->{'FINDER.screendump'};
my $run_eprimer = $config->{'DEPENDENCIES.run_eprimer'};
my $eprimer_args = $config->{'DEPENDENCIES.eprimer_args'};
my $debug = $config->{'COMMON.debug'};
my $flank_size = $config->{'COMMON.flank_size'};
my $remote_link = $config->{'FINDER.remote_link'};
my $primer3core = $config->{'DEPENDENCIES.primer3core'};
my $eprimer = $config->{'DEPENDENCIES.eprimer'};
my $dbname = $config->{'VIEWER.dbname'};
my $dbtype = $config->{'VIEWER.dbtype'};
my $dbusername = $config->{'VIEWER.gdbusername'};
my $dbusername2 = $config->{'VIEWER.sdbusername'};
my $cgiloc = $config->{'VIEWER.cgiloc'};
my $msatview = $config->{'VIEWER.msatview'};
my $run_mview = $config->{'ALIGNER.run_mview'};
my $printerror = 0; # note if an error must be printed to the error file
my $runird = 0;
########################################
# subdirectories created by msatfinder #
########################################
my $mine_dir = $config->{'COMMON.mine_dir'};
my $repeat_dir = $config->{'COMMON.repeat_dir'};
my $tab_dir = $config->{'COMMON.tab_dir'};
my $bigtab_dir = $config->{'COMMON.bigtab_dir'};
my $fasta_dir = $config->{'COMMON.fasta_dir'};
my $prime_dir = $config->{'COMMON.prime_dir'};
my $count_dir = $config->{'COMMON.count_dir'};
my @newdirs = ($mine_dir,$repeat_dir,$tab_dir,$bigtab_dir,$fasta_dir,$prime_dir,$count_dir);
##############################################
# determine which options have been selected #
##############################################
my %opts=();
getopts('abcdxhilt:e:f:m:s',\%opts);
# print help message
if (defined $opts{h})
{
print $usage;
exit;
}
if (defined $opts{s})
{
$screendump = 0;
}
# delete files
if (defined $opts{d})
{
print "Deleting existing data.\n";
foreach my $dir (@newdirs)
{
$dir =~ s/\///;
system("rm -rf $dir") == 0 or warn "Having trouble deleting directory $dir, $!";
}
print "Exiting.\n";
exit;
}
# delete ALL files
if (defined $opts{x})
{
print "Deleting ALL old data.\n";
foreach my $dir (@newdirs)
{
$dir =~ s/\///;
system("rm -rf $dir*") == 0 or warn "Having trouble deleting directory $dir, $!";
}
print "Exiting.\n";
exit;
}
# backup files
if (defined $opts{b})
{
print "Backing up date files with suffix $datestring\n";
foreach my $move (@newdirs)
{
$move =~ s/\///;
system("cp -r $cwd/$move $cwd/$move.$datestring") == 0 or warn "Can't copy $move, $!";
}
}
# check for interrupts
if (defined $opts{i})
{
$runird = 1;
}
# which engine to use
my $engine;
if (defined $opts{e})
{
$engine = $opts{e};
}
else
{
$engine = 1;
}
if ($engine == 1) { print "Using regexp engine.\n" if ($screendump == 1); }
elsif ($engine == 2) { print "Using multipass engine.\n" if ($screendump == 1); }
elsif ($engine == 3) { print "Using iterative engine.\n" if ($screendump == 1); }
else { die "Somehow, no engine has been defined!\n"; }
print "Current directory: $cwd\n" if ($screendump == 1);
# what are the flanks?
if (defined $opts{f})
{
if ($opts{f} eq "")
{
$flank_size = 300;
}
else
{
$flank_size = $opts{f};
}
print "Overriding flank size in config file - using value: $flank_size\n" if ($screendump == 1);
}
#####################################
# set up motif range and thresholds #
#####################################
my $threshold = $config->{'FINDER.motif_threshold'};
$threshold =~ s/^\|//;
$threshold =~ s/\|$//;
my @thresholds;
my @motif_range;
# load motif ranges into array
my @motif_range_pre = split(/\|/, $threshold);
# remove any duplicates
my %seen = ();
my @threshes=();
foreach my $blah (@motif_range_pre)
{
my ($mot,$thresh) = split(/,/,$blah);
$thresholds[$mot-1] = $thresh;
push(@threshes,$thresh);
$seen{$mot}++;
}
my @uniq = keys %seen;
@motif_range = sort { $a <=> $b } @uniq;
print "Using motif types: ", join(",",@motif_range), "\n" if ($screendump == 1);
die "You must specify motif types to search for.\nExiting!\n" unless (@motif_range);
# check that there are thresholds appropriate to
# each motif type...
my $unspec = 0;
my $typeerror = 0;
foreach my $type (@motif_range)
{
$unspec++ unless ($thresholds[$type-1] =~ /^\d+$/ and $thresholds[$type-1] > 0);
$typeerror++ unless ($type =~ /^\d+$/);
}
# dodgy thresholds
if ($typeerror >= 1)
{
if ($typeerror == 1)
{
print "Error - you have entered a motif type incorrectly: \n";
}
else
{
print "Error - some motif types entered incorrectly:\n";
}
foreach my $type (@motif_range)
{
print "* $type\n" unless ($type =~ /^\d+$/);
}
print "Please edit the .rc file and try again. Exiting!\n";
exit;
}
# oops, at least one threshold undefined
if ($unspec >= 1)
{
if ($unspec == 1)
{
print "Error - a threshold is not defined correctly:\n";
}
else
{
print "Error - some thresholds are not specified. You have supplied the following:\n";
}
print "motif\tthreshold\n";
foreach my $type (@motif_range)
{
my $defstring;
if (@thresholds[$type-1] > 0)
{
$defstring = @thresholds[$type-1];
}
else
{
$defstring = "MISSING";
}
print "$type:\t$defstring\n";
}
print "Please edit the .rc file and try again. Exiting!\n";
exit;
}
###############################################################
# open a file containing a list of the genomes to be searched #
###############################################################
my @infiles = ();
my @nreg = ();
my $list_file;
if ($opts{l})
{
if (@ARGV)
{
chomp($list_file = shift);
}
unless (defined $list_file)
{
print "You need to specify the name of a list file to process.\n";
my @possibles = glob "*\.list";
if (@possibles)
{
print "Please select one of the following files:\n";
foreach (@possibles)
{
print " - $_\n";
}
print "Type one of the above filenames (use the up arrow to select),\n or type in another.\n";
# get the user input
my $term = new Term::ReadLine 'choose file';
my $prompt = "Select an file: ";
foreach (@possibles) { $term->addhistory($_); }
$term->ornaments('0');
$list_file = $term->readline($prompt);
}
else
{
print "I couln't find any list files in $cwd. Please choose a filename, or select X to exit.\n";
# get the user input
my $term = new Term::ReadLine 'choose file';
my $prompt = "Select an file: ";
$term->ornaments('0');
$list_file = $term->readline($prompt);
exit if ($list_file =~ /^[Xx]/);
}
}
# actually open the file at last...
open (LISTFILE, "$list_file") or die "Can't open the file \"$list_file\": $!\nPlease check you have a valid list file, and try again.";
while (my $infile = <LISTFILE>)
{
chomp $infile;
push (@infiles, $infile);
}
close LISTFILE;
}
else
{
@infiles = @ARGV;
}
# exit if no infiles
unless (@infiles)
{
print "You don't seem to have specified any files to process...\n";
print $usage;
exit;
}
# apply the override
if ($override == 1)
{
$artemis = 0;
$mine = 0;
$fastafile = 0;
$sumswitch = 0;
$screendump = 0;
$run_eprimer = 0;
}
# check the deps
my @deps = qw(primer3_core eprimer3);
my %find = ();
$find{primer3_core} = $primer3core;
$find{eprimer3} = $eprimer;
if ($run_eprimer == 1)
{
&depcheck(\%find,$screendump,@deps);
}
# die if you have more things to look for than thresholds
if (scalar @motif_range > scalar @thresholds)
{
die "You seem to have more types of msat to look for than you have thresholds! Please edit the config file and try again.\nExiting!\n";
}
# precalculate some stuff for findmotifs_regex
my $minrep = &min(@threshes);
my $maxmotiflen = scalar(@thresholds);
#Consistency check - see findmotifs_regex
if( $minrep < 3 and $engine == 1) { print "Can't cope with finding less than three repeats of patterns! (\$minrep is $minrep) whilst using the regex engine.\n"; exit; };
if( $thresholds[0] =~ /\d+/ and $thresholds[0] < scalar(@thresholds) and $engine == 1) { print "Threshold for monos too small - cannot resolve ambiguities.\n"; exit; };
# this makes sure that your directories exist
# before trying to write anything to them
my $dir;
foreach $dir (@newdirs)
{
$dir =~ s/\///;
if (-e "$cwd/$dir") { unlink glob "$dir/*"; }
unless (-e "$cwd/$dir") { mkdir "$cwd/$dir" or warn "Can't create $dir"; }
}
#################################################################
# an explication of main variables used throughout this script, #
# except for all the ones I haven't bothered to list here. #
#################################################################
my $aat; # %A divided by %AT
my $abs_path; # path to $repeat_dir (same as $cwd . $repeat_dir)
my $allfile; # one of the NC_xxx.xxx numbers in @all_files
my $all_files2; # prepares a list of files w/ and w/o repeats
my $alphabet; # DNA, RNA or protein?
my $analysis_type; # how the .db files were prepared
my $ATgenome; # AT% in the entire genome
my $blaster; # the entire repeat plus flanking sequence
my $cdsnum; # number of CDS regions found per genome
my $cgc; # %C divided by %CG
my $CGgen_flankseq; # GC content of flank
my $CGgen_repeat; # GC content of repeat
my $CGgenome; # % CG in the complete genome
my $CGmatch; # see the previous CG variable
my $checklength; #
my $checkright; # Determine actual size of
my $checkright_len; # flanks, and the position
my $checkright_len_pc; # of the repeat in the
my $checkleft; # genome (dist from L & R).
my $checkleft_len; #
my $checkleft_len_pc; #
my $circular; # linear or circular DNA/RNA?
my $count; # counts the number of genomes
my $coding; # is this repeat coding or non-coding?
my $def; # Genbank DEFINITION line
my $dodgy; # file without valid content
my $end; # used for determining repeat length
my $entry; # CGI object used for MINE.db writing
my $feature; # header for the .msat_tab file
my $feature_plus_flank; # header for the .flank_tab file
my $file; # the NC_xxx.xxx number currently being examined
my $filein; # the Bio::SeqIO object
my $flankseq; # flanking sequence only
my $fname; # what the fasta file is called
my $fout; # the famous lovely fasta header
my $genome_len; # total length of the genome
my $gentaxon; # a more general taxonomic category
my $howmany; # number of list files in $cwd
my $isaaa = 0; # is a amino acid...
my $isformat; # what format is the file?
my $join; # manipulation of Genbank CDS lines
my $left; # sequence upstream of the repeat
my $linkfile; # symlink to NC file, found in $cwd/<Msat/Flank>_tab
my $loc; # genbank locus
my $match_count; # number of matches found
my $match_len; # length of the match
my $matrix_file; # file with num. reps. vs. size
my $mineend; # "end" of filename on MINE.db and fasta repeat files
my $minenum; # number of repeats found per genome
my $motif_type; # mono, di, tri etc.
my $motif_revcom; # motif reverse compliment
my $numall; # total number of msats found
my $numint; # total number of interrupted msats found
my $numfiles; # number of files surveyed
my $numreps; # number of repeats ($mineum minus the zeros)
my $percentcode; # percentage coding for each genome
my $prefix; # the taxonomic group (phages, viruses etc.)
my $realfile; # file that $linkfile links to
my $replength; # stores the longest repeat length
my $repsum; # sum of repeat length in this genome
my $repsumpc; # percentage of this genome consisting of repeats
my $reverse; # set to 1 if the gene is a "compliment"
my $right; # sequence downstream of the repeat
my $sequence_string; # does what it says on the tin
my $strand; # ss or ds?
my $organism; # genbank ORGANISM
my $tabfile; # name of the feature table associated with $file
my $tempcoding; # sum of total number of coding bases
my $totalreps = 0; # number of genomes containing repeats
my $totalreppc; # percentage of genomes containing repeats
my $primercount = 0; # count total number of genomes with primers
# these variables are responsible for c/gc content &c.
my $base_a;
my $base_t;
my $base_g;
my $base_c;
# arrays and hashes
my @all_files=(); # stores all the $file seen
my @all_files2=(); # stores a little more than @all_files (for output 8)
my @genome_len=(); # list of genome lengths
my @line=(); # lines of the genbank file
my %mineseen=(); # stores the highest $minenum for each $file
my %ncseen=(); # print each $file once to the brief summary
my @dodgy=(); # files that contain invalid content
my $total_ids; # how many unique seqs examined?
my %repeat_counter=(); # store up the total type and number of repeats;
my @short_names=(); # all short names (first key to repeat_counter)
my @all_motifs=(); # all motif types ever found (second key to repeat_counter)
my %motifs_by_genome=(); # all motif types found in one particular genome
my %max_replength=(); # longest number of repeat units for any repeat in a genome
my %has_msat=(); # remember the genomes with msats in
my %unique_motifs=(); # unique motifs from all genomes
my %repseen=(); # sums up the total length of repeats
# in the whole genome
my %genlenhash=(); # matches genome length to $file
my %defseen=(); # matches $def to @all_files2
my %primercheck=(); # can primers be made for this particular sequence?
my %pccodreps=(); # percentage of repeats in coding region
my $genename; # remember the start of each repeat, to determine
my $protname; # which gene it is in, later.
my $prodname;
my %duplicates; # deals with any duplicated sequence names
# hashes used for determining which
# entries are saved into a CSV text file
# later in the script
%ncseen=();
%mineseen=();
###################################
# .db files prepared by msatfinder #
###################################
$analysis_type="msatfinder, run on $date, thresholds >" . join(",",@thresholds);
# determine $prefix (taxonomic_group) from
# the name of the working directory
($prefix = $cwd) =~ s#.*/##;
$prefix =~ /(\w+)\.*/;
$prefix = lc $1;
$cwd .= "/";
# set up the taxon information for use in
# the final database file
$gentaxon = $config->{"FINDER.$prefix"};
unless (defined $gentaxon)
{
$gentaxon = $prefix;
}
# more will be added here to allow more generic
# categorisation of the organelles, bacteria &c.
# N.B. "specific" and "generic" taxa are notes
# for the convenience of the user only (e.g. they
# remind me what directories I put things in.
#########################################
# Where should the output files go? #
#########################################
# The summarised repeats now go in a
# subdirectory of the working directory.
# I have called this "./Repeats"
$abs_path = $cwd . $repeat_dir; # path to $repeat_dir
##########################################
# Open the core output files for writing #
##########################################
# a list of files that seem corrupted (some genbank links are broken resulting in 'empty' files
# during automated download from NCBI
open (OUTPUT_FILE1, ">$abs_path$prefix.errors") or die "Can't open $abs_path$prefix.errors file: $!";
# an index file giving the search parameters and details
open (OUTPUT_FILE2, ">$abs_path$prefix.index") or die "Can't open $abs_path$prefix.index file: $!";
# summary data of coding regions, etc. for each rep file
open (OUTPUT_FILE3, ">$abs_path$prefix.repeats") or die "Can't open $abs_path$prefix.summary file: $!";
# a list of all files, whether or not repeats are present
open (OUTPUT_FILE5, ">$abs_path$prefix.genomes") or die "Can't open $abs_path$prefix.total_sum: $!";
#########################################
# initialize some variables #
#########################################
$| = 1; # flush the buffer...
$count = 0; # number of genomes...
#########################
#########################
# Start searching files #
#########################
#########################
# Read through the list of file names to get all files to search
my $headerprint = 0;
foreach my $file (@infiles)
{
# take in the list of files
push (@all_files, $file);
$numfiles = @all_files;
# announce the cuurent file being searched
print "-----\n" if ($screendump == 1);
print "Searching file: $file\n" if ($screendump == 1);
# MINE file rep number setting
$minenum = "0";
++$count;
$sequence_string = undef;
##############################
# check if it's a fasta file #
# if not, get LOCUS #
##############################
$alphabet = "undefined";
$strand = "undefined";
$organism = "undefined";
$def = "undefined";
my $oldstop = 0;
my ($oldline,$olderline) = ("ftang","ftang");
$isformat = 5;
open (IN, "<$file") or die "Can't open the genome file $file: $!";
my $sprotorembl = 0;
while (my $line =<IN>)
{
chomp($line);
# fasta format
if ($line =~ "^>")
{
print "It looks like this is a FASTA file: $file\n" if ($screendump == 1);
$isformat = 1;
last;
}
# Swissprot format
elsif ($line =~ /^ID/)
{
# could be EMBL or Swissprot
$sprotorembl = 1;
last;
}
# genbank format - the original, needs a lot of
# processing to extract info. that bioperl can't get
elsif ( $line =~ /^LOCUS/)
{
print "It looks like this is a Genbank file: $file\n" if ($screendump == 1);
$isformat = 0;
# get alphabet, and strandedness
# I've assumed that DNA is ds unless
# specifically stated otherwise.
# NCBI claim that this is the case.
my @locs = split(/\s/, $line);
foreach my $loc (@locs)
{
if ($loc =~ /NA/)
{
if ($loc =~ /(\D\D)-(\D+)/)
{
$strand = lc $1;
$alphabet = lc $2;
}
else
{
$strand = "ds";
$alphabet = lc $loc;
}
}
}
}
elsif ($isformat == 5) # assume must be ASCII format
{
print "I don't recognise the format of this this file: $file\nI'll assume that it's ASCII." if ($screendump == 1);
$isformat = 4;
last;
}
# definition
elsif ($line =~ /^\s*DEFINITION\s*/)
{
$def = $line;
$def =~ s/DEFINITION\s+//;
}
# species name
elsif ($line =~ /^\s*ORGANISM\s*/)
{
$organism = "$line";
$organism =~ s/\s*ORGANISM\s*\b//;
}
# exit the loop after reading the important stuff
elsif ($line =~ "FEATURES") { last; }
# match the old line, in case a definition
# extends over two lines (e.g. ORGANISM)
if ($oldline =~ /^DEFINITION/ and $line =~ /^\s+/)
{
$line =~ s/\s+//;
$def = "$def " . $line;
print "Case 1: gbline is $line, oldline is $oldline, def is $def\n" if ($debug == 1);
}
if ($oldline =~ /^\s*ORGANISM/ and $line =~ /^\s+/)
{
$line =~ s/\s+//;
$organism = "$organism " . $line;
print "Case 2: gbline is $line, oldline is $oldline, organism is $organism\n" if ($debug == 1);
}
if ($olderline =~ /^\s*ORGANISM/ and $line =~ /^\s+/)
{
$line =~ s/\s+//;
$organism = "$organism " . $line;
print "Case 3: gbline is $line, olderline is $olderline, organism is $organism\n" if ($debug == 1);
}
# saves the previous line
$olderline = $oldline;
$oldline = $line;
}
close IN;
# swissprot or EMBL format?
if ($sprotorembl == 1)
{
# see if file is swissprot
# if not, it must be EMBL
my $testfile = Bio::SeqIO->new(-file => "$file",
-format => 'EMBL');
my $testseq;
while (1)
{
my $testseq;
eval
{
$testfile->verbose(2);
undef $@;
$testseq = $filein->next_seq()
}; #Done eval
if($@)
{
print "It looks like this is an EMBL file.\n" if ($screendump == 1);
$isformat = 3;
last;
}
else
{
print "It looks like this is a Swissprot file.\n" if ($screendump == 1);
$isformat = 2;
last;
}
}
$testfile->close();
}
# new object, depeding on format
if ($isformat == 1) # FASTA
{
$filein = Bio::SeqIO->new(-file => "$file",
-format => 'Fasta');
}
elsif ($isformat == 2) # Swissprot
{
$filein = Bio::SeqIO->new(-file => "$file",
-format => 'swiss');
}
elsif ($isformat == 3) # EMBL
{
$filein = Bio::SeqIO->new(-file => "$file",
-format => 'EMBL');
}
elsif ($isformat == 0) # genbank
{
$filein = Bio::SeqIO->new(-file => "$file",
-format => 'genbank');
}
elsif ($isformat == 4) # ASCII
{
$filein = Bio::SeqIO->new(-file => "$file",
-format => 'raw');
}
else { die "Unknown file type - please report this error.\n"; }
###########################################
# loop through every sequence in the file #
###########################################
@nreg=();
my $noofseqs = 1;
print "Reading sequences from file $file...\n" if ($screendump == 1);
SEQ: while (my $seq = $filein->next_seq()) # this point is very slow...
{
last unless $seq;
# how much of this sequence is coding
$tempcoding = 0;
$cdsnum = 0;
# first, check if amino acid not dna
if ($seq->alphabet() =~ /protein/)
{
$isaaa = 1;
print "This looks like an amino acid sequence.\n" if ($screendump == 1);
}
else
{
print "This looks like a nucleic acid sequence.\n" if ($screendump == 1);
}
# print headers
&fileheaders($isformat,$isaaa) if ($headerprint == 0);
$headerprint = 1;
# get the ID of this sequence
# and the sequence string
$sequence_string = lc($seq->seq());
$genome_len = length $sequence_string;
my $id = $seq->display_id();
$id =~ s/;//;
$id =~ s/\.gbk//;
# checks for duplicated sequence names
if ($duplicates{$id} == 1)
{
$duplicates{$id}++;
next;
}
else
{
$duplicates{$id} = 1;
}
# create a short name to refer to
# this particular sequence
my ($short_name,@ids);
if ($isformat == 4)
{
$short_name = $datestring . "_" . $noofseqs;
}
else
{
@ids = split(/\|/, $id);
if ($id =~ /^gi/)
{
if (defined $ids[4]) { $short_name = $ids[4]; }
else { $short_name = $ids[1]; }
}
elsif ($id =~ /^gb/) { $short_name = $ids[2]; }
elsif ($id =~ /^ref/) { $short_name = $ids[1]; }
else { $short_name = $id; }
}
# N.B. if the FASTA filename has certain characters in then
# it will cause msatfinder to crash. Get rid of them here.
$short_name =~ s/\./_/g;
$short_name =~ s/\|/_/g;
$short_name =~ s/:/_/g;
$short_name =~ s/,/_/g;
if ($short_name eq "")
{
print "Invalid name in FASTA header. Please replace with something like \"seq1\", \"seq2\" etc.\nExiting!\n";
die;
}
$noofseqs++;
# check for a valid sequence
if (! $seq->validate_seq($sequence_string))
{
print "Sequence $short_name is invalid!\n";
print OUTPUT_FILE1 "INVALID_SEQ|$short_name\n";
$printerror = 1;
next SEQ;
}
# count msats in CDS regions for this genome
$pccodreps{$short_name} = 0;
push(@short_names,$short_name);
$reverse = 0;
# stuff needed to get the species details
my $sp;
my $ps;
my ($species, $genus, @classification, $common_name, $sub_species, $binomial, $division, $gdate, @gdates, $specific_host, $lab_host, $db_xref, $note, $feature_count) = "";
my $ann;
my (@annotations1,@annotations2);
##################################################
# if a genbank file, extract further information #
##################################################
if ($isformat == 0 or $isformat == 2 or $isformat == 3)
{
# species object
$sp = $seq->species();
# information on the organism
$alphabet = $seq->alphabet() unless (defined $alphabet);
eval { $genus = $sp->genus(); } or $genus = "NA";
eval { $species = $sp->species(); } or $species = "NA";
eval { @classification = $sp->classification(); } or @classification = qw(na);
eval { $common_name = $sp->common_name(); } or $common_name = "NA";
eval { $sub_species = $sp->sub_species(); } or $sub_species = "NA";
eval { $binomial = $sp->binomial(); } or $binomial = "NA";
eval { $division = $seq->division(); } or $division = "NA";
@gdates = $seq->get_dates();
my $gdate1 = $gdates[0];
my ($d1,$d2,$d3) = split("-",$gdate1);
$gdate = $d3 . "-" . $dtrans{$d2} . "-" . $d1;
$circular = 'linear';
$circular = 'circular' if $seq->is_circular();
$feature_count = $seq->feature_count();
# features
my $whirley = Whirley->new(4);
print "Reading all annotations in sequence...\n" if ($screendump == 1);
foreach my $feat ($seq->all_SeqFeatures()) # this part is very slow...
{
print STDERR "Please wait: ", $whirley->(), "\r" if ($screendump == 1);
my $tag;
eval { $tag = $feat->primary_tag(); } or $tag = "wibble";
# source: get hosts, notes &c. for this genome
if ($tag =~ "source")
{
my @tags = $feat->all_tags();
foreach my $val (@tags)
{
my @tagvalues = $feat->each_tag_value($val);
if ($val =~ /specific_host/) { $specific_host = $tagvalues[0]; }
if ($val =~ /lab_host/) { $lab_host = $tagvalues[0]; }
if ($val =~ /note/) { $note = $tagvalues[0]; }
if ($val =~ /db_xref/)
{
$db_xref = $tagvalues[0];
$db_xref =~ s/taxon://;
}
}
}
# get start, stop and other stuff here.
if ($tag =~ "CDS")
{
$cdsnum++;
my $location = new Bio::Location::Split;
$location = $feat->location();
if ($location->isa('Bio::Location::Split'))
{
my @sublocs = $location->sub_Location();
foreach my $loc (@sublocs)
{
my $featstart = $loc->start();
my $featend = $loc->end();
&addregion($featstart,$featend);
}
}
else
{
my $featstart = $feat->start();
my $featend = $feat->end();
&addregion($featstart,$featend);
}
}
}
}
########################################
# calculate other things based on data #
# from these info.-rich formats #
# but not swissprot - is amino acid #
########################################
unless ($isaaa == 1)
{
# how much coding DNA is present?
$tempcoding = &howlong || "0";
if ($tempcoding > $genome_len)
{
print "Something's wrong here!\n";
print "Tempcoding: $tempcoding\n";
print "Length: $genome_len\n";
print OUTPUT_FILE1 "CODING_MISMATCH|$short_name|$tempcoding|$genome_len\n";
$printerror = 1;
}
# determine the base count
$base_a = $sequence_string =~ tr/aA/aA/;
$base_c = $sequence_string =~ tr/cC/cC/;
$base_g = $sequence_string =~ tr/gG/gG/;
$base_t = $sequence_string =~ tr/tT/tT/;
# check it!
my $totlen = $genome_len - ($base_a + $base_t + $base_c + $base_g);
if( $totlen < 0 )
{
warn "Base count larger than seq length in $short_name!\n";